PackageManagerService.java revision 0b3cf692f66f13dcb7bf8c6fec15bda84b24efee
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralResolveInfo; 125import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.Process; 181import android.os.RemoteCallbackList; 182import android.os.RemoteException; 183import android.os.ResultReceiver; 184import android.os.SELinux; 185import android.os.ServiceManager; 186import android.os.SystemClock; 187import android.os.SystemProperties; 188import android.os.Trace; 189import android.os.UserHandle; 190import android.os.UserManager; 191import android.os.UserManagerInternal; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.provider.Settings.Global; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.logging.MetricsLogger; 229import com.android.internal.os.IParcelFileDescriptorFactory; 230import com.android.internal.os.InstallerConnection.InstallerException; 231import com.android.internal.os.SomeArgs; 232import com.android.internal.os.Zygote; 233import com.android.internal.telephony.CarrierAppUtils; 234import com.android.internal.util.ArrayUtils; 235import com.android.internal.util.FastPrintWriter; 236import com.android.internal.util.FastXmlSerializer; 237import com.android.internal.util.IndentingPrintWriter; 238import com.android.internal.util.Preconditions; 239import com.android.internal.util.XmlUtils; 240import com.android.server.AttributeCache; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedOutputStream; 266import java.io.BufferedReader; 267import java.io.ByteArrayInputStream; 268import java.io.ByteArrayOutputStream; 269import java.io.File; 270import java.io.FileDescriptor; 271import java.io.FileInputStream; 272import java.io.FileNotFoundException; 273import java.io.FileOutputStream; 274import java.io.FileReader; 275import java.io.FilenameFilter; 276import java.io.IOException; 277import java.io.PrintWriter; 278import java.nio.charset.StandardCharsets; 279import java.security.DigestInputStream; 280import java.security.MessageDigest; 281import java.security.NoSuchAlgorithmException; 282import java.security.PublicKey; 283import java.security.cert.Certificate; 284import java.security.cert.CertificateEncodingException; 285import java.security.cert.CertificateException; 286import java.text.SimpleDateFormat; 287import java.util.ArrayList; 288import java.util.Arrays; 289import java.util.Collection; 290import java.util.Collections; 291import java.util.Comparator; 292import java.util.Date; 293import java.util.HashSet; 294import java.util.Iterator; 295import java.util.List; 296import java.util.Map; 297import java.util.Objects; 298import java.util.Set; 299import java.util.concurrent.CountDownLatch; 300import java.util.concurrent.TimeUnit; 301import java.util.concurrent.atomic.AtomicBoolean; 302import java.util.concurrent.atomic.AtomicInteger; 303 304/** 305 * Keep track of all those APKs everywhere. 306 * <p> 307 * Internally there are two important locks: 308 * <ul> 309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 310 * and other related state. It is a fine-grained lock that should only be held 311 * momentarily, as it's one of the most contended locks in the system. 312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 313 * operations typically involve heavy lifting of application data on disk. Since 314 * {@code installd} is single-threaded, and it's operations can often be slow, 315 * this lock should never be acquired while already holding {@link #mPackages}. 316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 317 * holding {@link #mInstallLock}. 318 * </ul> 319 * Many internal methods rely on the caller to hold the appropriate locks, and 320 * this contract is expressed through method name suffixes: 321 * <ul> 322 * <li>fooLI(): the caller must hold {@link #mInstallLock} 323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 324 * being modified must be frozen 325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 327 * </ul> 328 * <p> 329 * Because this class is very central to the platform's security; please run all 330 * CTS and unit tests whenever making modifications: 331 * 332 * <pre> 333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 335 * </pre> 336 */ 337public class PackageManagerService extends IPackageManager.Stub { 338 static final String TAG = "PackageManager"; 339 static final boolean DEBUG_SETTINGS = false; 340 static final boolean DEBUG_PREFERRED = false; 341 static final boolean DEBUG_UPGRADE = false; 342 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 343 private static final boolean DEBUG_BACKUP = false; 344 private static final boolean DEBUG_INSTALL = false; 345 private static final boolean DEBUG_REMOVE = false; 346 private static final boolean DEBUG_BROADCASTS = false; 347 private static final boolean DEBUG_SHOW_INFO = false; 348 private static final boolean DEBUG_PACKAGE_INFO = false; 349 private static final boolean DEBUG_INTENT_MATCHING = false; 350 private static final boolean DEBUG_PACKAGE_SCANNING = false; 351 private static final boolean DEBUG_VERIFY = false; 352 private static final boolean DEBUG_FILTERS = false; 353 354 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 355 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 356 // user, but by default initialize to this. 357 static final boolean DEBUG_DEXOPT = false; 358 359 private static final boolean DEBUG_ABI_SELECTION = false; 360 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 361 private static final boolean DEBUG_TRIAGED_MISSING = false; 362 private static final boolean DEBUG_APP_DATA = false; 363 364 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 365 366 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 367 368 private static final int RADIO_UID = Process.PHONE_UID; 369 private static final int LOG_UID = Process.LOG_UID; 370 private static final int NFC_UID = Process.NFC_UID; 371 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 372 private static final int SHELL_UID = Process.SHELL_UID; 373 374 // Cap the size of permission trees that 3rd party apps can define 375 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 376 377 // Suffix used during package installation when copying/moving 378 // package apks to install directory. 379 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 380 381 static final int SCAN_NO_DEX = 1<<1; 382 static final int SCAN_FORCE_DEX = 1<<2; 383 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 384 static final int SCAN_NEW_INSTALL = 1<<4; 385 static final int SCAN_NO_PATHS = 1<<5; 386 static final int SCAN_UPDATE_TIME = 1<<6; 387 static final int SCAN_DEFER_DEX = 1<<7; 388 static final int SCAN_BOOTING = 1<<8; 389 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 390 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 391 static final int SCAN_REPLACING = 1<<11; 392 static final int SCAN_REQUIRE_KNOWN = 1<<12; 393 static final int SCAN_MOVE = 1<<13; 394 static final int SCAN_INITIAL = 1<<14; 395 static final int SCAN_CHECK_ONLY = 1<<15; 396 static final int SCAN_DONT_KILL_APP = 1<<17; 397 static final int SCAN_IGNORE_FROZEN = 1<<18; 398 399 static final int REMOVE_CHATTY = 1<<16; 400 401 private static final int[] EMPTY_INT_ARRAY = new int[0]; 402 403 /** 404 * Timeout (in milliseconds) after which the watchdog should declare that 405 * our handler thread is wedged. The usual default for such things is one 406 * minute but we sometimes do very lengthy I/O operations on this thread, 407 * such as installing multi-gigabyte applications, so ours needs to be longer. 408 */ 409 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 410 411 /** 412 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 413 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 414 * settings entry if available, otherwise we use the hardcoded default. If it's been 415 * more than this long since the last fstrim, we force one during the boot sequence. 416 * 417 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 418 * one gets run at the next available charging+idle time. This final mandatory 419 * no-fstrim check kicks in only of the other scheduling criteria is never met. 420 */ 421 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 422 423 /** 424 * Whether verification is enabled by default. 425 */ 426 private static final boolean DEFAULT_VERIFY_ENABLE = true; 427 428 /** 429 * The default maximum time to wait for the verification agent to return in 430 * milliseconds. 431 */ 432 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 433 434 /** 435 * The default response for package verification timeout. 436 * 437 * This can be either PackageManager.VERIFICATION_ALLOW or 438 * PackageManager.VERIFICATION_REJECT. 439 */ 440 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 441 442 static final String PLATFORM_PACKAGE_NAME = "android"; 443 444 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 445 446 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 447 DEFAULT_CONTAINER_PACKAGE, 448 "com.android.defcontainer.DefaultContainerService"); 449 450 private static final String KILL_APP_REASON_GIDS_CHANGED = 451 "permission grant or revoke changed gids"; 452 453 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 454 "permissions revoked"; 455 456 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 457 458 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 459 460 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 461 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 public static final int REASON_CORE_APP = 8; 506 507 public static final int REASON_LAST = REASON_CORE_APP; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 535 /** The location for ASEC container files on internal storage. */ 536 final String mAsecInternalPath; 537 538 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 539 // LOCK HELD. Can be called with mInstallLock held. 540 @GuardedBy("mInstallLock") 541 final Installer mInstaller; 542 543 /** Directory where installed third-party apps stored */ 544 final File mAppInstallDir; 545 final File mEphemeralInstallDir; 546 547 /** 548 * Directory to which applications installed internally have their 549 * 32 bit native libraries copied. 550 */ 551 private File mAppLib32InstallDir; 552 553 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 554 // apps. 555 final File mDrmAppPrivateInstallDir; 556 557 // ---------------------------------------------------------------- 558 559 // Lock for state used when installing and doing other long running 560 // operations. Methods that must be called with this lock held have 561 // the suffix "LI". 562 final Object mInstallLock = new Object(); 563 564 // ---------------------------------------------------------------- 565 566 // Keys are String (package name), values are Package. This also serves 567 // as the lock for the global state. Methods that must be called with 568 // this lock held have the prefix "LP". 569 @GuardedBy("mPackages") 570 final ArrayMap<String, PackageParser.Package> mPackages = 571 new ArrayMap<String, PackageParser.Package>(); 572 573 final ArrayMap<String, Set<String>> mKnownCodebase = 574 new ArrayMap<String, Set<String>>(); 575 576 // Tracks available target package names -> overlay package paths. 577 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 578 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 579 580 /** 581 * Tracks new system packages [received in an OTA] that we expect to 582 * find updated user-installed versions. Keys are package name, values 583 * are package location. 584 */ 585 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 586 /** 587 * Tracks high priority intent filters for protected actions. During boot, certain 588 * filter actions are protected and should never be allowed to have a high priority 589 * intent filter for them. However, there is one, and only one exception -- the 590 * setup wizard. It must be able to define a high priority intent filter for these 591 * actions to ensure there are no escapes from the wizard. We need to delay processing 592 * of these during boot as we need to look at all of the system packages in order 593 * to know which component is the setup wizard. 594 */ 595 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 596 /** 597 * Whether or not processing protected filters should be deferred. 598 */ 599 private boolean mDeferProtectedFilters = true; 600 601 /** 602 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 603 */ 604 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 605 /** 606 * Whether or not system app permissions should be promoted from install to runtime. 607 */ 608 boolean mPromoteSystemApps; 609 610 @GuardedBy("mPackages") 611 final Settings mSettings; 612 613 /** 614 * Set of package names that are currently "frozen", which means active 615 * surgery is being done on the code/data for that package. The platform 616 * will refuse to launch frozen packages to avoid race conditions. 617 * 618 * @see PackageFreezer 619 */ 620 @GuardedBy("mPackages") 621 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 622 623 final ProtectedPackages mProtectedPackages; 624 625 boolean mFirstBoot; 626 627 // System configuration read by SystemConfig. 628 final int[] mGlobalGids; 629 final SparseArray<ArraySet<String>> mSystemPermissions; 630 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 631 632 // If mac_permissions.xml was found for seinfo labeling. 633 boolean mFoundPolicyFile; 634 635 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 636 637 public static final class SharedLibraryEntry { 638 public final String path; 639 public final String apk; 640 641 SharedLibraryEntry(String _path, String _apk) { 642 path = _path; 643 apk = _apk; 644 } 645 } 646 647 // Currently known shared libraries. 648 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 649 new ArrayMap<String, SharedLibraryEntry>(); 650 651 // All available activities, for your resolving pleasure. 652 final ActivityIntentResolver mActivities = 653 new ActivityIntentResolver(); 654 655 // All available receivers, for your resolving pleasure. 656 final ActivityIntentResolver mReceivers = 657 new ActivityIntentResolver(); 658 659 // All available services, for your resolving pleasure. 660 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 661 662 // All available providers, for your resolving pleasure. 663 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 664 665 // Mapping from provider base names (first directory in content URI codePath) 666 // to the provider information. 667 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 668 new ArrayMap<String, PackageParser.Provider>(); 669 670 // Mapping from instrumentation class names to info about them. 671 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 672 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 673 674 // Mapping from permission names to info about them. 675 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 676 new ArrayMap<String, PackageParser.PermissionGroup>(); 677 678 // Packages whose data we have transfered into another package, thus 679 // should no longer exist. 680 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 681 682 // Broadcast actions that are only available to the system. 683 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 684 685 /** List of packages waiting for verification. */ 686 final SparseArray<PackageVerificationState> mPendingVerification 687 = new SparseArray<PackageVerificationState>(); 688 689 /** Set of packages associated with each app op permission. */ 690 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 691 692 final PackageInstallerService mInstallerService; 693 694 private final PackageDexOptimizer mPackageDexOptimizer; 695 696 private AtomicInteger mNextMoveId = new AtomicInteger(); 697 private final MoveCallbacks mMoveCallbacks; 698 699 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 700 701 // Cache of users who need badging. 702 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 703 704 /** Token for keys in mPendingVerification. */ 705 private int mPendingVerificationToken = 0; 706 707 volatile boolean mSystemReady; 708 volatile boolean mSafeMode; 709 volatile boolean mHasSystemUidErrors; 710 711 ApplicationInfo mAndroidApplication; 712 final ActivityInfo mResolveActivity = new ActivityInfo(); 713 final ResolveInfo mResolveInfo = new ResolveInfo(); 714 ComponentName mResolveComponentName; 715 PackageParser.Package mPlatformPackage; 716 ComponentName mCustomResolverComponentName; 717 718 boolean mResolverReplaced = false; 719 720 private final @Nullable ComponentName mIntentFilterVerifierComponent; 721 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 722 723 private int mIntentFilterVerificationToken = 0; 724 725 /** Component that knows whether or not an ephemeral application exists */ 726 final ComponentName mEphemeralResolverComponent; 727 /** The service connection to the ephemeral resolver */ 728 final EphemeralResolverConnection mEphemeralResolverConnection; 729 730 /** Component used to install ephemeral applications */ 731 final ComponentName mEphemeralInstallerComponent; 732 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 733 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 734 735 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 736 = new SparseArray<IntentFilterVerificationState>(); 737 738 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 739 740 // List of packages names to keep cached, even if they are uninstalled for all users 741 private List<String> mKeepUninstalledPackages; 742 743 private UserManagerInternal mUserManagerInternal; 744 745 private static class IFVerificationParams { 746 PackageParser.Package pkg; 747 boolean replacing; 748 int userId; 749 int verifierUid; 750 751 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 752 int _userId, int _verifierUid) { 753 pkg = _pkg; 754 replacing = _replacing; 755 userId = _userId; 756 replacing = _replacing; 757 verifierUid = _verifierUid; 758 } 759 } 760 761 private interface IntentFilterVerifier<T extends IntentFilter> { 762 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 763 T filter, String packageName); 764 void startVerifications(int userId); 765 void receiveVerificationResponse(int verificationId); 766 } 767 768 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 769 private Context mContext; 770 private ComponentName mIntentFilterVerifierComponent; 771 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 772 773 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 774 mContext = context; 775 mIntentFilterVerifierComponent = verifierComponent; 776 } 777 778 private String getDefaultScheme() { 779 return IntentFilter.SCHEME_HTTPS; 780 } 781 782 @Override 783 public void startVerifications(int userId) { 784 // Launch verifications requests 785 int count = mCurrentIntentFilterVerifications.size(); 786 for (int n=0; n<count; n++) { 787 int verificationId = mCurrentIntentFilterVerifications.get(n); 788 final IntentFilterVerificationState ivs = 789 mIntentFilterVerificationStates.get(verificationId); 790 791 String packageName = ivs.getPackageName(); 792 793 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 794 final int filterCount = filters.size(); 795 ArraySet<String> domainsSet = new ArraySet<>(); 796 for (int m=0; m<filterCount; m++) { 797 PackageParser.ActivityIntentInfo filter = filters.get(m); 798 domainsSet.addAll(filter.getHostsList()); 799 } 800 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 801 synchronized (mPackages) { 802 if (mSettings.createIntentFilterVerificationIfNeededLPw( 803 packageName, domainsList) != null) { 804 scheduleWriteSettingsLocked(); 805 } 806 } 807 sendVerificationRequest(userId, verificationId, ivs); 808 } 809 mCurrentIntentFilterVerifications.clear(); 810 } 811 812 private void sendVerificationRequest(int userId, int verificationId, 813 IntentFilterVerificationState ivs) { 814 815 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 818 verificationId); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 821 getDefaultScheme()); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 824 ivs.getHostsString()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 827 ivs.getPackageName()); 828 verificationIntent.setComponent(mIntentFilterVerifierComponent); 829 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 830 831 UserHandle user = new UserHandle(userId); 832 mContext.sendBroadcastAsUser(verificationIntent, user); 833 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 834 "Sending IntentFilter verification broadcast"); 835 } 836 837 public void receiveVerificationResponse(int verificationId) { 838 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 839 840 final boolean verified = ivs.isVerified(); 841 842 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 843 final int count = filters.size(); 844 if (DEBUG_DOMAIN_VERIFICATION) { 845 Slog.i(TAG, "Received verification response " + verificationId 846 + " for " + count + " filters, verified=" + verified); 847 } 848 for (int n=0; n<count; n++) { 849 PackageParser.ActivityIntentInfo filter = filters.get(n); 850 filter.setVerified(verified); 851 852 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 853 + " verified with result:" + verified + " and hosts:" 854 + ivs.getHostsString()); 855 } 856 857 mIntentFilterVerificationStates.remove(verificationId); 858 859 final String packageName = ivs.getPackageName(); 860 IntentFilterVerificationInfo ivi = null; 861 862 synchronized (mPackages) { 863 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 864 } 865 if (ivi == null) { 866 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 867 + verificationId + " packageName:" + packageName); 868 return; 869 } 870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 871 "Updating IntentFilterVerificationInfo for package " + packageName 872 +" verificationId:" + verificationId); 873 874 synchronized (mPackages) { 875 if (verified) { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 877 } else { 878 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 879 } 880 scheduleWriteSettingsLocked(); 881 882 final int userId = ivs.getUserId(); 883 if (userId != UserHandle.USER_ALL) { 884 final int userStatus = 885 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 886 887 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 888 boolean needUpdate = false; 889 890 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 891 // already been set by the User thru the Disambiguation dialog 892 switch (userStatus) { 893 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 894 if (verified) { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 896 } else { 897 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 898 } 899 needUpdate = true; 900 break; 901 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 needUpdate = true; 906 } 907 break; 908 909 default: 910 // Nothing to do 911 } 912 913 if (needUpdate) { 914 mSettings.updateIntentFilterVerificationStatusLPw( 915 packageName, updatedStatus, userId); 916 scheduleWritePackageRestrictionsLocked(userId); 917 } 918 } 919 } 920 } 921 922 @Override 923 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 924 ActivityIntentInfo filter, String packageName) { 925 if (!hasValidDomains(filter)) { 926 return false; 927 } 928 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 929 if (ivs == null) { 930 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 931 packageName); 932 } 933 if (DEBUG_DOMAIN_VERIFICATION) { 934 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 935 } 936 ivs.addFilter(filter); 937 return true; 938 } 939 940 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 941 int userId, int verificationId, String packageName) { 942 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 943 verifierUid, userId, packageName); 944 ivs.setPendingState(); 945 synchronized (mPackages) { 946 mIntentFilterVerificationStates.append(verificationId, ivs); 947 mCurrentIntentFilterVerifications.add(verificationId); 948 } 949 return ivs; 950 } 951 } 952 953 private static boolean hasValidDomains(ActivityIntentInfo filter) { 954 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 955 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 956 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 957 } 958 959 // Set of pending broadcasts for aggregating enable/disable of components. 960 static class PendingPackageBroadcasts { 961 // for each user id, a map of <package name -> components within that package> 962 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 963 964 public PendingPackageBroadcasts() { 965 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 966 } 967 968 public ArrayList<String> get(int userId, String packageName) { 969 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 970 return packages.get(packageName); 971 } 972 973 public void put(int userId, String packageName, ArrayList<String> components) { 974 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 975 packages.put(packageName, components); 976 } 977 978 public void remove(int userId, String packageName) { 979 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 980 if (packages != null) { 981 packages.remove(packageName); 982 } 983 } 984 985 public void remove(int userId) { 986 mUidMap.remove(userId); 987 } 988 989 public int userIdCount() { 990 return mUidMap.size(); 991 } 992 993 public int userIdAt(int n) { 994 return mUidMap.keyAt(n); 995 } 996 997 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 998 return mUidMap.get(userId); 999 } 1000 1001 public int size() { 1002 // total number of pending broadcast entries across all userIds 1003 int num = 0; 1004 for (int i = 0; i< mUidMap.size(); i++) { 1005 num += mUidMap.valueAt(i).size(); 1006 } 1007 return num; 1008 } 1009 1010 public void clear() { 1011 mUidMap.clear(); 1012 } 1013 1014 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1015 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1016 if (map == null) { 1017 map = new ArrayMap<String, ArrayList<String>>(); 1018 mUidMap.put(userId, map); 1019 } 1020 return map; 1021 } 1022 } 1023 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1024 1025 // Service Connection to remote media container service to copy 1026 // package uri's from external media onto secure containers 1027 // or internal storage. 1028 private IMediaContainerService mContainerService = null; 1029 1030 static final int SEND_PENDING_BROADCAST = 1; 1031 static final int MCS_BOUND = 3; 1032 static final int END_COPY = 4; 1033 static final int INIT_COPY = 5; 1034 static final int MCS_UNBIND = 6; 1035 static final int START_CLEANING_PACKAGE = 7; 1036 static final int FIND_INSTALL_LOC = 8; 1037 static final int POST_INSTALL = 9; 1038 static final int MCS_RECONNECT = 10; 1039 static final int MCS_GIVE_UP = 11; 1040 static final int UPDATED_MEDIA_STATUS = 12; 1041 static final int WRITE_SETTINGS = 13; 1042 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1043 static final int PACKAGE_VERIFIED = 15; 1044 static final int CHECK_PENDING_VERIFICATION = 16; 1045 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1046 static final int INTENT_FILTER_VERIFIED = 18; 1047 static final int WRITE_PACKAGE_LIST = 19; 1048 1049 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1050 1051 // Delay time in millisecs 1052 static final int BROADCAST_DELAY = 10 * 1000; 1053 1054 static UserManagerService sUserManager; 1055 1056 // Stores a list of users whose package restrictions file needs to be updated 1057 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1058 1059 final private DefaultContainerConnection mDefContainerConn = 1060 new DefaultContainerConnection(); 1061 class DefaultContainerConnection implements ServiceConnection { 1062 public void onServiceConnected(ComponentName name, IBinder service) { 1063 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1064 IMediaContainerService imcs = 1065 IMediaContainerService.Stub.asInterface(service); 1066 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1067 } 1068 1069 public void onServiceDisconnected(ComponentName name) { 1070 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1071 } 1072 } 1073 1074 // Recordkeeping of restore-after-install operations that are currently in flight 1075 // between the Package Manager and the Backup Manager 1076 static class PostInstallData { 1077 public InstallArgs args; 1078 public PackageInstalledInfo res; 1079 1080 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1081 args = _a; 1082 res = _r; 1083 } 1084 } 1085 1086 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1087 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1088 1089 // XML tags for backup/restore of various bits of state 1090 private static final String TAG_PREFERRED_BACKUP = "pa"; 1091 private static final String TAG_DEFAULT_APPS = "da"; 1092 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1093 1094 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1095 private static final String TAG_ALL_GRANTS = "rt-grants"; 1096 private static final String TAG_GRANT = "grant"; 1097 private static final String ATTR_PACKAGE_NAME = "pkg"; 1098 1099 private static final String TAG_PERMISSION = "perm"; 1100 private static final String ATTR_PERMISSION_NAME = "name"; 1101 private static final String ATTR_IS_GRANTED = "g"; 1102 private static final String ATTR_USER_SET = "set"; 1103 private static final String ATTR_USER_FIXED = "fixed"; 1104 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1105 1106 // System/policy permission grants are not backed up 1107 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1108 FLAG_PERMISSION_POLICY_FIXED 1109 | FLAG_PERMISSION_SYSTEM_FIXED 1110 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1111 1112 // And we back up these user-adjusted states 1113 private static final int USER_RUNTIME_GRANT_MASK = 1114 FLAG_PERMISSION_USER_SET 1115 | FLAG_PERMISSION_USER_FIXED 1116 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1117 1118 final @Nullable String mRequiredVerifierPackage; 1119 final @NonNull String mRequiredInstallerPackage; 1120 final @Nullable String mSetupWizardPackage; 1121 final @NonNull String mServicesSystemSharedLibraryPackageName; 1122 final @NonNull String mSharedSystemSharedLibraryPackageName; 1123 1124 private final PackageUsage mPackageUsage = new PackageUsage(); 1125 private final CompilerStats mCompilerStats = new CompilerStats(); 1126 1127 class PackageHandler extends Handler { 1128 private boolean mBound = false; 1129 final ArrayList<HandlerParams> mPendingInstalls = 1130 new ArrayList<HandlerParams>(); 1131 1132 private boolean connectToService() { 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1134 " DefaultContainerService"); 1135 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1137 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1138 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1140 mBound = true; 1141 return true; 1142 } 1143 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1144 return false; 1145 } 1146 1147 private void disconnectService() { 1148 mContainerService = null; 1149 mBound = false; 1150 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1151 mContext.unbindService(mDefContainerConn); 1152 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1153 } 1154 1155 PackageHandler(Looper looper) { 1156 super(looper); 1157 } 1158 1159 public void handleMessage(Message msg) { 1160 try { 1161 doHandleMessage(msg); 1162 } finally { 1163 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1164 } 1165 } 1166 1167 void doHandleMessage(Message msg) { 1168 switch (msg.what) { 1169 case INIT_COPY: { 1170 HandlerParams params = (HandlerParams) msg.obj; 1171 int idx = mPendingInstalls.size(); 1172 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1173 // If a bind was already initiated we dont really 1174 // need to do anything. The pending install 1175 // will be processed later on. 1176 if (!mBound) { 1177 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1178 System.identityHashCode(mHandler)); 1179 // If this is the only one pending we might 1180 // have to bind to the service again. 1181 if (!connectToService()) { 1182 Slog.e(TAG, "Failed to bind to media container service"); 1183 params.serviceError(); 1184 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1185 System.identityHashCode(mHandler)); 1186 if (params.traceMethod != null) { 1187 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1188 params.traceCookie); 1189 } 1190 return; 1191 } else { 1192 // Once we bind to the service, the first 1193 // pending request will be processed. 1194 mPendingInstalls.add(idx, params); 1195 } 1196 } else { 1197 mPendingInstalls.add(idx, params); 1198 // Already bound to the service. Just make 1199 // sure we trigger off processing the first request. 1200 if (idx == 0) { 1201 mHandler.sendEmptyMessage(MCS_BOUND); 1202 } 1203 } 1204 break; 1205 } 1206 case MCS_BOUND: { 1207 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1208 if (msg.obj != null) { 1209 mContainerService = (IMediaContainerService) msg.obj; 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 } 1213 if (mContainerService == null) { 1214 if (!mBound) { 1215 // Something seriously wrong since we are not bound and we are not 1216 // waiting for connection. Bail out. 1217 Slog.e(TAG, "Cannot bind to media container service"); 1218 for (HandlerParams params : mPendingInstalls) { 1219 // Indicate service bind error 1220 params.serviceError(); 1221 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1222 System.identityHashCode(params)); 1223 if (params.traceMethod != null) { 1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1225 params.traceMethod, params.traceCookie); 1226 } 1227 return; 1228 } 1229 mPendingInstalls.clear(); 1230 } else { 1231 Slog.w(TAG, "Waiting to connect to media container service"); 1232 } 1233 } else if (mPendingInstalls.size() > 0) { 1234 HandlerParams params = mPendingInstalls.get(0); 1235 if (params != null) { 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1237 System.identityHashCode(params)); 1238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1239 if (params.startCopy()) { 1240 // We are done... look for more work or to 1241 // go idle. 1242 if (DEBUG_SD_INSTALL) Log.i(TAG, 1243 "Checking for more work or unbind..."); 1244 // Delete pending install 1245 if (mPendingInstalls.size() > 0) { 1246 mPendingInstalls.remove(0); 1247 } 1248 if (mPendingInstalls.size() == 0) { 1249 if (mBound) { 1250 if (DEBUG_SD_INSTALL) Log.i(TAG, 1251 "Posting delayed MCS_UNBIND"); 1252 removeMessages(MCS_UNBIND); 1253 Message ubmsg = obtainMessage(MCS_UNBIND); 1254 // Unbind after a little delay, to avoid 1255 // continual thrashing. 1256 sendMessageDelayed(ubmsg, 10000); 1257 } 1258 } else { 1259 // There are more pending requests in queue. 1260 // Just post MCS_BOUND message to trigger processing 1261 // of next pending install. 1262 if (DEBUG_SD_INSTALL) Log.i(TAG, 1263 "Posting MCS_BOUND for next work"); 1264 mHandler.sendEmptyMessage(MCS_BOUND); 1265 } 1266 } 1267 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1268 } 1269 } else { 1270 // Should never happen ideally. 1271 Slog.w(TAG, "Empty queue"); 1272 } 1273 break; 1274 } 1275 case MCS_RECONNECT: { 1276 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1277 if (mPendingInstalls.size() > 0) { 1278 if (mBound) { 1279 disconnectService(); 1280 } 1281 if (!connectToService()) { 1282 Slog.e(TAG, "Failed to bind to media container service"); 1283 for (HandlerParams params : mPendingInstalls) { 1284 // Indicate service bind error 1285 params.serviceError(); 1286 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1287 System.identityHashCode(params)); 1288 } 1289 mPendingInstalls.clear(); 1290 } 1291 } 1292 break; 1293 } 1294 case MCS_UNBIND: { 1295 // If there is no actual work left, then time to unbind. 1296 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1297 1298 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1299 if (mBound) { 1300 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1301 1302 disconnectService(); 1303 } 1304 } else if (mPendingInstalls.size() > 0) { 1305 // There are more pending requests in queue. 1306 // Just post MCS_BOUND message to trigger processing 1307 // of next pending install. 1308 mHandler.sendEmptyMessage(MCS_BOUND); 1309 } 1310 1311 break; 1312 } 1313 case MCS_GIVE_UP: { 1314 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1315 HandlerParams params = mPendingInstalls.remove(0); 1316 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1317 System.identityHashCode(params)); 1318 break; 1319 } 1320 case SEND_PENDING_BROADCAST: { 1321 String packages[]; 1322 ArrayList<String> components[]; 1323 int size = 0; 1324 int uids[]; 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1326 synchronized (mPackages) { 1327 if (mPendingBroadcasts == null) { 1328 return; 1329 } 1330 size = mPendingBroadcasts.size(); 1331 if (size <= 0) { 1332 // Nothing to be done. Just return 1333 return; 1334 } 1335 packages = new String[size]; 1336 components = new ArrayList[size]; 1337 uids = new int[size]; 1338 int i = 0; // filling out the above arrays 1339 1340 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1341 int packageUserId = mPendingBroadcasts.userIdAt(n); 1342 Iterator<Map.Entry<String, ArrayList<String>>> it 1343 = mPendingBroadcasts.packagesForUserId(packageUserId) 1344 .entrySet().iterator(); 1345 while (it.hasNext() && i < size) { 1346 Map.Entry<String, ArrayList<String>> ent = it.next(); 1347 packages[i] = ent.getKey(); 1348 components[i] = ent.getValue(); 1349 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1350 uids[i] = (ps != null) 1351 ? UserHandle.getUid(packageUserId, ps.appId) 1352 : -1; 1353 i++; 1354 } 1355 } 1356 size = i; 1357 mPendingBroadcasts.clear(); 1358 } 1359 // Send broadcasts 1360 for (int i = 0; i < size; i++) { 1361 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1362 } 1363 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1364 break; 1365 } 1366 case START_CLEANING_PACKAGE: { 1367 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1368 final String packageName = (String)msg.obj; 1369 final int userId = msg.arg1; 1370 final boolean andCode = msg.arg2 != 0; 1371 synchronized (mPackages) { 1372 if (userId == UserHandle.USER_ALL) { 1373 int[] users = sUserManager.getUserIds(); 1374 for (int user : users) { 1375 mSettings.addPackageToCleanLPw( 1376 new PackageCleanItem(user, packageName, andCode)); 1377 } 1378 } else { 1379 mSettings.addPackageToCleanLPw( 1380 new PackageCleanItem(userId, packageName, andCode)); 1381 } 1382 } 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1384 startCleaningPackages(); 1385 } break; 1386 case POST_INSTALL: { 1387 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1388 1389 PostInstallData data = mRunningInstalls.get(msg.arg1); 1390 final boolean didRestore = (msg.arg2 != 0); 1391 mRunningInstalls.delete(msg.arg1); 1392 1393 if (data != null) { 1394 InstallArgs args = data.args; 1395 PackageInstalledInfo parentRes = data.res; 1396 1397 final boolean grantPermissions = (args.installFlags 1398 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1399 final boolean killApp = (args.installFlags 1400 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1401 final String[] grantedPermissions = args.installGrantPermissions; 1402 1403 // Handle the parent package 1404 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1405 grantedPermissions, didRestore, args.installerPackageName, 1406 args.observer); 1407 1408 // Handle the child packages 1409 final int childCount = (parentRes.addedChildPackages != null) 1410 ? parentRes.addedChildPackages.size() : 0; 1411 for (int i = 0; i < childCount; i++) { 1412 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1413 handlePackagePostInstall(childRes, grantPermissions, killApp, 1414 grantedPermissions, false, args.installerPackageName, 1415 args.observer); 1416 } 1417 1418 // Log tracing if needed 1419 if (args.traceMethod != null) { 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1421 args.traceCookie); 1422 } 1423 } else { 1424 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1425 } 1426 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1428 } break; 1429 case UPDATED_MEDIA_STATUS: { 1430 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1431 boolean reportStatus = msg.arg1 == 1; 1432 boolean doGc = msg.arg2 == 1; 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1434 if (doGc) { 1435 // Force a gc to clear up stale containers. 1436 Runtime.getRuntime().gc(); 1437 } 1438 if (msg.obj != null) { 1439 @SuppressWarnings("unchecked") 1440 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1441 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1442 // Unload containers 1443 unloadAllContainers(args); 1444 } 1445 if (reportStatus) { 1446 try { 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1448 PackageHelper.getMountService().finishMediaUpdate(); 1449 } catch (RemoteException e) { 1450 Log.e(TAG, "MountService not running?"); 1451 } 1452 } 1453 } break; 1454 case WRITE_SETTINGS: { 1455 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1456 synchronized (mPackages) { 1457 removeMessages(WRITE_SETTINGS); 1458 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1459 mSettings.writeLPr(); 1460 mDirtyUsers.clear(); 1461 } 1462 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1463 } break; 1464 case WRITE_PACKAGE_RESTRICTIONS: { 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1466 synchronized (mPackages) { 1467 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1468 for (int userId : mDirtyUsers) { 1469 mSettings.writePackageRestrictionsLPr(userId); 1470 } 1471 mDirtyUsers.clear(); 1472 } 1473 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1474 } break; 1475 case WRITE_PACKAGE_LIST: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_PACKAGE_LIST); 1479 mSettings.writePackageListLPr(msg.arg1); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case CHECK_PENDING_VERIFICATION: { 1484 final int verificationId = msg.arg1; 1485 final PackageVerificationState state = mPendingVerification.get(verificationId); 1486 1487 if ((state != null) && !state.timeoutExtended()) { 1488 final InstallArgs args = state.getInstallArgs(); 1489 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1490 1491 Slog.i(TAG, "Verification timed out for " + originUri); 1492 mPendingVerification.remove(verificationId); 1493 1494 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1495 1496 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1497 Slog.i(TAG, "Continuing with installation of " + originUri); 1498 state.setVerifierResponse(Binder.getCallingUid(), 1499 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1500 broadcastPackageVerified(verificationId, originUri, 1501 PackageManager.VERIFICATION_ALLOW, 1502 state.getInstallArgs().getUser()); 1503 try { 1504 ret = args.copyApk(mContainerService, true); 1505 } catch (RemoteException e) { 1506 Slog.e(TAG, "Could not contact the ContainerService"); 1507 } 1508 } else { 1509 broadcastPackageVerified(verificationId, originUri, 1510 PackageManager.VERIFICATION_REJECT, 1511 state.getInstallArgs().getUser()); 1512 } 1513 1514 Trace.asyncTraceEnd( 1515 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1516 1517 processPendingInstall(args, ret); 1518 mHandler.sendEmptyMessage(MCS_UNBIND); 1519 } 1520 break; 1521 } 1522 case PACKAGE_VERIFIED: { 1523 final int verificationId = msg.arg1; 1524 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 if (state == null) { 1527 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1528 break; 1529 } 1530 1531 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1532 1533 state.setVerifierResponse(response.callerUid, response.code); 1534 1535 if (state.isVerificationComplete()) { 1536 mPendingVerification.remove(verificationId); 1537 1538 final InstallArgs args = state.getInstallArgs(); 1539 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1540 1541 int ret; 1542 if (state.isInstallAllowed()) { 1543 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1544 broadcastPackageVerified(verificationId, originUri, 1545 response.code, state.getInstallArgs().getUser()); 1546 try { 1547 ret = args.copyApk(mContainerService, true); 1548 } catch (RemoteException e) { 1549 Slog.e(TAG, "Could not contact the ContainerService"); 1550 } 1551 } else { 1552 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1553 } 1554 1555 Trace.asyncTraceEnd( 1556 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1557 1558 processPendingInstall(args, ret); 1559 mHandler.sendEmptyMessage(MCS_UNBIND); 1560 } 1561 1562 break; 1563 } 1564 case START_INTENT_FILTER_VERIFICATIONS: { 1565 IFVerificationParams params = (IFVerificationParams) msg.obj; 1566 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1567 params.replacing, params.pkg); 1568 break; 1569 } 1570 case INTENT_FILTER_VERIFIED: { 1571 final int verificationId = msg.arg1; 1572 1573 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1574 verificationId); 1575 if (state == null) { 1576 Slog.w(TAG, "Invalid IntentFilter verification token " 1577 + verificationId + " received"); 1578 break; 1579 } 1580 1581 final int userId = state.getUserId(); 1582 1583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1584 "Processing IntentFilter verification with token:" 1585 + verificationId + " and userId:" + userId); 1586 1587 final IntentFilterVerificationResponse response = 1588 (IntentFilterVerificationResponse) msg.obj; 1589 1590 state.setVerifierResponse(response.callerUid, response.code); 1591 1592 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1593 "IntentFilter verification with token:" + verificationId 1594 + " and userId:" + userId 1595 + " is settings verifier response with response code:" 1596 + response.code); 1597 1598 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1599 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1600 + response.getFailedDomainsString()); 1601 } 1602 1603 if (state.isVerificationComplete()) { 1604 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1605 } else { 1606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1607 "IntentFilter verification with token:" + verificationId 1608 + " was not said to be complete"); 1609 } 1610 1611 break; 1612 } 1613 } 1614 } 1615 } 1616 1617 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1618 boolean killApp, String[] grantedPermissions, 1619 boolean launchedForRestore, String installerPackage, 1620 IPackageInstallObserver2 installObserver) { 1621 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1622 // Send the removed broadcasts 1623 if (res.removedInfo != null) { 1624 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1625 } 1626 1627 // Now that we successfully installed the package, grant runtime 1628 // permissions if requested before broadcasting the install. 1629 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1630 >= Build.VERSION_CODES.M) { 1631 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1632 } 1633 1634 final boolean update = res.removedInfo != null 1635 && res.removedInfo.removedPackage != null; 1636 1637 // If this is the first time we have child packages for a disabled privileged 1638 // app that had no children, we grant requested runtime permissions to the new 1639 // children if the parent on the system image had them already granted. 1640 if (res.pkg.parentPackage != null) { 1641 synchronized (mPackages) { 1642 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1643 } 1644 } 1645 1646 synchronized (mPackages) { 1647 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1648 } 1649 1650 final String packageName = res.pkg.applicationInfo.packageName; 1651 Bundle extras = new Bundle(1); 1652 extras.putInt(Intent.EXTRA_UID, res.uid); 1653 1654 // Determine the set of users who are adding this package for 1655 // the first time vs. those who are seeing an update. 1656 int[] firstUsers = EMPTY_INT_ARRAY; 1657 int[] updateUsers = EMPTY_INT_ARRAY; 1658 if (res.origUsers == null || res.origUsers.length == 0) { 1659 firstUsers = res.newUsers; 1660 } else { 1661 for (int newUser : res.newUsers) { 1662 boolean isNew = true; 1663 for (int origUser : res.origUsers) { 1664 if (origUser == newUser) { 1665 isNew = false; 1666 break; 1667 } 1668 } 1669 if (isNew) { 1670 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1671 } else { 1672 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1673 } 1674 } 1675 } 1676 1677 // Send installed broadcasts if the install/update is not ephemeral 1678 if (!isEphemeral(res.pkg)) { 1679 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1680 1681 // Send added for users that see the package for the first time 1682 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1683 extras, 0 /*flags*/, null /*targetPackage*/, 1684 null /*finishedReceiver*/, firstUsers); 1685 1686 // Send added for users that don't see the package for the first time 1687 if (update) { 1688 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1689 } 1690 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1691 extras, 0 /*flags*/, null /*targetPackage*/, 1692 null /*finishedReceiver*/, updateUsers); 1693 1694 // Send replaced for users that don't see the package for the first time 1695 if (update) { 1696 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1697 packageName, extras, 0 /*flags*/, 1698 null /*targetPackage*/, null /*finishedReceiver*/, 1699 updateUsers); 1700 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1701 null /*package*/, null /*extras*/, 0 /*flags*/, 1702 packageName /*targetPackage*/, 1703 null /*finishedReceiver*/, updateUsers); 1704 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1705 // First-install and we did a restore, so we're responsible for the 1706 // first-launch broadcast. 1707 if (DEBUG_BACKUP) { 1708 Slog.i(TAG, "Post-restore of " + packageName 1709 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1710 } 1711 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1712 } 1713 1714 // Send broadcast package appeared if forward locked/external for all users 1715 // treat asec-hosted packages like removable media on upgrade 1716 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1717 if (DEBUG_INSTALL) { 1718 Slog.i(TAG, "upgrading pkg " + res.pkg 1719 + " is ASEC-hosted -> AVAILABLE"); 1720 } 1721 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1722 ArrayList<String> pkgList = new ArrayList<>(1); 1723 pkgList.add(packageName); 1724 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1725 } 1726 } 1727 1728 // Work that needs to happen on first install within each user 1729 if (firstUsers != null && firstUsers.length > 0) { 1730 synchronized (mPackages) { 1731 for (int userId : firstUsers) { 1732 // If this app is a browser and it's newly-installed for some 1733 // users, clear any default-browser state in those users. The 1734 // app's nature doesn't depend on the user, so we can just check 1735 // its browser nature in any user and generalize. 1736 if (packageIsBrowser(packageName, userId)) { 1737 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1738 } 1739 1740 // We may also need to apply pending (restored) runtime 1741 // permission grants within these users. 1742 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1743 } 1744 } 1745 } 1746 1747 // Log current value of "unknown sources" setting 1748 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1749 getUnknownSourcesSettings()); 1750 1751 // Force a gc to clear up things 1752 Runtime.getRuntime().gc(); 1753 1754 // Remove the replaced package's older resources safely now 1755 // We delete after a gc for applications on sdcard. 1756 if (res.removedInfo != null && res.removedInfo.args != null) { 1757 synchronized (mInstallLock) { 1758 res.removedInfo.args.doPostDeleteLI(true); 1759 } 1760 } 1761 } 1762 1763 // If someone is watching installs - notify them 1764 if (installObserver != null) { 1765 try { 1766 Bundle extras = extrasForInstallResult(res); 1767 installObserver.onPackageInstalled(res.name, res.returnCode, 1768 res.returnMsg, extras); 1769 } catch (RemoteException e) { 1770 Slog.i(TAG, "Observer no longer exists."); 1771 } 1772 } 1773 } 1774 1775 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1776 PackageParser.Package pkg) { 1777 if (pkg.parentPackage == null) { 1778 return; 1779 } 1780 if (pkg.requestedPermissions == null) { 1781 return; 1782 } 1783 final PackageSetting disabledSysParentPs = mSettings 1784 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1785 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1786 || !disabledSysParentPs.isPrivileged() 1787 || (disabledSysParentPs.childPackageNames != null 1788 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1789 return; 1790 } 1791 final int[] allUserIds = sUserManager.getUserIds(); 1792 final int permCount = pkg.requestedPermissions.size(); 1793 for (int i = 0; i < permCount; i++) { 1794 String permission = pkg.requestedPermissions.get(i); 1795 BasePermission bp = mSettings.mPermissions.get(permission); 1796 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1797 continue; 1798 } 1799 for (int userId : allUserIds) { 1800 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1801 permission, userId)) { 1802 grantRuntimePermission(pkg.packageName, permission, userId); 1803 } 1804 } 1805 } 1806 } 1807 1808 private StorageEventListener mStorageListener = new StorageEventListener() { 1809 @Override 1810 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1811 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1812 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1813 final String volumeUuid = vol.getFsUuid(); 1814 1815 // Clean up any users or apps that were removed or recreated 1816 // while this volume was missing 1817 reconcileUsers(volumeUuid); 1818 reconcileApps(volumeUuid); 1819 1820 // Clean up any install sessions that expired or were 1821 // cancelled while this volume was missing 1822 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1823 1824 loadPrivatePackages(vol); 1825 1826 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1827 unloadPrivatePackages(vol); 1828 } 1829 } 1830 1831 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1832 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1833 updateExternalMediaStatus(true, false); 1834 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1835 updateExternalMediaStatus(false, false); 1836 } 1837 } 1838 } 1839 1840 @Override 1841 public void onVolumeForgotten(String fsUuid) { 1842 if (TextUtils.isEmpty(fsUuid)) { 1843 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1844 return; 1845 } 1846 1847 // Remove any apps installed on the forgotten volume 1848 synchronized (mPackages) { 1849 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1850 for (PackageSetting ps : packages) { 1851 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1852 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1853 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1854 } 1855 1856 mSettings.onVolumeForgotten(fsUuid); 1857 mSettings.writeLPr(); 1858 } 1859 } 1860 }; 1861 1862 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1863 String[] grantedPermissions) { 1864 for (int userId : userIds) { 1865 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1866 } 1867 1868 // We could have touched GID membership, so flush out packages.list 1869 synchronized (mPackages) { 1870 mSettings.writePackageListLPr(); 1871 } 1872 } 1873 1874 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1875 String[] grantedPermissions) { 1876 SettingBase sb = (SettingBase) pkg.mExtras; 1877 if (sb == null) { 1878 return; 1879 } 1880 1881 PermissionsState permissionsState = sb.getPermissionsState(); 1882 1883 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1884 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1885 1886 for (String permission : pkg.requestedPermissions) { 1887 final BasePermission bp; 1888 synchronized (mPackages) { 1889 bp = mSettings.mPermissions.get(permission); 1890 } 1891 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1892 && (grantedPermissions == null 1893 || ArrayUtils.contains(grantedPermissions, permission))) { 1894 final int flags = permissionsState.getPermissionFlags(permission, userId); 1895 // Installer cannot change immutable permissions. 1896 if ((flags & immutableFlags) == 0) { 1897 grantRuntimePermission(pkg.packageName, permission, userId); 1898 } 1899 } 1900 } 1901 } 1902 1903 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1904 Bundle extras = null; 1905 switch (res.returnCode) { 1906 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1907 extras = new Bundle(); 1908 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1909 res.origPermission); 1910 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1911 res.origPackage); 1912 break; 1913 } 1914 case PackageManager.INSTALL_SUCCEEDED: { 1915 extras = new Bundle(); 1916 extras.putBoolean(Intent.EXTRA_REPLACING, 1917 res.removedInfo != null && res.removedInfo.removedPackage != null); 1918 break; 1919 } 1920 } 1921 return extras; 1922 } 1923 1924 void scheduleWriteSettingsLocked() { 1925 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1926 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1927 } 1928 } 1929 1930 void scheduleWritePackageListLocked(int userId) { 1931 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1932 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1933 msg.arg1 = userId; 1934 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1935 } 1936 } 1937 1938 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1939 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1940 scheduleWritePackageRestrictionsLocked(userId); 1941 } 1942 1943 void scheduleWritePackageRestrictionsLocked(int userId) { 1944 final int[] userIds = (userId == UserHandle.USER_ALL) 1945 ? sUserManager.getUserIds() : new int[]{userId}; 1946 for (int nextUserId : userIds) { 1947 if (!sUserManager.exists(nextUserId)) return; 1948 mDirtyUsers.add(nextUserId); 1949 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1950 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1951 } 1952 } 1953 } 1954 1955 public static PackageManagerService main(Context context, Installer installer, 1956 boolean factoryTest, boolean onlyCore) { 1957 // Self-check for initial settings. 1958 PackageManagerServiceCompilerMapping.checkProperties(); 1959 1960 PackageManagerService m = new PackageManagerService(context, installer, 1961 factoryTest, onlyCore); 1962 m.enableSystemUserPackages(); 1963 ServiceManager.addService("package", m); 1964 return m; 1965 } 1966 1967 private void enableSystemUserPackages() { 1968 if (!UserManager.isSplitSystemUser()) { 1969 return; 1970 } 1971 // For system user, enable apps based on the following conditions: 1972 // - app is whitelisted or belong to one of these groups: 1973 // -- system app which has no launcher icons 1974 // -- system app which has INTERACT_ACROSS_USERS permission 1975 // -- system IME app 1976 // - app is not in the blacklist 1977 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1978 Set<String> enableApps = new ArraySet<>(); 1979 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1980 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1981 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1982 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1983 enableApps.addAll(wlApps); 1984 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1985 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1986 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1987 enableApps.removeAll(blApps); 1988 Log.i(TAG, "Applications installed for system user: " + enableApps); 1989 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1990 UserHandle.SYSTEM); 1991 final int allAppsSize = allAps.size(); 1992 synchronized (mPackages) { 1993 for (int i = 0; i < allAppsSize; i++) { 1994 String pName = allAps.get(i); 1995 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1996 // Should not happen, but we shouldn't be failing if it does 1997 if (pkgSetting == null) { 1998 continue; 1999 } 2000 boolean install = enableApps.contains(pName); 2001 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2002 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2003 + " for system user"); 2004 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2005 } 2006 } 2007 } 2008 } 2009 2010 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2011 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2012 Context.DISPLAY_SERVICE); 2013 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2014 } 2015 2016 /** 2017 * Requests that files preopted on a secondary system partition be copied to the data partition 2018 * if possible. Note that the actual copying of the files is accomplished by init for security 2019 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2020 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2021 */ 2022 private static void requestCopyPreoptedFiles() { 2023 final int WAIT_TIME_MS = 100; 2024 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2025 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2026 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2027 // We will wait for up to 100 seconds. 2028 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2029 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2030 try { 2031 Thread.sleep(WAIT_TIME_MS); 2032 } catch (InterruptedException e) { 2033 // Do nothing 2034 } 2035 if (SystemClock.uptimeMillis() > timeEnd) { 2036 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2037 Slog.wtf(TAG, "cppreopt did not finish!"); 2038 break; 2039 } 2040 } 2041 } 2042 } 2043 2044 public PackageManagerService(Context context, Installer installer, 2045 boolean factoryTest, boolean onlyCore) { 2046 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2047 SystemClock.uptimeMillis()); 2048 2049 if (mSdkVersion <= 0) { 2050 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2051 } 2052 2053 mContext = context; 2054 mFactoryTest = factoryTest; 2055 mOnlyCore = onlyCore; 2056 mMetrics = new DisplayMetrics(); 2057 mSettings = new Settings(mPackages); 2058 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2059 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2060 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2061 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2062 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2063 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2064 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2065 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2066 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2067 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2068 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2069 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2070 2071 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2072 if (separateProcesses != null && separateProcesses.length() > 0) { 2073 if ("*".equals(separateProcesses)) { 2074 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2075 mSeparateProcesses = null; 2076 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2077 } else { 2078 mDefParseFlags = 0; 2079 mSeparateProcesses = separateProcesses.split(","); 2080 Slog.w(TAG, "Running with debug.separate_processes: " 2081 + separateProcesses); 2082 } 2083 } else { 2084 mDefParseFlags = 0; 2085 mSeparateProcesses = null; 2086 } 2087 2088 mInstaller = installer; 2089 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2090 "*dexopt*"); 2091 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2092 2093 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2094 FgThread.get().getLooper()); 2095 2096 getDefaultDisplayMetrics(context, mMetrics); 2097 2098 SystemConfig systemConfig = SystemConfig.getInstance(); 2099 mGlobalGids = systemConfig.getGlobalGids(); 2100 mSystemPermissions = systemConfig.getSystemPermissions(); 2101 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2102 2103 mProtectedPackages = new ProtectedPackages(mContext); 2104 2105 synchronized (mInstallLock) { 2106 // writer 2107 synchronized (mPackages) { 2108 mHandlerThread = new ServiceThread(TAG, 2109 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2110 mHandlerThread.start(); 2111 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2112 mProcessLoggingHandler = new ProcessLoggingHandler(); 2113 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2114 2115 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2116 2117 File dataDir = Environment.getDataDirectory(); 2118 mAppInstallDir = new File(dataDir, "app"); 2119 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2120 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2121 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2122 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2123 2124 sUserManager = new UserManagerService(context, this, mPackages); 2125 2126 // Propagate permission configuration in to package manager. 2127 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2128 = systemConfig.getPermissions(); 2129 for (int i=0; i<permConfig.size(); i++) { 2130 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2131 BasePermission bp = mSettings.mPermissions.get(perm.name); 2132 if (bp == null) { 2133 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2134 mSettings.mPermissions.put(perm.name, bp); 2135 } 2136 if (perm.gids != null) { 2137 bp.setGids(perm.gids, perm.perUser); 2138 } 2139 } 2140 2141 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2142 for (int i=0; i<libConfig.size(); i++) { 2143 mSharedLibraries.put(libConfig.keyAt(i), 2144 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2145 } 2146 2147 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2148 2149 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2150 2151 if (mFirstBoot) { 2152 requestCopyPreoptedFiles(); 2153 } 2154 2155 String customResolverActivity = Resources.getSystem().getString( 2156 R.string.config_customResolverActivity); 2157 if (TextUtils.isEmpty(customResolverActivity)) { 2158 customResolverActivity = null; 2159 } else { 2160 mCustomResolverComponentName = ComponentName.unflattenFromString( 2161 customResolverActivity); 2162 } 2163 2164 long startTime = SystemClock.uptimeMillis(); 2165 2166 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2167 startTime); 2168 2169 // Set flag to monitor and not change apk file paths when 2170 // scanning install directories. 2171 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2172 2173 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2174 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2175 2176 if (bootClassPath == null) { 2177 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2178 } 2179 2180 if (systemServerClassPath == null) { 2181 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2182 } 2183 2184 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2185 final String[] dexCodeInstructionSets = 2186 getDexCodeInstructionSets( 2187 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2188 2189 /** 2190 * Ensure all external libraries have had dexopt run on them. 2191 */ 2192 if (mSharedLibraries.size() > 0) { 2193 // NOTE: For now, we're compiling these system "shared libraries" 2194 // (and framework jars) into all available architectures. It's possible 2195 // to compile them only when we come across an app that uses them (there's 2196 // already logic for that in scanPackageLI) but that adds some complexity. 2197 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2198 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2199 final String lib = libEntry.path; 2200 if (lib == null) { 2201 continue; 2202 } 2203 2204 try { 2205 // Shared libraries do not have profiles so we perform a full 2206 // AOT compilation (if needed). 2207 int dexoptNeeded = DexFile.getDexOptNeeded( 2208 lib, dexCodeInstructionSet, 2209 getCompilerFilterForReason(REASON_SHARED_APK), 2210 false /* newProfile */); 2211 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2212 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2213 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2214 getCompilerFilterForReason(REASON_SHARED_APK), 2215 StorageManager.UUID_PRIVATE_INTERNAL, 2216 SKIP_SHARED_LIBRARY_CHECK); 2217 } 2218 } catch (FileNotFoundException e) { 2219 Slog.w(TAG, "Library not found: " + lib); 2220 } catch (IOException | InstallerException e) { 2221 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2222 + e.getMessage()); 2223 } 2224 } 2225 } 2226 } 2227 2228 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2229 2230 final VersionInfo ver = mSettings.getInternalVersion(); 2231 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2232 2233 // when upgrading from pre-M, promote system app permissions from install to runtime 2234 mPromoteSystemApps = 2235 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2236 2237 // When upgrading from pre-N, we need to handle package extraction like first boot, 2238 // as there is no profiling data available. 2239 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2240 2241 // save off the names of pre-existing system packages prior to scanning; we don't 2242 // want to automatically grant runtime permissions for new system apps 2243 if (mPromoteSystemApps) { 2244 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2245 while (pkgSettingIter.hasNext()) { 2246 PackageSetting ps = pkgSettingIter.next(); 2247 if (isSystemApp(ps)) { 2248 mExistingSystemPackages.add(ps.name); 2249 } 2250 } 2251 } 2252 2253 // Collect vendor overlay packages. 2254 // (Do this before scanning any apps.) 2255 // For security and version matching reason, only consider 2256 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2257 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2258 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2259 | PackageParser.PARSE_IS_SYSTEM 2260 | PackageParser.PARSE_IS_SYSTEM_DIR 2261 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2262 2263 // Find base frameworks (resource packages without code). 2264 scanDirTracedLI(frameworkDir, mDefParseFlags 2265 | PackageParser.PARSE_IS_SYSTEM 2266 | PackageParser.PARSE_IS_SYSTEM_DIR 2267 | PackageParser.PARSE_IS_PRIVILEGED, 2268 scanFlags | SCAN_NO_DEX, 0); 2269 2270 // Collected privileged system packages. 2271 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2272 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2273 | PackageParser.PARSE_IS_SYSTEM 2274 | PackageParser.PARSE_IS_SYSTEM_DIR 2275 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2276 2277 // Collect ordinary system packages. 2278 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2279 scanDirTracedLI(systemAppDir, mDefParseFlags 2280 | PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2282 2283 // Collect all vendor packages. 2284 File vendorAppDir = new File("/vendor/app"); 2285 try { 2286 vendorAppDir = vendorAppDir.getCanonicalFile(); 2287 } catch (IOException e) { 2288 // failed to look up canonical path, continue with original one 2289 } 2290 scanDirTracedLI(vendorAppDir, mDefParseFlags 2291 | PackageParser.PARSE_IS_SYSTEM 2292 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2293 2294 // Collect all OEM packages. 2295 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2296 scanDirTracedLI(oemAppDir, mDefParseFlags 2297 | PackageParser.PARSE_IS_SYSTEM 2298 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2299 2300 // Prune any system packages that no longer exist. 2301 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2302 if (!mOnlyCore) { 2303 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2304 while (psit.hasNext()) { 2305 PackageSetting ps = psit.next(); 2306 2307 /* 2308 * If this is not a system app, it can't be a 2309 * disable system app. 2310 */ 2311 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2312 continue; 2313 } 2314 2315 /* 2316 * If the package is scanned, it's not erased. 2317 */ 2318 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2319 if (scannedPkg != null) { 2320 /* 2321 * If the system app is both scanned and in the 2322 * disabled packages list, then it must have been 2323 * added via OTA. Remove it from the currently 2324 * scanned package so the previously user-installed 2325 * application can be scanned. 2326 */ 2327 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2328 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2329 + ps.name + "; removing system app. Last known codePath=" 2330 + ps.codePathString + ", installStatus=" + ps.installStatus 2331 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2332 + scannedPkg.mVersionCode); 2333 removePackageLI(scannedPkg, true); 2334 mExpectingBetter.put(ps.name, ps.codePath); 2335 } 2336 2337 continue; 2338 } 2339 2340 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2341 psit.remove(); 2342 logCriticalInfo(Log.WARN, "System package " + ps.name 2343 + " no longer exists; it's data will be wiped"); 2344 // Actual deletion of code and data will be handled by later 2345 // reconciliation step 2346 } else { 2347 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2348 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2349 possiblyDeletedUpdatedSystemApps.add(ps.name); 2350 } 2351 } 2352 } 2353 } 2354 2355 //look for any incomplete package installations 2356 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2357 for (int i = 0; i < deletePkgsList.size(); i++) { 2358 // Actual deletion of code and data will be handled by later 2359 // reconciliation step 2360 final String packageName = deletePkgsList.get(i).name; 2361 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2362 synchronized (mPackages) { 2363 mSettings.removePackageLPw(packageName); 2364 } 2365 } 2366 2367 //delete tmp files 2368 deleteTempPackageFiles(); 2369 2370 // Remove any shared userIDs that have no associated packages 2371 mSettings.pruneSharedUsersLPw(); 2372 2373 if (!mOnlyCore) { 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2375 SystemClock.uptimeMillis()); 2376 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2377 2378 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2379 | PackageParser.PARSE_FORWARD_LOCK, 2380 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2381 2382 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2383 | PackageParser.PARSE_IS_EPHEMERAL, 2384 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2385 2386 /** 2387 * Remove disable package settings for any updated system 2388 * apps that were removed via an OTA. If they're not a 2389 * previously-updated app, remove them completely. 2390 * Otherwise, just revoke their system-level permissions. 2391 */ 2392 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2393 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2394 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2395 2396 String msg; 2397 if (deletedPkg == null) { 2398 msg = "Updated system package " + deletedAppName 2399 + " no longer exists; it's data will be wiped"; 2400 // Actual deletion of code and data will be handled by later 2401 // reconciliation step 2402 } else { 2403 msg = "Updated system app + " + deletedAppName 2404 + " no longer present; removing system privileges for " 2405 + deletedAppName; 2406 2407 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2408 2409 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2410 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2411 } 2412 logCriticalInfo(Log.WARN, msg); 2413 } 2414 2415 /** 2416 * Make sure all system apps that we expected to appear on 2417 * the userdata partition actually showed up. If they never 2418 * appeared, crawl back and revive the system version. 2419 */ 2420 for (int i = 0; i < mExpectingBetter.size(); i++) { 2421 final String packageName = mExpectingBetter.keyAt(i); 2422 if (!mPackages.containsKey(packageName)) { 2423 final File scanFile = mExpectingBetter.valueAt(i); 2424 2425 logCriticalInfo(Log.WARN, "Expected better " + packageName 2426 + " but never showed up; reverting to system"); 2427 2428 int reparseFlags = mDefParseFlags; 2429 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2430 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2431 | PackageParser.PARSE_IS_SYSTEM_DIR 2432 | PackageParser.PARSE_IS_PRIVILEGED; 2433 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2434 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2435 | PackageParser.PARSE_IS_SYSTEM_DIR; 2436 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2437 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR; 2439 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2440 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR; 2442 } else { 2443 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2444 continue; 2445 } 2446 2447 mSettings.enableSystemPackageLPw(packageName); 2448 2449 try { 2450 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2451 } catch (PackageManagerException e) { 2452 Slog.e(TAG, "Failed to parse original system package: " 2453 + e.getMessage()); 2454 } 2455 } 2456 } 2457 } 2458 mExpectingBetter.clear(); 2459 2460 // Resolve protected action filters. Only the setup wizard is allowed to 2461 // have a high priority filter for these actions. 2462 mSetupWizardPackage = getSetupWizardPackageName(); 2463 if (mProtectedFilters.size() > 0) { 2464 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2465 Slog.i(TAG, "No setup wizard;" 2466 + " All protected intents capped to priority 0"); 2467 } 2468 for (ActivityIntentInfo filter : mProtectedFilters) { 2469 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2470 if (DEBUG_FILTERS) { 2471 Slog.i(TAG, "Found setup wizard;" 2472 + " allow priority " + filter.getPriority() + ";" 2473 + " package: " + filter.activity.info.packageName 2474 + " activity: " + filter.activity.className 2475 + " priority: " + filter.getPriority()); 2476 } 2477 // skip setup wizard; allow it to keep the high priority filter 2478 continue; 2479 } 2480 Slog.w(TAG, "Protected action; cap priority to 0;" 2481 + " package: " + filter.activity.info.packageName 2482 + " activity: " + filter.activity.className 2483 + " origPrio: " + filter.getPriority()); 2484 filter.setPriority(0); 2485 } 2486 } 2487 mDeferProtectedFilters = false; 2488 mProtectedFilters.clear(); 2489 2490 // Now that we know all of the shared libraries, update all clients to have 2491 // the correct library paths. 2492 updateAllSharedLibrariesLPw(); 2493 2494 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2495 // NOTE: We ignore potential failures here during a system scan (like 2496 // the rest of the commands above) because there's precious little we 2497 // can do about it. A settings error is reported, though. 2498 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2499 false /* boot complete */); 2500 } 2501 2502 // Now that we know all the packages we are keeping, 2503 // read and update their last usage times. 2504 mPackageUsage.read(mPackages); 2505 mCompilerStats.read(); 2506 2507 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2508 SystemClock.uptimeMillis()); 2509 Slog.i(TAG, "Time to scan packages: " 2510 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2511 + " seconds"); 2512 2513 // If the platform SDK has changed since the last time we booted, 2514 // we need to re-grant app permission to catch any new ones that 2515 // appear. This is really a hack, and means that apps can in some 2516 // cases get permissions that the user didn't initially explicitly 2517 // allow... it would be nice to have some better way to handle 2518 // this situation. 2519 int updateFlags = UPDATE_PERMISSIONS_ALL; 2520 if (ver.sdkVersion != mSdkVersion) { 2521 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2522 + mSdkVersion + "; regranting permissions for internal storage"); 2523 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2524 } 2525 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2526 ver.sdkVersion = mSdkVersion; 2527 2528 // If this is the first boot or an update from pre-M, and it is a normal 2529 // boot, then we need to initialize the default preferred apps across 2530 // all defined users. 2531 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2532 for (UserInfo user : sUserManager.getUsers(true)) { 2533 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2534 applyFactoryDefaultBrowserLPw(user.id); 2535 primeDomainVerificationsLPw(user.id); 2536 } 2537 } 2538 2539 // Prepare storage for system user really early during boot, 2540 // since core system apps like SettingsProvider and SystemUI 2541 // can't wait for user to start 2542 final int storageFlags; 2543 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2544 storageFlags = StorageManager.FLAG_STORAGE_DE; 2545 } else { 2546 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2547 } 2548 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2549 storageFlags); 2550 2551 // If this is first boot after an OTA, and a normal boot, then 2552 // we need to clear code cache directories. 2553 // Note that we do *not* clear the application profiles. These remain valid 2554 // across OTAs and are used to drive profile verification (post OTA) and 2555 // profile compilation (without waiting to collect a fresh set of profiles). 2556 if (mIsUpgrade && !onlyCore) { 2557 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2558 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2559 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2560 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2561 // No apps are running this early, so no need to freeze 2562 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2563 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2564 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2565 } 2566 } 2567 ver.fingerprint = Build.FINGERPRINT; 2568 } 2569 2570 checkDefaultBrowser(); 2571 2572 // clear only after permissions and other defaults have been updated 2573 mExistingSystemPackages.clear(); 2574 mPromoteSystemApps = false; 2575 2576 // All the changes are done during package scanning. 2577 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2578 2579 // can downgrade to reader 2580 mSettings.writeLPr(); 2581 2582 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2583 // early on (before the package manager declares itself as early) because other 2584 // components in the system server might ask for package contexts for these apps. 2585 // 2586 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2587 // (i.e, that the data partition is unavailable). 2588 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2589 long start = System.nanoTime(); 2590 List<PackageParser.Package> coreApps = new ArrayList<>(); 2591 for (PackageParser.Package pkg : mPackages.values()) { 2592 if (pkg.coreApp) { 2593 coreApps.add(pkg); 2594 } 2595 } 2596 2597 int[] stats = performDexOptUpgrade(coreApps, false, 2598 getCompilerFilterForReason(REASON_CORE_APP)); 2599 2600 final int elapsedTimeSeconds = 2601 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2602 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2603 2604 if (DEBUG_DEXOPT) { 2605 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2606 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2607 } 2608 2609 2610 // TODO: Should we log these stats to tron too ? 2611 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2612 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2613 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2614 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2615 } 2616 2617 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2618 SystemClock.uptimeMillis()); 2619 2620 if (!mOnlyCore) { 2621 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2622 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2623 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2624 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2625 mIntentFilterVerifierComponent); 2626 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2627 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2628 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2629 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2630 } else { 2631 mRequiredVerifierPackage = null; 2632 mRequiredInstallerPackage = null; 2633 mIntentFilterVerifierComponent = null; 2634 mIntentFilterVerifier = null; 2635 mServicesSystemSharedLibraryPackageName = null; 2636 mSharedSystemSharedLibraryPackageName = null; 2637 } 2638 2639 mInstallerService = new PackageInstallerService(context, this); 2640 2641 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2642 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2643 // both the installer and resolver must be present to enable ephemeral 2644 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2645 if (DEBUG_EPHEMERAL) { 2646 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2647 + " installer:" + ephemeralInstallerComponent); 2648 } 2649 mEphemeralResolverComponent = ephemeralResolverComponent; 2650 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2651 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2652 mEphemeralResolverConnection = 2653 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2654 } else { 2655 if (DEBUG_EPHEMERAL) { 2656 final String missingComponent = 2657 (ephemeralResolverComponent == null) 2658 ? (ephemeralInstallerComponent == null) 2659 ? "resolver and installer" 2660 : "resolver" 2661 : "installer"; 2662 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2663 } 2664 mEphemeralResolverComponent = null; 2665 mEphemeralInstallerComponent = null; 2666 mEphemeralResolverConnection = null; 2667 } 2668 2669 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2670 } // synchronized (mPackages) 2671 } // synchronized (mInstallLock) 2672 2673 // Now after opening every single application zip, make sure they 2674 // are all flushed. Not really needed, but keeps things nice and 2675 // tidy. 2676 Runtime.getRuntime().gc(); 2677 2678 // The initial scanning above does many calls into installd while 2679 // holding the mPackages lock, but we're mostly interested in yelling 2680 // once we have a booted system. 2681 mInstaller.setWarnIfHeld(mPackages); 2682 2683 // Expose private service for system components to use. 2684 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2685 } 2686 2687 @Override 2688 public boolean isFirstBoot() { 2689 return mFirstBoot; 2690 } 2691 2692 @Override 2693 public boolean isOnlyCoreApps() { 2694 return mOnlyCore; 2695 } 2696 2697 @Override 2698 public boolean isUpgrade() { 2699 return mIsUpgrade; 2700 } 2701 2702 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2703 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2704 2705 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2706 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2707 UserHandle.USER_SYSTEM); 2708 if (matches.size() == 1) { 2709 return matches.get(0).getComponentInfo().packageName; 2710 } else { 2711 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2712 return null; 2713 } 2714 } 2715 2716 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2717 synchronized (mPackages) { 2718 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2719 if (libraryEntry == null) { 2720 throw new IllegalStateException("Missing required shared library:" + libraryName); 2721 } 2722 return libraryEntry.apk; 2723 } 2724 } 2725 2726 private @NonNull String getRequiredInstallerLPr() { 2727 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2728 intent.addCategory(Intent.CATEGORY_DEFAULT); 2729 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2730 2731 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2732 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2733 UserHandle.USER_SYSTEM); 2734 if (matches.size() == 1) { 2735 ResolveInfo resolveInfo = matches.get(0); 2736 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2737 throw new RuntimeException("The installer must be a privileged app"); 2738 } 2739 return matches.get(0).getComponentInfo().packageName; 2740 } else { 2741 throw new RuntimeException("There must be exactly one installer; found " + matches); 2742 } 2743 } 2744 2745 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2746 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2747 2748 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2749 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2750 UserHandle.USER_SYSTEM); 2751 ResolveInfo best = null; 2752 final int N = matches.size(); 2753 for (int i = 0; i < N; i++) { 2754 final ResolveInfo cur = matches.get(i); 2755 final String packageName = cur.getComponentInfo().packageName; 2756 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2757 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2758 continue; 2759 } 2760 2761 if (best == null || cur.priority > best.priority) { 2762 best = cur; 2763 } 2764 } 2765 2766 if (best != null) { 2767 return best.getComponentInfo().getComponentName(); 2768 } else { 2769 throw new RuntimeException("There must be at least one intent filter verifier"); 2770 } 2771 } 2772 2773 private @Nullable ComponentName getEphemeralResolverLPr() { 2774 final String[] packageArray = 2775 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2776 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2777 if (DEBUG_EPHEMERAL) { 2778 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2779 } 2780 return null; 2781 } 2782 2783 final int resolveFlags = 2784 MATCH_DIRECT_BOOT_AWARE 2785 | MATCH_DIRECT_BOOT_UNAWARE 2786 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2787 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2788 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2789 resolveFlags, UserHandle.USER_SYSTEM); 2790 2791 final int N = resolvers.size(); 2792 if (N == 0) { 2793 if (DEBUG_EPHEMERAL) { 2794 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2795 } 2796 return null; 2797 } 2798 2799 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2800 for (int i = 0; i < N; i++) { 2801 final ResolveInfo info = resolvers.get(i); 2802 2803 if (info.serviceInfo == null) { 2804 continue; 2805 } 2806 2807 final String packageName = info.serviceInfo.packageName; 2808 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2809 if (DEBUG_EPHEMERAL) { 2810 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2811 + " pkg: " + packageName + ", info:" + info); 2812 } 2813 continue; 2814 } 2815 2816 if (DEBUG_EPHEMERAL) { 2817 Slog.v(TAG, "Ephemeral resolver found;" 2818 + " pkg: " + packageName + ", info:" + info); 2819 } 2820 return new ComponentName(packageName, info.serviceInfo.name); 2821 } 2822 if (DEBUG_EPHEMERAL) { 2823 Slog.v(TAG, "Ephemeral resolver NOT found"); 2824 } 2825 return null; 2826 } 2827 2828 private @Nullable ComponentName getEphemeralInstallerLPr() { 2829 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2830 intent.addCategory(Intent.CATEGORY_DEFAULT); 2831 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2832 2833 final int resolveFlags = 2834 MATCH_DIRECT_BOOT_AWARE 2835 | MATCH_DIRECT_BOOT_UNAWARE 2836 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2837 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2838 resolveFlags, UserHandle.USER_SYSTEM); 2839 if (matches.size() == 0) { 2840 return null; 2841 } else if (matches.size() == 1) { 2842 return matches.get(0).getComponentInfo().getComponentName(); 2843 } else { 2844 throw new RuntimeException( 2845 "There must be at most one ephemeral installer; found " + matches); 2846 } 2847 } 2848 2849 private void primeDomainVerificationsLPw(int userId) { 2850 if (DEBUG_DOMAIN_VERIFICATION) { 2851 Slog.d(TAG, "Priming domain verifications in user " + userId); 2852 } 2853 2854 SystemConfig systemConfig = SystemConfig.getInstance(); 2855 ArraySet<String> packages = systemConfig.getLinkedApps(); 2856 ArraySet<String> domains = new ArraySet<String>(); 2857 2858 for (String packageName : packages) { 2859 PackageParser.Package pkg = mPackages.get(packageName); 2860 if (pkg != null) { 2861 if (!pkg.isSystemApp()) { 2862 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2863 continue; 2864 } 2865 2866 domains.clear(); 2867 for (PackageParser.Activity a : pkg.activities) { 2868 for (ActivityIntentInfo filter : a.intents) { 2869 if (hasValidDomains(filter)) { 2870 domains.addAll(filter.getHostsList()); 2871 } 2872 } 2873 } 2874 2875 if (domains.size() > 0) { 2876 if (DEBUG_DOMAIN_VERIFICATION) { 2877 Slog.v(TAG, " + " + packageName); 2878 } 2879 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2880 // state w.r.t. the formal app-linkage "no verification attempted" state; 2881 // and then 'always' in the per-user state actually used for intent resolution. 2882 final IntentFilterVerificationInfo ivi; 2883 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2884 new ArrayList<String>(domains)); 2885 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2886 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2887 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2888 } else { 2889 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2890 + "' does not handle web links"); 2891 } 2892 } else { 2893 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2894 } 2895 } 2896 2897 scheduleWritePackageRestrictionsLocked(userId); 2898 scheduleWriteSettingsLocked(); 2899 } 2900 2901 private void applyFactoryDefaultBrowserLPw(int userId) { 2902 // The default browser app's package name is stored in a string resource, 2903 // with a product-specific overlay used for vendor customization. 2904 String browserPkg = mContext.getResources().getString( 2905 com.android.internal.R.string.default_browser); 2906 if (!TextUtils.isEmpty(browserPkg)) { 2907 // non-empty string => required to be a known package 2908 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2909 if (ps == null) { 2910 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2911 browserPkg = null; 2912 } else { 2913 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2914 } 2915 } 2916 2917 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2918 // default. If there's more than one, just leave everything alone. 2919 if (browserPkg == null) { 2920 calculateDefaultBrowserLPw(userId); 2921 } 2922 } 2923 2924 private void calculateDefaultBrowserLPw(int userId) { 2925 List<String> allBrowsers = resolveAllBrowserApps(userId); 2926 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2927 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2928 } 2929 2930 private List<String> resolveAllBrowserApps(int userId) { 2931 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2932 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2933 PackageManager.MATCH_ALL, userId); 2934 2935 final int count = list.size(); 2936 List<String> result = new ArrayList<String>(count); 2937 for (int i=0; i<count; i++) { 2938 ResolveInfo info = list.get(i); 2939 if (info.activityInfo == null 2940 || !info.handleAllWebDataURI 2941 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2942 || result.contains(info.activityInfo.packageName)) { 2943 continue; 2944 } 2945 result.add(info.activityInfo.packageName); 2946 } 2947 2948 return result; 2949 } 2950 2951 private boolean packageIsBrowser(String packageName, int userId) { 2952 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2953 PackageManager.MATCH_ALL, userId); 2954 final int N = list.size(); 2955 for (int i = 0; i < N; i++) { 2956 ResolveInfo info = list.get(i); 2957 if (packageName.equals(info.activityInfo.packageName)) { 2958 return true; 2959 } 2960 } 2961 return false; 2962 } 2963 2964 private void checkDefaultBrowser() { 2965 final int myUserId = UserHandle.myUserId(); 2966 final String packageName = getDefaultBrowserPackageName(myUserId); 2967 if (packageName != null) { 2968 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2969 if (info == null) { 2970 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2971 synchronized (mPackages) { 2972 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2973 } 2974 } 2975 } 2976 } 2977 2978 @Override 2979 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2980 throws RemoteException { 2981 try { 2982 return super.onTransact(code, data, reply, flags); 2983 } catch (RuntimeException e) { 2984 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2985 Slog.wtf(TAG, "Package Manager Crash", e); 2986 } 2987 throw e; 2988 } 2989 } 2990 2991 static int[] appendInts(int[] cur, int[] add) { 2992 if (add == null) return cur; 2993 if (cur == null) return add; 2994 final int N = add.length; 2995 for (int i=0; i<N; i++) { 2996 cur = appendInt(cur, add[i]); 2997 } 2998 return cur; 2999 } 3000 3001 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3002 if (!sUserManager.exists(userId)) return null; 3003 if (ps == null) { 3004 return null; 3005 } 3006 final PackageParser.Package p = ps.pkg; 3007 if (p == null) { 3008 return null; 3009 } 3010 3011 final PermissionsState permissionsState = ps.getPermissionsState(); 3012 3013 // Compute GIDs only if requested 3014 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3015 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3016 // Compute granted permissions only if package has requested permissions 3017 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3018 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3019 final PackageUserState state = ps.readUserState(userId); 3020 3021 return PackageParser.generatePackageInfo(p, gids, flags, 3022 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3023 } 3024 3025 @Override 3026 public void checkPackageStartable(String packageName, int userId) { 3027 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3028 3029 synchronized (mPackages) { 3030 final PackageSetting ps = mSettings.mPackages.get(packageName); 3031 if (ps == null) { 3032 throw new SecurityException("Package " + packageName + " was not found!"); 3033 } 3034 3035 if (!ps.getInstalled(userId)) { 3036 throw new SecurityException( 3037 "Package " + packageName + " was not installed for user " + userId + "!"); 3038 } 3039 3040 if (mSafeMode && !ps.isSystem()) { 3041 throw new SecurityException("Package " + packageName + " not a system app!"); 3042 } 3043 3044 if (mFrozenPackages.contains(packageName)) { 3045 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3046 } 3047 3048 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3049 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3050 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3051 } 3052 } 3053 } 3054 3055 @Override 3056 public boolean isPackageAvailable(String packageName, int userId) { 3057 if (!sUserManager.exists(userId)) return false; 3058 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3059 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3060 synchronized (mPackages) { 3061 PackageParser.Package p = mPackages.get(packageName); 3062 if (p != null) { 3063 final PackageSetting ps = (PackageSetting) p.mExtras; 3064 if (ps != null) { 3065 final PackageUserState state = ps.readUserState(userId); 3066 if (state != null) { 3067 return PackageParser.isAvailable(state); 3068 } 3069 } 3070 } 3071 } 3072 return false; 3073 } 3074 3075 @Override 3076 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3077 if (!sUserManager.exists(userId)) return null; 3078 flags = updateFlagsForPackage(flags, userId, packageName); 3079 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3080 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3081 // reader 3082 synchronized (mPackages) { 3083 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3084 PackageParser.Package p = null; 3085 if (matchFactoryOnly) { 3086 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3087 if (ps != null) { 3088 return generatePackageInfo(ps, flags, userId); 3089 } 3090 } 3091 if (p == null) { 3092 p = mPackages.get(packageName); 3093 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3094 return null; 3095 } 3096 } 3097 if (DEBUG_PACKAGE_INFO) 3098 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3099 if (p != null) { 3100 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3101 } 3102 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3103 final PackageSetting ps = mSettings.mPackages.get(packageName); 3104 return generatePackageInfo(ps, flags, userId); 3105 } 3106 } 3107 return null; 3108 } 3109 3110 @Override 3111 public String[] currentToCanonicalPackageNames(String[] names) { 3112 String[] out = new String[names.length]; 3113 // reader 3114 synchronized (mPackages) { 3115 for (int i=names.length-1; i>=0; i--) { 3116 PackageSetting ps = mSettings.mPackages.get(names[i]); 3117 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3118 } 3119 } 3120 return out; 3121 } 3122 3123 @Override 3124 public String[] canonicalToCurrentPackageNames(String[] names) { 3125 String[] out = new String[names.length]; 3126 // reader 3127 synchronized (mPackages) { 3128 for (int i=names.length-1; i>=0; i--) { 3129 String cur = mSettings.mRenamedPackages.get(names[i]); 3130 out[i] = cur != null ? cur : names[i]; 3131 } 3132 } 3133 return out; 3134 } 3135 3136 @Override 3137 public int getPackageUid(String packageName, int flags, int userId) { 3138 if (!sUserManager.exists(userId)) return -1; 3139 flags = updateFlagsForPackage(flags, userId, packageName); 3140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3141 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3142 3143 // reader 3144 synchronized (mPackages) { 3145 final PackageParser.Package p = mPackages.get(packageName); 3146 if (p != null && p.isMatch(flags)) { 3147 return UserHandle.getUid(userId, p.applicationInfo.uid); 3148 } 3149 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3150 final PackageSetting ps = mSettings.mPackages.get(packageName); 3151 if (ps != null && ps.isMatch(flags)) { 3152 return UserHandle.getUid(userId, ps.appId); 3153 } 3154 } 3155 } 3156 3157 return -1; 3158 } 3159 3160 @Override 3161 public int[] getPackageGids(String packageName, int flags, int userId) { 3162 if (!sUserManager.exists(userId)) return null; 3163 flags = updateFlagsForPackage(flags, userId, packageName); 3164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3165 false /* requireFullPermission */, false /* checkShell */, 3166 "getPackageGids"); 3167 3168 // reader 3169 synchronized (mPackages) { 3170 final PackageParser.Package p = mPackages.get(packageName); 3171 if (p != null && p.isMatch(flags)) { 3172 PackageSetting ps = (PackageSetting) p.mExtras; 3173 return ps.getPermissionsState().computeGids(userId); 3174 } 3175 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3176 final PackageSetting ps = mSettings.mPackages.get(packageName); 3177 if (ps != null && ps.isMatch(flags)) { 3178 return ps.getPermissionsState().computeGids(userId); 3179 } 3180 } 3181 } 3182 3183 return null; 3184 } 3185 3186 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3187 if (bp.perm != null) { 3188 return PackageParser.generatePermissionInfo(bp.perm, flags); 3189 } 3190 PermissionInfo pi = new PermissionInfo(); 3191 pi.name = bp.name; 3192 pi.packageName = bp.sourcePackage; 3193 pi.nonLocalizedLabel = bp.name; 3194 pi.protectionLevel = bp.protectionLevel; 3195 return pi; 3196 } 3197 3198 @Override 3199 public PermissionInfo getPermissionInfo(String name, int flags) { 3200 // reader 3201 synchronized (mPackages) { 3202 final BasePermission p = mSettings.mPermissions.get(name); 3203 if (p != null) { 3204 return generatePermissionInfo(p, flags); 3205 } 3206 return null; 3207 } 3208 } 3209 3210 @Override 3211 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3212 int flags) { 3213 // reader 3214 synchronized (mPackages) { 3215 if (group != null && !mPermissionGroups.containsKey(group)) { 3216 // This is thrown as NameNotFoundException 3217 return null; 3218 } 3219 3220 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3221 for (BasePermission p : mSettings.mPermissions.values()) { 3222 if (group == null) { 3223 if (p.perm == null || p.perm.info.group == null) { 3224 out.add(generatePermissionInfo(p, flags)); 3225 } 3226 } else { 3227 if (p.perm != null && group.equals(p.perm.info.group)) { 3228 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3229 } 3230 } 3231 } 3232 return new ParceledListSlice<>(out); 3233 } 3234 } 3235 3236 @Override 3237 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3238 // reader 3239 synchronized (mPackages) { 3240 return PackageParser.generatePermissionGroupInfo( 3241 mPermissionGroups.get(name), flags); 3242 } 3243 } 3244 3245 @Override 3246 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3247 // reader 3248 synchronized (mPackages) { 3249 final int N = mPermissionGroups.size(); 3250 ArrayList<PermissionGroupInfo> out 3251 = new ArrayList<PermissionGroupInfo>(N); 3252 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3253 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3254 } 3255 return new ParceledListSlice<>(out); 3256 } 3257 } 3258 3259 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3260 int userId) { 3261 if (!sUserManager.exists(userId)) return null; 3262 PackageSetting ps = mSettings.mPackages.get(packageName); 3263 if (ps != null) { 3264 if (ps.pkg == null) { 3265 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3266 if (pInfo != null) { 3267 return pInfo.applicationInfo; 3268 } 3269 return null; 3270 } 3271 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3272 ps.readUserState(userId), userId); 3273 } 3274 return null; 3275 } 3276 3277 @Override 3278 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForApplication(flags, userId, packageName); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3282 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3283 // writer 3284 synchronized (mPackages) { 3285 PackageParser.Package p = mPackages.get(packageName); 3286 if (DEBUG_PACKAGE_INFO) Log.v( 3287 TAG, "getApplicationInfo " + packageName 3288 + ": " + p); 3289 if (p != null) { 3290 PackageSetting ps = mSettings.mPackages.get(packageName); 3291 if (ps == null) return null; 3292 // Note: isEnabledLP() does not apply here - always return info 3293 return PackageParser.generateApplicationInfo( 3294 p, flags, ps.readUserState(userId), userId); 3295 } 3296 if ("android".equals(packageName)||"system".equals(packageName)) { 3297 return mAndroidApplication; 3298 } 3299 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3300 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3301 } 3302 } 3303 return null; 3304 } 3305 3306 @Override 3307 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3308 final IPackageDataObserver observer) { 3309 mContext.enforceCallingOrSelfPermission( 3310 android.Manifest.permission.CLEAR_APP_CACHE, null); 3311 // Queue up an async operation since clearing cache may take a little while. 3312 mHandler.post(new Runnable() { 3313 public void run() { 3314 mHandler.removeCallbacks(this); 3315 boolean success = true; 3316 synchronized (mInstallLock) { 3317 try { 3318 mInstaller.freeCache(volumeUuid, freeStorageSize); 3319 } catch (InstallerException e) { 3320 Slog.w(TAG, "Couldn't clear application caches: " + e); 3321 success = false; 3322 } 3323 } 3324 if (observer != null) { 3325 try { 3326 observer.onRemoveCompleted(null, success); 3327 } catch (RemoteException e) { 3328 Slog.w(TAG, "RemoveException when invoking call back"); 3329 } 3330 } 3331 } 3332 }); 3333 } 3334 3335 @Override 3336 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3337 final IntentSender pi) { 3338 mContext.enforceCallingOrSelfPermission( 3339 android.Manifest.permission.CLEAR_APP_CACHE, null); 3340 // Queue up an async operation since clearing cache may take a little while. 3341 mHandler.post(new Runnable() { 3342 public void run() { 3343 mHandler.removeCallbacks(this); 3344 boolean success = true; 3345 synchronized (mInstallLock) { 3346 try { 3347 mInstaller.freeCache(volumeUuid, freeStorageSize); 3348 } catch (InstallerException e) { 3349 Slog.w(TAG, "Couldn't clear application caches: " + e); 3350 success = false; 3351 } 3352 } 3353 if(pi != null) { 3354 try { 3355 // Callback via pending intent 3356 int code = success ? 1 : 0; 3357 pi.sendIntent(null, code, null, 3358 null, null); 3359 } catch (SendIntentException e1) { 3360 Slog.i(TAG, "Failed to send pending intent"); 3361 } 3362 } 3363 } 3364 }); 3365 } 3366 3367 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3368 synchronized (mInstallLock) { 3369 try { 3370 mInstaller.freeCache(volumeUuid, freeStorageSize); 3371 } catch (InstallerException e) { 3372 throw new IOException("Failed to free enough space", e); 3373 } 3374 } 3375 } 3376 3377 /** 3378 * Update given flags based on encryption status of current user. 3379 */ 3380 private int updateFlags(int flags, int userId) { 3381 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3382 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3383 // Caller expressed an explicit opinion about what encryption 3384 // aware/unaware components they want to see, so fall through and 3385 // give them what they want 3386 } else { 3387 // Caller expressed no opinion, so match based on user state 3388 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3389 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3390 } else { 3391 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3392 } 3393 } 3394 return flags; 3395 } 3396 3397 private UserManagerInternal getUserManagerInternal() { 3398 if (mUserManagerInternal == null) { 3399 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3400 } 3401 return mUserManagerInternal; 3402 } 3403 3404 /** 3405 * Update given flags when being used to request {@link PackageInfo}. 3406 */ 3407 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3408 boolean triaged = true; 3409 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3410 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3411 // Caller is asking for component details, so they'd better be 3412 // asking for specific encryption matching behavior, or be triaged 3413 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3414 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3415 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3416 triaged = false; 3417 } 3418 } 3419 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3420 | PackageManager.MATCH_SYSTEM_ONLY 3421 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3422 triaged = false; 3423 } 3424 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3425 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3426 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3427 } 3428 return updateFlags(flags, userId); 3429 } 3430 3431 /** 3432 * Update given flags when being used to request {@link ApplicationInfo}. 3433 */ 3434 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3435 return updateFlagsForPackage(flags, userId, cookie); 3436 } 3437 3438 /** 3439 * Update given flags when being used to request {@link ComponentInfo}. 3440 */ 3441 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3442 if (cookie instanceof Intent) { 3443 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3444 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3445 } 3446 } 3447 3448 boolean triaged = true; 3449 // Caller is asking for component details, so they'd better be 3450 // asking for specific encryption matching behavior, or be triaged 3451 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3452 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3453 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3454 triaged = false; 3455 } 3456 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3457 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3458 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3459 } 3460 3461 return updateFlags(flags, userId); 3462 } 3463 3464 /** 3465 * Update given flags when being used to request {@link ResolveInfo}. 3466 */ 3467 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3468 // Safe mode means we shouldn't match any third-party components 3469 if (mSafeMode) { 3470 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3471 } 3472 3473 return updateFlagsForComponent(flags, userId, cookie); 3474 } 3475 3476 @Override 3477 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3478 if (!sUserManager.exists(userId)) return null; 3479 flags = updateFlagsForComponent(flags, userId, component); 3480 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3481 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3482 synchronized (mPackages) { 3483 PackageParser.Activity a = mActivities.mActivities.get(component); 3484 3485 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3486 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3487 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3488 if (ps == null) return null; 3489 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3490 userId); 3491 } 3492 if (mResolveComponentName.equals(component)) { 3493 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3494 new PackageUserState(), userId); 3495 } 3496 } 3497 return null; 3498 } 3499 3500 @Override 3501 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3502 String resolvedType) { 3503 synchronized (mPackages) { 3504 if (component.equals(mResolveComponentName)) { 3505 // The resolver supports EVERYTHING! 3506 return true; 3507 } 3508 PackageParser.Activity a = mActivities.mActivities.get(component); 3509 if (a == null) { 3510 return false; 3511 } 3512 for (int i=0; i<a.intents.size(); i++) { 3513 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3514 intent.getData(), intent.getCategories(), TAG) >= 0) { 3515 return true; 3516 } 3517 } 3518 return false; 3519 } 3520 } 3521 3522 @Override 3523 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3524 if (!sUserManager.exists(userId)) return null; 3525 flags = updateFlagsForComponent(flags, userId, component); 3526 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3527 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3528 synchronized (mPackages) { 3529 PackageParser.Activity a = mReceivers.mActivities.get(component); 3530 if (DEBUG_PACKAGE_INFO) Log.v( 3531 TAG, "getReceiverInfo " + component + ": " + a); 3532 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3533 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3534 if (ps == null) return null; 3535 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3536 userId); 3537 } 3538 } 3539 return null; 3540 } 3541 3542 @Override 3543 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3544 if (!sUserManager.exists(userId)) return null; 3545 flags = updateFlagsForComponent(flags, userId, component); 3546 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3547 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3548 synchronized (mPackages) { 3549 PackageParser.Service s = mServices.mServices.get(component); 3550 if (DEBUG_PACKAGE_INFO) Log.v( 3551 TAG, "getServiceInfo " + component + ": " + s); 3552 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3553 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3554 if (ps == null) return null; 3555 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3556 userId); 3557 } 3558 } 3559 return null; 3560 } 3561 3562 @Override 3563 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3564 if (!sUserManager.exists(userId)) return null; 3565 flags = updateFlagsForComponent(flags, userId, component); 3566 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3567 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3568 synchronized (mPackages) { 3569 PackageParser.Provider p = mProviders.mProviders.get(component); 3570 if (DEBUG_PACKAGE_INFO) Log.v( 3571 TAG, "getProviderInfo " + component + ": " + p); 3572 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3573 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3574 if (ps == null) return null; 3575 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3576 userId); 3577 } 3578 } 3579 return null; 3580 } 3581 3582 @Override 3583 public String[] getSystemSharedLibraryNames() { 3584 Set<String> libSet; 3585 synchronized (mPackages) { 3586 libSet = mSharedLibraries.keySet(); 3587 int size = libSet.size(); 3588 if (size > 0) { 3589 String[] libs = new String[size]; 3590 libSet.toArray(libs); 3591 return libs; 3592 } 3593 } 3594 return null; 3595 } 3596 3597 @Override 3598 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3599 synchronized (mPackages) { 3600 return mServicesSystemSharedLibraryPackageName; 3601 } 3602 } 3603 3604 @Override 3605 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3606 synchronized (mPackages) { 3607 return mSharedSystemSharedLibraryPackageName; 3608 } 3609 } 3610 3611 @Override 3612 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3613 synchronized (mPackages) { 3614 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3615 3616 final FeatureInfo fi = new FeatureInfo(); 3617 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3618 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3619 res.add(fi); 3620 3621 return new ParceledListSlice<>(res); 3622 } 3623 } 3624 3625 @Override 3626 public boolean hasSystemFeature(String name, int version) { 3627 synchronized (mPackages) { 3628 final FeatureInfo feat = mAvailableFeatures.get(name); 3629 if (feat == null) { 3630 return false; 3631 } else { 3632 return feat.version >= version; 3633 } 3634 } 3635 } 3636 3637 @Override 3638 public int checkPermission(String permName, String pkgName, int userId) { 3639 if (!sUserManager.exists(userId)) { 3640 return PackageManager.PERMISSION_DENIED; 3641 } 3642 3643 synchronized (mPackages) { 3644 final PackageParser.Package p = mPackages.get(pkgName); 3645 if (p != null && p.mExtras != null) { 3646 final PackageSetting ps = (PackageSetting) p.mExtras; 3647 final PermissionsState permissionsState = ps.getPermissionsState(); 3648 if (permissionsState.hasPermission(permName, userId)) { 3649 return PackageManager.PERMISSION_GRANTED; 3650 } 3651 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3652 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3653 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3654 return PackageManager.PERMISSION_GRANTED; 3655 } 3656 } 3657 } 3658 3659 return PackageManager.PERMISSION_DENIED; 3660 } 3661 3662 @Override 3663 public int checkUidPermission(String permName, int uid) { 3664 final int userId = UserHandle.getUserId(uid); 3665 3666 if (!sUserManager.exists(userId)) { 3667 return PackageManager.PERMISSION_DENIED; 3668 } 3669 3670 synchronized (mPackages) { 3671 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3672 if (obj != null) { 3673 final SettingBase ps = (SettingBase) obj; 3674 final PermissionsState permissionsState = ps.getPermissionsState(); 3675 if (permissionsState.hasPermission(permName, userId)) { 3676 return PackageManager.PERMISSION_GRANTED; 3677 } 3678 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3679 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3680 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3681 return PackageManager.PERMISSION_GRANTED; 3682 } 3683 } else { 3684 ArraySet<String> perms = mSystemPermissions.get(uid); 3685 if (perms != null) { 3686 if (perms.contains(permName)) { 3687 return PackageManager.PERMISSION_GRANTED; 3688 } 3689 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3690 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3691 return PackageManager.PERMISSION_GRANTED; 3692 } 3693 } 3694 } 3695 } 3696 3697 return PackageManager.PERMISSION_DENIED; 3698 } 3699 3700 @Override 3701 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3702 if (UserHandle.getCallingUserId() != userId) { 3703 mContext.enforceCallingPermission( 3704 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3705 "isPermissionRevokedByPolicy for user " + userId); 3706 } 3707 3708 if (checkPermission(permission, packageName, userId) 3709 == PackageManager.PERMISSION_GRANTED) { 3710 return false; 3711 } 3712 3713 final long identity = Binder.clearCallingIdentity(); 3714 try { 3715 final int flags = getPermissionFlags(permission, packageName, userId); 3716 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3717 } finally { 3718 Binder.restoreCallingIdentity(identity); 3719 } 3720 } 3721 3722 @Override 3723 public String getPermissionControllerPackageName() { 3724 synchronized (mPackages) { 3725 return mRequiredInstallerPackage; 3726 } 3727 } 3728 3729 /** 3730 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3731 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3732 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3733 * @param message the message to log on security exception 3734 */ 3735 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3736 boolean checkShell, String message) { 3737 if (userId < 0) { 3738 throw new IllegalArgumentException("Invalid userId " + userId); 3739 } 3740 if (checkShell) { 3741 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3742 } 3743 if (userId == UserHandle.getUserId(callingUid)) return; 3744 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3745 if (requireFullPermission) { 3746 mContext.enforceCallingOrSelfPermission( 3747 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3748 } else { 3749 try { 3750 mContext.enforceCallingOrSelfPermission( 3751 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3752 } catch (SecurityException se) { 3753 mContext.enforceCallingOrSelfPermission( 3754 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3755 } 3756 } 3757 } 3758 } 3759 3760 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3761 if (callingUid == Process.SHELL_UID) { 3762 if (userHandle >= 0 3763 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3764 throw new SecurityException("Shell does not have permission to access user " 3765 + userHandle); 3766 } else if (userHandle < 0) { 3767 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3768 + Debug.getCallers(3)); 3769 } 3770 } 3771 } 3772 3773 private BasePermission findPermissionTreeLP(String permName) { 3774 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3775 if (permName.startsWith(bp.name) && 3776 permName.length() > bp.name.length() && 3777 permName.charAt(bp.name.length()) == '.') { 3778 return bp; 3779 } 3780 } 3781 return null; 3782 } 3783 3784 private BasePermission checkPermissionTreeLP(String permName) { 3785 if (permName != null) { 3786 BasePermission bp = findPermissionTreeLP(permName); 3787 if (bp != null) { 3788 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3789 return bp; 3790 } 3791 throw new SecurityException("Calling uid " 3792 + Binder.getCallingUid() 3793 + " is not allowed to add to permission tree " 3794 + bp.name + " owned by uid " + bp.uid); 3795 } 3796 } 3797 throw new SecurityException("No permission tree found for " + permName); 3798 } 3799 3800 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3801 if (s1 == null) { 3802 return s2 == null; 3803 } 3804 if (s2 == null) { 3805 return false; 3806 } 3807 if (s1.getClass() != s2.getClass()) { 3808 return false; 3809 } 3810 return s1.equals(s2); 3811 } 3812 3813 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3814 if (pi1.icon != pi2.icon) return false; 3815 if (pi1.logo != pi2.logo) return false; 3816 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3817 if (!compareStrings(pi1.name, pi2.name)) return false; 3818 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3819 // We'll take care of setting this one. 3820 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3821 // These are not currently stored in settings. 3822 //if (!compareStrings(pi1.group, pi2.group)) return false; 3823 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3824 //if (pi1.labelRes != pi2.labelRes) return false; 3825 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3826 return true; 3827 } 3828 3829 int permissionInfoFootprint(PermissionInfo info) { 3830 int size = info.name.length(); 3831 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3832 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3833 return size; 3834 } 3835 3836 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3837 int size = 0; 3838 for (BasePermission perm : mSettings.mPermissions.values()) { 3839 if (perm.uid == tree.uid) { 3840 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3841 } 3842 } 3843 return size; 3844 } 3845 3846 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3847 // We calculate the max size of permissions defined by this uid and throw 3848 // if that plus the size of 'info' would exceed our stated maximum. 3849 if (tree.uid != Process.SYSTEM_UID) { 3850 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3851 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3852 throw new SecurityException("Permission tree size cap exceeded"); 3853 } 3854 } 3855 } 3856 3857 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3858 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3859 throw new SecurityException("Label must be specified in permission"); 3860 } 3861 BasePermission tree = checkPermissionTreeLP(info.name); 3862 BasePermission bp = mSettings.mPermissions.get(info.name); 3863 boolean added = bp == null; 3864 boolean changed = true; 3865 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3866 if (added) { 3867 enforcePermissionCapLocked(info, tree); 3868 bp = new BasePermission(info.name, tree.sourcePackage, 3869 BasePermission.TYPE_DYNAMIC); 3870 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3871 throw new SecurityException( 3872 "Not allowed to modify non-dynamic permission " 3873 + info.name); 3874 } else { 3875 if (bp.protectionLevel == fixedLevel 3876 && bp.perm.owner.equals(tree.perm.owner) 3877 && bp.uid == tree.uid 3878 && comparePermissionInfos(bp.perm.info, info)) { 3879 changed = false; 3880 } 3881 } 3882 bp.protectionLevel = fixedLevel; 3883 info = new PermissionInfo(info); 3884 info.protectionLevel = fixedLevel; 3885 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3886 bp.perm.info.packageName = tree.perm.info.packageName; 3887 bp.uid = tree.uid; 3888 if (added) { 3889 mSettings.mPermissions.put(info.name, bp); 3890 } 3891 if (changed) { 3892 if (!async) { 3893 mSettings.writeLPr(); 3894 } else { 3895 scheduleWriteSettingsLocked(); 3896 } 3897 } 3898 return added; 3899 } 3900 3901 @Override 3902 public boolean addPermission(PermissionInfo info) { 3903 synchronized (mPackages) { 3904 return addPermissionLocked(info, false); 3905 } 3906 } 3907 3908 @Override 3909 public boolean addPermissionAsync(PermissionInfo info) { 3910 synchronized (mPackages) { 3911 return addPermissionLocked(info, true); 3912 } 3913 } 3914 3915 @Override 3916 public void removePermission(String name) { 3917 synchronized (mPackages) { 3918 checkPermissionTreeLP(name); 3919 BasePermission bp = mSettings.mPermissions.get(name); 3920 if (bp != null) { 3921 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3922 throw new SecurityException( 3923 "Not allowed to modify non-dynamic permission " 3924 + name); 3925 } 3926 mSettings.mPermissions.remove(name); 3927 mSettings.writeLPr(); 3928 } 3929 } 3930 } 3931 3932 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3933 BasePermission bp) { 3934 int index = pkg.requestedPermissions.indexOf(bp.name); 3935 if (index == -1) { 3936 throw new SecurityException("Package " + pkg.packageName 3937 + " has not requested permission " + bp.name); 3938 } 3939 if (!bp.isRuntime() && !bp.isDevelopment()) { 3940 throw new SecurityException("Permission " + bp.name 3941 + " is not a changeable permission type"); 3942 } 3943 } 3944 3945 @Override 3946 public void grantRuntimePermission(String packageName, String name, final int userId) { 3947 if (!sUserManager.exists(userId)) { 3948 Log.e(TAG, "No such user:" + userId); 3949 return; 3950 } 3951 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3954 "grantRuntimePermission"); 3955 3956 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3957 true /* requireFullPermission */, true /* checkShell */, 3958 "grantRuntimePermission"); 3959 3960 final int uid; 3961 final SettingBase sb; 3962 3963 synchronized (mPackages) { 3964 final PackageParser.Package pkg = mPackages.get(packageName); 3965 if (pkg == null) { 3966 throw new IllegalArgumentException("Unknown package: " + packageName); 3967 } 3968 3969 final BasePermission bp = mSettings.mPermissions.get(name); 3970 if (bp == null) { 3971 throw new IllegalArgumentException("Unknown permission: " + name); 3972 } 3973 3974 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3975 3976 // If a permission review is required for legacy apps we represent 3977 // their permissions as always granted runtime ones since we need 3978 // to keep the review required permission flag per user while an 3979 // install permission's state is shared across all users. 3980 if (Build.PERMISSIONS_REVIEW_REQUIRED 3981 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3982 && bp.isRuntime()) { 3983 return; 3984 } 3985 3986 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3987 sb = (SettingBase) pkg.mExtras; 3988 if (sb == null) { 3989 throw new IllegalArgumentException("Unknown package: " + packageName); 3990 } 3991 3992 final PermissionsState permissionsState = sb.getPermissionsState(); 3993 3994 final int flags = permissionsState.getPermissionFlags(name, userId); 3995 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3996 throw new SecurityException("Cannot grant system fixed permission " 3997 + name + " for package " + packageName); 3998 } 3999 4000 if (bp.isDevelopment()) { 4001 // Development permissions must be handled specially, since they are not 4002 // normal runtime permissions. For now they apply to all users. 4003 if (permissionsState.grantInstallPermission(bp) != 4004 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4005 scheduleWriteSettingsLocked(); 4006 } 4007 return; 4008 } 4009 4010 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4011 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4012 return; 4013 } 4014 4015 final int result = permissionsState.grantRuntimePermission(bp, userId); 4016 switch (result) { 4017 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4018 return; 4019 } 4020 4021 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4022 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4023 mHandler.post(new Runnable() { 4024 @Override 4025 public void run() { 4026 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4027 } 4028 }); 4029 } 4030 break; 4031 } 4032 4033 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4034 4035 // Not critical if that is lost - app has to request again. 4036 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4037 } 4038 4039 // Only need to do this if user is initialized. Otherwise it's a new user 4040 // and there are no processes running as the user yet and there's no need 4041 // to make an expensive call to remount processes for the changed permissions. 4042 if (READ_EXTERNAL_STORAGE.equals(name) 4043 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4044 final long token = Binder.clearCallingIdentity(); 4045 try { 4046 if (sUserManager.isInitialized(userId)) { 4047 MountServiceInternal mountServiceInternal = LocalServices.getService( 4048 MountServiceInternal.class); 4049 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4050 } 4051 } finally { 4052 Binder.restoreCallingIdentity(token); 4053 } 4054 } 4055 } 4056 4057 @Override 4058 public void revokeRuntimePermission(String packageName, String name, int userId) { 4059 if (!sUserManager.exists(userId)) { 4060 Log.e(TAG, "No such user:" + userId); 4061 return; 4062 } 4063 4064 mContext.enforceCallingOrSelfPermission( 4065 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4066 "revokeRuntimePermission"); 4067 4068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4069 true /* requireFullPermission */, true /* checkShell */, 4070 "revokeRuntimePermission"); 4071 4072 final int appId; 4073 4074 synchronized (mPackages) { 4075 final PackageParser.Package pkg = mPackages.get(packageName); 4076 if (pkg == null) { 4077 throw new IllegalArgumentException("Unknown package: " + packageName); 4078 } 4079 4080 final BasePermission bp = mSettings.mPermissions.get(name); 4081 if (bp == null) { 4082 throw new IllegalArgumentException("Unknown permission: " + name); 4083 } 4084 4085 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4086 4087 // If a permission review is required for legacy apps we represent 4088 // their permissions as always granted runtime ones since we need 4089 // to keep the review required permission flag per user while an 4090 // install permission's state is shared across all users. 4091 if (Build.PERMISSIONS_REVIEW_REQUIRED 4092 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4093 && bp.isRuntime()) { 4094 return; 4095 } 4096 4097 SettingBase sb = (SettingBase) pkg.mExtras; 4098 if (sb == null) { 4099 throw new IllegalArgumentException("Unknown package: " + packageName); 4100 } 4101 4102 final PermissionsState permissionsState = sb.getPermissionsState(); 4103 4104 final int flags = permissionsState.getPermissionFlags(name, userId); 4105 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4106 throw new SecurityException("Cannot revoke system fixed permission " 4107 + name + " for package " + packageName); 4108 } 4109 4110 if (bp.isDevelopment()) { 4111 // Development permissions must be handled specially, since they are not 4112 // normal runtime permissions. For now they apply to all users. 4113 if (permissionsState.revokeInstallPermission(bp) != 4114 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4115 scheduleWriteSettingsLocked(); 4116 } 4117 return; 4118 } 4119 4120 if (permissionsState.revokeRuntimePermission(bp, userId) == 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 return; 4123 } 4124 4125 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4126 4127 // Critical, after this call app should never have the permission. 4128 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4129 4130 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4131 } 4132 4133 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4134 } 4135 4136 @Override 4137 public void resetRuntimePermissions() { 4138 mContext.enforceCallingOrSelfPermission( 4139 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4140 "revokeRuntimePermission"); 4141 4142 int callingUid = Binder.getCallingUid(); 4143 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4144 mContext.enforceCallingOrSelfPermission( 4145 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4146 "resetRuntimePermissions"); 4147 } 4148 4149 synchronized (mPackages) { 4150 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4151 for (int userId : UserManagerService.getInstance().getUserIds()) { 4152 final int packageCount = mPackages.size(); 4153 for (int i = 0; i < packageCount; i++) { 4154 PackageParser.Package pkg = mPackages.valueAt(i); 4155 if (!(pkg.mExtras instanceof PackageSetting)) { 4156 continue; 4157 } 4158 PackageSetting ps = (PackageSetting) pkg.mExtras; 4159 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4160 } 4161 } 4162 } 4163 } 4164 4165 @Override 4166 public int getPermissionFlags(String name, String packageName, int userId) { 4167 if (!sUserManager.exists(userId)) { 4168 return 0; 4169 } 4170 4171 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4172 4173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4174 true /* requireFullPermission */, false /* checkShell */, 4175 "getPermissionFlags"); 4176 4177 synchronized (mPackages) { 4178 final PackageParser.Package pkg = mPackages.get(packageName); 4179 if (pkg == null) { 4180 return 0; 4181 } 4182 4183 final BasePermission bp = mSettings.mPermissions.get(name); 4184 if (bp == null) { 4185 return 0; 4186 } 4187 4188 SettingBase sb = (SettingBase) pkg.mExtras; 4189 if (sb == null) { 4190 return 0; 4191 } 4192 4193 PermissionsState permissionsState = sb.getPermissionsState(); 4194 return permissionsState.getPermissionFlags(name, userId); 4195 } 4196 } 4197 4198 @Override 4199 public void updatePermissionFlags(String name, String packageName, int flagMask, 4200 int flagValues, int userId) { 4201 if (!sUserManager.exists(userId)) { 4202 return; 4203 } 4204 4205 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4206 4207 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4208 true /* requireFullPermission */, true /* checkShell */, 4209 "updatePermissionFlags"); 4210 4211 // Only the system can change these flags and nothing else. 4212 if (getCallingUid() != Process.SYSTEM_UID) { 4213 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4214 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4215 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4216 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4217 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4218 } 4219 4220 synchronized (mPackages) { 4221 final PackageParser.Package pkg = mPackages.get(packageName); 4222 if (pkg == null) { 4223 throw new IllegalArgumentException("Unknown package: " + packageName); 4224 } 4225 4226 final BasePermission bp = mSettings.mPermissions.get(name); 4227 if (bp == null) { 4228 throw new IllegalArgumentException("Unknown permission: " + name); 4229 } 4230 4231 SettingBase sb = (SettingBase) pkg.mExtras; 4232 if (sb == null) { 4233 throw new IllegalArgumentException("Unknown package: " + packageName); 4234 } 4235 4236 PermissionsState permissionsState = sb.getPermissionsState(); 4237 4238 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4239 4240 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4241 // Install and runtime permissions are stored in different places, 4242 // so figure out what permission changed and persist the change. 4243 if (permissionsState.getInstallPermissionState(name) != null) { 4244 scheduleWriteSettingsLocked(); 4245 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4246 || hadState) { 4247 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4248 } 4249 } 4250 } 4251 } 4252 4253 /** 4254 * Update the permission flags for all packages and runtime permissions of a user in order 4255 * to allow device or profile owner to remove POLICY_FIXED. 4256 */ 4257 @Override 4258 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4259 if (!sUserManager.exists(userId)) { 4260 return; 4261 } 4262 4263 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4264 4265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4266 true /* requireFullPermission */, true /* checkShell */, 4267 "updatePermissionFlagsForAllApps"); 4268 4269 // Only the system can change system fixed flags. 4270 if (getCallingUid() != Process.SYSTEM_UID) { 4271 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4272 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4273 } 4274 4275 synchronized (mPackages) { 4276 boolean changed = false; 4277 final int packageCount = mPackages.size(); 4278 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4279 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4280 SettingBase sb = (SettingBase) pkg.mExtras; 4281 if (sb == null) { 4282 continue; 4283 } 4284 PermissionsState permissionsState = sb.getPermissionsState(); 4285 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4286 userId, flagMask, flagValues); 4287 } 4288 if (changed) { 4289 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4290 } 4291 } 4292 } 4293 4294 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4295 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4296 != PackageManager.PERMISSION_GRANTED 4297 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4298 != PackageManager.PERMISSION_GRANTED) { 4299 throw new SecurityException(message + " requires " 4300 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4301 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4302 } 4303 } 4304 4305 @Override 4306 public boolean shouldShowRequestPermissionRationale(String permissionName, 4307 String packageName, int userId) { 4308 if (UserHandle.getCallingUserId() != userId) { 4309 mContext.enforceCallingPermission( 4310 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4311 "canShowRequestPermissionRationale for user " + userId); 4312 } 4313 4314 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4315 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4316 return false; 4317 } 4318 4319 if (checkPermission(permissionName, packageName, userId) 4320 == PackageManager.PERMISSION_GRANTED) { 4321 return false; 4322 } 4323 4324 final int flags; 4325 4326 final long identity = Binder.clearCallingIdentity(); 4327 try { 4328 flags = getPermissionFlags(permissionName, 4329 packageName, userId); 4330 } finally { 4331 Binder.restoreCallingIdentity(identity); 4332 } 4333 4334 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4335 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4336 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4337 4338 if ((flags & fixedFlags) != 0) { 4339 return false; 4340 } 4341 4342 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4343 } 4344 4345 @Override 4346 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4347 mContext.enforceCallingOrSelfPermission( 4348 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4349 "addOnPermissionsChangeListener"); 4350 4351 synchronized (mPackages) { 4352 mOnPermissionChangeListeners.addListenerLocked(listener); 4353 } 4354 } 4355 4356 @Override 4357 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4358 synchronized (mPackages) { 4359 mOnPermissionChangeListeners.removeListenerLocked(listener); 4360 } 4361 } 4362 4363 @Override 4364 public boolean isProtectedBroadcast(String actionName) { 4365 synchronized (mPackages) { 4366 if (mProtectedBroadcasts.contains(actionName)) { 4367 return true; 4368 } else if (actionName != null) { 4369 // TODO: remove these terrible hacks 4370 if (actionName.startsWith("android.net.netmon.lingerExpired") 4371 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4372 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4373 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4374 return true; 4375 } 4376 } 4377 } 4378 return false; 4379 } 4380 4381 @Override 4382 public int checkSignatures(String pkg1, String pkg2) { 4383 synchronized (mPackages) { 4384 final PackageParser.Package p1 = mPackages.get(pkg1); 4385 final PackageParser.Package p2 = mPackages.get(pkg2); 4386 if (p1 == null || p1.mExtras == null 4387 || p2 == null || p2.mExtras == null) { 4388 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4389 } 4390 return compareSignatures(p1.mSignatures, p2.mSignatures); 4391 } 4392 } 4393 4394 @Override 4395 public int checkUidSignatures(int uid1, int uid2) { 4396 // Map to base uids. 4397 uid1 = UserHandle.getAppId(uid1); 4398 uid2 = UserHandle.getAppId(uid2); 4399 // reader 4400 synchronized (mPackages) { 4401 Signature[] s1; 4402 Signature[] s2; 4403 Object obj = mSettings.getUserIdLPr(uid1); 4404 if (obj != null) { 4405 if (obj instanceof SharedUserSetting) { 4406 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4407 } else if (obj instanceof PackageSetting) { 4408 s1 = ((PackageSetting)obj).signatures.mSignatures; 4409 } else { 4410 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4411 } 4412 } else { 4413 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4414 } 4415 obj = mSettings.getUserIdLPr(uid2); 4416 if (obj != null) { 4417 if (obj instanceof SharedUserSetting) { 4418 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4419 } else if (obj instanceof PackageSetting) { 4420 s2 = ((PackageSetting)obj).signatures.mSignatures; 4421 } else { 4422 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4423 } 4424 } else { 4425 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4426 } 4427 return compareSignatures(s1, s2); 4428 } 4429 } 4430 4431 /** 4432 * This method should typically only be used when granting or revoking 4433 * permissions, since the app may immediately restart after this call. 4434 * <p> 4435 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4436 * guard your work against the app being relaunched. 4437 */ 4438 private void killUid(int appId, int userId, String reason) { 4439 final long identity = Binder.clearCallingIdentity(); 4440 try { 4441 IActivityManager am = ActivityManagerNative.getDefault(); 4442 if (am != null) { 4443 try { 4444 am.killUid(appId, userId, reason); 4445 } catch (RemoteException e) { 4446 /* ignore - same process */ 4447 } 4448 } 4449 } finally { 4450 Binder.restoreCallingIdentity(identity); 4451 } 4452 } 4453 4454 /** 4455 * Compares two sets of signatures. Returns: 4456 * <br /> 4457 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4458 * <br /> 4459 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4460 * <br /> 4461 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4462 * <br /> 4463 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4464 * <br /> 4465 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4466 */ 4467 static int compareSignatures(Signature[] s1, Signature[] s2) { 4468 if (s1 == null) { 4469 return s2 == null 4470 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4471 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4472 } 4473 4474 if (s2 == null) { 4475 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4476 } 4477 4478 if (s1.length != s2.length) { 4479 return PackageManager.SIGNATURE_NO_MATCH; 4480 } 4481 4482 // Since both signature sets are of size 1, we can compare without HashSets. 4483 if (s1.length == 1) { 4484 return s1[0].equals(s2[0]) ? 4485 PackageManager.SIGNATURE_MATCH : 4486 PackageManager.SIGNATURE_NO_MATCH; 4487 } 4488 4489 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4490 for (Signature sig : s1) { 4491 set1.add(sig); 4492 } 4493 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4494 for (Signature sig : s2) { 4495 set2.add(sig); 4496 } 4497 // Make sure s2 contains all signatures in s1. 4498 if (set1.equals(set2)) { 4499 return PackageManager.SIGNATURE_MATCH; 4500 } 4501 return PackageManager.SIGNATURE_NO_MATCH; 4502 } 4503 4504 /** 4505 * If the database version for this type of package (internal storage or 4506 * external storage) is less than the version where package signatures 4507 * were updated, return true. 4508 */ 4509 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4510 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4511 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4512 } 4513 4514 /** 4515 * Used for backward compatibility to make sure any packages with 4516 * certificate chains get upgraded to the new style. {@code existingSigs} 4517 * will be in the old format (since they were stored on disk from before the 4518 * system upgrade) and {@code scannedSigs} will be in the newer format. 4519 */ 4520 private int compareSignaturesCompat(PackageSignatures existingSigs, 4521 PackageParser.Package scannedPkg) { 4522 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4523 return PackageManager.SIGNATURE_NO_MATCH; 4524 } 4525 4526 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4527 for (Signature sig : existingSigs.mSignatures) { 4528 existingSet.add(sig); 4529 } 4530 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4531 for (Signature sig : scannedPkg.mSignatures) { 4532 try { 4533 Signature[] chainSignatures = sig.getChainSignatures(); 4534 for (Signature chainSig : chainSignatures) { 4535 scannedCompatSet.add(chainSig); 4536 } 4537 } catch (CertificateEncodingException e) { 4538 scannedCompatSet.add(sig); 4539 } 4540 } 4541 /* 4542 * Make sure the expanded scanned set contains all signatures in the 4543 * existing one. 4544 */ 4545 if (scannedCompatSet.equals(existingSet)) { 4546 // Migrate the old signatures to the new scheme. 4547 existingSigs.assignSignatures(scannedPkg.mSignatures); 4548 // The new KeySets will be re-added later in the scanning process. 4549 synchronized (mPackages) { 4550 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4551 } 4552 return PackageManager.SIGNATURE_MATCH; 4553 } 4554 return PackageManager.SIGNATURE_NO_MATCH; 4555 } 4556 4557 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4558 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4559 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4560 } 4561 4562 private int compareSignaturesRecover(PackageSignatures existingSigs, 4563 PackageParser.Package scannedPkg) { 4564 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4565 return PackageManager.SIGNATURE_NO_MATCH; 4566 } 4567 4568 String msg = null; 4569 try { 4570 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4571 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4572 + scannedPkg.packageName); 4573 return PackageManager.SIGNATURE_MATCH; 4574 } 4575 } catch (CertificateException e) { 4576 msg = e.getMessage(); 4577 } 4578 4579 logCriticalInfo(Log.INFO, 4580 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4581 return PackageManager.SIGNATURE_NO_MATCH; 4582 } 4583 4584 @Override 4585 public List<String> getAllPackages() { 4586 synchronized (mPackages) { 4587 return new ArrayList<String>(mPackages.keySet()); 4588 } 4589 } 4590 4591 @Override 4592 public String[] getPackagesForUid(int uid) { 4593 uid = UserHandle.getAppId(uid); 4594 // reader 4595 synchronized (mPackages) { 4596 Object obj = mSettings.getUserIdLPr(uid); 4597 if (obj instanceof SharedUserSetting) { 4598 final SharedUserSetting sus = (SharedUserSetting) obj; 4599 final int N = sus.packages.size(); 4600 final String[] res = new String[N]; 4601 for (int i = 0; i < N; i++) { 4602 res[i] = sus.packages.valueAt(i).name; 4603 } 4604 return res; 4605 } else if (obj instanceof PackageSetting) { 4606 final PackageSetting ps = (PackageSetting) obj; 4607 return new String[] { ps.name }; 4608 } 4609 } 4610 return null; 4611 } 4612 4613 @Override 4614 public String getNameForUid(int uid) { 4615 // reader 4616 synchronized (mPackages) { 4617 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4618 if (obj instanceof SharedUserSetting) { 4619 final SharedUserSetting sus = (SharedUserSetting) obj; 4620 return sus.name + ":" + sus.userId; 4621 } else if (obj instanceof PackageSetting) { 4622 final PackageSetting ps = (PackageSetting) obj; 4623 return ps.name; 4624 } 4625 } 4626 return null; 4627 } 4628 4629 @Override 4630 public int getUidForSharedUser(String sharedUserName) { 4631 if(sharedUserName == null) { 4632 return -1; 4633 } 4634 // reader 4635 synchronized (mPackages) { 4636 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4637 if (suid == null) { 4638 return -1; 4639 } 4640 return suid.userId; 4641 } 4642 } 4643 4644 @Override 4645 public int getFlagsForUid(int uid) { 4646 synchronized (mPackages) { 4647 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4648 if (obj instanceof SharedUserSetting) { 4649 final SharedUserSetting sus = (SharedUserSetting) obj; 4650 return sus.pkgFlags; 4651 } else if (obj instanceof PackageSetting) { 4652 final PackageSetting ps = (PackageSetting) obj; 4653 return ps.pkgFlags; 4654 } 4655 } 4656 return 0; 4657 } 4658 4659 @Override 4660 public int getPrivateFlagsForUid(int uid) { 4661 synchronized (mPackages) { 4662 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4663 if (obj instanceof SharedUserSetting) { 4664 final SharedUserSetting sus = (SharedUserSetting) obj; 4665 return sus.pkgPrivateFlags; 4666 } else if (obj instanceof PackageSetting) { 4667 final PackageSetting ps = (PackageSetting) obj; 4668 return ps.pkgPrivateFlags; 4669 } 4670 } 4671 return 0; 4672 } 4673 4674 @Override 4675 public boolean isUidPrivileged(int uid) { 4676 uid = UserHandle.getAppId(uid); 4677 // reader 4678 synchronized (mPackages) { 4679 Object obj = mSettings.getUserIdLPr(uid); 4680 if (obj instanceof SharedUserSetting) { 4681 final SharedUserSetting sus = (SharedUserSetting) obj; 4682 final Iterator<PackageSetting> it = sus.packages.iterator(); 4683 while (it.hasNext()) { 4684 if (it.next().isPrivileged()) { 4685 return true; 4686 } 4687 } 4688 } else if (obj instanceof PackageSetting) { 4689 final PackageSetting ps = (PackageSetting) obj; 4690 return ps.isPrivileged(); 4691 } 4692 } 4693 return false; 4694 } 4695 4696 @Override 4697 public String[] getAppOpPermissionPackages(String permissionName) { 4698 synchronized (mPackages) { 4699 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4700 if (pkgs == null) { 4701 return null; 4702 } 4703 return pkgs.toArray(new String[pkgs.size()]); 4704 } 4705 } 4706 4707 @Override 4708 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4709 int flags, int userId) { 4710 try { 4711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4712 4713 if (!sUserManager.exists(userId)) return null; 4714 flags = updateFlagsForResolve(flags, userId, intent); 4715 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4716 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4717 4718 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4719 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4720 flags, userId); 4721 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4722 4723 final ResolveInfo bestChoice = 4724 chooseBestActivity(intent, resolvedType, flags, query, userId); 4725 4726 if (isEphemeralAllowed(intent, query, userId)) { 4727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4728 final EphemeralResolveInfo ai = 4729 getEphemeralResolveInfo(intent, resolvedType, userId); 4730 if (ai != null) { 4731 if (DEBUG_EPHEMERAL) { 4732 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4733 } 4734 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4735 bestChoice.ephemeralResolveInfo = ai; 4736 } 4737 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4738 } 4739 return bestChoice; 4740 } finally { 4741 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4742 } 4743 } 4744 4745 @Override 4746 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4747 IntentFilter filter, int match, ComponentName activity) { 4748 final int userId = UserHandle.getCallingUserId(); 4749 if (DEBUG_PREFERRED) { 4750 Log.v(TAG, "setLastChosenActivity intent=" + intent 4751 + " resolvedType=" + resolvedType 4752 + " flags=" + flags 4753 + " filter=" + filter 4754 + " match=" + match 4755 + " activity=" + activity); 4756 filter.dump(new PrintStreamPrinter(System.out), " "); 4757 } 4758 intent.setComponent(null); 4759 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4760 userId); 4761 // Find any earlier preferred or last chosen entries and nuke them 4762 findPreferredActivity(intent, resolvedType, 4763 flags, query, 0, false, true, false, userId); 4764 // Add the new activity as the last chosen for this filter 4765 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4766 "Setting last chosen"); 4767 } 4768 4769 @Override 4770 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4771 final int userId = UserHandle.getCallingUserId(); 4772 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4773 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4774 userId); 4775 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4776 false, false, false, userId); 4777 } 4778 4779 4780 private boolean isEphemeralAllowed( 4781 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4782 // Short circuit and return early if possible. 4783 if (DISABLE_EPHEMERAL_APPS) { 4784 return false; 4785 } 4786 final int callingUser = UserHandle.getCallingUserId(); 4787 if (callingUser != UserHandle.USER_SYSTEM) { 4788 return false; 4789 } 4790 if (mEphemeralResolverConnection == null) { 4791 return false; 4792 } 4793 if (intent.getComponent() != null) { 4794 return false; 4795 } 4796 if (intent.getPackage() != null) { 4797 return false; 4798 } 4799 final boolean isWebUri = hasWebURI(intent); 4800 if (!isWebUri) { 4801 return false; 4802 } 4803 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4804 synchronized (mPackages) { 4805 final int count = resolvedActivites.size(); 4806 for (int n = 0; n < count; n++) { 4807 ResolveInfo info = resolvedActivites.get(n); 4808 String packageName = info.activityInfo.packageName; 4809 PackageSetting ps = mSettings.mPackages.get(packageName); 4810 if (ps != null) { 4811 // Try to get the status from User settings first 4812 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4813 int status = (int) (packedStatus >> 32); 4814 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4815 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4816 if (DEBUG_EPHEMERAL) { 4817 Slog.v(TAG, "DENY ephemeral apps;" 4818 + " pkg: " + packageName + ", status: " + status); 4819 } 4820 return false; 4821 } 4822 } 4823 } 4824 } 4825 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4826 return true; 4827 } 4828 4829 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4830 int userId) { 4831 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4832 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4833 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 4834 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4835 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4836 ephemeralPrefixCount); 4837 final int[] shaPrefix = digest.getDigestPrefix(); 4838 final byte[][] digestBytes = digest.getDigestBytes(); 4839 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4840 mEphemeralResolverConnection.getEphemeralResolveInfoList( 4841 shaPrefix, ephemeralPrefixMask); 4842 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4843 // No hash prefix match; there are no ephemeral apps for this domain. 4844 return null; 4845 } 4846 4847 // Go in reverse order so we match the narrowest scope first. 4848 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4849 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4850 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4851 continue; 4852 } 4853 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4854 // No filters; this should never happen. 4855 if (filters.isEmpty()) { 4856 continue; 4857 } 4858 // We have a domain match; resolve the filters to see if anything matches. 4859 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4860 for (int j = filters.size() - 1; j >= 0; --j) { 4861 final EphemeralResolveIntentInfo intentInfo = 4862 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4863 ephemeralResolver.addFilter(intentInfo); 4864 } 4865 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4866 intent, resolvedType, false /*defaultOnly*/, userId); 4867 if (!matchedResolveInfoList.isEmpty()) { 4868 return matchedResolveInfoList.get(0); 4869 } 4870 } 4871 } 4872 // Hash or filter mis-match; no ephemeral apps for this domain. 4873 return null; 4874 } 4875 4876 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4877 int flags, List<ResolveInfo> query, int userId) { 4878 if (query != null) { 4879 final int N = query.size(); 4880 if (N == 1) { 4881 return query.get(0); 4882 } else if (N > 1) { 4883 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4884 // If there is more than one activity with the same priority, 4885 // then let the user decide between them. 4886 ResolveInfo r0 = query.get(0); 4887 ResolveInfo r1 = query.get(1); 4888 if (DEBUG_INTENT_MATCHING || debug) { 4889 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4890 + r1.activityInfo.name + "=" + r1.priority); 4891 } 4892 // If the first activity has a higher priority, or a different 4893 // default, then it is always desirable to pick it. 4894 if (r0.priority != r1.priority 4895 || r0.preferredOrder != r1.preferredOrder 4896 || r0.isDefault != r1.isDefault) { 4897 return query.get(0); 4898 } 4899 // If we have saved a preference for a preferred activity for 4900 // this Intent, use that. 4901 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4902 flags, query, r0.priority, true, false, debug, userId); 4903 if (ri != null) { 4904 return ri; 4905 } 4906 ri = new ResolveInfo(mResolveInfo); 4907 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4908 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4909 // If all of the options come from the same package, show the application's 4910 // label and icon instead of the generic resolver's. 4911 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4912 // and then throw away the ResolveInfo itself, meaning that the caller loses 4913 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4914 // a fallback for this case; we only set the target package's resources on 4915 // the ResolveInfo, not the ActivityInfo. 4916 final String intentPackage = intent.getPackage(); 4917 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4918 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4919 ri.resolvePackageName = intentPackage; 4920 if (userNeedsBadging(userId)) { 4921 ri.noResourceId = true; 4922 } else { 4923 ri.icon = appi.icon; 4924 } 4925 ri.iconResourceId = appi.icon; 4926 ri.labelRes = appi.labelRes; 4927 } 4928 ri.activityInfo.applicationInfo = new ApplicationInfo( 4929 ri.activityInfo.applicationInfo); 4930 if (userId != 0) { 4931 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4932 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4933 } 4934 // Make sure that the resolver is displayable in car mode 4935 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4936 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4937 return ri; 4938 } 4939 } 4940 return null; 4941 } 4942 4943 /** 4944 * Return true if the given list is not empty and all of its contents have 4945 * an activityInfo with the given package name. 4946 */ 4947 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4948 if (ArrayUtils.isEmpty(list)) { 4949 return false; 4950 } 4951 for (int i = 0, N = list.size(); i < N; i++) { 4952 final ResolveInfo ri = list.get(i); 4953 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4954 if (ai == null || !packageName.equals(ai.packageName)) { 4955 return false; 4956 } 4957 } 4958 return true; 4959 } 4960 4961 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4962 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4963 final int N = query.size(); 4964 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4965 .get(userId); 4966 // Get the list of persistent preferred activities that handle the intent 4967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4968 List<PersistentPreferredActivity> pprefs = ppir != null 4969 ? ppir.queryIntent(intent, resolvedType, 4970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4971 : null; 4972 if (pprefs != null && pprefs.size() > 0) { 4973 final int M = pprefs.size(); 4974 for (int i=0; i<M; i++) { 4975 final PersistentPreferredActivity ppa = pprefs.get(i); 4976 if (DEBUG_PREFERRED || debug) { 4977 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4978 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4979 + "\n component=" + ppa.mComponent); 4980 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4981 } 4982 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4983 flags | MATCH_DISABLED_COMPONENTS, userId); 4984 if (DEBUG_PREFERRED || debug) { 4985 Slog.v(TAG, "Found persistent preferred activity:"); 4986 if (ai != null) { 4987 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4988 } else { 4989 Slog.v(TAG, " null"); 4990 } 4991 } 4992 if (ai == null) { 4993 // This previously registered persistent preferred activity 4994 // component is no longer known. Ignore it and do NOT remove it. 4995 continue; 4996 } 4997 for (int j=0; j<N; j++) { 4998 final ResolveInfo ri = query.get(j); 4999 if (!ri.activityInfo.applicationInfo.packageName 5000 .equals(ai.applicationInfo.packageName)) { 5001 continue; 5002 } 5003 if (!ri.activityInfo.name.equals(ai.name)) { 5004 continue; 5005 } 5006 // Found a persistent preference that can handle the intent. 5007 if (DEBUG_PREFERRED || debug) { 5008 Slog.v(TAG, "Returning persistent preferred activity: " + 5009 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5010 } 5011 return ri; 5012 } 5013 } 5014 } 5015 return null; 5016 } 5017 5018 // TODO: handle preferred activities missing while user has amnesia 5019 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5020 List<ResolveInfo> query, int priority, boolean always, 5021 boolean removeMatches, boolean debug, int userId) { 5022 if (!sUserManager.exists(userId)) return null; 5023 flags = updateFlagsForResolve(flags, userId, intent); 5024 // writer 5025 synchronized (mPackages) { 5026 if (intent.getSelector() != null) { 5027 intent = intent.getSelector(); 5028 } 5029 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5030 5031 // Try to find a matching persistent preferred activity. 5032 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5033 debug, userId); 5034 5035 // If a persistent preferred activity matched, use it. 5036 if (pri != null) { 5037 return pri; 5038 } 5039 5040 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5041 // Get the list of preferred activities that handle the intent 5042 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5043 List<PreferredActivity> prefs = pir != null 5044 ? pir.queryIntent(intent, resolvedType, 5045 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5046 : null; 5047 if (prefs != null && prefs.size() > 0) { 5048 boolean changed = false; 5049 try { 5050 // First figure out how good the original match set is. 5051 // We will only allow preferred activities that came 5052 // from the same match quality. 5053 int match = 0; 5054 5055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5056 5057 final int N = query.size(); 5058 for (int j=0; j<N; j++) { 5059 final ResolveInfo ri = query.get(j); 5060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5061 + ": 0x" + Integer.toHexString(match)); 5062 if (ri.match > match) { 5063 match = ri.match; 5064 } 5065 } 5066 5067 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5068 + Integer.toHexString(match)); 5069 5070 match &= IntentFilter.MATCH_CATEGORY_MASK; 5071 final int M = prefs.size(); 5072 for (int i=0; i<M; i++) { 5073 final PreferredActivity pa = prefs.get(i); 5074 if (DEBUG_PREFERRED || debug) { 5075 Slog.v(TAG, "Checking PreferredActivity ds=" 5076 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5077 + "\n component=" + pa.mPref.mComponent); 5078 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5079 } 5080 if (pa.mPref.mMatch != match) { 5081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5082 + Integer.toHexString(pa.mPref.mMatch)); 5083 continue; 5084 } 5085 // If it's not an "always" type preferred activity and that's what we're 5086 // looking for, skip it. 5087 if (always && !pa.mPref.mAlways) { 5088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5089 continue; 5090 } 5091 final ActivityInfo ai = getActivityInfo( 5092 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5093 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5094 userId); 5095 if (DEBUG_PREFERRED || debug) { 5096 Slog.v(TAG, "Found preferred activity:"); 5097 if (ai != null) { 5098 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5099 } else { 5100 Slog.v(TAG, " null"); 5101 } 5102 } 5103 if (ai == null) { 5104 // This previously registered preferred activity 5105 // component is no longer known. Most likely an update 5106 // to the app was installed and in the new version this 5107 // component no longer exists. Clean it up by removing 5108 // it from the preferred activities list, and skip it. 5109 Slog.w(TAG, "Removing dangling preferred activity: " 5110 + pa.mPref.mComponent); 5111 pir.removeFilter(pa); 5112 changed = true; 5113 continue; 5114 } 5115 for (int j=0; j<N; j++) { 5116 final ResolveInfo ri = query.get(j); 5117 if (!ri.activityInfo.applicationInfo.packageName 5118 .equals(ai.applicationInfo.packageName)) { 5119 continue; 5120 } 5121 if (!ri.activityInfo.name.equals(ai.name)) { 5122 continue; 5123 } 5124 5125 if (removeMatches) { 5126 pir.removeFilter(pa); 5127 changed = true; 5128 if (DEBUG_PREFERRED) { 5129 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5130 } 5131 break; 5132 } 5133 5134 // Okay we found a previously set preferred or last chosen app. 5135 // If the result set is different from when this 5136 // was created, we need to clear it and re-ask the 5137 // user their preference, if we're looking for an "always" type entry. 5138 if (always && !pa.mPref.sameSet(query)) { 5139 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5140 + intent + " type " + resolvedType); 5141 if (DEBUG_PREFERRED) { 5142 Slog.v(TAG, "Removing preferred activity since set changed " 5143 + pa.mPref.mComponent); 5144 } 5145 pir.removeFilter(pa); 5146 // Re-add the filter as a "last chosen" entry (!always) 5147 PreferredActivity lastChosen = new PreferredActivity( 5148 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5149 pir.addFilter(lastChosen); 5150 changed = true; 5151 return null; 5152 } 5153 5154 // Yay! Either the set matched or we're looking for the last chosen 5155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5156 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5157 return ri; 5158 } 5159 } 5160 } finally { 5161 if (changed) { 5162 if (DEBUG_PREFERRED) { 5163 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5164 } 5165 scheduleWritePackageRestrictionsLocked(userId); 5166 } 5167 } 5168 } 5169 } 5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5171 return null; 5172 } 5173 5174 /* 5175 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5176 */ 5177 @Override 5178 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5179 int targetUserId) { 5180 mContext.enforceCallingOrSelfPermission( 5181 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5182 List<CrossProfileIntentFilter> matches = 5183 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5184 if (matches != null) { 5185 int size = matches.size(); 5186 for (int i = 0; i < size; i++) { 5187 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5188 } 5189 } 5190 if (hasWebURI(intent)) { 5191 // cross-profile app linking works only towards the parent. 5192 final UserInfo parent = getProfileParent(sourceUserId); 5193 synchronized(mPackages) { 5194 int flags = updateFlagsForResolve(0, parent.id, intent); 5195 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5196 intent, resolvedType, flags, sourceUserId, parent.id); 5197 return xpDomainInfo != null; 5198 } 5199 } 5200 return false; 5201 } 5202 5203 private UserInfo getProfileParent(int userId) { 5204 final long identity = Binder.clearCallingIdentity(); 5205 try { 5206 return sUserManager.getProfileParent(userId); 5207 } finally { 5208 Binder.restoreCallingIdentity(identity); 5209 } 5210 } 5211 5212 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5213 String resolvedType, int userId) { 5214 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5215 if (resolver != null) { 5216 return resolver.queryIntent(intent, resolvedType, false, userId); 5217 } 5218 return null; 5219 } 5220 5221 @Override 5222 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5223 String resolvedType, int flags, int userId) { 5224 try { 5225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5226 5227 return new ParceledListSlice<>( 5228 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5229 } finally { 5230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5231 } 5232 } 5233 5234 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5235 String resolvedType, int flags, int userId) { 5236 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5237 flags = updateFlagsForResolve(flags, userId, intent); 5238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5239 false /* requireFullPermission */, false /* checkShell */, 5240 "query intent activities"); 5241 ComponentName comp = intent.getComponent(); 5242 if (comp == null) { 5243 if (intent.getSelector() != null) { 5244 intent = intent.getSelector(); 5245 comp = intent.getComponent(); 5246 } 5247 } 5248 5249 if (comp != null) { 5250 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5251 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5252 if (ai != null) { 5253 final ResolveInfo ri = new ResolveInfo(); 5254 ri.activityInfo = ai; 5255 list.add(ri); 5256 } 5257 return list; 5258 } 5259 5260 // reader 5261 synchronized (mPackages) { 5262 final String pkgName = intent.getPackage(); 5263 if (pkgName == null) { 5264 List<CrossProfileIntentFilter> matchingFilters = 5265 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5266 // Check for results that need to skip the current profile. 5267 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5268 resolvedType, flags, userId); 5269 if (xpResolveInfo != null) { 5270 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5271 result.add(xpResolveInfo); 5272 return filterIfNotSystemUser(result, userId); 5273 } 5274 5275 // Check for results in the current profile. 5276 List<ResolveInfo> result = mActivities.queryIntent( 5277 intent, resolvedType, flags, userId); 5278 result = filterIfNotSystemUser(result, userId); 5279 5280 // Check for cross profile results. 5281 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5282 xpResolveInfo = queryCrossProfileIntents( 5283 matchingFilters, intent, resolvedType, flags, userId, 5284 hasNonNegativePriorityResult); 5285 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5286 boolean isVisibleToUser = filterIfNotSystemUser( 5287 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5288 if (isVisibleToUser) { 5289 result.add(xpResolveInfo); 5290 Collections.sort(result, mResolvePrioritySorter); 5291 } 5292 } 5293 if (hasWebURI(intent)) { 5294 CrossProfileDomainInfo xpDomainInfo = null; 5295 final UserInfo parent = getProfileParent(userId); 5296 if (parent != null) { 5297 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5298 flags, userId, parent.id); 5299 } 5300 if (xpDomainInfo != null) { 5301 if (xpResolveInfo != null) { 5302 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5303 // in the result. 5304 result.remove(xpResolveInfo); 5305 } 5306 if (result.size() == 0) { 5307 result.add(xpDomainInfo.resolveInfo); 5308 return result; 5309 } 5310 } else if (result.size() <= 1) { 5311 return result; 5312 } 5313 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5314 xpDomainInfo, userId); 5315 Collections.sort(result, mResolvePrioritySorter); 5316 } 5317 return result; 5318 } 5319 final PackageParser.Package pkg = mPackages.get(pkgName); 5320 if (pkg != null) { 5321 return filterIfNotSystemUser( 5322 mActivities.queryIntentForPackage( 5323 intent, resolvedType, flags, pkg.activities, userId), 5324 userId); 5325 } 5326 return new ArrayList<ResolveInfo>(); 5327 } 5328 } 5329 5330 private static class CrossProfileDomainInfo { 5331 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5332 ResolveInfo resolveInfo; 5333 /* Best domain verification status of the activities found in the other profile */ 5334 int bestDomainVerificationStatus; 5335 } 5336 5337 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5338 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5339 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5340 sourceUserId)) { 5341 return null; 5342 } 5343 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5344 resolvedType, flags, parentUserId); 5345 5346 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5347 return null; 5348 } 5349 CrossProfileDomainInfo result = null; 5350 int size = resultTargetUser.size(); 5351 for (int i = 0; i < size; i++) { 5352 ResolveInfo riTargetUser = resultTargetUser.get(i); 5353 // Intent filter verification is only for filters that specify a host. So don't return 5354 // those that handle all web uris. 5355 if (riTargetUser.handleAllWebDataURI) { 5356 continue; 5357 } 5358 String packageName = riTargetUser.activityInfo.packageName; 5359 PackageSetting ps = mSettings.mPackages.get(packageName); 5360 if (ps == null) { 5361 continue; 5362 } 5363 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5364 int status = (int)(verificationState >> 32); 5365 if (result == null) { 5366 result = new CrossProfileDomainInfo(); 5367 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5368 sourceUserId, parentUserId); 5369 result.bestDomainVerificationStatus = status; 5370 } else { 5371 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5372 result.bestDomainVerificationStatus); 5373 } 5374 } 5375 // Don't consider matches with status NEVER across profiles. 5376 if (result != null && result.bestDomainVerificationStatus 5377 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5378 return null; 5379 } 5380 return result; 5381 } 5382 5383 /** 5384 * Verification statuses are ordered from the worse to the best, except for 5385 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5386 */ 5387 private int bestDomainVerificationStatus(int status1, int status2) { 5388 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5389 return status2; 5390 } 5391 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5392 return status1; 5393 } 5394 return (int) MathUtils.max(status1, status2); 5395 } 5396 5397 private boolean isUserEnabled(int userId) { 5398 long callingId = Binder.clearCallingIdentity(); 5399 try { 5400 UserInfo userInfo = sUserManager.getUserInfo(userId); 5401 return userInfo != null && userInfo.isEnabled(); 5402 } finally { 5403 Binder.restoreCallingIdentity(callingId); 5404 } 5405 } 5406 5407 /** 5408 * Filter out activities with systemUserOnly flag set, when current user is not System. 5409 * 5410 * @return filtered list 5411 */ 5412 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5413 if (userId == UserHandle.USER_SYSTEM) { 5414 return resolveInfos; 5415 } 5416 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5417 ResolveInfo info = resolveInfos.get(i); 5418 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5419 resolveInfos.remove(i); 5420 } 5421 } 5422 return resolveInfos; 5423 } 5424 5425 /** 5426 * @param resolveInfos list of resolve infos in descending priority order 5427 * @return if the list contains a resolve info with non-negative priority 5428 */ 5429 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5430 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5431 } 5432 5433 private static boolean hasWebURI(Intent intent) { 5434 if (intent.getData() == null) { 5435 return false; 5436 } 5437 final String scheme = intent.getScheme(); 5438 if (TextUtils.isEmpty(scheme)) { 5439 return false; 5440 } 5441 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5442 } 5443 5444 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5445 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5446 int userId) { 5447 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5448 5449 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5450 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5451 candidates.size()); 5452 } 5453 5454 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5455 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5456 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5457 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5458 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5459 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5460 5461 synchronized (mPackages) { 5462 final int count = candidates.size(); 5463 // First, try to use linked apps. Partition the candidates into four lists: 5464 // one for the final results, one for the "do not use ever", one for "undefined status" 5465 // and finally one for "browser app type". 5466 for (int n=0; n<count; n++) { 5467 ResolveInfo info = candidates.get(n); 5468 String packageName = info.activityInfo.packageName; 5469 PackageSetting ps = mSettings.mPackages.get(packageName); 5470 if (ps != null) { 5471 // Add to the special match all list (Browser use case) 5472 if (info.handleAllWebDataURI) { 5473 matchAllList.add(info); 5474 continue; 5475 } 5476 // Try to get the status from User settings first 5477 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5478 int status = (int)(packedStatus >> 32); 5479 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5480 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5481 if (DEBUG_DOMAIN_VERIFICATION) { 5482 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5483 + " : linkgen=" + linkGeneration); 5484 } 5485 // Use link-enabled generation as preferredOrder, i.e. 5486 // prefer newly-enabled over earlier-enabled. 5487 info.preferredOrder = linkGeneration; 5488 alwaysList.add(info); 5489 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5490 if (DEBUG_DOMAIN_VERIFICATION) { 5491 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5492 } 5493 neverList.add(info); 5494 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5495 if (DEBUG_DOMAIN_VERIFICATION) { 5496 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5497 } 5498 alwaysAskList.add(info); 5499 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5500 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5501 if (DEBUG_DOMAIN_VERIFICATION) { 5502 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5503 } 5504 undefinedList.add(info); 5505 } 5506 } 5507 } 5508 5509 // We'll want to include browser possibilities in a few cases 5510 boolean includeBrowser = false; 5511 5512 // First try to add the "always" resolution(s) for the current user, if any 5513 if (alwaysList.size() > 0) { 5514 result.addAll(alwaysList); 5515 } else { 5516 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5517 result.addAll(undefinedList); 5518 // Maybe add one for the other profile. 5519 if (xpDomainInfo != null && ( 5520 xpDomainInfo.bestDomainVerificationStatus 5521 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5522 result.add(xpDomainInfo.resolveInfo); 5523 } 5524 includeBrowser = true; 5525 } 5526 5527 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5528 // If there were 'always' entries their preferred order has been set, so we also 5529 // back that off to make the alternatives equivalent 5530 if (alwaysAskList.size() > 0) { 5531 for (ResolveInfo i : result) { 5532 i.preferredOrder = 0; 5533 } 5534 result.addAll(alwaysAskList); 5535 includeBrowser = true; 5536 } 5537 5538 if (includeBrowser) { 5539 // Also add browsers (all of them or only the default one) 5540 if (DEBUG_DOMAIN_VERIFICATION) { 5541 Slog.v(TAG, " ...including browsers in candidate set"); 5542 } 5543 if ((matchFlags & MATCH_ALL) != 0) { 5544 result.addAll(matchAllList); 5545 } else { 5546 // Browser/generic handling case. If there's a default browser, go straight 5547 // to that (but only if there is no other higher-priority match). 5548 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5549 int maxMatchPrio = 0; 5550 ResolveInfo defaultBrowserMatch = null; 5551 final int numCandidates = matchAllList.size(); 5552 for (int n = 0; n < numCandidates; n++) { 5553 ResolveInfo info = matchAllList.get(n); 5554 // track the highest overall match priority... 5555 if (info.priority > maxMatchPrio) { 5556 maxMatchPrio = info.priority; 5557 } 5558 // ...and the highest-priority default browser match 5559 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5560 if (defaultBrowserMatch == null 5561 || (defaultBrowserMatch.priority < info.priority)) { 5562 if (debug) { 5563 Slog.v(TAG, "Considering default browser match " + info); 5564 } 5565 defaultBrowserMatch = info; 5566 } 5567 } 5568 } 5569 if (defaultBrowserMatch != null 5570 && defaultBrowserMatch.priority >= maxMatchPrio 5571 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5572 { 5573 if (debug) { 5574 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5575 } 5576 result.add(defaultBrowserMatch); 5577 } else { 5578 result.addAll(matchAllList); 5579 } 5580 } 5581 5582 // If there is nothing selected, add all candidates and remove the ones that the user 5583 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5584 if (result.size() == 0) { 5585 result.addAll(candidates); 5586 result.removeAll(neverList); 5587 } 5588 } 5589 } 5590 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5591 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5592 result.size()); 5593 for (ResolveInfo info : result) { 5594 Slog.v(TAG, " + " + info.activityInfo); 5595 } 5596 } 5597 return result; 5598 } 5599 5600 // Returns a packed value as a long: 5601 // 5602 // high 'int'-sized word: link status: undefined/ask/never/always. 5603 // low 'int'-sized word: relative priority among 'always' results. 5604 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5605 long result = ps.getDomainVerificationStatusForUser(userId); 5606 // if none available, get the master status 5607 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5608 if (ps.getIntentFilterVerificationInfo() != null) { 5609 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5610 } 5611 } 5612 return result; 5613 } 5614 5615 private ResolveInfo querySkipCurrentProfileIntents( 5616 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5617 int flags, int sourceUserId) { 5618 if (matchingFilters != null) { 5619 int size = matchingFilters.size(); 5620 for (int i = 0; i < size; i ++) { 5621 CrossProfileIntentFilter filter = matchingFilters.get(i); 5622 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5623 // Checking if there are activities in the target user that can handle the 5624 // intent. 5625 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5626 resolvedType, flags, sourceUserId); 5627 if (resolveInfo != null) { 5628 return resolveInfo; 5629 } 5630 } 5631 } 5632 } 5633 return null; 5634 } 5635 5636 // Return matching ResolveInfo in target user if any. 5637 private ResolveInfo queryCrossProfileIntents( 5638 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5639 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5640 if (matchingFilters != null) { 5641 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5642 // match the same intent. For performance reasons, it is better not to 5643 // run queryIntent twice for the same userId 5644 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5645 int size = matchingFilters.size(); 5646 for (int i = 0; i < size; i++) { 5647 CrossProfileIntentFilter filter = matchingFilters.get(i); 5648 int targetUserId = filter.getTargetUserId(); 5649 boolean skipCurrentProfile = 5650 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5651 boolean skipCurrentProfileIfNoMatchFound = 5652 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5653 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5654 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5655 // Checking if there are activities in the target user that can handle the 5656 // intent. 5657 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5658 resolvedType, flags, sourceUserId); 5659 if (resolveInfo != null) return resolveInfo; 5660 alreadyTriedUserIds.put(targetUserId, true); 5661 } 5662 } 5663 } 5664 return null; 5665 } 5666 5667 /** 5668 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5669 * will forward the intent to the filter's target user. 5670 * Otherwise, returns null. 5671 */ 5672 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5673 String resolvedType, int flags, int sourceUserId) { 5674 int targetUserId = filter.getTargetUserId(); 5675 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5676 resolvedType, flags, targetUserId); 5677 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5678 // If all the matches in the target profile are suspended, return null. 5679 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5680 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5681 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5682 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5683 targetUserId); 5684 } 5685 } 5686 } 5687 return null; 5688 } 5689 5690 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5691 int sourceUserId, int targetUserId) { 5692 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5693 long ident = Binder.clearCallingIdentity(); 5694 boolean targetIsProfile; 5695 try { 5696 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5697 } finally { 5698 Binder.restoreCallingIdentity(ident); 5699 } 5700 String className; 5701 if (targetIsProfile) { 5702 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5703 } else { 5704 className = FORWARD_INTENT_TO_PARENT; 5705 } 5706 ComponentName forwardingActivityComponentName = new ComponentName( 5707 mAndroidApplication.packageName, className); 5708 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5709 sourceUserId); 5710 if (!targetIsProfile) { 5711 forwardingActivityInfo.showUserIcon = targetUserId; 5712 forwardingResolveInfo.noResourceId = true; 5713 } 5714 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5715 forwardingResolveInfo.priority = 0; 5716 forwardingResolveInfo.preferredOrder = 0; 5717 forwardingResolveInfo.match = 0; 5718 forwardingResolveInfo.isDefault = true; 5719 forwardingResolveInfo.filter = filter; 5720 forwardingResolveInfo.targetUserId = targetUserId; 5721 return forwardingResolveInfo; 5722 } 5723 5724 @Override 5725 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5726 Intent[] specifics, String[] specificTypes, Intent intent, 5727 String resolvedType, int flags, int userId) { 5728 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5729 specificTypes, intent, resolvedType, flags, userId)); 5730 } 5731 5732 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5733 Intent[] specifics, String[] specificTypes, Intent intent, 5734 String resolvedType, int flags, int userId) { 5735 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5736 flags = updateFlagsForResolve(flags, userId, intent); 5737 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5738 false /* requireFullPermission */, false /* checkShell */, 5739 "query intent activity options"); 5740 final String resultsAction = intent.getAction(); 5741 5742 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5743 | PackageManager.GET_RESOLVED_FILTER, userId); 5744 5745 if (DEBUG_INTENT_MATCHING) { 5746 Log.v(TAG, "Query " + intent + ": " + results); 5747 } 5748 5749 int specificsPos = 0; 5750 int N; 5751 5752 // todo: note that the algorithm used here is O(N^2). This 5753 // isn't a problem in our current environment, but if we start running 5754 // into situations where we have more than 5 or 10 matches then this 5755 // should probably be changed to something smarter... 5756 5757 // First we go through and resolve each of the specific items 5758 // that were supplied, taking care of removing any corresponding 5759 // duplicate items in the generic resolve list. 5760 if (specifics != null) { 5761 for (int i=0; i<specifics.length; i++) { 5762 final Intent sintent = specifics[i]; 5763 if (sintent == null) { 5764 continue; 5765 } 5766 5767 if (DEBUG_INTENT_MATCHING) { 5768 Log.v(TAG, "Specific #" + i + ": " + sintent); 5769 } 5770 5771 String action = sintent.getAction(); 5772 if (resultsAction != null && resultsAction.equals(action)) { 5773 // If this action was explicitly requested, then don't 5774 // remove things that have it. 5775 action = null; 5776 } 5777 5778 ResolveInfo ri = null; 5779 ActivityInfo ai = null; 5780 5781 ComponentName comp = sintent.getComponent(); 5782 if (comp == null) { 5783 ri = resolveIntent( 5784 sintent, 5785 specificTypes != null ? specificTypes[i] : null, 5786 flags, userId); 5787 if (ri == null) { 5788 continue; 5789 } 5790 if (ri == mResolveInfo) { 5791 // ACK! Must do something better with this. 5792 } 5793 ai = ri.activityInfo; 5794 comp = new ComponentName(ai.applicationInfo.packageName, 5795 ai.name); 5796 } else { 5797 ai = getActivityInfo(comp, flags, userId); 5798 if (ai == null) { 5799 continue; 5800 } 5801 } 5802 5803 // Look for any generic query activities that are duplicates 5804 // of this specific one, and remove them from the results. 5805 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5806 N = results.size(); 5807 int j; 5808 for (j=specificsPos; j<N; j++) { 5809 ResolveInfo sri = results.get(j); 5810 if ((sri.activityInfo.name.equals(comp.getClassName()) 5811 && sri.activityInfo.applicationInfo.packageName.equals( 5812 comp.getPackageName())) 5813 || (action != null && sri.filter.matchAction(action))) { 5814 results.remove(j); 5815 if (DEBUG_INTENT_MATCHING) Log.v( 5816 TAG, "Removing duplicate item from " + j 5817 + " due to specific " + specificsPos); 5818 if (ri == null) { 5819 ri = sri; 5820 } 5821 j--; 5822 N--; 5823 } 5824 } 5825 5826 // Add this specific item to its proper place. 5827 if (ri == null) { 5828 ri = new ResolveInfo(); 5829 ri.activityInfo = ai; 5830 } 5831 results.add(specificsPos, ri); 5832 ri.specificIndex = i; 5833 specificsPos++; 5834 } 5835 } 5836 5837 // Now we go through the remaining generic results and remove any 5838 // duplicate actions that are found here. 5839 N = results.size(); 5840 for (int i=specificsPos; i<N-1; i++) { 5841 final ResolveInfo rii = results.get(i); 5842 if (rii.filter == null) { 5843 continue; 5844 } 5845 5846 // Iterate over all of the actions of this result's intent 5847 // filter... typically this should be just one. 5848 final Iterator<String> it = rii.filter.actionsIterator(); 5849 if (it == null) { 5850 continue; 5851 } 5852 while (it.hasNext()) { 5853 final String action = it.next(); 5854 if (resultsAction != null && resultsAction.equals(action)) { 5855 // If this action was explicitly requested, then don't 5856 // remove things that have it. 5857 continue; 5858 } 5859 for (int j=i+1; j<N; j++) { 5860 final ResolveInfo rij = results.get(j); 5861 if (rij.filter != null && rij.filter.hasAction(action)) { 5862 results.remove(j); 5863 if (DEBUG_INTENT_MATCHING) Log.v( 5864 TAG, "Removing duplicate item from " + j 5865 + " due to action " + action + " at " + i); 5866 j--; 5867 N--; 5868 } 5869 } 5870 } 5871 5872 // If the caller didn't request filter information, drop it now 5873 // so we don't have to marshall/unmarshall it. 5874 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5875 rii.filter = null; 5876 } 5877 } 5878 5879 // Filter out the caller activity if so requested. 5880 if (caller != null) { 5881 N = results.size(); 5882 for (int i=0; i<N; i++) { 5883 ActivityInfo ainfo = results.get(i).activityInfo; 5884 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5885 && caller.getClassName().equals(ainfo.name)) { 5886 results.remove(i); 5887 break; 5888 } 5889 } 5890 } 5891 5892 // If the caller didn't request filter information, 5893 // drop them now so we don't have to 5894 // marshall/unmarshall it. 5895 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5896 N = results.size(); 5897 for (int i=0; i<N; i++) { 5898 results.get(i).filter = null; 5899 } 5900 } 5901 5902 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5903 return results; 5904 } 5905 5906 @Override 5907 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5908 String resolvedType, int flags, int userId) { 5909 return new ParceledListSlice<>( 5910 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5911 } 5912 5913 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5914 String resolvedType, int flags, int userId) { 5915 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5916 flags = updateFlagsForResolve(flags, userId, intent); 5917 ComponentName comp = intent.getComponent(); 5918 if (comp == null) { 5919 if (intent.getSelector() != null) { 5920 intent = intent.getSelector(); 5921 comp = intent.getComponent(); 5922 } 5923 } 5924 if (comp != null) { 5925 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5926 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5927 if (ai != null) { 5928 ResolveInfo ri = new ResolveInfo(); 5929 ri.activityInfo = ai; 5930 list.add(ri); 5931 } 5932 return list; 5933 } 5934 5935 // reader 5936 synchronized (mPackages) { 5937 String pkgName = intent.getPackage(); 5938 if (pkgName == null) { 5939 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5940 } 5941 final PackageParser.Package pkg = mPackages.get(pkgName); 5942 if (pkg != null) { 5943 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5944 userId); 5945 } 5946 return Collections.emptyList(); 5947 } 5948 } 5949 5950 @Override 5951 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5952 if (!sUserManager.exists(userId)) return null; 5953 flags = updateFlagsForResolve(flags, userId, intent); 5954 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5955 if (query != null) { 5956 if (query.size() >= 1) { 5957 // If there is more than one service with the same priority, 5958 // just arbitrarily pick the first one. 5959 return query.get(0); 5960 } 5961 } 5962 return null; 5963 } 5964 5965 @Override 5966 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5967 String resolvedType, int flags, int userId) { 5968 return new ParceledListSlice<>( 5969 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5970 } 5971 5972 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5973 String resolvedType, int flags, int userId) { 5974 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5975 flags = updateFlagsForResolve(flags, userId, intent); 5976 ComponentName comp = intent.getComponent(); 5977 if (comp == null) { 5978 if (intent.getSelector() != null) { 5979 intent = intent.getSelector(); 5980 comp = intent.getComponent(); 5981 } 5982 } 5983 if (comp != null) { 5984 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5985 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5986 if (si != null) { 5987 final ResolveInfo ri = new ResolveInfo(); 5988 ri.serviceInfo = si; 5989 list.add(ri); 5990 } 5991 return list; 5992 } 5993 5994 // reader 5995 synchronized (mPackages) { 5996 String pkgName = intent.getPackage(); 5997 if (pkgName == null) { 5998 return mServices.queryIntent(intent, resolvedType, flags, userId); 5999 } 6000 final PackageParser.Package pkg = mPackages.get(pkgName); 6001 if (pkg != null) { 6002 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6003 userId); 6004 } 6005 return Collections.emptyList(); 6006 } 6007 } 6008 6009 @Override 6010 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6011 String resolvedType, int flags, int userId) { 6012 return new ParceledListSlice<>( 6013 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6014 } 6015 6016 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6017 Intent intent, String resolvedType, int flags, int userId) { 6018 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6019 flags = updateFlagsForResolve(flags, userId, intent); 6020 ComponentName comp = intent.getComponent(); 6021 if (comp == null) { 6022 if (intent.getSelector() != null) { 6023 intent = intent.getSelector(); 6024 comp = intent.getComponent(); 6025 } 6026 } 6027 if (comp != null) { 6028 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6029 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6030 if (pi != null) { 6031 final ResolveInfo ri = new ResolveInfo(); 6032 ri.providerInfo = pi; 6033 list.add(ri); 6034 } 6035 return list; 6036 } 6037 6038 // reader 6039 synchronized (mPackages) { 6040 String pkgName = intent.getPackage(); 6041 if (pkgName == null) { 6042 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6043 } 6044 final PackageParser.Package pkg = mPackages.get(pkgName); 6045 if (pkg != null) { 6046 return mProviders.queryIntentForPackage( 6047 intent, resolvedType, flags, pkg.providers, userId); 6048 } 6049 return Collections.emptyList(); 6050 } 6051 } 6052 6053 @Override 6054 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6055 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6056 flags = updateFlagsForPackage(flags, userId, null); 6057 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6058 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6059 true /* requireFullPermission */, false /* checkShell */, 6060 "get installed packages"); 6061 6062 // writer 6063 synchronized (mPackages) { 6064 ArrayList<PackageInfo> list; 6065 if (listUninstalled) { 6066 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6067 for (PackageSetting ps : mSettings.mPackages.values()) { 6068 final PackageInfo pi; 6069 if (ps.pkg != null) { 6070 pi = generatePackageInfo(ps, flags, userId); 6071 } else { 6072 pi = generatePackageInfo(ps, flags, userId); 6073 } 6074 if (pi != null) { 6075 list.add(pi); 6076 } 6077 } 6078 } else { 6079 list = new ArrayList<PackageInfo>(mPackages.size()); 6080 for (PackageParser.Package p : mPackages.values()) { 6081 final PackageInfo pi = 6082 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6083 if (pi != null) { 6084 list.add(pi); 6085 } 6086 } 6087 } 6088 6089 return new ParceledListSlice<PackageInfo>(list); 6090 } 6091 } 6092 6093 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6094 String[] permissions, boolean[] tmp, int flags, int userId) { 6095 int numMatch = 0; 6096 final PermissionsState permissionsState = ps.getPermissionsState(); 6097 for (int i=0; i<permissions.length; i++) { 6098 final String permission = permissions[i]; 6099 if (permissionsState.hasPermission(permission, userId)) { 6100 tmp[i] = true; 6101 numMatch++; 6102 } else { 6103 tmp[i] = false; 6104 } 6105 } 6106 if (numMatch == 0) { 6107 return; 6108 } 6109 final PackageInfo pi; 6110 if (ps.pkg != null) { 6111 pi = generatePackageInfo(ps, flags, userId); 6112 } else { 6113 pi = generatePackageInfo(ps, flags, userId); 6114 } 6115 // The above might return null in cases of uninstalled apps or install-state 6116 // skew across users/profiles. 6117 if (pi != null) { 6118 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6119 if (numMatch == permissions.length) { 6120 pi.requestedPermissions = permissions; 6121 } else { 6122 pi.requestedPermissions = new String[numMatch]; 6123 numMatch = 0; 6124 for (int i=0; i<permissions.length; i++) { 6125 if (tmp[i]) { 6126 pi.requestedPermissions[numMatch] = permissions[i]; 6127 numMatch++; 6128 } 6129 } 6130 } 6131 } 6132 list.add(pi); 6133 } 6134 } 6135 6136 @Override 6137 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6138 String[] permissions, int flags, int userId) { 6139 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6140 flags = updateFlagsForPackage(flags, userId, permissions); 6141 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6142 6143 // writer 6144 synchronized (mPackages) { 6145 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6146 boolean[] tmpBools = new boolean[permissions.length]; 6147 if (listUninstalled) { 6148 for (PackageSetting ps : mSettings.mPackages.values()) { 6149 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6150 } 6151 } else { 6152 for (PackageParser.Package pkg : mPackages.values()) { 6153 PackageSetting ps = (PackageSetting)pkg.mExtras; 6154 if (ps != null) { 6155 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6156 userId); 6157 } 6158 } 6159 } 6160 6161 return new ParceledListSlice<PackageInfo>(list); 6162 } 6163 } 6164 6165 @Override 6166 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6167 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6168 flags = updateFlagsForApplication(flags, userId, null); 6169 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6170 6171 // writer 6172 synchronized (mPackages) { 6173 ArrayList<ApplicationInfo> list; 6174 if (listUninstalled) { 6175 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6176 for (PackageSetting ps : mSettings.mPackages.values()) { 6177 ApplicationInfo ai; 6178 if (ps.pkg != null) { 6179 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6180 ps.readUserState(userId), userId); 6181 } else { 6182 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6183 } 6184 if (ai != null) { 6185 list.add(ai); 6186 } 6187 } 6188 } else { 6189 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6190 for (PackageParser.Package p : mPackages.values()) { 6191 if (p.mExtras != null) { 6192 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6193 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6194 if (ai != null) { 6195 list.add(ai); 6196 } 6197 } 6198 } 6199 } 6200 6201 return new ParceledListSlice<ApplicationInfo>(list); 6202 } 6203 } 6204 6205 @Override 6206 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6207 if (DISABLE_EPHEMERAL_APPS) { 6208 return null; 6209 } 6210 6211 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6212 "getEphemeralApplications"); 6213 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6214 true /* requireFullPermission */, false /* checkShell */, 6215 "getEphemeralApplications"); 6216 synchronized (mPackages) { 6217 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6218 .getEphemeralApplicationsLPw(userId); 6219 if (ephemeralApps != null) { 6220 return new ParceledListSlice<>(ephemeralApps); 6221 } 6222 } 6223 return null; 6224 } 6225 6226 @Override 6227 public boolean isEphemeralApplication(String packageName, int userId) { 6228 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6229 true /* requireFullPermission */, false /* checkShell */, 6230 "isEphemeral"); 6231 if (DISABLE_EPHEMERAL_APPS) { 6232 return false; 6233 } 6234 6235 if (!isCallerSameApp(packageName)) { 6236 return false; 6237 } 6238 synchronized (mPackages) { 6239 PackageParser.Package pkg = mPackages.get(packageName); 6240 if (pkg != null) { 6241 return pkg.applicationInfo.isEphemeralApp(); 6242 } 6243 } 6244 return false; 6245 } 6246 6247 @Override 6248 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6249 if (DISABLE_EPHEMERAL_APPS) { 6250 return null; 6251 } 6252 6253 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6254 true /* requireFullPermission */, false /* checkShell */, 6255 "getCookie"); 6256 if (!isCallerSameApp(packageName)) { 6257 return null; 6258 } 6259 synchronized (mPackages) { 6260 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6261 packageName, userId); 6262 } 6263 } 6264 6265 @Override 6266 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6267 if (DISABLE_EPHEMERAL_APPS) { 6268 return true; 6269 } 6270 6271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6272 true /* requireFullPermission */, true /* checkShell */, 6273 "setCookie"); 6274 if (!isCallerSameApp(packageName)) { 6275 return false; 6276 } 6277 synchronized (mPackages) { 6278 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6279 packageName, cookie, userId); 6280 } 6281 } 6282 6283 @Override 6284 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6285 if (DISABLE_EPHEMERAL_APPS) { 6286 return null; 6287 } 6288 6289 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6290 "getEphemeralApplicationIcon"); 6291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6292 true /* requireFullPermission */, false /* checkShell */, 6293 "getEphemeralApplicationIcon"); 6294 synchronized (mPackages) { 6295 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6296 packageName, userId); 6297 } 6298 } 6299 6300 private boolean isCallerSameApp(String packageName) { 6301 PackageParser.Package pkg = mPackages.get(packageName); 6302 return pkg != null 6303 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6304 } 6305 6306 @Override 6307 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6308 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6309 } 6310 6311 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6312 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6313 6314 // reader 6315 synchronized (mPackages) { 6316 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6317 final int userId = UserHandle.getCallingUserId(); 6318 while (i.hasNext()) { 6319 final PackageParser.Package p = i.next(); 6320 if (p.applicationInfo == null) continue; 6321 6322 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6323 && !p.applicationInfo.isDirectBootAware(); 6324 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6325 && p.applicationInfo.isDirectBootAware(); 6326 6327 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6328 && (!mSafeMode || isSystemApp(p)) 6329 && (matchesUnaware || matchesAware)) { 6330 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6331 if (ps != null) { 6332 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6333 ps.readUserState(userId), userId); 6334 if (ai != null) { 6335 finalList.add(ai); 6336 } 6337 } 6338 } 6339 } 6340 } 6341 6342 return finalList; 6343 } 6344 6345 @Override 6346 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6347 if (!sUserManager.exists(userId)) return null; 6348 flags = updateFlagsForComponent(flags, userId, name); 6349 // reader 6350 synchronized (mPackages) { 6351 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6352 PackageSetting ps = provider != null 6353 ? mSettings.mPackages.get(provider.owner.packageName) 6354 : null; 6355 return ps != null 6356 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6357 ? PackageParser.generateProviderInfo(provider, flags, 6358 ps.readUserState(userId), userId) 6359 : null; 6360 } 6361 } 6362 6363 /** 6364 * @deprecated 6365 */ 6366 @Deprecated 6367 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6368 // reader 6369 synchronized (mPackages) { 6370 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6371 .entrySet().iterator(); 6372 final int userId = UserHandle.getCallingUserId(); 6373 while (i.hasNext()) { 6374 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6375 PackageParser.Provider p = entry.getValue(); 6376 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6377 6378 if (ps != null && p.syncable 6379 && (!mSafeMode || (p.info.applicationInfo.flags 6380 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6381 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6382 ps.readUserState(userId), userId); 6383 if (info != null) { 6384 outNames.add(entry.getKey()); 6385 outInfo.add(info); 6386 } 6387 } 6388 } 6389 } 6390 } 6391 6392 @Override 6393 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6394 int uid, int flags) { 6395 final int userId = processName != null ? UserHandle.getUserId(uid) 6396 : UserHandle.getCallingUserId(); 6397 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6398 flags = updateFlagsForComponent(flags, userId, processName); 6399 6400 ArrayList<ProviderInfo> finalList = null; 6401 // reader 6402 synchronized (mPackages) { 6403 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6404 while (i.hasNext()) { 6405 final PackageParser.Provider p = i.next(); 6406 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6407 if (ps != null && p.info.authority != null 6408 && (processName == null 6409 || (p.info.processName.equals(processName) 6410 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6411 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6412 if (finalList == null) { 6413 finalList = new ArrayList<ProviderInfo>(3); 6414 } 6415 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6416 ps.readUserState(userId), userId); 6417 if (info != null) { 6418 finalList.add(info); 6419 } 6420 } 6421 } 6422 } 6423 6424 if (finalList != null) { 6425 Collections.sort(finalList, mProviderInitOrderSorter); 6426 return new ParceledListSlice<ProviderInfo>(finalList); 6427 } 6428 6429 return ParceledListSlice.emptyList(); 6430 } 6431 6432 @Override 6433 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6434 // reader 6435 synchronized (mPackages) { 6436 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6437 return PackageParser.generateInstrumentationInfo(i, flags); 6438 } 6439 } 6440 6441 @Override 6442 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6443 String targetPackage, int flags) { 6444 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6445 } 6446 6447 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6448 int flags) { 6449 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6450 6451 // reader 6452 synchronized (mPackages) { 6453 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6454 while (i.hasNext()) { 6455 final PackageParser.Instrumentation p = i.next(); 6456 if (targetPackage == null 6457 || targetPackage.equals(p.info.targetPackage)) { 6458 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6459 flags); 6460 if (ii != null) { 6461 finalList.add(ii); 6462 } 6463 } 6464 } 6465 } 6466 6467 return finalList; 6468 } 6469 6470 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6471 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6472 if (overlays == null) { 6473 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6474 return; 6475 } 6476 for (PackageParser.Package opkg : overlays.values()) { 6477 // Not much to do if idmap fails: we already logged the error 6478 // and we certainly don't want to abort installation of pkg simply 6479 // because an overlay didn't fit properly. For these reasons, 6480 // ignore the return value of createIdmapForPackagePairLI. 6481 createIdmapForPackagePairLI(pkg, opkg); 6482 } 6483 } 6484 6485 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6486 PackageParser.Package opkg) { 6487 if (!opkg.mTrustedOverlay) { 6488 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6489 opkg.baseCodePath + ": overlay not trusted"); 6490 return false; 6491 } 6492 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6493 if (overlaySet == null) { 6494 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6495 opkg.baseCodePath + " but target package has no known overlays"); 6496 return false; 6497 } 6498 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6499 // TODO: generate idmap for split APKs 6500 try { 6501 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6502 } catch (InstallerException e) { 6503 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6504 + opkg.baseCodePath); 6505 return false; 6506 } 6507 PackageParser.Package[] overlayArray = 6508 overlaySet.values().toArray(new PackageParser.Package[0]); 6509 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6510 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6511 return p1.mOverlayPriority - p2.mOverlayPriority; 6512 } 6513 }; 6514 Arrays.sort(overlayArray, cmp); 6515 6516 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6517 int i = 0; 6518 for (PackageParser.Package p : overlayArray) { 6519 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6520 } 6521 return true; 6522 } 6523 6524 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6525 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6526 try { 6527 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6528 } finally { 6529 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6530 } 6531 } 6532 6533 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6534 final File[] files = dir.listFiles(); 6535 if (ArrayUtils.isEmpty(files)) { 6536 Log.d(TAG, "No files in app dir " + dir); 6537 return; 6538 } 6539 6540 if (DEBUG_PACKAGE_SCANNING) { 6541 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6542 + " flags=0x" + Integer.toHexString(parseFlags)); 6543 } 6544 6545 for (File file : files) { 6546 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6547 && !PackageInstallerService.isStageName(file.getName()); 6548 if (!isPackage) { 6549 // Ignore entries which are not packages 6550 continue; 6551 } 6552 try { 6553 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6554 scanFlags, currentTime, null); 6555 } catch (PackageManagerException e) { 6556 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6557 6558 // Delete invalid userdata apps 6559 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6560 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6561 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6562 removeCodePathLI(file); 6563 } 6564 } 6565 } 6566 } 6567 6568 private static File getSettingsProblemFile() { 6569 File dataDir = Environment.getDataDirectory(); 6570 File systemDir = new File(dataDir, "system"); 6571 File fname = new File(systemDir, "uiderrors.txt"); 6572 return fname; 6573 } 6574 6575 static void reportSettingsProblem(int priority, String msg) { 6576 logCriticalInfo(priority, msg); 6577 } 6578 6579 static void logCriticalInfo(int priority, String msg) { 6580 Slog.println(priority, TAG, msg); 6581 EventLogTags.writePmCriticalInfo(msg); 6582 try { 6583 File fname = getSettingsProblemFile(); 6584 FileOutputStream out = new FileOutputStream(fname, true); 6585 PrintWriter pw = new FastPrintWriter(out); 6586 SimpleDateFormat formatter = new SimpleDateFormat(); 6587 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6588 pw.println(dateString + ": " + msg); 6589 pw.close(); 6590 FileUtils.setPermissions( 6591 fname.toString(), 6592 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6593 -1, -1); 6594 } catch (java.io.IOException e) { 6595 } 6596 } 6597 6598 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6599 if (srcFile.isDirectory()) { 6600 final File baseFile = new File(pkg.baseCodePath); 6601 long maxModifiedTime = baseFile.lastModified(); 6602 if (pkg.splitCodePaths != null) { 6603 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6604 final File splitFile = new File(pkg.splitCodePaths[i]); 6605 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6606 } 6607 } 6608 return maxModifiedTime; 6609 } 6610 return srcFile.lastModified(); 6611 } 6612 6613 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6614 final int policyFlags) throws PackageManagerException { 6615 if (ps != null 6616 && ps.codePath.equals(srcFile) 6617 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6618 && !isCompatSignatureUpdateNeeded(pkg) 6619 && !isRecoverSignatureUpdateNeeded(pkg)) { 6620 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6621 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6622 ArraySet<PublicKey> signingKs; 6623 synchronized (mPackages) { 6624 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6625 } 6626 if (ps.signatures.mSignatures != null 6627 && ps.signatures.mSignatures.length != 0 6628 && signingKs != null) { 6629 // Optimization: reuse the existing cached certificates 6630 // if the package appears to be unchanged. 6631 pkg.mSignatures = ps.signatures.mSignatures; 6632 pkg.mSigningKeys = signingKs; 6633 return; 6634 } 6635 6636 Slog.w(TAG, "PackageSetting for " + ps.name 6637 + " is missing signatures. Collecting certs again to recover them."); 6638 } else { 6639 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6640 } 6641 6642 try { 6643 PackageParser.collectCertificates(pkg, policyFlags); 6644 } catch (PackageParserException e) { 6645 throw PackageManagerException.from(e); 6646 } 6647 } 6648 6649 /** 6650 * Traces a package scan. 6651 * @see #scanPackageLI(File, int, int, long, UserHandle) 6652 */ 6653 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6654 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6656 try { 6657 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6658 } finally { 6659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6660 } 6661 } 6662 6663 /** 6664 * Scans a package and returns the newly parsed package. 6665 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6666 */ 6667 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6668 long currentTime, UserHandle user) throws PackageManagerException { 6669 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6670 PackageParser pp = new PackageParser(); 6671 pp.setSeparateProcesses(mSeparateProcesses); 6672 pp.setOnlyCoreApps(mOnlyCore); 6673 pp.setDisplayMetrics(mMetrics); 6674 6675 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6676 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6677 } 6678 6679 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6680 final PackageParser.Package pkg; 6681 try { 6682 pkg = pp.parsePackage(scanFile, parseFlags); 6683 } catch (PackageParserException e) { 6684 throw PackageManagerException.from(e); 6685 } finally { 6686 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6687 } 6688 6689 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6690 } 6691 6692 /** 6693 * Scans a package and returns the newly parsed package. 6694 * @throws PackageManagerException on a parse error. 6695 */ 6696 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6697 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6698 throws PackageManagerException { 6699 // If the package has children and this is the first dive in the function 6700 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6701 // packages (parent and children) would be successfully scanned before the 6702 // actual scan since scanning mutates internal state and we want to atomically 6703 // install the package and its children. 6704 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6705 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6706 scanFlags |= SCAN_CHECK_ONLY; 6707 } 6708 } else { 6709 scanFlags &= ~SCAN_CHECK_ONLY; 6710 } 6711 6712 // Scan the parent 6713 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6714 scanFlags, currentTime, user); 6715 6716 // Scan the children 6717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6718 for (int i = 0; i < childCount; i++) { 6719 PackageParser.Package childPackage = pkg.childPackages.get(i); 6720 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6721 currentTime, user); 6722 } 6723 6724 6725 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6726 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6727 } 6728 6729 return scannedPkg; 6730 } 6731 6732 /** 6733 * Scans a package and returns the newly parsed package. 6734 * @throws PackageManagerException on a parse error. 6735 */ 6736 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6737 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6738 throws PackageManagerException { 6739 PackageSetting ps = null; 6740 PackageSetting updatedPkg; 6741 // reader 6742 synchronized (mPackages) { 6743 // Look to see if we already know about this package. 6744 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6745 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6746 // This package has been renamed to its original name. Let's 6747 // use that. 6748 ps = mSettings.peekPackageLPr(oldName); 6749 } 6750 // If there was no original package, see one for the real package name. 6751 if (ps == null) { 6752 ps = mSettings.peekPackageLPr(pkg.packageName); 6753 } 6754 // Check to see if this package could be hiding/updating a system 6755 // package. Must look for it either under the original or real 6756 // package name depending on our state. 6757 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6758 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6759 6760 // If this is a package we don't know about on the system partition, we 6761 // may need to remove disabled child packages on the system partition 6762 // or may need to not add child packages if the parent apk is updated 6763 // on the data partition and no longer defines this child package. 6764 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6765 // If this is a parent package for an updated system app and this system 6766 // app got an OTA update which no longer defines some of the child packages 6767 // we have to prune them from the disabled system packages. 6768 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6769 if (disabledPs != null) { 6770 final int scannedChildCount = (pkg.childPackages != null) 6771 ? pkg.childPackages.size() : 0; 6772 final int disabledChildCount = disabledPs.childPackageNames != null 6773 ? disabledPs.childPackageNames.size() : 0; 6774 for (int i = 0; i < disabledChildCount; i++) { 6775 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6776 boolean disabledPackageAvailable = false; 6777 for (int j = 0; j < scannedChildCount; j++) { 6778 PackageParser.Package childPkg = pkg.childPackages.get(j); 6779 if (childPkg.packageName.equals(disabledChildPackageName)) { 6780 disabledPackageAvailable = true; 6781 break; 6782 } 6783 } 6784 if (!disabledPackageAvailable) { 6785 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6786 } 6787 } 6788 } 6789 } 6790 } 6791 6792 boolean updatedPkgBetter = false; 6793 // First check if this is a system package that may involve an update 6794 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6795 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6796 // it needs to drop FLAG_PRIVILEGED. 6797 if (locationIsPrivileged(scanFile)) { 6798 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6799 } else { 6800 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6801 } 6802 6803 if (ps != null && !ps.codePath.equals(scanFile)) { 6804 // The path has changed from what was last scanned... check the 6805 // version of the new path against what we have stored to determine 6806 // what to do. 6807 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6808 if (pkg.mVersionCode <= ps.versionCode) { 6809 // The system package has been updated and the code path does not match 6810 // Ignore entry. Skip it. 6811 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6812 + " ignored: updated version " + ps.versionCode 6813 + " better than this " + pkg.mVersionCode); 6814 if (!updatedPkg.codePath.equals(scanFile)) { 6815 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6816 + ps.name + " changing from " + updatedPkg.codePathString 6817 + " to " + scanFile); 6818 updatedPkg.codePath = scanFile; 6819 updatedPkg.codePathString = scanFile.toString(); 6820 updatedPkg.resourcePath = scanFile; 6821 updatedPkg.resourcePathString = scanFile.toString(); 6822 } 6823 updatedPkg.pkg = pkg; 6824 updatedPkg.versionCode = pkg.mVersionCode; 6825 6826 // Update the disabled system child packages to point to the package too. 6827 final int childCount = updatedPkg.childPackageNames != null 6828 ? updatedPkg.childPackageNames.size() : 0; 6829 for (int i = 0; i < childCount; i++) { 6830 String childPackageName = updatedPkg.childPackageNames.get(i); 6831 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6832 childPackageName); 6833 if (updatedChildPkg != null) { 6834 updatedChildPkg.pkg = pkg; 6835 updatedChildPkg.versionCode = pkg.mVersionCode; 6836 } 6837 } 6838 6839 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6840 + scanFile + " ignored: updated version " + ps.versionCode 6841 + " better than this " + pkg.mVersionCode); 6842 } else { 6843 // The current app on the system partition is better than 6844 // what we have updated to on the data partition; switch 6845 // back to the system partition version. 6846 // At this point, its safely assumed that package installation for 6847 // apps in system partition will go through. If not there won't be a working 6848 // version of the app 6849 // writer 6850 synchronized (mPackages) { 6851 // Just remove the loaded entries from package lists. 6852 mPackages.remove(ps.name); 6853 } 6854 6855 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6856 + " reverting from " + ps.codePathString 6857 + ": new version " + pkg.mVersionCode 6858 + " better than installed " + ps.versionCode); 6859 6860 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6861 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6862 synchronized (mInstallLock) { 6863 args.cleanUpResourcesLI(); 6864 } 6865 synchronized (mPackages) { 6866 mSettings.enableSystemPackageLPw(ps.name); 6867 } 6868 updatedPkgBetter = true; 6869 } 6870 } 6871 } 6872 6873 if (updatedPkg != null) { 6874 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6875 // initially 6876 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6877 6878 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6879 // flag set initially 6880 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6881 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6882 } 6883 } 6884 6885 // Verify certificates against what was last scanned 6886 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6887 6888 /* 6889 * A new system app appeared, but we already had a non-system one of the 6890 * same name installed earlier. 6891 */ 6892 boolean shouldHideSystemApp = false; 6893 if (updatedPkg == null && ps != null 6894 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6895 /* 6896 * Check to make sure the signatures match first. If they don't, 6897 * wipe the installed application and its data. 6898 */ 6899 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6900 != PackageManager.SIGNATURE_MATCH) { 6901 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6902 + " signatures don't match existing userdata copy; removing"); 6903 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6904 "scanPackageInternalLI")) { 6905 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6906 } 6907 ps = null; 6908 } else { 6909 /* 6910 * If the newly-added system app is an older version than the 6911 * already installed version, hide it. It will be scanned later 6912 * and re-added like an update. 6913 */ 6914 if (pkg.mVersionCode <= ps.versionCode) { 6915 shouldHideSystemApp = true; 6916 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6917 + " but new version " + pkg.mVersionCode + " better than installed " 6918 + ps.versionCode + "; hiding system"); 6919 } else { 6920 /* 6921 * The newly found system app is a newer version that the 6922 * one previously installed. Simply remove the 6923 * already-installed application and replace it with our own 6924 * while keeping the application data. 6925 */ 6926 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6927 + " reverting from " + ps.codePathString + ": new version " 6928 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6929 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6930 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6931 synchronized (mInstallLock) { 6932 args.cleanUpResourcesLI(); 6933 } 6934 } 6935 } 6936 } 6937 6938 // The apk is forward locked (not public) if its code and resources 6939 // are kept in different files. (except for app in either system or 6940 // vendor path). 6941 // TODO grab this value from PackageSettings 6942 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6943 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6944 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6945 } 6946 } 6947 6948 // TODO: extend to support forward-locked splits 6949 String resourcePath = null; 6950 String baseResourcePath = null; 6951 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6952 if (ps != null && ps.resourcePathString != null) { 6953 resourcePath = ps.resourcePathString; 6954 baseResourcePath = ps.resourcePathString; 6955 } else { 6956 // Should not happen at all. Just log an error. 6957 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6958 } 6959 } else { 6960 resourcePath = pkg.codePath; 6961 baseResourcePath = pkg.baseCodePath; 6962 } 6963 6964 // Set application objects path explicitly. 6965 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6966 pkg.setApplicationInfoCodePath(pkg.codePath); 6967 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6968 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6969 pkg.setApplicationInfoResourcePath(resourcePath); 6970 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6971 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6972 6973 // Note that we invoke the following method only if we are about to unpack an application 6974 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6975 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6976 6977 /* 6978 * If the system app should be overridden by a previously installed 6979 * data, hide the system app now and let the /data/app scan pick it up 6980 * again. 6981 */ 6982 if (shouldHideSystemApp) { 6983 synchronized (mPackages) { 6984 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6985 } 6986 } 6987 6988 return scannedPkg; 6989 } 6990 6991 private static String fixProcessName(String defProcessName, 6992 String processName, int uid) { 6993 if (processName == null) { 6994 return defProcessName; 6995 } 6996 return processName; 6997 } 6998 6999 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7000 throws PackageManagerException { 7001 if (pkgSetting.signatures.mSignatures != null) { 7002 // Already existing package. Make sure signatures match 7003 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7004 == PackageManager.SIGNATURE_MATCH; 7005 if (!match) { 7006 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7007 == PackageManager.SIGNATURE_MATCH; 7008 } 7009 if (!match) { 7010 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7011 == PackageManager.SIGNATURE_MATCH; 7012 } 7013 if (!match) { 7014 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7015 + pkg.packageName + " signatures do not match the " 7016 + "previously installed version; ignoring!"); 7017 } 7018 } 7019 7020 // Check for shared user signatures 7021 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7022 // Already existing package. Make sure signatures match 7023 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7024 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7025 if (!match) { 7026 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7027 == PackageManager.SIGNATURE_MATCH; 7028 } 7029 if (!match) { 7030 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7031 == PackageManager.SIGNATURE_MATCH; 7032 } 7033 if (!match) { 7034 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7035 "Package " + pkg.packageName 7036 + " has no signatures that match those in shared user " 7037 + pkgSetting.sharedUser.name + "; ignoring!"); 7038 } 7039 } 7040 } 7041 7042 /** 7043 * Enforces that only the system UID or root's UID can call a method exposed 7044 * via Binder. 7045 * 7046 * @param message used as message if SecurityException is thrown 7047 * @throws SecurityException if the caller is not system or root 7048 */ 7049 private static final void enforceSystemOrRoot(String message) { 7050 final int uid = Binder.getCallingUid(); 7051 if (uid != Process.SYSTEM_UID && uid != 0) { 7052 throw new SecurityException(message); 7053 } 7054 } 7055 7056 @Override 7057 public void performFstrimIfNeeded() { 7058 enforceSystemOrRoot("Only the system can request fstrim"); 7059 7060 // Before everything else, see whether we need to fstrim. 7061 try { 7062 IMountService ms = PackageHelper.getMountService(); 7063 if (ms != null) { 7064 boolean doTrim = false; 7065 final long interval = android.provider.Settings.Global.getLong( 7066 mContext.getContentResolver(), 7067 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7068 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7069 if (interval > 0) { 7070 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7071 if (timeSinceLast > interval) { 7072 doTrim = true; 7073 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7074 + "; running immediately"); 7075 } 7076 } 7077 if (doTrim) { 7078 if (!isFirstBoot()) { 7079 try { 7080 ActivityManagerNative.getDefault().showBootMessage( 7081 mContext.getResources().getString( 7082 R.string.android_upgrading_fstrim), true); 7083 } catch (RemoteException e) { 7084 } 7085 } 7086 ms.runMaintenance(); 7087 } 7088 } else { 7089 Slog.e(TAG, "Mount service unavailable!"); 7090 } 7091 } catch (RemoteException e) { 7092 // Can't happen; MountService is local 7093 } 7094 } 7095 7096 @Override 7097 public void updatePackagesIfNeeded() { 7098 enforceSystemOrRoot("Only the system can request package update"); 7099 7100 // We need to re-extract after an OTA. 7101 boolean causeUpgrade = isUpgrade(); 7102 7103 // First boot or factory reset. 7104 // Note: we also handle devices that are upgrading to N right now as if it is their 7105 // first boot, as they do not have profile data. 7106 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7107 7108 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7109 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7110 7111 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7112 return; 7113 } 7114 7115 List<PackageParser.Package> pkgs; 7116 synchronized (mPackages) { 7117 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7118 } 7119 7120 final long startTime = System.nanoTime(); 7121 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7122 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7123 7124 final int elapsedTimeSeconds = 7125 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7126 7127 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7128 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7129 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7130 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7131 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7132 } 7133 7134 /** 7135 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7136 * containing statistics about the invocation. The array consists of three elements, 7137 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7138 * and {@code numberOfPackagesFailed}. 7139 */ 7140 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7141 String compilerFilter) { 7142 7143 int numberOfPackagesVisited = 0; 7144 int numberOfPackagesOptimized = 0; 7145 int numberOfPackagesSkipped = 0; 7146 int numberOfPackagesFailed = 0; 7147 final int numberOfPackagesToDexopt = pkgs.size(); 7148 7149 for (PackageParser.Package pkg : pkgs) { 7150 numberOfPackagesVisited++; 7151 7152 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7153 if (DEBUG_DEXOPT) { 7154 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7155 } 7156 numberOfPackagesSkipped++; 7157 continue; 7158 } 7159 7160 if (DEBUG_DEXOPT) { 7161 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7162 numberOfPackagesToDexopt + ": " + pkg.packageName); 7163 } 7164 7165 if (showDialog) { 7166 try { 7167 ActivityManagerNative.getDefault().showBootMessage( 7168 mContext.getResources().getString(R.string.android_upgrading_apk, 7169 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7170 } catch (RemoteException e) { 7171 } 7172 } 7173 7174 // If the OTA updates a system app which was previously preopted to a non-preopted state 7175 // the app might end up being verified at runtime. That's because by default the apps 7176 // are verify-profile but for preopted apps there's no profile. 7177 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7178 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7179 // filter (by default interpret-only). 7180 // Note that at this stage unused apps are already filtered. 7181 if (isSystemApp(pkg) && 7182 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7183 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7184 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7185 } 7186 7187 // checkProfiles is false to avoid merging profiles during boot which 7188 // might interfere with background compilation (b/28612421). 7189 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7190 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7191 // trade-off worth doing to save boot time work. 7192 int dexOptStatus = performDexOptTraced(pkg.packageName, 7193 false /* checkProfiles */, 7194 compilerFilter, 7195 false /* force */); 7196 switch (dexOptStatus) { 7197 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7198 numberOfPackagesOptimized++; 7199 break; 7200 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7201 numberOfPackagesSkipped++; 7202 break; 7203 case PackageDexOptimizer.DEX_OPT_FAILED: 7204 numberOfPackagesFailed++; 7205 break; 7206 default: 7207 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7208 break; 7209 } 7210 } 7211 7212 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7213 numberOfPackagesFailed }; 7214 } 7215 7216 @Override 7217 public void notifyPackageUse(String packageName, int reason) { 7218 synchronized (mPackages) { 7219 PackageParser.Package p = mPackages.get(packageName); 7220 if (p == null) { 7221 return; 7222 } 7223 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7224 } 7225 } 7226 7227 // TODO: this is not used nor needed. Delete it. 7228 @Override 7229 public boolean performDexOptIfNeeded(String packageName) { 7230 int dexOptStatus = performDexOptTraced(packageName, 7231 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7232 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7233 } 7234 7235 @Override 7236 public boolean performDexOpt(String packageName, 7237 boolean checkProfiles, int compileReason, boolean force) { 7238 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7239 getCompilerFilterForReason(compileReason), force); 7240 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7241 } 7242 7243 @Override 7244 public boolean performDexOptMode(String packageName, 7245 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7246 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7247 targetCompilerFilter, force); 7248 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7249 } 7250 7251 private int performDexOptTraced(String packageName, 7252 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7253 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7254 try { 7255 return performDexOptInternal(packageName, checkProfiles, 7256 targetCompilerFilter, force); 7257 } finally { 7258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7259 } 7260 } 7261 7262 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7263 // if the package can now be considered up to date for the given filter. 7264 private int performDexOptInternal(String packageName, 7265 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7266 PackageParser.Package p; 7267 synchronized (mPackages) { 7268 p = mPackages.get(packageName); 7269 if (p == null) { 7270 // Package could not be found. Report failure. 7271 return PackageDexOptimizer.DEX_OPT_FAILED; 7272 } 7273 mPackageUsage.maybeWriteAsync(mPackages); 7274 mCompilerStats.maybeWriteAsync(); 7275 } 7276 long callingId = Binder.clearCallingIdentity(); 7277 try { 7278 synchronized (mInstallLock) { 7279 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7280 targetCompilerFilter, force); 7281 } 7282 } finally { 7283 Binder.restoreCallingIdentity(callingId); 7284 } 7285 } 7286 7287 public ArraySet<String> getOptimizablePackages() { 7288 ArraySet<String> pkgs = new ArraySet<String>(); 7289 synchronized (mPackages) { 7290 for (PackageParser.Package p : mPackages.values()) { 7291 if (PackageDexOptimizer.canOptimizePackage(p)) { 7292 pkgs.add(p.packageName); 7293 } 7294 } 7295 } 7296 return pkgs; 7297 } 7298 7299 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7300 boolean checkProfiles, String targetCompilerFilter, 7301 boolean force) { 7302 // Select the dex optimizer based on the force parameter. 7303 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7304 // allocate an object here. 7305 PackageDexOptimizer pdo = force 7306 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7307 : mPackageDexOptimizer; 7308 7309 // Optimize all dependencies first. Note: we ignore the return value and march on 7310 // on errors. 7311 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7312 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7313 if (!deps.isEmpty()) { 7314 for (PackageParser.Package depPackage : deps) { 7315 // TODO: Analyze and investigate if we (should) profile libraries. 7316 // Currently this will do a full compilation of the library by default. 7317 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7318 false /* checkProfiles */, 7319 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7320 getOrCreateCompilerPackageStats(depPackage)); 7321 } 7322 } 7323 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7324 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7325 } 7326 7327 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7328 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7329 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7330 Set<String> collectedNames = new HashSet<>(); 7331 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7332 7333 retValue.remove(p); 7334 7335 return retValue; 7336 } else { 7337 return Collections.emptyList(); 7338 } 7339 } 7340 7341 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7342 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7343 if (!collectedNames.contains(p.packageName)) { 7344 collectedNames.add(p.packageName); 7345 collected.add(p); 7346 7347 if (p.usesLibraries != null) { 7348 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7349 } 7350 if (p.usesOptionalLibraries != null) { 7351 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7352 collectedNames); 7353 } 7354 } 7355 } 7356 7357 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7358 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7359 for (String libName : libs) { 7360 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7361 if (libPkg != null) { 7362 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7363 } 7364 } 7365 } 7366 7367 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7368 synchronized (mPackages) { 7369 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7370 if (lib != null && lib.apk != null) { 7371 return mPackages.get(lib.apk); 7372 } 7373 } 7374 return null; 7375 } 7376 7377 public void shutdown() { 7378 mPackageUsage.writeNow(mPackages); 7379 mCompilerStats.writeNow(); 7380 } 7381 7382 @Override 7383 public void dumpProfiles(String packageName) { 7384 PackageParser.Package pkg; 7385 synchronized (mPackages) { 7386 pkg = mPackages.get(packageName); 7387 if (pkg == null) { 7388 throw new IllegalArgumentException("Unknown package: " + packageName); 7389 } 7390 } 7391 /* Only the shell, root, or the app user should be able to dump profiles. */ 7392 int callingUid = Binder.getCallingUid(); 7393 if (callingUid != Process.SHELL_UID && 7394 callingUid != Process.ROOT_UID && 7395 callingUid != pkg.applicationInfo.uid) { 7396 throw new SecurityException("dumpProfiles"); 7397 } 7398 7399 synchronized (mInstallLock) { 7400 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7401 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7402 try { 7403 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7404 String gid = Integer.toString(sharedGid); 7405 String codePaths = TextUtils.join(";", allCodePaths); 7406 mInstaller.dumpProfiles(gid, packageName, codePaths); 7407 } catch (InstallerException e) { 7408 Slog.w(TAG, "Failed to dump profiles", e); 7409 } 7410 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7411 } 7412 } 7413 7414 @Override 7415 public void forceDexOpt(String packageName) { 7416 enforceSystemOrRoot("forceDexOpt"); 7417 7418 PackageParser.Package pkg; 7419 synchronized (mPackages) { 7420 pkg = mPackages.get(packageName); 7421 if (pkg == null) { 7422 throw new IllegalArgumentException("Unknown package: " + packageName); 7423 } 7424 } 7425 7426 synchronized (mInstallLock) { 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7428 7429 // Whoever is calling forceDexOpt wants a fully compiled package. 7430 // Don't use profiles since that may cause compilation to be skipped. 7431 final int res = performDexOptInternalWithDependenciesLI(pkg, 7432 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7433 true /* force */); 7434 7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7436 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7437 throw new IllegalStateException("Failed to dexopt: " + res); 7438 } 7439 } 7440 } 7441 7442 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7443 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7444 Slog.w(TAG, "Unable to update from " + oldPkg.name 7445 + " to " + newPkg.packageName 7446 + ": old package not in system partition"); 7447 return false; 7448 } else if (mPackages.get(oldPkg.name) != null) { 7449 Slog.w(TAG, "Unable to update from " + oldPkg.name 7450 + " to " + newPkg.packageName 7451 + ": old package still exists"); 7452 return false; 7453 } 7454 return true; 7455 } 7456 7457 void removeCodePathLI(File codePath) { 7458 if (codePath.isDirectory()) { 7459 try { 7460 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7461 } catch (InstallerException e) { 7462 Slog.w(TAG, "Failed to remove code path", e); 7463 } 7464 } else { 7465 codePath.delete(); 7466 } 7467 } 7468 7469 private int[] resolveUserIds(int userId) { 7470 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7471 } 7472 7473 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7474 if (pkg == null) { 7475 Slog.wtf(TAG, "Package was null!", new Throwable()); 7476 return; 7477 } 7478 clearAppDataLeafLIF(pkg, userId, flags); 7479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7480 for (int i = 0; i < childCount; i++) { 7481 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7482 } 7483 } 7484 7485 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7486 final PackageSetting ps; 7487 synchronized (mPackages) { 7488 ps = mSettings.mPackages.get(pkg.packageName); 7489 } 7490 for (int realUserId : resolveUserIds(userId)) { 7491 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7492 try { 7493 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7494 ceDataInode); 7495 } catch (InstallerException e) { 7496 Slog.w(TAG, String.valueOf(e)); 7497 } 7498 } 7499 } 7500 7501 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7502 if (pkg == null) { 7503 Slog.wtf(TAG, "Package was null!", new Throwable()); 7504 return; 7505 } 7506 destroyAppDataLeafLIF(pkg, userId, flags); 7507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7508 for (int i = 0; i < childCount; i++) { 7509 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7510 } 7511 } 7512 7513 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7514 final PackageSetting ps; 7515 synchronized (mPackages) { 7516 ps = mSettings.mPackages.get(pkg.packageName); 7517 } 7518 for (int realUserId : resolveUserIds(userId)) { 7519 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7520 try { 7521 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7522 ceDataInode); 7523 } catch (InstallerException e) { 7524 Slog.w(TAG, String.valueOf(e)); 7525 } 7526 } 7527 } 7528 7529 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7530 if (pkg == null) { 7531 Slog.wtf(TAG, "Package was null!", new Throwable()); 7532 return; 7533 } 7534 destroyAppProfilesLeafLIF(pkg); 7535 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7537 for (int i = 0; i < childCount; i++) { 7538 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7539 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7540 true /* removeBaseMarker */); 7541 } 7542 } 7543 7544 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7545 boolean removeBaseMarker) { 7546 if (pkg.isForwardLocked()) { 7547 return; 7548 } 7549 7550 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7551 try { 7552 path = PackageManagerServiceUtils.realpath(new File(path)); 7553 } catch (IOException e) { 7554 // TODO: Should we return early here ? 7555 Slog.w(TAG, "Failed to get canonical path", e); 7556 continue; 7557 } 7558 7559 final String useMarker = path.replace('/', '@'); 7560 for (int realUserId : resolveUserIds(userId)) { 7561 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7562 if (removeBaseMarker) { 7563 File foreignUseMark = new File(profileDir, useMarker); 7564 if (foreignUseMark.exists()) { 7565 if (!foreignUseMark.delete()) { 7566 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7567 + pkg.packageName); 7568 } 7569 } 7570 } 7571 7572 File[] markers = profileDir.listFiles(); 7573 if (markers != null) { 7574 final String searchString = "@" + pkg.packageName + "@"; 7575 // We also delete all markers that contain the package name we're 7576 // uninstalling. These are associated with secondary dex-files belonging 7577 // to the package. Reconstructing the path of these dex files is messy 7578 // in general. 7579 for (File marker : markers) { 7580 if (marker.getName().indexOf(searchString) > 0) { 7581 if (!marker.delete()) { 7582 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7583 + pkg.packageName); 7584 } 7585 } 7586 } 7587 } 7588 } 7589 } 7590 } 7591 7592 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7593 try { 7594 mInstaller.destroyAppProfiles(pkg.packageName); 7595 } catch (InstallerException e) { 7596 Slog.w(TAG, String.valueOf(e)); 7597 } 7598 } 7599 7600 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7601 if (pkg == null) { 7602 Slog.wtf(TAG, "Package was null!", new Throwable()); 7603 return; 7604 } 7605 clearAppProfilesLeafLIF(pkg); 7606 // We don't remove the base foreign use marker when clearing profiles because 7607 // we will rename it when the app is updated. Unlike the actual profile contents, 7608 // the foreign use marker is good across installs. 7609 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7611 for (int i = 0; i < childCount; i++) { 7612 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7613 } 7614 } 7615 7616 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7617 try { 7618 mInstaller.clearAppProfiles(pkg.packageName); 7619 } catch (InstallerException e) { 7620 Slog.w(TAG, String.valueOf(e)); 7621 } 7622 } 7623 7624 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7625 long lastUpdateTime) { 7626 // Set parent install/update time 7627 PackageSetting ps = (PackageSetting) pkg.mExtras; 7628 if (ps != null) { 7629 ps.firstInstallTime = firstInstallTime; 7630 ps.lastUpdateTime = lastUpdateTime; 7631 } 7632 // Set children install/update time 7633 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7634 for (int i = 0; i < childCount; i++) { 7635 PackageParser.Package childPkg = pkg.childPackages.get(i); 7636 ps = (PackageSetting) childPkg.mExtras; 7637 if (ps != null) { 7638 ps.firstInstallTime = firstInstallTime; 7639 ps.lastUpdateTime = lastUpdateTime; 7640 } 7641 } 7642 } 7643 7644 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7645 PackageParser.Package changingLib) { 7646 if (file.path != null) { 7647 usesLibraryFiles.add(file.path); 7648 return; 7649 } 7650 PackageParser.Package p = mPackages.get(file.apk); 7651 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7652 // If we are doing this while in the middle of updating a library apk, 7653 // then we need to make sure to use that new apk for determining the 7654 // dependencies here. (We haven't yet finished committing the new apk 7655 // to the package manager state.) 7656 if (p == null || p.packageName.equals(changingLib.packageName)) { 7657 p = changingLib; 7658 } 7659 } 7660 if (p != null) { 7661 usesLibraryFiles.addAll(p.getAllCodePaths()); 7662 } 7663 } 7664 7665 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7666 PackageParser.Package changingLib) throws PackageManagerException { 7667 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7668 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7669 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7670 for (int i=0; i<N; i++) { 7671 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7672 if (file == null) { 7673 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7674 "Package " + pkg.packageName + " requires unavailable shared library " 7675 + pkg.usesLibraries.get(i) + "; failing!"); 7676 } 7677 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7678 } 7679 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7680 for (int i=0; i<N; i++) { 7681 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7682 if (file == null) { 7683 Slog.w(TAG, "Package " + pkg.packageName 7684 + " desires unavailable shared library " 7685 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7686 } else { 7687 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7688 } 7689 } 7690 N = usesLibraryFiles.size(); 7691 if (N > 0) { 7692 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7693 } else { 7694 pkg.usesLibraryFiles = null; 7695 } 7696 } 7697 } 7698 7699 private static boolean hasString(List<String> list, List<String> which) { 7700 if (list == null) { 7701 return false; 7702 } 7703 for (int i=list.size()-1; i>=0; i--) { 7704 for (int j=which.size()-1; j>=0; j--) { 7705 if (which.get(j).equals(list.get(i))) { 7706 return true; 7707 } 7708 } 7709 } 7710 return false; 7711 } 7712 7713 private void updateAllSharedLibrariesLPw() { 7714 for (PackageParser.Package pkg : mPackages.values()) { 7715 try { 7716 updateSharedLibrariesLPw(pkg, null); 7717 } catch (PackageManagerException e) { 7718 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7719 } 7720 } 7721 } 7722 7723 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7724 PackageParser.Package changingPkg) { 7725 ArrayList<PackageParser.Package> res = null; 7726 for (PackageParser.Package pkg : mPackages.values()) { 7727 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7728 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7729 if (res == null) { 7730 res = new ArrayList<PackageParser.Package>(); 7731 } 7732 res.add(pkg); 7733 try { 7734 updateSharedLibrariesLPw(pkg, changingPkg); 7735 } catch (PackageManagerException e) { 7736 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7737 } 7738 } 7739 } 7740 return res; 7741 } 7742 7743 /** 7744 * Derive the value of the {@code cpuAbiOverride} based on the provided 7745 * value and an optional stored value from the package settings. 7746 */ 7747 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7748 String cpuAbiOverride = null; 7749 7750 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7751 cpuAbiOverride = null; 7752 } else if (abiOverride != null) { 7753 cpuAbiOverride = abiOverride; 7754 } else if (settings != null) { 7755 cpuAbiOverride = settings.cpuAbiOverrideString; 7756 } 7757 7758 return cpuAbiOverride; 7759 } 7760 7761 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7762 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7763 throws PackageManagerException { 7764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7765 // If the package has children and this is the first dive in the function 7766 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7767 // whether all packages (parent and children) would be successfully scanned 7768 // before the actual scan since scanning mutates internal state and we want 7769 // to atomically install the package and its children. 7770 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7771 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7772 scanFlags |= SCAN_CHECK_ONLY; 7773 } 7774 } else { 7775 scanFlags &= ~SCAN_CHECK_ONLY; 7776 } 7777 7778 final PackageParser.Package scannedPkg; 7779 try { 7780 // Scan the parent 7781 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7782 // Scan the children 7783 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7784 for (int i = 0; i < childCount; i++) { 7785 PackageParser.Package childPkg = pkg.childPackages.get(i); 7786 scanPackageLI(childPkg, policyFlags, 7787 scanFlags, currentTime, user); 7788 } 7789 } finally { 7790 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7791 } 7792 7793 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7794 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7795 } 7796 7797 return scannedPkg; 7798 } 7799 7800 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7801 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7802 boolean success = false; 7803 try { 7804 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7805 currentTime, user); 7806 success = true; 7807 return res; 7808 } finally { 7809 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7810 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7811 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7812 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7813 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7814 } 7815 } 7816 } 7817 7818 /** 7819 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7820 */ 7821 private static boolean apkHasCode(String fileName) { 7822 StrictJarFile jarFile = null; 7823 try { 7824 jarFile = new StrictJarFile(fileName, 7825 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7826 return jarFile.findEntry("classes.dex") != null; 7827 } catch (IOException ignore) { 7828 } finally { 7829 try { 7830 if (jarFile != null) { 7831 jarFile.close(); 7832 } 7833 } catch (IOException ignore) {} 7834 } 7835 return false; 7836 } 7837 7838 /** 7839 * Enforces code policy for the package. This ensures that if an APK has 7840 * declared hasCode="true" in its manifest that the APK actually contains 7841 * code. 7842 * 7843 * @throws PackageManagerException If bytecode could not be found when it should exist 7844 */ 7845 private static void enforceCodePolicy(PackageParser.Package pkg) 7846 throws PackageManagerException { 7847 final boolean shouldHaveCode = 7848 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7849 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7850 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7851 "Package " + pkg.baseCodePath + " code is missing"); 7852 } 7853 7854 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7855 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7856 final boolean splitShouldHaveCode = 7857 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7858 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7859 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7860 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7861 } 7862 } 7863 } 7864 } 7865 7866 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7867 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7868 throws PackageManagerException { 7869 final File scanFile = new File(pkg.codePath); 7870 if (pkg.applicationInfo.getCodePath() == null || 7871 pkg.applicationInfo.getResourcePath() == null) { 7872 // Bail out. The resource and code paths haven't been set. 7873 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7874 "Code and resource paths haven't been set correctly"); 7875 } 7876 7877 // Apply policy 7878 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7879 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7880 if (pkg.applicationInfo.isDirectBootAware()) { 7881 // we're direct boot aware; set for all components 7882 for (PackageParser.Service s : pkg.services) { 7883 s.info.encryptionAware = s.info.directBootAware = true; 7884 } 7885 for (PackageParser.Provider p : pkg.providers) { 7886 p.info.encryptionAware = p.info.directBootAware = true; 7887 } 7888 for (PackageParser.Activity a : pkg.activities) { 7889 a.info.encryptionAware = a.info.directBootAware = true; 7890 } 7891 for (PackageParser.Activity r : pkg.receivers) { 7892 r.info.encryptionAware = r.info.directBootAware = true; 7893 } 7894 } 7895 } else { 7896 // Only allow system apps to be flagged as core apps. 7897 pkg.coreApp = false; 7898 // clear flags not applicable to regular apps 7899 pkg.applicationInfo.privateFlags &= 7900 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7901 pkg.applicationInfo.privateFlags &= 7902 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7903 } 7904 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7905 7906 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7907 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7908 } 7909 7910 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7911 enforceCodePolicy(pkg); 7912 } 7913 7914 if (mCustomResolverComponentName != null && 7915 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7916 setUpCustomResolverActivity(pkg); 7917 } 7918 7919 if (pkg.packageName.equals("android")) { 7920 synchronized (mPackages) { 7921 if (mAndroidApplication != null) { 7922 Slog.w(TAG, "*************************************************"); 7923 Slog.w(TAG, "Core android package being redefined. Skipping."); 7924 Slog.w(TAG, " file=" + scanFile); 7925 Slog.w(TAG, "*************************************************"); 7926 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7927 "Core android package being redefined. Skipping."); 7928 } 7929 7930 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7931 // Set up information for our fall-back user intent resolution activity. 7932 mPlatformPackage = pkg; 7933 pkg.mVersionCode = mSdkVersion; 7934 mAndroidApplication = pkg.applicationInfo; 7935 7936 if (!mResolverReplaced) { 7937 mResolveActivity.applicationInfo = mAndroidApplication; 7938 mResolveActivity.name = ResolverActivity.class.getName(); 7939 mResolveActivity.packageName = mAndroidApplication.packageName; 7940 mResolveActivity.processName = "system:ui"; 7941 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7942 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7943 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7944 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7945 mResolveActivity.exported = true; 7946 mResolveActivity.enabled = true; 7947 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7948 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7949 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7950 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7951 | ActivityInfo.CONFIG_ORIENTATION 7952 | ActivityInfo.CONFIG_KEYBOARD 7953 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7954 mResolveInfo.activityInfo = mResolveActivity; 7955 mResolveInfo.priority = 0; 7956 mResolveInfo.preferredOrder = 0; 7957 mResolveInfo.match = 0; 7958 mResolveComponentName = new ComponentName( 7959 mAndroidApplication.packageName, mResolveActivity.name); 7960 } 7961 } 7962 } 7963 } 7964 7965 if (DEBUG_PACKAGE_SCANNING) { 7966 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7967 Log.d(TAG, "Scanning package " + pkg.packageName); 7968 } 7969 7970 synchronized (mPackages) { 7971 if (mPackages.containsKey(pkg.packageName) 7972 || mSharedLibraries.containsKey(pkg.packageName)) { 7973 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7974 "Application package " + pkg.packageName 7975 + " already installed. Skipping duplicate."); 7976 } 7977 7978 // If we're only installing presumed-existing packages, require that the 7979 // scanned APK is both already known and at the path previously established 7980 // for it. Previously unknown packages we pick up normally, but if we have an 7981 // a priori expectation about this package's install presence, enforce it. 7982 // With a singular exception for new system packages. When an OTA contains 7983 // a new system package, we allow the codepath to change from a system location 7984 // to the user-installed location. If we don't allow this change, any newer, 7985 // user-installed version of the application will be ignored. 7986 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7987 if (mExpectingBetter.containsKey(pkg.packageName)) { 7988 logCriticalInfo(Log.WARN, 7989 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7990 } else { 7991 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7992 if (known != null) { 7993 if (DEBUG_PACKAGE_SCANNING) { 7994 Log.d(TAG, "Examining " + pkg.codePath 7995 + " and requiring known paths " + known.codePathString 7996 + " & " + known.resourcePathString); 7997 } 7998 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7999 || !pkg.applicationInfo.getResourcePath().equals( 8000 known.resourcePathString)) { 8001 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8002 "Application package " + pkg.packageName 8003 + " found at " + pkg.applicationInfo.getCodePath() 8004 + " but expected at " + known.codePathString 8005 + "; ignoring."); 8006 } 8007 } 8008 } 8009 } 8010 } 8011 8012 // Initialize package source and resource directories 8013 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8014 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8015 8016 SharedUserSetting suid = null; 8017 PackageSetting pkgSetting = null; 8018 8019 if (!isSystemApp(pkg)) { 8020 // Only system apps can use these features. 8021 pkg.mOriginalPackages = null; 8022 pkg.mRealPackage = null; 8023 pkg.mAdoptPermissions = null; 8024 } 8025 8026 // Getting the package setting may have a side-effect, so if we 8027 // are only checking if scan would succeed, stash a copy of the 8028 // old setting to restore at the end. 8029 PackageSetting nonMutatedPs = null; 8030 8031 // writer 8032 synchronized (mPackages) { 8033 if (pkg.mSharedUserId != null) { 8034 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8035 if (suid == null) { 8036 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8037 "Creating application package " + pkg.packageName 8038 + " for shared user failed"); 8039 } 8040 if (DEBUG_PACKAGE_SCANNING) { 8041 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8042 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8043 + "): packages=" + suid.packages); 8044 } 8045 } 8046 8047 // Check if we are renaming from an original package name. 8048 PackageSetting origPackage = null; 8049 String realName = null; 8050 if (pkg.mOriginalPackages != null) { 8051 // This package may need to be renamed to a previously 8052 // installed name. Let's check on that... 8053 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8054 if (pkg.mOriginalPackages.contains(renamed)) { 8055 // This package had originally been installed as the 8056 // original name, and we have already taken care of 8057 // transitioning to the new one. Just update the new 8058 // one to continue using the old name. 8059 realName = pkg.mRealPackage; 8060 if (!pkg.packageName.equals(renamed)) { 8061 // Callers into this function may have already taken 8062 // care of renaming the package; only do it here if 8063 // it is not already done. 8064 pkg.setPackageName(renamed); 8065 } 8066 8067 } else { 8068 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8069 if ((origPackage = mSettings.peekPackageLPr( 8070 pkg.mOriginalPackages.get(i))) != null) { 8071 // We do have the package already installed under its 8072 // original name... should we use it? 8073 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8074 // New package is not compatible with original. 8075 origPackage = null; 8076 continue; 8077 } else if (origPackage.sharedUser != null) { 8078 // Make sure uid is compatible between packages. 8079 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8080 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8081 + " to " + pkg.packageName + ": old uid " 8082 + origPackage.sharedUser.name 8083 + " differs from " + pkg.mSharedUserId); 8084 origPackage = null; 8085 continue; 8086 } 8087 // TODO: Add case when shared user id is added [b/28144775] 8088 } else { 8089 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8090 + pkg.packageName + " to old name " + origPackage.name); 8091 } 8092 break; 8093 } 8094 } 8095 } 8096 } 8097 8098 if (mTransferedPackages.contains(pkg.packageName)) { 8099 Slog.w(TAG, "Package " + pkg.packageName 8100 + " was transferred to another, but its .apk remains"); 8101 } 8102 8103 // See comments in nonMutatedPs declaration 8104 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8105 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8106 if (foundPs != null) { 8107 nonMutatedPs = new PackageSetting(foundPs); 8108 } 8109 } 8110 8111 // Just create the setting, don't add it yet. For already existing packages 8112 // the PkgSetting exists already and doesn't have to be created. 8113 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8114 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8115 pkg.applicationInfo.primaryCpuAbi, 8116 pkg.applicationInfo.secondaryCpuAbi, 8117 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8118 user, false); 8119 if (pkgSetting == null) { 8120 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8121 "Creating application package " + pkg.packageName + " failed"); 8122 } 8123 8124 if (pkgSetting.origPackage != null) { 8125 // If we are first transitioning from an original package, 8126 // fix up the new package's name now. We need to do this after 8127 // looking up the package under its new name, so getPackageLP 8128 // can take care of fiddling things correctly. 8129 pkg.setPackageName(origPackage.name); 8130 8131 // File a report about this. 8132 String msg = "New package " + pkgSetting.realName 8133 + " renamed to replace old package " + pkgSetting.name; 8134 reportSettingsProblem(Log.WARN, msg); 8135 8136 // Make a note of it. 8137 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8138 mTransferedPackages.add(origPackage.name); 8139 } 8140 8141 // No longer need to retain this. 8142 pkgSetting.origPackage = null; 8143 } 8144 8145 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8146 // Make a note of it. 8147 mTransferedPackages.add(pkg.packageName); 8148 } 8149 8150 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8151 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8152 } 8153 8154 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8155 // Check all shared libraries and map to their actual file path. 8156 // We only do this here for apps not on a system dir, because those 8157 // are the only ones that can fail an install due to this. We 8158 // will take care of the system apps by updating all of their 8159 // library paths after the scan is done. 8160 updateSharedLibrariesLPw(pkg, null); 8161 } 8162 8163 if (mFoundPolicyFile) { 8164 SELinuxMMAC.assignSeinfoValue(pkg); 8165 } 8166 8167 pkg.applicationInfo.uid = pkgSetting.appId; 8168 pkg.mExtras = pkgSetting; 8169 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8170 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8171 // We just determined the app is signed correctly, so bring 8172 // over the latest parsed certs. 8173 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8174 } else { 8175 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8176 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8177 "Package " + pkg.packageName + " upgrade keys do not match the " 8178 + "previously installed version"); 8179 } else { 8180 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8181 String msg = "System package " + pkg.packageName 8182 + " signature changed; retaining data."; 8183 reportSettingsProblem(Log.WARN, msg); 8184 } 8185 } 8186 } else { 8187 try { 8188 verifySignaturesLP(pkgSetting, pkg); 8189 // We just determined the app is signed correctly, so bring 8190 // over the latest parsed certs. 8191 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8192 } catch (PackageManagerException e) { 8193 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8194 throw e; 8195 } 8196 // The signature has changed, but this package is in the system 8197 // image... let's recover! 8198 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8199 // However... if this package is part of a shared user, but it 8200 // doesn't match the signature of the shared user, let's fail. 8201 // What this means is that you can't change the signatures 8202 // associated with an overall shared user, which doesn't seem all 8203 // that unreasonable. 8204 if (pkgSetting.sharedUser != null) { 8205 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8206 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8207 throw new PackageManagerException( 8208 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8209 "Signature mismatch for shared user: " 8210 + pkgSetting.sharedUser); 8211 } 8212 } 8213 // File a report about this. 8214 String msg = "System package " + pkg.packageName 8215 + " signature changed; retaining data."; 8216 reportSettingsProblem(Log.WARN, msg); 8217 } 8218 } 8219 // Verify that this new package doesn't have any content providers 8220 // that conflict with existing packages. Only do this if the 8221 // package isn't already installed, since we don't want to break 8222 // things that are installed. 8223 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8224 final int N = pkg.providers.size(); 8225 int i; 8226 for (i=0; i<N; i++) { 8227 PackageParser.Provider p = pkg.providers.get(i); 8228 if (p.info.authority != null) { 8229 String names[] = p.info.authority.split(";"); 8230 for (int j = 0; j < names.length; j++) { 8231 if (mProvidersByAuthority.containsKey(names[j])) { 8232 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8233 final String otherPackageName = 8234 ((other != null && other.getComponentName() != null) ? 8235 other.getComponentName().getPackageName() : "?"); 8236 throw new PackageManagerException( 8237 INSTALL_FAILED_CONFLICTING_PROVIDER, 8238 "Can't install because provider name " + names[j] 8239 + " (in package " + pkg.applicationInfo.packageName 8240 + ") is already used by " + otherPackageName); 8241 } 8242 } 8243 } 8244 } 8245 } 8246 8247 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8248 // This package wants to adopt ownership of permissions from 8249 // another package. 8250 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8251 final String origName = pkg.mAdoptPermissions.get(i); 8252 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8253 if (orig != null) { 8254 if (verifyPackageUpdateLPr(orig, pkg)) { 8255 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8256 + pkg.packageName); 8257 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8258 } 8259 } 8260 } 8261 } 8262 } 8263 8264 final String pkgName = pkg.packageName; 8265 8266 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8267 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8268 pkg.applicationInfo.processName = fixProcessName( 8269 pkg.applicationInfo.packageName, 8270 pkg.applicationInfo.processName, 8271 pkg.applicationInfo.uid); 8272 8273 if (pkg != mPlatformPackage) { 8274 // Get all of our default paths setup 8275 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8276 } 8277 8278 final String path = scanFile.getPath(); 8279 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8280 8281 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8282 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8283 8284 // Some system apps still use directory structure for native libraries 8285 // in which case we might end up not detecting abi solely based on apk 8286 // structure. Try to detect abi based on directory structure. 8287 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8288 pkg.applicationInfo.primaryCpuAbi == null) { 8289 setBundledAppAbisAndRoots(pkg, pkgSetting); 8290 setNativeLibraryPaths(pkg); 8291 } 8292 8293 } else { 8294 if ((scanFlags & SCAN_MOVE) != 0) { 8295 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8296 // but we already have this packages package info in the PackageSetting. We just 8297 // use that and derive the native library path based on the new codepath. 8298 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8299 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8300 } 8301 8302 // Set native library paths again. For moves, the path will be updated based on the 8303 // ABIs we've determined above. For non-moves, the path will be updated based on the 8304 // ABIs we determined during compilation, but the path will depend on the final 8305 // package path (after the rename away from the stage path). 8306 setNativeLibraryPaths(pkg); 8307 } 8308 8309 // This is a special case for the "system" package, where the ABI is 8310 // dictated by the zygote configuration (and init.rc). We should keep track 8311 // of this ABI so that we can deal with "normal" applications that run under 8312 // the same UID correctly. 8313 if (mPlatformPackage == pkg) { 8314 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8315 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8316 } 8317 8318 // If there's a mismatch between the abi-override in the package setting 8319 // and the abiOverride specified for the install. Warn about this because we 8320 // would've already compiled the app without taking the package setting into 8321 // account. 8322 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8323 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8324 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8325 " for package " + pkg.packageName); 8326 } 8327 } 8328 8329 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8330 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8331 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8332 8333 // Copy the derived override back to the parsed package, so that we can 8334 // update the package settings accordingly. 8335 pkg.cpuAbiOverride = cpuAbiOverride; 8336 8337 if (DEBUG_ABI_SELECTION) { 8338 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8339 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8340 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8341 } 8342 8343 // Push the derived path down into PackageSettings so we know what to 8344 // clean up at uninstall time. 8345 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8346 8347 if (DEBUG_ABI_SELECTION) { 8348 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8349 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8350 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8351 } 8352 8353 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8354 // We don't do this here during boot because we can do it all 8355 // at once after scanning all existing packages. 8356 // 8357 // We also do this *before* we perform dexopt on this package, so that 8358 // we can avoid redundant dexopts, and also to make sure we've got the 8359 // code and package path correct. 8360 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8361 pkg, true /* boot complete */); 8362 } 8363 8364 if (mFactoryTest && pkg.requestedPermissions.contains( 8365 android.Manifest.permission.FACTORY_TEST)) { 8366 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8367 } 8368 8369 if (isSystemApp(pkg)) { 8370 pkgSetting.isOrphaned = true; 8371 } 8372 8373 ArrayList<PackageParser.Package> clientLibPkgs = null; 8374 8375 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8376 if (nonMutatedPs != null) { 8377 synchronized (mPackages) { 8378 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8379 } 8380 } 8381 return pkg; 8382 } 8383 8384 // Only privileged apps and updated privileged apps can add child packages. 8385 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8386 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8387 throw new PackageManagerException("Only privileged apps and updated " 8388 + "privileged apps can add child packages. Ignoring package " 8389 + pkg.packageName); 8390 } 8391 final int childCount = pkg.childPackages.size(); 8392 for (int i = 0; i < childCount; i++) { 8393 PackageParser.Package childPkg = pkg.childPackages.get(i); 8394 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8395 childPkg.packageName)) { 8396 throw new PackageManagerException("Cannot override a child package of " 8397 + "another disabled system app. Ignoring package " + pkg.packageName); 8398 } 8399 } 8400 } 8401 8402 // writer 8403 synchronized (mPackages) { 8404 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8405 // Only system apps can add new shared libraries. 8406 if (pkg.libraryNames != null) { 8407 for (int i=0; i<pkg.libraryNames.size(); i++) { 8408 String name = pkg.libraryNames.get(i); 8409 boolean allowed = false; 8410 if (pkg.isUpdatedSystemApp()) { 8411 // New library entries can only be added through the 8412 // system image. This is important to get rid of a lot 8413 // of nasty edge cases: for example if we allowed a non- 8414 // system update of the app to add a library, then uninstalling 8415 // the update would make the library go away, and assumptions 8416 // we made such as through app install filtering would now 8417 // have allowed apps on the device which aren't compatible 8418 // with it. Better to just have the restriction here, be 8419 // conservative, and create many fewer cases that can negatively 8420 // impact the user experience. 8421 final PackageSetting sysPs = mSettings 8422 .getDisabledSystemPkgLPr(pkg.packageName); 8423 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8424 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8425 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8426 allowed = true; 8427 break; 8428 } 8429 } 8430 } 8431 } else { 8432 allowed = true; 8433 } 8434 if (allowed) { 8435 if (!mSharedLibraries.containsKey(name)) { 8436 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8437 } else if (!name.equals(pkg.packageName)) { 8438 Slog.w(TAG, "Package " + pkg.packageName + " library " 8439 + name + " already exists; skipping"); 8440 } 8441 } else { 8442 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8443 + name + " that is not declared on system image; skipping"); 8444 } 8445 } 8446 if ((scanFlags & SCAN_BOOTING) == 0) { 8447 // If we are not booting, we need to update any applications 8448 // that are clients of our shared library. If we are booting, 8449 // this will all be done once the scan is complete. 8450 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8451 } 8452 } 8453 } 8454 } 8455 8456 if ((scanFlags & SCAN_BOOTING) != 0) { 8457 // No apps can run during boot scan, so they don't need to be frozen 8458 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8459 // Caller asked to not kill app, so it's probably not frozen 8460 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8461 // Caller asked us to ignore frozen check for some reason; they 8462 // probably didn't know the package name 8463 } else { 8464 // We're doing major surgery on this package, so it better be frozen 8465 // right now to keep it from launching 8466 checkPackageFrozen(pkgName); 8467 } 8468 8469 // Also need to kill any apps that are dependent on the library. 8470 if (clientLibPkgs != null) { 8471 for (int i=0; i<clientLibPkgs.size(); i++) { 8472 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8473 killApplication(clientPkg.applicationInfo.packageName, 8474 clientPkg.applicationInfo.uid, "update lib"); 8475 } 8476 } 8477 8478 // Make sure we're not adding any bogus keyset info 8479 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8480 ksms.assertScannedPackageValid(pkg); 8481 8482 // writer 8483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8484 8485 boolean createIdmapFailed = false; 8486 synchronized (mPackages) { 8487 // We don't expect installation to fail beyond this point 8488 8489 if (pkgSetting.pkg != null) { 8490 // Note that |user| might be null during the initial boot scan. If a codePath 8491 // for an app has changed during a boot scan, it's due to an app update that's 8492 // part of the system partition and marker changes must be applied to all users. 8493 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8494 (user != null) ? user : UserHandle.ALL); 8495 } 8496 8497 // Add the new setting to mSettings 8498 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8499 // Add the new setting to mPackages 8500 mPackages.put(pkg.applicationInfo.packageName, pkg); 8501 // Make sure we don't accidentally delete its data. 8502 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8503 while (iter.hasNext()) { 8504 PackageCleanItem item = iter.next(); 8505 if (pkgName.equals(item.packageName)) { 8506 iter.remove(); 8507 } 8508 } 8509 8510 // Take care of first install / last update times. 8511 if (currentTime != 0) { 8512 if (pkgSetting.firstInstallTime == 0) { 8513 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8514 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8515 pkgSetting.lastUpdateTime = currentTime; 8516 } 8517 } else if (pkgSetting.firstInstallTime == 0) { 8518 // We need *something*. Take time time stamp of the file. 8519 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8520 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8521 if (scanFileTime != pkgSetting.timeStamp) { 8522 // A package on the system image has changed; consider this 8523 // to be an update. 8524 pkgSetting.lastUpdateTime = scanFileTime; 8525 } 8526 } 8527 8528 // Add the package's KeySets to the global KeySetManagerService 8529 ksms.addScannedPackageLPw(pkg); 8530 8531 int N = pkg.providers.size(); 8532 StringBuilder r = null; 8533 int i; 8534 for (i=0; i<N; i++) { 8535 PackageParser.Provider p = pkg.providers.get(i); 8536 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8537 p.info.processName, pkg.applicationInfo.uid); 8538 mProviders.addProvider(p); 8539 p.syncable = p.info.isSyncable; 8540 if (p.info.authority != null) { 8541 String names[] = p.info.authority.split(";"); 8542 p.info.authority = null; 8543 for (int j = 0; j < names.length; j++) { 8544 if (j == 1 && p.syncable) { 8545 // We only want the first authority for a provider to possibly be 8546 // syncable, so if we already added this provider using a different 8547 // authority clear the syncable flag. We copy the provider before 8548 // changing it because the mProviders object contains a reference 8549 // to a provider that we don't want to change. 8550 // Only do this for the second authority since the resulting provider 8551 // object can be the same for all future authorities for this provider. 8552 p = new PackageParser.Provider(p); 8553 p.syncable = false; 8554 } 8555 if (!mProvidersByAuthority.containsKey(names[j])) { 8556 mProvidersByAuthority.put(names[j], p); 8557 if (p.info.authority == null) { 8558 p.info.authority = names[j]; 8559 } else { 8560 p.info.authority = p.info.authority + ";" + names[j]; 8561 } 8562 if (DEBUG_PACKAGE_SCANNING) { 8563 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8564 Log.d(TAG, "Registered content provider: " + names[j] 8565 + ", className = " + p.info.name + ", isSyncable = " 8566 + p.info.isSyncable); 8567 } 8568 } else { 8569 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8570 Slog.w(TAG, "Skipping provider name " + names[j] + 8571 " (in package " + pkg.applicationInfo.packageName + 8572 "): name already used by " 8573 + ((other != null && other.getComponentName() != null) 8574 ? other.getComponentName().getPackageName() : "?")); 8575 } 8576 } 8577 } 8578 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8579 if (r == null) { 8580 r = new StringBuilder(256); 8581 } else { 8582 r.append(' '); 8583 } 8584 r.append(p.info.name); 8585 } 8586 } 8587 if (r != null) { 8588 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8589 } 8590 8591 N = pkg.services.size(); 8592 r = null; 8593 for (i=0; i<N; i++) { 8594 PackageParser.Service s = pkg.services.get(i); 8595 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8596 s.info.processName, pkg.applicationInfo.uid); 8597 mServices.addService(s); 8598 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8599 if (r == null) { 8600 r = new StringBuilder(256); 8601 } else { 8602 r.append(' '); 8603 } 8604 r.append(s.info.name); 8605 } 8606 } 8607 if (r != null) { 8608 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8609 } 8610 8611 N = pkg.receivers.size(); 8612 r = null; 8613 for (i=0; i<N; i++) { 8614 PackageParser.Activity a = pkg.receivers.get(i); 8615 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8616 a.info.processName, pkg.applicationInfo.uid); 8617 mReceivers.addActivity(a, "receiver"); 8618 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8619 if (r == null) { 8620 r = new StringBuilder(256); 8621 } else { 8622 r.append(' '); 8623 } 8624 r.append(a.info.name); 8625 } 8626 } 8627 if (r != null) { 8628 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8629 } 8630 8631 N = pkg.activities.size(); 8632 r = null; 8633 for (i=0; i<N; i++) { 8634 PackageParser.Activity a = pkg.activities.get(i); 8635 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8636 a.info.processName, pkg.applicationInfo.uid); 8637 mActivities.addActivity(a, "activity"); 8638 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8639 if (r == null) { 8640 r = new StringBuilder(256); 8641 } else { 8642 r.append(' '); 8643 } 8644 r.append(a.info.name); 8645 } 8646 } 8647 if (r != null) { 8648 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8649 } 8650 8651 N = pkg.permissionGroups.size(); 8652 r = null; 8653 for (i=0; i<N; i++) { 8654 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8655 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8656 final String curPackageName = cur == null ? null : cur.info.packageName; 8657 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8658 if (cur == null || isPackageUpdate) { 8659 mPermissionGroups.put(pg.info.name, pg); 8660 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8661 if (r == null) { 8662 r = new StringBuilder(256); 8663 } else { 8664 r.append(' '); 8665 } 8666 if (isPackageUpdate) { 8667 r.append("UPD:"); 8668 } 8669 r.append(pg.info.name); 8670 } 8671 } else { 8672 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8673 + pg.info.packageName + " ignored: original from " 8674 + cur.info.packageName); 8675 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8676 if (r == null) { 8677 r = new StringBuilder(256); 8678 } else { 8679 r.append(' '); 8680 } 8681 r.append("DUP:"); 8682 r.append(pg.info.name); 8683 } 8684 } 8685 } 8686 if (r != null) { 8687 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8688 } 8689 8690 N = pkg.permissions.size(); 8691 r = null; 8692 for (i=0; i<N; i++) { 8693 PackageParser.Permission p = pkg.permissions.get(i); 8694 8695 // Assume by default that we did not install this permission into the system. 8696 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8697 8698 // Now that permission groups have a special meaning, we ignore permission 8699 // groups for legacy apps to prevent unexpected behavior. In particular, 8700 // permissions for one app being granted to someone just becase they happen 8701 // to be in a group defined by another app (before this had no implications). 8702 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8703 p.group = mPermissionGroups.get(p.info.group); 8704 // Warn for a permission in an unknown group. 8705 if (p.info.group != null && p.group == null) { 8706 Slog.w(TAG, "Permission " + p.info.name + " from package " 8707 + p.info.packageName + " in an unknown group " + p.info.group); 8708 } 8709 } 8710 8711 ArrayMap<String, BasePermission> permissionMap = 8712 p.tree ? mSettings.mPermissionTrees 8713 : mSettings.mPermissions; 8714 BasePermission bp = permissionMap.get(p.info.name); 8715 8716 // Allow system apps to redefine non-system permissions 8717 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8718 final boolean currentOwnerIsSystem = (bp.perm != null 8719 && isSystemApp(bp.perm.owner)); 8720 if (isSystemApp(p.owner)) { 8721 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8722 // It's a built-in permission and no owner, take ownership now 8723 bp.packageSetting = pkgSetting; 8724 bp.perm = p; 8725 bp.uid = pkg.applicationInfo.uid; 8726 bp.sourcePackage = p.info.packageName; 8727 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8728 } else if (!currentOwnerIsSystem) { 8729 String msg = "New decl " + p.owner + " of permission " 8730 + p.info.name + " is system; overriding " + bp.sourcePackage; 8731 reportSettingsProblem(Log.WARN, msg); 8732 bp = null; 8733 } 8734 } 8735 } 8736 8737 if (bp == null) { 8738 bp = new BasePermission(p.info.name, p.info.packageName, 8739 BasePermission.TYPE_NORMAL); 8740 permissionMap.put(p.info.name, bp); 8741 } 8742 8743 if (bp.perm == null) { 8744 if (bp.sourcePackage == null 8745 || bp.sourcePackage.equals(p.info.packageName)) { 8746 BasePermission tree = findPermissionTreeLP(p.info.name); 8747 if (tree == null 8748 || tree.sourcePackage.equals(p.info.packageName)) { 8749 bp.packageSetting = pkgSetting; 8750 bp.perm = p; 8751 bp.uid = pkg.applicationInfo.uid; 8752 bp.sourcePackage = p.info.packageName; 8753 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8754 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8755 if (r == null) { 8756 r = new StringBuilder(256); 8757 } else { 8758 r.append(' '); 8759 } 8760 r.append(p.info.name); 8761 } 8762 } else { 8763 Slog.w(TAG, "Permission " + p.info.name + " from package " 8764 + p.info.packageName + " ignored: base tree " 8765 + tree.name + " is from package " 8766 + tree.sourcePackage); 8767 } 8768 } else { 8769 Slog.w(TAG, "Permission " + p.info.name + " from package " 8770 + p.info.packageName + " ignored: original from " 8771 + bp.sourcePackage); 8772 } 8773 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8774 if (r == null) { 8775 r = new StringBuilder(256); 8776 } else { 8777 r.append(' '); 8778 } 8779 r.append("DUP:"); 8780 r.append(p.info.name); 8781 } 8782 if (bp.perm == p) { 8783 bp.protectionLevel = p.info.protectionLevel; 8784 } 8785 } 8786 8787 if (r != null) { 8788 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8789 } 8790 8791 N = pkg.instrumentation.size(); 8792 r = null; 8793 for (i=0; i<N; i++) { 8794 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8795 a.info.packageName = pkg.applicationInfo.packageName; 8796 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8797 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8798 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8799 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8800 a.info.dataDir = pkg.applicationInfo.dataDir; 8801 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8802 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8803 8804 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8805 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8806 mInstrumentation.put(a.getComponentName(), a); 8807 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8808 if (r == null) { 8809 r = new StringBuilder(256); 8810 } else { 8811 r.append(' '); 8812 } 8813 r.append(a.info.name); 8814 } 8815 } 8816 if (r != null) { 8817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8818 } 8819 8820 if (pkg.protectedBroadcasts != null) { 8821 N = pkg.protectedBroadcasts.size(); 8822 for (i=0; i<N; i++) { 8823 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8824 } 8825 } 8826 8827 pkgSetting.setTimeStamp(scanFileTime); 8828 8829 // Create idmap files for pairs of (packages, overlay packages). 8830 // Note: "android", ie framework-res.apk, is handled by native layers. 8831 if (pkg.mOverlayTarget != null) { 8832 // This is an overlay package. 8833 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8834 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8835 mOverlays.put(pkg.mOverlayTarget, 8836 new ArrayMap<String, PackageParser.Package>()); 8837 } 8838 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8839 map.put(pkg.packageName, pkg); 8840 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8841 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8842 createIdmapFailed = true; 8843 } 8844 } 8845 } else if (mOverlays.containsKey(pkg.packageName) && 8846 !pkg.packageName.equals("android")) { 8847 // This is a regular package, with one or more known overlay packages. 8848 createIdmapsForPackageLI(pkg); 8849 } 8850 } 8851 8852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8853 8854 if (createIdmapFailed) { 8855 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8856 "scanPackageLI failed to createIdmap"); 8857 } 8858 return pkg; 8859 } 8860 8861 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8862 PackageParser.Package update, UserHandle user) { 8863 if (existing.applicationInfo == null || update.applicationInfo == null) { 8864 // This isn't due to an app installation. 8865 return; 8866 } 8867 8868 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8869 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8870 8871 // The codePath hasn't changed, so there's nothing for us to do. 8872 if (Objects.equals(oldCodePath, newCodePath)) { 8873 return; 8874 } 8875 8876 File canonicalNewCodePath; 8877 try { 8878 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8879 } catch (IOException e) { 8880 Slog.w(TAG, "Failed to get canonical path.", e); 8881 return; 8882 } 8883 8884 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8885 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8886 // that the last component of the path (i.e, the name) doesn't need canonicalization 8887 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8888 // but may change in the future. Hopefully this function won't exist at that point. 8889 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8890 oldCodePath.getName()); 8891 8892 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8893 // with "@". 8894 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8895 if (!oldMarkerPrefix.endsWith("@")) { 8896 oldMarkerPrefix += "@"; 8897 } 8898 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8899 if (!newMarkerPrefix.endsWith("@")) { 8900 newMarkerPrefix += "@"; 8901 } 8902 8903 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8904 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8905 for (String updatedPath : updatedPaths) { 8906 String updatedPathName = new File(updatedPath).getName(); 8907 markerSuffixes.add(updatedPathName.replace('/', '@')); 8908 } 8909 8910 for (int userId : resolveUserIds(user.getIdentifier())) { 8911 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8912 8913 for (String markerSuffix : markerSuffixes) { 8914 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 8915 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 8916 if (oldForeignUseMark.exists()) { 8917 try { 8918 Os.rename(oldForeignUseMark.getAbsolutePath(), 8919 newForeignUseMark.getAbsolutePath()); 8920 } catch (ErrnoException e) { 8921 Slog.w(TAG, "Failed to rename foreign use marker", e); 8922 oldForeignUseMark.delete(); 8923 } 8924 } 8925 } 8926 } 8927 } 8928 8929 /** 8930 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8931 * is derived purely on the basis of the contents of {@code scanFile} and 8932 * {@code cpuAbiOverride}. 8933 * 8934 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8935 */ 8936 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8937 String cpuAbiOverride, boolean extractLibs) 8938 throws PackageManagerException { 8939 // TODO: We can probably be smarter about this stuff. For installed apps, 8940 // we can calculate this information at install time once and for all. For 8941 // system apps, we can probably assume that this information doesn't change 8942 // after the first boot scan. As things stand, we do lots of unnecessary work. 8943 8944 // Give ourselves some initial paths; we'll come back for another 8945 // pass once we've determined ABI below. 8946 setNativeLibraryPaths(pkg); 8947 8948 // We would never need to extract libs for forward-locked and external packages, 8949 // since the container service will do it for us. We shouldn't attempt to 8950 // extract libs from system app when it was not updated. 8951 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8952 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8953 extractLibs = false; 8954 } 8955 8956 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8957 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8958 8959 NativeLibraryHelper.Handle handle = null; 8960 try { 8961 handle = NativeLibraryHelper.Handle.create(pkg); 8962 // TODO(multiArch): This can be null for apps that didn't go through the 8963 // usual installation process. We can calculate it again, like we 8964 // do during install time. 8965 // 8966 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8967 // unnecessary. 8968 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8969 8970 // Null out the abis so that they can be recalculated. 8971 pkg.applicationInfo.primaryCpuAbi = null; 8972 pkg.applicationInfo.secondaryCpuAbi = null; 8973 if (isMultiArch(pkg.applicationInfo)) { 8974 // Warn if we've set an abiOverride for multi-lib packages.. 8975 // By definition, we need to copy both 32 and 64 bit libraries for 8976 // such packages. 8977 if (pkg.cpuAbiOverride != null 8978 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8979 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8980 } 8981 8982 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8983 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8984 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8985 if (extractLibs) { 8986 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8987 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8988 useIsaSpecificSubdirs); 8989 } else { 8990 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8991 } 8992 } 8993 8994 maybeThrowExceptionForMultiArchCopy( 8995 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8996 8997 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8998 if (extractLibs) { 8999 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9000 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9001 useIsaSpecificSubdirs); 9002 } else { 9003 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9004 } 9005 } 9006 9007 maybeThrowExceptionForMultiArchCopy( 9008 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9009 9010 if (abi64 >= 0) { 9011 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9012 } 9013 9014 if (abi32 >= 0) { 9015 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9016 if (abi64 >= 0) { 9017 if (pkg.use32bitAbi) { 9018 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9019 pkg.applicationInfo.primaryCpuAbi = abi; 9020 } else { 9021 pkg.applicationInfo.secondaryCpuAbi = abi; 9022 } 9023 } else { 9024 pkg.applicationInfo.primaryCpuAbi = abi; 9025 } 9026 } 9027 9028 } else { 9029 String[] abiList = (cpuAbiOverride != null) ? 9030 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9031 9032 // Enable gross and lame hacks for apps that are built with old 9033 // SDK tools. We must scan their APKs for renderscript bitcode and 9034 // not launch them if it's present. Don't bother checking on devices 9035 // that don't have 64 bit support. 9036 boolean needsRenderScriptOverride = false; 9037 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9038 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9039 abiList = Build.SUPPORTED_32_BIT_ABIS; 9040 needsRenderScriptOverride = true; 9041 } 9042 9043 final int copyRet; 9044 if (extractLibs) { 9045 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9046 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9047 } else { 9048 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9049 } 9050 9051 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9052 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9053 "Error unpackaging native libs for app, errorCode=" + copyRet); 9054 } 9055 9056 if (copyRet >= 0) { 9057 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9058 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9059 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9060 } else if (needsRenderScriptOverride) { 9061 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9062 } 9063 } 9064 } catch (IOException ioe) { 9065 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9066 } finally { 9067 IoUtils.closeQuietly(handle); 9068 } 9069 9070 // Now that we've calculated the ABIs and determined if it's an internal app, 9071 // we will go ahead and populate the nativeLibraryPath. 9072 setNativeLibraryPaths(pkg); 9073 } 9074 9075 /** 9076 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9077 * i.e, so that all packages can be run inside a single process if required. 9078 * 9079 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9080 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9081 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9082 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9083 * updating a package that belongs to a shared user. 9084 * 9085 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9086 * adds unnecessary complexity. 9087 */ 9088 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9089 PackageParser.Package scannedPackage, boolean bootComplete) { 9090 String requiredInstructionSet = null; 9091 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9092 requiredInstructionSet = VMRuntime.getInstructionSet( 9093 scannedPackage.applicationInfo.primaryCpuAbi); 9094 } 9095 9096 PackageSetting requirer = null; 9097 for (PackageSetting ps : packagesForUser) { 9098 // If packagesForUser contains scannedPackage, we skip it. This will happen 9099 // when scannedPackage is an update of an existing package. Without this check, 9100 // we will never be able to change the ABI of any package belonging to a shared 9101 // user, even if it's compatible with other packages. 9102 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9103 if (ps.primaryCpuAbiString == null) { 9104 continue; 9105 } 9106 9107 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9108 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9109 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9110 // this but there's not much we can do. 9111 String errorMessage = "Instruction set mismatch, " 9112 + ((requirer == null) ? "[caller]" : requirer) 9113 + " requires " + requiredInstructionSet + " whereas " + ps 9114 + " requires " + instructionSet; 9115 Slog.w(TAG, errorMessage); 9116 } 9117 9118 if (requiredInstructionSet == null) { 9119 requiredInstructionSet = instructionSet; 9120 requirer = ps; 9121 } 9122 } 9123 } 9124 9125 if (requiredInstructionSet != null) { 9126 String adjustedAbi; 9127 if (requirer != null) { 9128 // requirer != null implies that either scannedPackage was null or that scannedPackage 9129 // did not require an ABI, in which case we have to adjust scannedPackage to match 9130 // the ABI of the set (which is the same as requirer's ABI) 9131 adjustedAbi = requirer.primaryCpuAbiString; 9132 if (scannedPackage != null) { 9133 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9134 } 9135 } else { 9136 // requirer == null implies that we're updating all ABIs in the set to 9137 // match scannedPackage. 9138 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9139 } 9140 9141 for (PackageSetting ps : packagesForUser) { 9142 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9143 if (ps.primaryCpuAbiString != null) { 9144 continue; 9145 } 9146 9147 ps.primaryCpuAbiString = adjustedAbi; 9148 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9149 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9150 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9151 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9152 + " (requirer=" 9153 + (requirer == null ? "null" : requirer.pkg.packageName) 9154 + ", scannedPackage=" 9155 + (scannedPackage != null ? scannedPackage.packageName : "null") 9156 + ")"); 9157 try { 9158 mInstaller.rmdex(ps.codePathString, 9159 getDexCodeInstructionSet(getPreferredInstructionSet())); 9160 } catch (InstallerException ignored) { 9161 } 9162 } 9163 } 9164 } 9165 } 9166 } 9167 9168 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9169 synchronized (mPackages) { 9170 mResolverReplaced = true; 9171 // Set up information for custom user intent resolution activity. 9172 mResolveActivity.applicationInfo = pkg.applicationInfo; 9173 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9174 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9175 mResolveActivity.processName = pkg.applicationInfo.packageName; 9176 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9177 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9178 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9179 mResolveActivity.theme = 0; 9180 mResolveActivity.exported = true; 9181 mResolveActivity.enabled = true; 9182 mResolveInfo.activityInfo = mResolveActivity; 9183 mResolveInfo.priority = 0; 9184 mResolveInfo.preferredOrder = 0; 9185 mResolveInfo.match = 0; 9186 mResolveComponentName = mCustomResolverComponentName; 9187 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9188 mResolveComponentName); 9189 } 9190 } 9191 9192 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9193 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9194 9195 // Set up information for ephemeral installer activity 9196 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9197 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9198 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9199 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9200 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9201 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9202 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9203 mEphemeralInstallerActivity.theme = 0; 9204 mEphemeralInstallerActivity.exported = true; 9205 mEphemeralInstallerActivity.enabled = true; 9206 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9207 mEphemeralInstallerInfo.priority = 0; 9208 mEphemeralInstallerInfo.preferredOrder = 0; 9209 mEphemeralInstallerInfo.match = 0; 9210 9211 if (DEBUG_EPHEMERAL) { 9212 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9213 } 9214 } 9215 9216 private static String calculateBundledApkRoot(final String codePathString) { 9217 final File codePath = new File(codePathString); 9218 final File codeRoot; 9219 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9220 codeRoot = Environment.getRootDirectory(); 9221 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9222 codeRoot = Environment.getOemDirectory(); 9223 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9224 codeRoot = Environment.getVendorDirectory(); 9225 } else { 9226 // Unrecognized code path; take its top real segment as the apk root: 9227 // e.g. /something/app/blah.apk => /something 9228 try { 9229 File f = codePath.getCanonicalFile(); 9230 File parent = f.getParentFile(); // non-null because codePath is a file 9231 File tmp; 9232 while ((tmp = parent.getParentFile()) != null) { 9233 f = parent; 9234 parent = tmp; 9235 } 9236 codeRoot = f; 9237 Slog.w(TAG, "Unrecognized code path " 9238 + codePath + " - using " + codeRoot); 9239 } catch (IOException e) { 9240 // Can't canonicalize the code path -- shenanigans? 9241 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9242 return Environment.getRootDirectory().getPath(); 9243 } 9244 } 9245 return codeRoot.getPath(); 9246 } 9247 9248 /** 9249 * Derive and set the location of native libraries for the given package, 9250 * which varies depending on where and how the package was installed. 9251 */ 9252 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9253 final ApplicationInfo info = pkg.applicationInfo; 9254 final String codePath = pkg.codePath; 9255 final File codeFile = new File(codePath); 9256 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9257 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9258 9259 info.nativeLibraryRootDir = null; 9260 info.nativeLibraryRootRequiresIsa = false; 9261 info.nativeLibraryDir = null; 9262 info.secondaryNativeLibraryDir = null; 9263 9264 if (isApkFile(codeFile)) { 9265 // Monolithic install 9266 if (bundledApp) { 9267 // If "/system/lib64/apkname" exists, assume that is the per-package 9268 // native library directory to use; otherwise use "/system/lib/apkname". 9269 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9270 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9271 getPrimaryInstructionSet(info)); 9272 9273 // This is a bundled system app so choose the path based on the ABI. 9274 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9275 // is just the default path. 9276 final String apkName = deriveCodePathName(codePath); 9277 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9278 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9279 apkName).getAbsolutePath(); 9280 9281 if (info.secondaryCpuAbi != null) { 9282 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9283 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9284 secondaryLibDir, apkName).getAbsolutePath(); 9285 } 9286 } else if (asecApp) { 9287 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9288 .getAbsolutePath(); 9289 } else { 9290 final String apkName = deriveCodePathName(codePath); 9291 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9292 .getAbsolutePath(); 9293 } 9294 9295 info.nativeLibraryRootRequiresIsa = false; 9296 info.nativeLibraryDir = info.nativeLibraryRootDir; 9297 } else { 9298 // Cluster install 9299 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9300 info.nativeLibraryRootRequiresIsa = true; 9301 9302 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9303 getPrimaryInstructionSet(info)).getAbsolutePath(); 9304 9305 if (info.secondaryCpuAbi != null) { 9306 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9307 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9308 } 9309 } 9310 } 9311 9312 /** 9313 * Calculate the abis and roots for a bundled app. These can uniquely 9314 * be determined from the contents of the system partition, i.e whether 9315 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9316 * of this information, and instead assume that the system was built 9317 * sensibly. 9318 */ 9319 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9320 PackageSetting pkgSetting) { 9321 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9322 9323 // If "/system/lib64/apkname" exists, assume that is the per-package 9324 // native library directory to use; otherwise use "/system/lib/apkname". 9325 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9326 setBundledAppAbi(pkg, apkRoot, apkName); 9327 // pkgSetting might be null during rescan following uninstall of updates 9328 // to a bundled app, so accommodate that possibility. The settings in 9329 // that case will be established later from the parsed package. 9330 // 9331 // If the settings aren't null, sync them up with what we've just derived. 9332 // note that apkRoot isn't stored in the package settings. 9333 if (pkgSetting != null) { 9334 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9335 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9336 } 9337 } 9338 9339 /** 9340 * Deduces the ABI of a bundled app and sets the relevant fields on the 9341 * parsed pkg object. 9342 * 9343 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9344 * under which system libraries are installed. 9345 * @param apkName the name of the installed package. 9346 */ 9347 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9348 final File codeFile = new File(pkg.codePath); 9349 9350 final boolean has64BitLibs; 9351 final boolean has32BitLibs; 9352 if (isApkFile(codeFile)) { 9353 // Monolithic install 9354 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9355 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9356 } else { 9357 // Cluster install 9358 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9359 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9360 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9361 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9362 has64BitLibs = (new File(rootDir, isa)).exists(); 9363 } else { 9364 has64BitLibs = false; 9365 } 9366 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9367 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9368 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9369 has32BitLibs = (new File(rootDir, isa)).exists(); 9370 } else { 9371 has32BitLibs = false; 9372 } 9373 } 9374 9375 if (has64BitLibs && !has32BitLibs) { 9376 // The package has 64 bit libs, but not 32 bit libs. Its primary 9377 // ABI should be 64 bit. We can safely assume here that the bundled 9378 // native libraries correspond to the most preferred ABI in the list. 9379 9380 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9381 pkg.applicationInfo.secondaryCpuAbi = null; 9382 } else if (has32BitLibs && !has64BitLibs) { 9383 // The package has 32 bit libs but not 64 bit libs. Its primary 9384 // ABI should be 32 bit. 9385 9386 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9387 pkg.applicationInfo.secondaryCpuAbi = null; 9388 } else if (has32BitLibs && has64BitLibs) { 9389 // The application has both 64 and 32 bit bundled libraries. We check 9390 // here that the app declares multiArch support, and warn if it doesn't. 9391 // 9392 // We will be lenient here and record both ABIs. The primary will be the 9393 // ABI that's higher on the list, i.e, a device that's configured to prefer 9394 // 64 bit apps will see a 64 bit primary ABI, 9395 9396 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9397 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9398 } 9399 9400 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9401 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9402 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9403 } else { 9404 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9405 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9406 } 9407 } else { 9408 pkg.applicationInfo.primaryCpuAbi = null; 9409 pkg.applicationInfo.secondaryCpuAbi = null; 9410 } 9411 } 9412 9413 private void killApplication(String pkgName, int appId, String reason) { 9414 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9415 } 9416 9417 private void killApplication(String pkgName, int appId, int userId, String reason) { 9418 // Request the ActivityManager to kill the process(only for existing packages) 9419 // so that we do not end up in a confused state while the user is still using the older 9420 // version of the application while the new one gets installed. 9421 final long token = Binder.clearCallingIdentity(); 9422 try { 9423 IActivityManager am = ActivityManagerNative.getDefault(); 9424 if (am != null) { 9425 try { 9426 am.killApplication(pkgName, appId, userId, reason); 9427 } catch (RemoteException e) { 9428 } 9429 } 9430 } finally { 9431 Binder.restoreCallingIdentity(token); 9432 } 9433 } 9434 9435 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9436 // Remove the parent package setting 9437 PackageSetting ps = (PackageSetting) pkg.mExtras; 9438 if (ps != null) { 9439 removePackageLI(ps, chatty); 9440 } 9441 // Remove the child package setting 9442 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9443 for (int i = 0; i < childCount; i++) { 9444 PackageParser.Package childPkg = pkg.childPackages.get(i); 9445 ps = (PackageSetting) childPkg.mExtras; 9446 if (ps != null) { 9447 removePackageLI(ps, chatty); 9448 } 9449 } 9450 } 9451 9452 void removePackageLI(PackageSetting ps, boolean chatty) { 9453 if (DEBUG_INSTALL) { 9454 if (chatty) 9455 Log.d(TAG, "Removing package " + ps.name); 9456 } 9457 9458 // writer 9459 synchronized (mPackages) { 9460 mPackages.remove(ps.name); 9461 final PackageParser.Package pkg = ps.pkg; 9462 if (pkg != null) { 9463 cleanPackageDataStructuresLILPw(pkg, chatty); 9464 } 9465 } 9466 } 9467 9468 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9469 if (DEBUG_INSTALL) { 9470 if (chatty) 9471 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9472 } 9473 9474 // writer 9475 synchronized (mPackages) { 9476 // Remove the parent package 9477 mPackages.remove(pkg.applicationInfo.packageName); 9478 cleanPackageDataStructuresLILPw(pkg, chatty); 9479 9480 // Remove the child packages 9481 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9482 for (int i = 0; i < childCount; i++) { 9483 PackageParser.Package childPkg = pkg.childPackages.get(i); 9484 mPackages.remove(childPkg.applicationInfo.packageName); 9485 cleanPackageDataStructuresLILPw(childPkg, chatty); 9486 } 9487 } 9488 } 9489 9490 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9491 int N = pkg.providers.size(); 9492 StringBuilder r = null; 9493 int i; 9494 for (i=0; i<N; i++) { 9495 PackageParser.Provider p = pkg.providers.get(i); 9496 mProviders.removeProvider(p); 9497 if (p.info.authority == null) { 9498 9499 /* There was another ContentProvider with this authority when 9500 * this app was installed so this authority is null, 9501 * Ignore it as we don't have to unregister the provider. 9502 */ 9503 continue; 9504 } 9505 String names[] = p.info.authority.split(";"); 9506 for (int j = 0; j < names.length; j++) { 9507 if (mProvidersByAuthority.get(names[j]) == p) { 9508 mProvidersByAuthority.remove(names[j]); 9509 if (DEBUG_REMOVE) { 9510 if (chatty) 9511 Log.d(TAG, "Unregistered content provider: " + names[j] 9512 + ", className = " + p.info.name + ", isSyncable = " 9513 + p.info.isSyncable); 9514 } 9515 } 9516 } 9517 if (DEBUG_REMOVE && chatty) { 9518 if (r == null) { 9519 r = new StringBuilder(256); 9520 } else { 9521 r.append(' '); 9522 } 9523 r.append(p.info.name); 9524 } 9525 } 9526 if (r != null) { 9527 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9528 } 9529 9530 N = pkg.services.size(); 9531 r = null; 9532 for (i=0; i<N; i++) { 9533 PackageParser.Service s = pkg.services.get(i); 9534 mServices.removeService(s); 9535 if (chatty) { 9536 if (r == null) { 9537 r = new StringBuilder(256); 9538 } else { 9539 r.append(' '); 9540 } 9541 r.append(s.info.name); 9542 } 9543 } 9544 if (r != null) { 9545 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9546 } 9547 9548 N = pkg.receivers.size(); 9549 r = null; 9550 for (i=0; i<N; i++) { 9551 PackageParser.Activity a = pkg.receivers.get(i); 9552 mReceivers.removeActivity(a, "receiver"); 9553 if (DEBUG_REMOVE && chatty) { 9554 if (r == null) { 9555 r = new StringBuilder(256); 9556 } else { 9557 r.append(' '); 9558 } 9559 r.append(a.info.name); 9560 } 9561 } 9562 if (r != null) { 9563 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9564 } 9565 9566 N = pkg.activities.size(); 9567 r = null; 9568 for (i=0; i<N; i++) { 9569 PackageParser.Activity a = pkg.activities.get(i); 9570 mActivities.removeActivity(a, "activity"); 9571 if (DEBUG_REMOVE && chatty) { 9572 if (r == null) { 9573 r = new StringBuilder(256); 9574 } else { 9575 r.append(' '); 9576 } 9577 r.append(a.info.name); 9578 } 9579 } 9580 if (r != null) { 9581 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9582 } 9583 9584 N = pkg.permissions.size(); 9585 r = null; 9586 for (i=0; i<N; i++) { 9587 PackageParser.Permission p = pkg.permissions.get(i); 9588 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9589 if (bp == null) { 9590 bp = mSettings.mPermissionTrees.get(p.info.name); 9591 } 9592 if (bp != null && bp.perm == p) { 9593 bp.perm = null; 9594 if (DEBUG_REMOVE && chatty) { 9595 if (r == null) { 9596 r = new StringBuilder(256); 9597 } else { 9598 r.append(' '); 9599 } 9600 r.append(p.info.name); 9601 } 9602 } 9603 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9604 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9605 if (appOpPkgs != null) { 9606 appOpPkgs.remove(pkg.packageName); 9607 } 9608 } 9609 } 9610 if (r != null) { 9611 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9612 } 9613 9614 N = pkg.requestedPermissions.size(); 9615 r = null; 9616 for (i=0; i<N; i++) { 9617 String perm = pkg.requestedPermissions.get(i); 9618 BasePermission bp = mSettings.mPermissions.get(perm); 9619 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9620 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9621 if (appOpPkgs != null) { 9622 appOpPkgs.remove(pkg.packageName); 9623 if (appOpPkgs.isEmpty()) { 9624 mAppOpPermissionPackages.remove(perm); 9625 } 9626 } 9627 } 9628 } 9629 if (r != null) { 9630 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9631 } 9632 9633 N = pkg.instrumentation.size(); 9634 r = null; 9635 for (i=0; i<N; i++) { 9636 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9637 mInstrumentation.remove(a.getComponentName()); 9638 if (DEBUG_REMOVE && chatty) { 9639 if (r == null) { 9640 r = new StringBuilder(256); 9641 } else { 9642 r.append(' '); 9643 } 9644 r.append(a.info.name); 9645 } 9646 } 9647 if (r != null) { 9648 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9649 } 9650 9651 r = null; 9652 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9653 // Only system apps can hold shared libraries. 9654 if (pkg.libraryNames != null) { 9655 for (i=0; i<pkg.libraryNames.size(); i++) { 9656 String name = pkg.libraryNames.get(i); 9657 SharedLibraryEntry cur = mSharedLibraries.get(name); 9658 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9659 mSharedLibraries.remove(name); 9660 if (DEBUG_REMOVE && chatty) { 9661 if (r == null) { 9662 r = new StringBuilder(256); 9663 } else { 9664 r.append(' '); 9665 } 9666 r.append(name); 9667 } 9668 } 9669 } 9670 } 9671 } 9672 if (r != null) { 9673 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9674 } 9675 } 9676 9677 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9678 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9679 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9680 return true; 9681 } 9682 } 9683 return false; 9684 } 9685 9686 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9687 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9688 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9689 9690 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9691 // Update the parent permissions 9692 updatePermissionsLPw(pkg.packageName, pkg, flags); 9693 // Update the child permissions 9694 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9695 for (int i = 0; i < childCount; i++) { 9696 PackageParser.Package childPkg = pkg.childPackages.get(i); 9697 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9698 } 9699 } 9700 9701 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9702 int flags) { 9703 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9704 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9705 } 9706 9707 private void updatePermissionsLPw(String changingPkg, 9708 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9709 // Make sure there are no dangling permission trees. 9710 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9711 while (it.hasNext()) { 9712 final BasePermission bp = it.next(); 9713 if (bp.packageSetting == null) { 9714 // We may not yet have parsed the package, so just see if 9715 // we still know about its settings. 9716 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9717 } 9718 if (bp.packageSetting == null) { 9719 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9720 + " from package " + bp.sourcePackage); 9721 it.remove(); 9722 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9723 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9724 Slog.i(TAG, "Removing old permission tree: " + bp.name 9725 + " from package " + bp.sourcePackage); 9726 flags |= UPDATE_PERMISSIONS_ALL; 9727 it.remove(); 9728 } 9729 } 9730 } 9731 9732 // Make sure all dynamic permissions have been assigned to a package, 9733 // and make sure there are no dangling permissions. 9734 it = mSettings.mPermissions.values().iterator(); 9735 while (it.hasNext()) { 9736 final BasePermission bp = it.next(); 9737 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9738 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9739 + bp.name + " pkg=" + bp.sourcePackage 9740 + " info=" + bp.pendingInfo); 9741 if (bp.packageSetting == null && bp.pendingInfo != null) { 9742 final BasePermission tree = findPermissionTreeLP(bp.name); 9743 if (tree != null && tree.perm != null) { 9744 bp.packageSetting = tree.packageSetting; 9745 bp.perm = new PackageParser.Permission(tree.perm.owner, 9746 new PermissionInfo(bp.pendingInfo)); 9747 bp.perm.info.packageName = tree.perm.info.packageName; 9748 bp.perm.info.name = bp.name; 9749 bp.uid = tree.uid; 9750 } 9751 } 9752 } 9753 if (bp.packageSetting == null) { 9754 // We may not yet have parsed the package, so just see if 9755 // we still know about its settings. 9756 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9757 } 9758 if (bp.packageSetting == null) { 9759 Slog.w(TAG, "Removing dangling permission: " + bp.name 9760 + " from package " + bp.sourcePackage); 9761 it.remove(); 9762 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9763 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9764 Slog.i(TAG, "Removing old permission: " + bp.name 9765 + " from package " + bp.sourcePackage); 9766 flags |= UPDATE_PERMISSIONS_ALL; 9767 it.remove(); 9768 } 9769 } 9770 } 9771 9772 // Now update the permissions for all packages, in particular 9773 // replace the granted permissions of the system packages. 9774 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9775 for (PackageParser.Package pkg : mPackages.values()) { 9776 if (pkg != pkgInfo) { 9777 // Only replace for packages on requested volume 9778 final String volumeUuid = getVolumeUuidForPackage(pkg); 9779 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9780 && Objects.equals(replaceVolumeUuid, volumeUuid); 9781 grantPermissionsLPw(pkg, replace, changingPkg); 9782 } 9783 } 9784 } 9785 9786 if (pkgInfo != null) { 9787 // Only replace for packages on requested volume 9788 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9789 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9790 && Objects.equals(replaceVolumeUuid, volumeUuid); 9791 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9792 } 9793 } 9794 9795 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9796 String packageOfInterest) { 9797 // IMPORTANT: There are two types of permissions: install and runtime. 9798 // Install time permissions are granted when the app is installed to 9799 // all device users and users added in the future. Runtime permissions 9800 // are granted at runtime explicitly to specific users. Normal and signature 9801 // protected permissions are install time permissions. Dangerous permissions 9802 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9803 // otherwise they are runtime permissions. This function does not manage 9804 // runtime permissions except for the case an app targeting Lollipop MR1 9805 // being upgraded to target a newer SDK, in which case dangerous permissions 9806 // are transformed from install time to runtime ones. 9807 9808 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9809 if (ps == null) { 9810 return; 9811 } 9812 9813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9814 9815 PermissionsState permissionsState = ps.getPermissionsState(); 9816 PermissionsState origPermissions = permissionsState; 9817 9818 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9819 9820 boolean runtimePermissionsRevoked = false; 9821 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9822 9823 boolean changedInstallPermission = false; 9824 9825 if (replace) { 9826 ps.installPermissionsFixed = false; 9827 if (!ps.isSharedUser()) { 9828 origPermissions = new PermissionsState(permissionsState); 9829 permissionsState.reset(); 9830 } else { 9831 // We need to know only about runtime permission changes since the 9832 // calling code always writes the install permissions state but 9833 // the runtime ones are written only if changed. The only cases of 9834 // changed runtime permissions here are promotion of an install to 9835 // runtime and revocation of a runtime from a shared user. 9836 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9837 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9838 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9839 runtimePermissionsRevoked = true; 9840 } 9841 } 9842 } 9843 9844 permissionsState.setGlobalGids(mGlobalGids); 9845 9846 final int N = pkg.requestedPermissions.size(); 9847 for (int i=0; i<N; i++) { 9848 final String name = pkg.requestedPermissions.get(i); 9849 final BasePermission bp = mSettings.mPermissions.get(name); 9850 9851 if (DEBUG_INSTALL) { 9852 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9853 } 9854 9855 if (bp == null || bp.packageSetting == null) { 9856 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9857 Slog.w(TAG, "Unknown permission " + name 9858 + " in package " + pkg.packageName); 9859 } 9860 continue; 9861 } 9862 9863 final String perm = bp.name; 9864 boolean allowedSig = false; 9865 int grant = GRANT_DENIED; 9866 9867 // Keep track of app op permissions. 9868 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9869 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9870 if (pkgs == null) { 9871 pkgs = new ArraySet<>(); 9872 mAppOpPermissionPackages.put(bp.name, pkgs); 9873 } 9874 pkgs.add(pkg.packageName); 9875 } 9876 9877 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9878 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9879 >= Build.VERSION_CODES.M; 9880 switch (level) { 9881 case PermissionInfo.PROTECTION_NORMAL: { 9882 // For all apps normal permissions are install time ones. 9883 grant = GRANT_INSTALL; 9884 } break; 9885 9886 case PermissionInfo.PROTECTION_DANGEROUS: { 9887 // If a permission review is required for legacy apps we represent 9888 // their permissions as always granted runtime ones since we need 9889 // to keep the review required permission flag per user while an 9890 // install permission's state is shared across all users. 9891 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9892 // For legacy apps dangerous permissions are install time ones. 9893 grant = GRANT_INSTALL; 9894 } else if (origPermissions.hasInstallPermission(bp.name)) { 9895 // For legacy apps that became modern, install becomes runtime. 9896 grant = GRANT_UPGRADE; 9897 } else if (mPromoteSystemApps 9898 && isSystemApp(ps) 9899 && mExistingSystemPackages.contains(ps.name)) { 9900 // For legacy system apps, install becomes runtime. 9901 // We cannot check hasInstallPermission() for system apps since those 9902 // permissions were granted implicitly and not persisted pre-M. 9903 grant = GRANT_UPGRADE; 9904 } else { 9905 // For modern apps keep runtime permissions unchanged. 9906 grant = GRANT_RUNTIME; 9907 } 9908 } break; 9909 9910 case PermissionInfo.PROTECTION_SIGNATURE: { 9911 // For all apps signature permissions are install time ones. 9912 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9913 if (allowedSig) { 9914 grant = GRANT_INSTALL; 9915 } 9916 } break; 9917 } 9918 9919 if (DEBUG_INSTALL) { 9920 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9921 } 9922 9923 if (grant != GRANT_DENIED) { 9924 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9925 // If this is an existing, non-system package, then 9926 // we can't add any new permissions to it. 9927 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9928 // Except... if this is a permission that was added 9929 // to the platform (note: need to only do this when 9930 // updating the platform). 9931 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9932 grant = GRANT_DENIED; 9933 } 9934 } 9935 } 9936 9937 switch (grant) { 9938 case GRANT_INSTALL: { 9939 // Revoke this as runtime permission to handle the case of 9940 // a runtime permission being downgraded to an install one. 9941 // Also in permission review mode we keep dangerous permissions 9942 // for legacy apps 9943 for (int userId : UserManagerService.getInstance().getUserIds()) { 9944 if (origPermissions.getRuntimePermissionState( 9945 bp.name, userId) != null) { 9946 // Revoke the runtime permission and clear the flags. 9947 origPermissions.revokeRuntimePermission(bp, userId); 9948 origPermissions.updatePermissionFlags(bp, userId, 9949 PackageManager.MASK_PERMISSION_FLAGS, 0); 9950 // If we revoked a permission permission, we have to write. 9951 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9952 changedRuntimePermissionUserIds, userId); 9953 } 9954 } 9955 // Grant an install permission. 9956 if (permissionsState.grantInstallPermission(bp) != 9957 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9958 changedInstallPermission = true; 9959 } 9960 } break; 9961 9962 case GRANT_RUNTIME: { 9963 // Grant previously granted runtime permissions. 9964 for (int userId : UserManagerService.getInstance().getUserIds()) { 9965 PermissionState permissionState = origPermissions 9966 .getRuntimePermissionState(bp.name, userId); 9967 int flags = permissionState != null 9968 ? permissionState.getFlags() : 0; 9969 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9970 if (permissionsState.grantRuntimePermission(bp, userId) == 9971 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9972 // If we cannot put the permission as it was, we have to write. 9973 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9974 changedRuntimePermissionUserIds, userId); 9975 } 9976 // If the app supports runtime permissions no need for a review. 9977 if (Build.PERMISSIONS_REVIEW_REQUIRED 9978 && appSupportsRuntimePermissions 9979 && (flags & PackageManager 9980 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9981 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9982 // Since we changed the flags, we have to write. 9983 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9984 changedRuntimePermissionUserIds, userId); 9985 } 9986 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9987 && !appSupportsRuntimePermissions) { 9988 // For legacy apps that need a permission review, every new 9989 // runtime permission is granted but it is pending a review. 9990 // We also need to review only platform defined runtime 9991 // permissions as these are the only ones the platform knows 9992 // how to disable the API to simulate revocation as legacy 9993 // apps don't expect to run with revoked permissions. 9994 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9995 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9996 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9997 // We changed the flags, hence have to write. 9998 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9999 changedRuntimePermissionUserIds, userId); 10000 } 10001 } 10002 if (permissionsState.grantRuntimePermission(bp, userId) 10003 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10004 // We changed the permission, hence have to write. 10005 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10006 changedRuntimePermissionUserIds, userId); 10007 } 10008 } 10009 // Propagate the permission flags. 10010 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10011 } 10012 } break; 10013 10014 case GRANT_UPGRADE: { 10015 // Grant runtime permissions for a previously held install permission. 10016 PermissionState permissionState = origPermissions 10017 .getInstallPermissionState(bp.name); 10018 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10019 10020 if (origPermissions.revokeInstallPermission(bp) 10021 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10022 // We will be transferring the permission flags, so clear them. 10023 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10024 PackageManager.MASK_PERMISSION_FLAGS, 0); 10025 changedInstallPermission = true; 10026 } 10027 10028 // If the permission is not to be promoted to runtime we ignore it and 10029 // also its other flags as they are not applicable to install permissions. 10030 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10031 for (int userId : currentUserIds) { 10032 if (permissionsState.grantRuntimePermission(bp, userId) != 10033 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10034 // Transfer the permission flags. 10035 permissionsState.updatePermissionFlags(bp, userId, 10036 flags, flags); 10037 // If we granted the permission, we have to write. 10038 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10039 changedRuntimePermissionUserIds, userId); 10040 } 10041 } 10042 } 10043 } break; 10044 10045 default: { 10046 if (packageOfInterest == null 10047 || packageOfInterest.equals(pkg.packageName)) { 10048 Slog.w(TAG, "Not granting permission " + perm 10049 + " to package " + pkg.packageName 10050 + " because it was previously installed without"); 10051 } 10052 } break; 10053 } 10054 } else { 10055 if (permissionsState.revokeInstallPermission(bp) != 10056 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10057 // Also drop the permission flags. 10058 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10059 PackageManager.MASK_PERMISSION_FLAGS, 0); 10060 changedInstallPermission = true; 10061 Slog.i(TAG, "Un-granting permission " + perm 10062 + " from package " + pkg.packageName 10063 + " (protectionLevel=" + bp.protectionLevel 10064 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10065 + ")"); 10066 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10067 // Don't print warning for app op permissions, since it is fine for them 10068 // not to be granted, there is a UI for the user to decide. 10069 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10070 Slog.w(TAG, "Not granting permission " + perm 10071 + " to package " + pkg.packageName 10072 + " (protectionLevel=" + bp.protectionLevel 10073 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10074 + ")"); 10075 } 10076 } 10077 } 10078 } 10079 10080 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10081 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10082 // This is the first that we have heard about this package, so the 10083 // permissions we have now selected are fixed until explicitly 10084 // changed. 10085 ps.installPermissionsFixed = true; 10086 } 10087 10088 // Persist the runtime permissions state for users with changes. If permissions 10089 // were revoked because no app in the shared user declares them we have to 10090 // write synchronously to avoid losing runtime permissions state. 10091 for (int userId : changedRuntimePermissionUserIds) { 10092 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10093 } 10094 10095 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10096 } 10097 10098 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10099 boolean allowed = false; 10100 final int NP = PackageParser.NEW_PERMISSIONS.length; 10101 for (int ip=0; ip<NP; ip++) { 10102 final PackageParser.NewPermissionInfo npi 10103 = PackageParser.NEW_PERMISSIONS[ip]; 10104 if (npi.name.equals(perm) 10105 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10106 allowed = true; 10107 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10108 + pkg.packageName); 10109 break; 10110 } 10111 } 10112 return allowed; 10113 } 10114 10115 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10116 BasePermission bp, PermissionsState origPermissions) { 10117 boolean allowed; 10118 allowed = (compareSignatures( 10119 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10120 == PackageManager.SIGNATURE_MATCH) 10121 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10122 == PackageManager.SIGNATURE_MATCH); 10123 if (!allowed && (bp.protectionLevel 10124 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10125 if (isSystemApp(pkg)) { 10126 // For updated system applications, a system permission 10127 // is granted only if it had been defined by the original application. 10128 if (pkg.isUpdatedSystemApp()) { 10129 final PackageSetting sysPs = mSettings 10130 .getDisabledSystemPkgLPr(pkg.packageName); 10131 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10132 // If the original was granted this permission, we take 10133 // that grant decision as read and propagate it to the 10134 // update. 10135 if (sysPs.isPrivileged()) { 10136 allowed = true; 10137 } 10138 } else { 10139 // The system apk may have been updated with an older 10140 // version of the one on the data partition, but which 10141 // granted a new system permission that it didn't have 10142 // before. In this case we do want to allow the app to 10143 // now get the new permission if the ancestral apk is 10144 // privileged to get it. 10145 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10146 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10147 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10148 allowed = true; 10149 break; 10150 } 10151 } 10152 } 10153 // Also if a privileged parent package on the system image or any of 10154 // its children requested a privileged permission, the updated child 10155 // packages can also get the permission. 10156 if (pkg.parentPackage != null) { 10157 final PackageSetting disabledSysParentPs = mSettings 10158 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10159 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10160 && disabledSysParentPs.isPrivileged()) { 10161 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10162 allowed = true; 10163 } else if (disabledSysParentPs.pkg.childPackages != null) { 10164 final int count = disabledSysParentPs.pkg.childPackages.size(); 10165 for (int i = 0; i < count; i++) { 10166 PackageParser.Package disabledSysChildPkg = 10167 disabledSysParentPs.pkg.childPackages.get(i); 10168 if (isPackageRequestingPermission(disabledSysChildPkg, 10169 perm)) { 10170 allowed = true; 10171 break; 10172 } 10173 } 10174 } 10175 } 10176 } 10177 } 10178 } else { 10179 allowed = isPrivilegedApp(pkg); 10180 } 10181 } 10182 } 10183 if (!allowed) { 10184 if (!allowed && (bp.protectionLevel 10185 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10186 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10187 // If this was a previously normal/dangerous permission that got moved 10188 // to a system permission as part of the runtime permission redesign, then 10189 // we still want to blindly grant it to old apps. 10190 allowed = true; 10191 } 10192 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10193 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10194 // If this permission is to be granted to the system installer and 10195 // this app is an installer, then it gets the permission. 10196 allowed = true; 10197 } 10198 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10199 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10200 // If this permission is to be granted to the system verifier and 10201 // this app is a verifier, then it gets the permission. 10202 allowed = true; 10203 } 10204 if (!allowed && (bp.protectionLevel 10205 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10206 && isSystemApp(pkg)) { 10207 // Any pre-installed system app is allowed to get this permission. 10208 allowed = true; 10209 } 10210 if (!allowed && (bp.protectionLevel 10211 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10212 // For development permissions, a development permission 10213 // is granted only if it was already granted. 10214 allowed = origPermissions.hasInstallPermission(perm); 10215 } 10216 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10217 && pkg.packageName.equals(mSetupWizardPackage)) { 10218 // If this permission is to be granted to the system setup wizard and 10219 // this app is a setup wizard, then it gets the permission. 10220 allowed = true; 10221 } 10222 } 10223 return allowed; 10224 } 10225 10226 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10227 final int permCount = pkg.requestedPermissions.size(); 10228 for (int j = 0; j < permCount; j++) { 10229 String requestedPermission = pkg.requestedPermissions.get(j); 10230 if (permission.equals(requestedPermission)) { 10231 return true; 10232 } 10233 } 10234 return false; 10235 } 10236 10237 final class ActivityIntentResolver 10238 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10239 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10240 boolean defaultOnly, int userId) { 10241 if (!sUserManager.exists(userId)) return null; 10242 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10243 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10244 } 10245 10246 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10247 int userId) { 10248 if (!sUserManager.exists(userId)) return null; 10249 mFlags = flags; 10250 return super.queryIntent(intent, resolvedType, 10251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10252 } 10253 10254 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10255 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10256 if (!sUserManager.exists(userId)) return null; 10257 if (packageActivities == null) { 10258 return null; 10259 } 10260 mFlags = flags; 10261 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10262 final int N = packageActivities.size(); 10263 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10264 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10265 10266 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10267 for (int i = 0; i < N; ++i) { 10268 intentFilters = packageActivities.get(i).intents; 10269 if (intentFilters != null && intentFilters.size() > 0) { 10270 PackageParser.ActivityIntentInfo[] array = 10271 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10272 intentFilters.toArray(array); 10273 listCut.add(array); 10274 } 10275 } 10276 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10277 } 10278 10279 /** 10280 * Finds a privileged activity that matches the specified activity names. 10281 */ 10282 private PackageParser.Activity findMatchingActivity( 10283 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10284 for (PackageParser.Activity sysActivity : activityList) { 10285 if (sysActivity.info.name.equals(activityInfo.name)) { 10286 return sysActivity; 10287 } 10288 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10289 return sysActivity; 10290 } 10291 if (sysActivity.info.targetActivity != null) { 10292 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10293 return sysActivity; 10294 } 10295 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10296 return sysActivity; 10297 } 10298 } 10299 } 10300 return null; 10301 } 10302 10303 public class IterGenerator<E> { 10304 public Iterator<E> generate(ActivityIntentInfo info) { 10305 return null; 10306 } 10307 } 10308 10309 public class ActionIterGenerator extends IterGenerator<String> { 10310 @Override 10311 public Iterator<String> generate(ActivityIntentInfo info) { 10312 return info.actionsIterator(); 10313 } 10314 } 10315 10316 public class CategoriesIterGenerator extends IterGenerator<String> { 10317 @Override 10318 public Iterator<String> generate(ActivityIntentInfo info) { 10319 return info.categoriesIterator(); 10320 } 10321 } 10322 10323 public class SchemesIterGenerator extends IterGenerator<String> { 10324 @Override 10325 public Iterator<String> generate(ActivityIntentInfo info) { 10326 return info.schemesIterator(); 10327 } 10328 } 10329 10330 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10331 @Override 10332 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10333 return info.authoritiesIterator(); 10334 } 10335 } 10336 10337 /** 10338 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10339 * MODIFIED. Do not pass in a list that should not be changed. 10340 */ 10341 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10342 IterGenerator<T> generator, Iterator<T> searchIterator) { 10343 // loop through the set of actions; every one must be found in the intent filter 10344 while (searchIterator.hasNext()) { 10345 // we must have at least one filter in the list to consider a match 10346 if (intentList.size() == 0) { 10347 break; 10348 } 10349 10350 final T searchAction = searchIterator.next(); 10351 10352 // loop through the set of intent filters 10353 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10354 while (intentIter.hasNext()) { 10355 final ActivityIntentInfo intentInfo = intentIter.next(); 10356 boolean selectionFound = false; 10357 10358 // loop through the intent filter's selection criteria; at least one 10359 // of them must match the searched criteria 10360 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10361 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10362 final T intentSelection = intentSelectionIter.next(); 10363 if (intentSelection != null && intentSelection.equals(searchAction)) { 10364 selectionFound = true; 10365 break; 10366 } 10367 } 10368 10369 // the selection criteria wasn't found in this filter's set; this filter 10370 // is not a potential match 10371 if (!selectionFound) { 10372 intentIter.remove(); 10373 } 10374 } 10375 } 10376 } 10377 10378 private boolean isProtectedAction(ActivityIntentInfo filter) { 10379 final Iterator<String> actionsIter = filter.actionsIterator(); 10380 while (actionsIter != null && actionsIter.hasNext()) { 10381 final String filterAction = actionsIter.next(); 10382 if (PROTECTED_ACTIONS.contains(filterAction)) { 10383 return true; 10384 } 10385 } 10386 return false; 10387 } 10388 10389 /** 10390 * Adjusts the priority of the given intent filter according to policy. 10391 * <p> 10392 * <ul> 10393 * <li>The priority for non privileged applications is capped to '0'</li> 10394 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10395 * <li>The priority for unbundled updates to privileged applications is capped to the 10396 * priority defined on the system partition</li> 10397 * </ul> 10398 * <p> 10399 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10400 * allowed to obtain any priority on any action. 10401 */ 10402 private void adjustPriority( 10403 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10404 // nothing to do; priority is fine as-is 10405 if (intent.getPriority() <= 0) { 10406 return; 10407 } 10408 10409 final ActivityInfo activityInfo = intent.activity.info; 10410 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10411 10412 final boolean privilegedApp = 10413 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10414 if (!privilegedApp) { 10415 // non-privileged applications can never define a priority >0 10416 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10417 + " package: " + applicationInfo.packageName 10418 + " activity: " + intent.activity.className 10419 + " origPrio: " + intent.getPriority()); 10420 intent.setPriority(0); 10421 return; 10422 } 10423 10424 if (systemActivities == null) { 10425 // the system package is not disabled; we're parsing the system partition 10426 if (isProtectedAction(intent)) { 10427 if (mDeferProtectedFilters) { 10428 // We can't deal with these just yet. No component should ever obtain a 10429 // >0 priority for a protected actions, with ONE exception -- the setup 10430 // wizard. The setup wizard, however, cannot be known until we're able to 10431 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10432 // until all intent filters have been processed. Chicken, meet egg. 10433 // Let the filter temporarily have a high priority and rectify the 10434 // priorities after all system packages have been scanned. 10435 mProtectedFilters.add(intent); 10436 if (DEBUG_FILTERS) { 10437 Slog.i(TAG, "Protected action; save for later;" 10438 + " package: " + applicationInfo.packageName 10439 + " activity: " + intent.activity.className 10440 + " origPrio: " + intent.getPriority()); 10441 } 10442 return; 10443 } else { 10444 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10445 Slog.i(TAG, "No setup wizard;" 10446 + " All protected intents capped to priority 0"); 10447 } 10448 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10449 if (DEBUG_FILTERS) { 10450 Slog.i(TAG, "Found setup wizard;" 10451 + " allow priority " + intent.getPriority() + ";" 10452 + " package: " + intent.activity.info.packageName 10453 + " activity: " + intent.activity.className 10454 + " priority: " + intent.getPriority()); 10455 } 10456 // setup wizard gets whatever it wants 10457 return; 10458 } 10459 Slog.w(TAG, "Protected action; cap priority to 0;" 10460 + " package: " + intent.activity.info.packageName 10461 + " activity: " + intent.activity.className 10462 + " origPrio: " + intent.getPriority()); 10463 intent.setPriority(0); 10464 return; 10465 } 10466 } 10467 // privileged apps on the system image get whatever priority they request 10468 return; 10469 } 10470 10471 // privileged app unbundled update ... try to find the same activity 10472 final PackageParser.Activity foundActivity = 10473 findMatchingActivity(systemActivities, activityInfo); 10474 if (foundActivity == null) { 10475 // this is a new activity; it cannot obtain >0 priority 10476 if (DEBUG_FILTERS) { 10477 Slog.i(TAG, "New activity; cap priority to 0;" 10478 + " package: " + applicationInfo.packageName 10479 + " activity: " + intent.activity.className 10480 + " origPrio: " + intent.getPriority()); 10481 } 10482 intent.setPriority(0); 10483 return; 10484 } 10485 10486 // found activity, now check for filter equivalence 10487 10488 // a shallow copy is enough; we modify the list, not its contents 10489 final List<ActivityIntentInfo> intentListCopy = 10490 new ArrayList<>(foundActivity.intents); 10491 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10492 10493 // find matching action subsets 10494 final Iterator<String> actionsIterator = intent.actionsIterator(); 10495 if (actionsIterator != null) { 10496 getIntentListSubset( 10497 intentListCopy, new ActionIterGenerator(), actionsIterator); 10498 if (intentListCopy.size() == 0) { 10499 // no more intents to match; we're not equivalent 10500 if (DEBUG_FILTERS) { 10501 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10502 + " package: " + applicationInfo.packageName 10503 + " activity: " + intent.activity.className 10504 + " origPrio: " + intent.getPriority()); 10505 } 10506 intent.setPriority(0); 10507 return; 10508 } 10509 } 10510 10511 // find matching category subsets 10512 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10513 if (categoriesIterator != null) { 10514 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10515 categoriesIterator); 10516 if (intentListCopy.size() == 0) { 10517 // no more intents to match; we're not equivalent 10518 if (DEBUG_FILTERS) { 10519 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10520 + " package: " + applicationInfo.packageName 10521 + " activity: " + intent.activity.className 10522 + " origPrio: " + intent.getPriority()); 10523 } 10524 intent.setPriority(0); 10525 return; 10526 } 10527 } 10528 10529 // find matching schemes subsets 10530 final Iterator<String> schemesIterator = intent.schemesIterator(); 10531 if (schemesIterator != null) { 10532 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10533 schemesIterator); 10534 if (intentListCopy.size() == 0) { 10535 // no more intents to match; we're not equivalent 10536 if (DEBUG_FILTERS) { 10537 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10538 + " package: " + applicationInfo.packageName 10539 + " activity: " + intent.activity.className 10540 + " origPrio: " + intent.getPriority()); 10541 } 10542 intent.setPriority(0); 10543 return; 10544 } 10545 } 10546 10547 // find matching authorities subsets 10548 final Iterator<IntentFilter.AuthorityEntry> 10549 authoritiesIterator = intent.authoritiesIterator(); 10550 if (authoritiesIterator != null) { 10551 getIntentListSubset(intentListCopy, 10552 new AuthoritiesIterGenerator(), 10553 authoritiesIterator); 10554 if (intentListCopy.size() == 0) { 10555 // no more intents to match; we're not equivalent 10556 if (DEBUG_FILTERS) { 10557 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10558 + " package: " + applicationInfo.packageName 10559 + " activity: " + intent.activity.className 10560 + " origPrio: " + intent.getPriority()); 10561 } 10562 intent.setPriority(0); 10563 return; 10564 } 10565 } 10566 10567 // we found matching filter(s); app gets the max priority of all intents 10568 int cappedPriority = 0; 10569 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10570 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10571 } 10572 if (intent.getPriority() > cappedPriority) { 10573 if (DEBUG_FILTERS) { 10574 Slog.i(TAG, "Found matching filter(s);" 10575 + " cap priority to " + cappedPriority + ";" 10576 + " package: " + applicationInfo.packageName 10577 + " activity: " + intent.activity.className 10578 + " origPrio: " + intent.getPriority()); 10579 } 10580 intent.setPriority(cappedPriority); 10581 return; 10582 } 10583 // all this for nothing; the requested priority was <= what was on the system 10584 } 10585 10586 public final void addActivity(PackageParser.Activity a, String type) { 10587 mActivities.put(a.getComponentName(), a); 10588 if (DEBUG_SHOW_INFO) 10589 Log.v( 10590 TAG, " " + type + " " + 10591 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10592 if (DEBUG_SHOW_INFO) 10593 Log.v(TAG, " Class=" + a.info.name); 10594 final int NI = a.intents.size(); 10595 for (int j=0; j<NI; j++) { 10596 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10597 if ("activity".equals(type)) { 10598 final PackageSetting ps = 10599 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10600 final List<PackageParser.Activity> systemActivities = 10601 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10602 adjustPriority(systemActivities, intent); 10603 } 10604 if (DEBUG_SHOW_INFO) { 10605 Log.v(TAG, " IntentFilter:"); 10606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10607 } 10608 if (!intent.debugCheck()) { 10609 Log.w(TAG, "==> For Activity " + a.info.name); 10610 } 10611 addFilter(intent); 10612 } 10613 } 10614 10615 public final void removeActivity(PackageParser.Activity a, String type) { 10616 mActivities.remove(a.getComponentName()); 10617 if (DEBUG_SHOW_INFO) { 10618 Log.v(TAG, " " + type + " " 10619 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10620 : a.info.name) + ":"); 10621 Log.v(TAG, " Class=" + a.info.name); 10622 } 10623 final int NI = a.intents.size(); 10624 for (int j=0; j<NI; j++) { 10625 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10626 if (DEBUG_SHOW_INFO) { 10627 Log.v(TAG, " IntentFilter:"); 10628 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10629 } 10630 removeFilter(intent); 10631 } 10632 } 10633 10634 @Override 10635 protected boolean allowFilterResult( 10636 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10637 ActivityInfo filterAi = filter.activity.info; 10638 for (int i=dest.size()-1; i>=0; i--) { 10639 ActivityInfo destAi = dest.get(i).activityInfo; 10640 if (destAi.name == filterAi.name 10641 && destAi.packageName == filterAi.packageName) { 10642 return false; 10643 } 10644 } 10645 return true; 10646 } 10647 10648 @Override 10649 protected ActivityIntentInfo[] newArray(int size) { 10650 return new ActivityIntentInfo[size]; 10651 } 10652 10653 @Override 10654 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10655 if (!sUserManager.exists(userId)) return true; 10656 PackageParser.Package p = filter.activity.owner; 10657 if (p != null) { 10658 PackageSetting ps = (PackageSetting)p.mExtras; 10659 if (ps != null) { 10660 // System apps are never considered stopped for purposes of 10661 // filtering, because there may be no way for the user to 10662 // actually re-launch them. 10663 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10664 && ps.getStopped(userId); 10665 } 10666 } 10667 return false; 10668 } 10669 10670 @Override 10671 protected boolean isPackageForFilter(String packageName, 10672 PackageParser.ActivityIntentInfo info) { 10673 return packageName.equals(info.activity.owner.packageName); 10674 } 10675 10676 @Override 10677 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10678 int match, int userId) { 10679 if (!sUserManager.exists(userId)) return null; 10680 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10681 return null; 10682 } 10683 final PackageParser.Activity activity = info.activity; 10684 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10685 if (ps == null) { 10686 return null; 10687 } 10688 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10689 ps.readUserState(userId), userId); 10690 if (ai == null) { 10691 return null; 10692 } 10693 final ResolveInfo res = new ResolveInfo(); 10694 res.activityInfo = ai; 10695 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10696 res.filter = info; 10697 } 10698 if (info != null) { 10699 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10700 } 10701 res.priority = info.getPriority(); 10702 res.preferredOrder = activity.owner.mPreferredOrder; 10703 //System.out.println("Result: " + res.activityInfo.className + 10704 // " = " + res.priority); 10705 res.match = match; 10706 res.isDefault = info.hasDefault; 10707 res.labelRes = info.labelRes; 10708 res.nonLocalizedLabel = info.nonLocalizedLabel; 10709 if (userNeedsBadging(userId)) { 10710 res.noResourceId = true; 10711 } else { 10712 res.icon = info.icon; 10713 } 10714 res.iconResourceId = info.icon; 10715 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10716 return res; 10717 } 10718 10719 @Override 10720 protected void sortResults(List<ResolveInfo> results) { 10721 Collections.sort(results, mResolvePrioritySorter); 10722 } 10723 10724 @Override 10725 protected void dumpFilter(PrintWriter out, String prefix, 10726 PackageParser.ActivityIntentInfo filter) { 10727 out.print(prefix); out.print( 10728 Integer.toHexString(System.identityHashCode(filter.activity))); 10729 out.print(' '); 10730 filter.activity.printComponentShortName(out); 10731 out.print(" filter "); 10732 out.println(Integer.toHexString(System.identityHashCode(filter))); 10733 } 10734 10735 @Override 10736 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10737 return filter.activity; 10738 } 10739 10740 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10741 PackageParser.Activity activity = (PackageParser.Activity)label; 10742 out.print(prefix); out.print( 10743 Integer.toHexString(System.identityHashCode(activity))); 10744 out.print(' '); 10745 activity.printComponentShortName(out); 10746 if (count > 1) { 10747 out.print(" ("); out.print(count); out.print(" filters)"); 10748 } 10749 out.println(); 10750 } 10751 10752 // Keys are String (activity class name), values are Activity. 10753 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10754 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10755 private int mFlags; 10756 } 10757 10758 private final class ServiceIntentResolver 10759 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10760 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10761 boolean defaultOnly, int userId) { 10762 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10763 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10764 } 10765 10766 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10767 int userId) { 10768 if (!sUserManager.exists(userId)) return null; 10769 mFlags = flags; 10770 return super.queryIntent(intent, resolvedType, 10771 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10772 } 10773 10774 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10775 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10776 if (!sUserManager.exists(userId)) return null; 10777 if (packageServices == null) { 10778 return null; 10779 } 10780 mFlags = flags; 10781 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10782 final int N = packageServices.size(); 10783 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10784 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10785 10786 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10787 for (int i = 0; i < N; ++i) { 10788 intentFilters = packageServices.get(i).intents; 10789 if (intentFilters != null && intentFilters.size() > 0) { 10790 PackageParser.ServiceIntentInfo[] array = 10791 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10792 intentFilters.toArray(array); 10793 listCut.add(array); 10794 } 10795 } 10796 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10797 } 10798 10799 public final void addService(PackageParser.Service s) { 10800 mServices.put(s.getComponentName(), s); 10801 if (DEBUG_SHOW_INFO) { 10802 Log.v(TAG, " " 10803 + (s.info.nonLocalizedLabel != null 10804 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10805 Log.v(TAG, " Class=" + s.info.name); 10806 } 10807 final int NI = s.intents.size(); 10808 int j; 10809 for (j=0; j<NI; j++) { 10810 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10811 if (DEBUG_SHOW_INFO) { 10812 Log.v(TAG, " IntentFilter:"); 10813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10814 } 10815 if (!intent.debugCheck()) { 10816 Log.w(TAG, "==> For Service " + s.info.name); 10817 } 10818 addFilter(intent); 10819 } 10820 } 10821 10822 public final void removeService(PackageParser.Service s) { 10823 mServices.remove(s.getComponentName()); 10824 if (DEBUG_SHOW_INFO) { 10825 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10826 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10827 Log.v(TAG, " Class=" + s.info.name); 10828 } 10829 final int NI = s.intents.size(); 10830 int j; 10831 for (j=0; j<NI; j++) { 10832 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10833 if (DEBUG_SHOW_INFO) { 10834 Log.v(TAG, " IntentFilter:"); 10835 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10836 } 10837 removeFilter(intent); 10838 } 10839 } 10840 10841 @Override 10842 protected boolean allowFilterResult( 10843 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10844 ServiceInfo filterSi = filter.service.info; 10845 for (int i=dest.size()-1; i>=0; i--) { 10846 ServiceInfo destAi = dest.get(i).serviceInfo; 10847 if (destAi.name == filterSi.name 10848 && destAi.packageName == filterSi.packageName) { 10849 return false; 10850 } 10851 } 10852 return true; 10853 } 10854 10855 @Override 10856 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10857 return new PackageParser.ServiceIntentInfo[size]; 10858 } 10859 10860 @Override 10861 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10862 if (!sUserManager.exists(userId)) return true; 10863 PackageParser.Package p = filter.service.owner; 10864 if (p != null) { 10865 PackageSetting ps = (PackageSetting)p.mExtras; 10866 if (ps != null) { 10867 // System apps are never considered stopped for purposes of 10868 // filtering, because there may be no way for the user to 10869 // actually re-launch them. 10870 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10871 && ps.getStopped(userId); 10872 } 10873 } 10874 return false; 10875 } 10876 10877 @Override 10878 protected boolean isPackageForFilter(String packageName, 10879 PackageParser.ServiceIntentInfo info) { 10880 return packageName.equals(info.service.owner.packageName); 10881 } 10882 10883 @Override 10884 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10885 int match, int userId) { 10886 if (!sUserManager.exists(userId)) return null; 10887 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10888 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10889 return null; 10890 } 10891 final PackageParser.Service service = info.service; 10892 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10893 if (ps == null) { 10894 return null; 10895 } 10896 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10897 ps.readUserState(userId), userId); 10898 if (si == null) { 10899 return null; 10900 } 10901 final ResolveInfo res = new ResolveInfo(); 10902 res.serviceInfo = si; 10903 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10904 res.filter = filter; 10905 } 10906 res.priority = info.getPriority(); 10907 res.preferredOrder = service.owner.mPreferredOrder; 10908 res.match = match; 10909 res.isDefault = info.hasDefault; 10910 res.labelRes = info.labelRes; 10911 res.nonLocalizedLabel = info.nonLocalizedLabel; 10912 res.icon = info.icon; 10913 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10914 return res; 10915 } 10916 10917 @Override 10918 protected void sortResults(List<ResolveInfo> results) { 10919 Collections.sort(results, mResolvePrioritySorter); 10920 } 10921 10922 @Override 10923 protected void dumpFilter(PrintWriter out, String prefix, 10924 PackageParser.ServiceIntentInfo filter) { 10925 out.print(prefix); out.print( 10926 Integer.toHexString(System.identityHashCode(filter.service))); 10927 out.print(' '); 10928 filter.service.printComponentShortName(out); 10929 out.print(" filter "); 10930 out.println(Integer.toHexString(System.identityHashCode(filter))); 10931 } 10932 10933 @Override 10934 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10935 return filter.service; 10936 } 10937 10938 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10939 PackageParser.Service service = (PackageParser.Service)label; 10940 out.print(prefix); out.print( 10941 Integer.toHexString(System.identityHashCode(service))); 10942 out.print(' '); 10943 service.printComponentShortName(out); 10944 if (count > 1) { 10945 out.print(" ("); out.print(count); out.print(" filters)"); 10946 } 10947 out.println(); 10948 } 10949 10950// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10951// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10952// final List<ResolveInfo> retList = Lists.newArrayList(); 10953// while (i.hasNext()) { 10954// final ResolveInfo resolveInfo = (ResolveInfo) i; 10955// if (isEnabledLP(resolveInfo.serviceInfo)) { 10956// retList.add(resolveInfo); 10957// } 10958// } 10959// return retList; 10960// } 10961 10962 // Keys are String (activity class name), values are Activity. 10963 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10964 = new ArrayMap<ComponentName, PackageParser.Service>(); 10965 private int mFlags; 10966 }; 10967 10968 private final class ProviderIntentResolver 10969 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10970 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10971 boolean defaultOnly, int userId) { 10972 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10973 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10974 } 10975 10976 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10977 int userId) { 10978 if (!sUserManager.exists(userId)) 10979 return null; 10980 mFlags = flags; 10981 return super.queryIntent(intent, resolvedType, 10982 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10983 } 10984 10985 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10986 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10987 if (!sUserManager.exists(userId)) 10988 return null; 10989 if (packageProviders == null) { 10990 return null; 10991 } 10992 mFlags = flags; 10993 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10994 final int N = packageProviders.size(); 10995 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10996 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10997 10998 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10999 for (int i = 0; i < N; ++i) { 11000 intentFilters = packageProviders.get(i).intents; 11001 if (intentFilters != null && intentFilters.size() > 0) { 11002 PackageParser.ProviderIntentInfo[] array = 11003 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11004 intentFilters.toArray(array); 11005 listCut.add(array); 11006 } 11007 } 11008 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11009 } 11010 11011 public final void addProvider(PackageParser.Provider p) { 11012 if (mProviders.containsKey(p.getComponentName())) { 11013 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11014 return; 11015 } 11016 11017 mProviders.put(p.getComponentName(), p); 11018 if (DEBUG_SHOW_INFO) { 11019 Log.v(TAG, " " 11020 + (p.info.nonLocalizedLabel != null 11021 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11022 Log.v(TAG, " Class=" + p.info.name); 11023 } 11024 final int NI = p.intents.size(); 11025 int j; 11026 for (j = 0; j < NI; j++) { 11027 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11028 if (DEBUG_SHOW_INFO) { 11029 Log.v(TAG, " IntentFilter:"); 11030 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11031 } 11032 if (!intent.debugCheck()) { 11033 Log.w(TAG, "==> For Provider " + p.info.name); 11034 } 11035 addFilter(intent); 11036 } 11037 } 11038 11039 public final void removeProvider(PackageParser.Provider p) { 11040 mProviders.remove(p.getComponentName()); 11041 if (DEBUG_SHOW_INFO) { 11042 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11043 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11044 Log.v(TAG, " Class=" + p.info.name); 11045 } 11046 final int NI = p.intents.size(); 11047 int j; 11048 for (j = 0; j < NI; j++) { 11049 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11050 if (DEBUG_SHOW_INFO) { 11051 Log.v(TAG, " IntentFilter:"); 11052 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11053 } 11054 removeFilter(intent); 11055 } 11056 } 11057 11058 @Override 11059 protected boolean allowFilterResult( 11060 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11061 ProviderInfo filterPi = filter.provider.info; 11062 for (int i = dest.size() - 1; i >= 0; i--) { 11063 ProviderInfo destPi = dest.get(i).providerInfo; 11064 if (destPi.name == filterPi.name 11065 && destPi.packageName == filterPi.packageName) { 11066 return false; 11067 } 11068 } 11069 return true; 11070 } 11071 11072 @Override 11073 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11074 return new PackageParser.ProviderIntentInfo[size]; 11075 } 11076 11077 @Override 11078 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11079 if (!sUserManager.exists(userId)) 11080 return true; 11081 PackageParser.Package p = filter.provider.owner; 11082 if (p != null) { 11083 PackageSetting ps = (PackageSetting) p.mExtras; 11084 if (ps != null) { 11085 // System apps are never considered stopped for purposes of 11086 // filtering, because there may be no way for the user to 11087 // actually re-launch them. 11088 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11089 && ps.getStopped(userId); 11090 } 11091 } 11092 return false; 11093 } 11094 11095 @Override 11096 protected boolean isPackageForFilter(String packageName, 11097 PackageParser.ProviderIntentInfo info) { 11098 return packageName.equals(info.provider.owner.packageName); 11099 } 11100 11101 @Override 11102 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11103 int match, int userId) { 11104 if (!sUserManager.exists(userId)) 11105 return null; 11106 final PackageParser.ProviderIntentInfo info = filter; 11107 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11108 return null; 11109 } 11110 final PackageParser.Provider provider = info.provider; 11111 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11112 if (ps == null) { 11113 return null; 11114 } 11115 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11116 ps.readUserState(userId), userId); 11117 if (pi == null) { 11118 return null; 11119 } 11120 final ResolveInfo res = new ResolveInfo(); 11121 res.providerInfo = pi; 11122 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11123 res.filter = filter; 11124 } 11125 res.priority = info.getPriority(); 11126 res.preferredOrder = provider.owner.mPreferredOrder; 11127 res.match = match; 11128 res.isDefault = info.hasDefault; 11129 res.labelRes = info.labelRes; 11130 res.nonLocalizedLabel = info.nonLocalizedLabel; 11131 res.icon = info.icon; 11132 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11133 return res; 11134 } 11135 11136 @Override 11137 protected void sortResults(List<ResolveInfo> results) { 11138 Collections.sort(results, mResolvePrioritySorter); 11139 } 11140 11141 @Override 11142 protected void dumpFilter(PrintWriter out, String prefix, 11143 PackageParser.ProviderIntentInfo filter) { 11144 out.print(prefix); 11145 out.print( 11146 Integer.toHexString(System.identityHashCode(filter.provider))); 11147 out.print(' '); 11148 filter.provider.printComponentShortName(out); 11149 out.print(" filter "); 11150 out.println(Integer.toHexString(System.identityHashCode(filter))); 11151 } 11152 11153 @Override 11154 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11155 return filter.provider; 11156 } 11157 11158 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11159 PackageParser.Provider provider = (PackageParser.Provider)label; 11160 out.print(prefix); out.print( 11161 Integer.toHexString(System.identityHashCode(provider))); 11162 out.print(' '); 11163 provider.printComponentShortName(out); 11164 if (count > 1) { 11165 out.print(" ("); out.print(count); out.print(" filters)"); 11166 } 11167 out.println(); 11168 } 11169 11170 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11171 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11172 private int mFlags; 11173 } 11174 11175 private static final class EphemeralIntentResolver 11176 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11177 @Override 11178 protected EphemeralResolveIntentInfo[] newArray(int size) { 11179 return new EphemeralResolveIntentInfo[size]; 11180 } 11181 11182 @Override 11183 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11184 return true; 11185 } 11186 11187 @Override 11188 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11189 int userId) { 11190 if (!sUserManager.exists(userId)) { 11191 return null; 11192 } 11193 return info.getEphemeralResolveInfo(); 11194 } 11195 } 11196 11197 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11198 new Comparator<ResolveInfo>() { 11199 public int compare(ResolveInfo r1, ResolveInfo r2) { 11200 int v1 = r1.priority; 11201 int v2 = r2.priority; 11202 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11203 if (v1 != v2) { 11204 return (v1 > v2) ? -1 : 1; 11205 } 11206 v1 = r1.preferredOrder; 11207 v2 = r2.preferredOrder; 11208 if (v1 != v2) { 11209 return (v1 > v2) ? -1 : 1; 11210 } 11211 if (r1.isDefault != r2.isDefault) { 11212 return r1.isDefault ? -1 : 1; 11213 } 11214 v1 = r1.match; 11215 v2 = r2.match; 11216 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11217 if (v1 != v2) { 11218 return (v1 > v2) ? -1 : 1; 11219 } 11220 if (r1.system != r2.system) { 11221 return r1.system ? -1 : 1; 11222 } 11223 if (r1.activityInfo != null) { 11224 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11225 } 11226 if (r1.serviceInfo != null) { 11227 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11228 } 11229 if (r1.providerInfo != null) { 11230 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11231 } 11232 return 0; 11233 } 11234 }; 11235 11236 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11237 new Comparator<ProviderInfo>() { 11238 public int compare(ProviderInfo p1, ProviderInfo p2) { 11239 final int v1 = p1.initOrder; 11240 final int v2 = p2.initOrder; 11241 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11242 } 11243 }; 11244 11245 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11246 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11247 final int[] userIds) { 11248 mHandler.post(new Runnable() { 11249 @Override 11250 public void run() { 11251 try { 11252 final IActivityManager am = ActivityManagerNative.getDefault(); 11253 if (am == null) return; 11254 final int[] resolvedUserIds; 11255 if (userIds == null) { 11256 resolvedUserIds = am.getRunningUserIds(); 11257 } else { 11258 resolvedUserIds = userIds; 11259 } 11260 for (int id : resolvedUserIds) { 11261 final Intent intent = new Intent(action, 11262 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11263 if (extras != null) { 11264 intent.putExtras(extras); 11265 } 11266 if (targetPkg != null) { 11267 intent.setPackage(targetPkg); 11268 } 11269 // Modify the UID when posting to other users 11270 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11271 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11272 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11273 intent.putExtra(Intent.EXTRA_UID, uid); 11274 } 11275 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11276 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11277 if (DEBUG_BROADCASTS) { 11278 RuntimeException here = new RuntimeException("here"); 11279 here.fillInStackTrace(); 11280 Slog.d(TAG, "Sending to user " + id + ": " 11281 + intent.toShortString(false, true, false, false) 11282 + " " + intent.getExtras(), here); 11283 } 11284 am.broadcastIntent(null, intent, null, finishedReceiver, 11285 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11286 null, finishedReceiver != null, false, id); 11287 } 11288 } catch (RemoteException ex) { 11289 } 11290 } 11291 }); 11292 } 11293 11294 /** 11295 * Check if the external storage media is available. This is true if there 11296 * is a mounted external storage medium or if the external storage is 11297 * emulated. 11298 */ 11299 private boolean isExternalMediaAvailable() { 11300 return mMediaMounted || Environment.isExternalStorageEmulated(); 11301 } 11302 11303 @Override 11304 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11305 // writer 11306 synchronized (mPackages) { 11307 if (!isExternalMediaAvailable()) { 11308 // If the external storage is no longer mounted at this point, 11309 // the caller may not have been able to delete all of this 11310 // packages files and can not delete any more. Bail. 11311 return null; 11312 } 11313 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11314 if (lastPackage != null) { 11315 pkgs.remove(lastPackage); 11316 } 11317 if (pkgs.size() > 0) { 11318 return pkgs.get(0); 11319 } 11320 } 11321 return null; 11322 } 11323 11324 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11325 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11326 userId, andCode ? 1 : 0, packageName); 11327 if (mSystemReady) { 11328 msg.sendToTarget(); 11329 } else { 11330 if (mPostSystemReadyMessages == null) { 11331 mPostSystemReadyMessages = new ArrayList<>(); 11332 } 11333 mPostSystemReadyMessages.add(msg); 11334 } 11335 } 11336 11337 void startCleaningPackages() { 11338 // reader 11339 if (!isExternalMediaAvailable()) { 11340 return; 11341 } 11342 synchronized (mPackages) { 11343 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11344 return; 11345 } 11346 } 11347 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11348 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11349 IActivityManager am = ActivityManagerNative.getDefault(); 11350 if (am != null) { 11351 try { 11352 am.startService(null, intent, null, mContext.getOpPackageName(), 11353 UserHandle.USER_SYSTEM); 11354 } catch (RemoteException e) { 11355 } 11356 } 11357 } 11358 11359 @Override 11360 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11361 int installFlags, String installerPackageName, int userId) { 11362 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11363 11364 final int callingUid = Binder.getCallingUid(); 11365 enforceCrossUserPermission(callingUid, userId, 11366 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11367 11368 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11369 try { 11370 if (observer != null) { 11371 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11372 } 11373 } catch (RemoteException re) { 11374 } 11375 return; 11376 } 11377 11378 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11379 installFlags |= PackageManager.INSTALL_FROM_ADB; 11380 11381 } else { 11382 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11383 // about installerPackageName. 11384 11385 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11386 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11387 } 11388 11389 UserHandle user; 11390 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11391 user = UserHandle.ALL; 11392 } else { 11393 user = new UserHandle(userId); 11394 } 11395 11396 // Only system components can circumvent runtime permissions when installing. 11397 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11398 && mContext.checkCallingOrSelfPermission(Manifest.permission 11399 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11400 throw new SecurityException("You need the " 11401 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11402 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11403 } 11404 11405 final File originFile = new File(originPath); 11406 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11407 11408 final Message msg = mHandler.obtainMessage(INIT_COPY); 11409 final VerificationInfo verificationInfo = new VerificationInfo( 11410 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11411 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11412 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11413 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11414 null /*certificates*/); 11415 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11416 msg.obj = params; 11417 11418 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11419 System.identityHashCode(msg.obj)); 11420 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11421 System.identityHashCode(msg.obj)); 11422 11423 mHandler.sendMessage(msg); 11424 } 11425 11426 void installStage(String packageName, File stagedDir, String stagedCid, 11427 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11428 String installerPackageName, int installerUid, UserHandle user, 11429 Certificate[][] certificates) { 11430 if (DEBUG_EPHEMERAL) { 11431 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11432 Slog.d(TAG, "Ephemeral install of " + packageName); 11433 } 11434 } 11435 final VerificationInfo verificationInfo = new VerificationInfo( 11436 sessionParams.originatingUri, sessionParams.referrerUri, 11437 sessionParams.originatingUid, installerUid); 11438 11439 final OriginInfo origin; 11440 if (stagedDir != null) { 11441 origin = OriginInfo.fromStagedFile(stagedDir); 11442 } else { 11443 origin = OriginInfo.fromStagedContainer(stagedCid); 11444 } 11445 11446 final Message msg = mHandler.obtainMessage(INIT_COPY); 11447 final InstallParams params = new InstallParams(origin, null, observer, 11448 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11449 verificationInfo, user, sessionParams.abiOverride, 11450 sessionParams.grantedRuntimePermissions, certificates); 11451 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11452 msg.obj = params; 11453 11454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11455 System.identityHashCode(msg.obj)); 11456 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11457 System.identityHashCode(msg.obj)); 11458 11459 mHandler.sendMessage(msg); 11460 } 11461 11462 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11463 int userId) { 11464 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11465 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11466 } 11467 11468 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11469 int appId, int userId) { 11470 Bundle extras = new Bundle(1); 11471 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11472 11473 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11474 packageName, extras, 0, null, null, new int[] {userId}); 11475 try { 11476 IActivityManager am = ActivityManagerNative.getDefault(); 11477 if (isSystem && am.isUserRunning(userId, 0)) { 11478 // The just-installed/enabled app is bundled on the system, so presumed 11479 // to be able to run automatically without needing an explicit launch. 11480 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11481 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11482 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11483 .setPackage(packageName); 11484 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11485 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11486 } 11487 } catch (RemoteException e) { 11488 // shouldn't happen 11489 Slog.w(TAG, "Unable to bootstrap installed package", e); 11490 } 11491 } 11492 11493 @Override 11494 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11495 int userId) { 11496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11497 PackageSetting pkgSetting; 11498 final int uid = Binder.getCallingUid(); 11499 enforceCrossUserPermission(uid, userId, 11500 true /* requireFullPermission */, true /* checkShell */, 11501 "setApplicationHiddenSetting for user " + userId); 11502 11503 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11504 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11505 return false; 11506 } 11507 11508 long callingId = Binder.clearCallingIdentity(); 11509 try { 11510 boolean sendAdded = false; 11511 boolean sendRemoved = false; 11512 // writer 11513 synchronized (mPackages) { 11514 pkgSetting = mSettings.mPackages.get(packageName); 11515 if (pkgSetting == null) { 11516 return false; 11517 } 11518 // Do not allow "android" is being disabled 11519 if ("android".equals(packageName)) { 11520 Slog.w(TAG, "Cannot hide package: android"); 11521 return false; 11522 } 11523 // Only allow protected packages to hide themselves. 11524 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11525 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11526 Slog.w(TAG, "Not hiding protected package: " + packageName); 11527 return false; 11528 } 11529 11530 if (pkgSetting.getHidden(userId) != hidden) { 11531 pkgSetting.setHidden(hidden, userId); 11532 mSettings.writePackageRestrictionsLPr(userId); 11533 if (hidden) { 11534 sendRemoved = true; 11535 } else { 11536 sendAdded = true; 11537 } 11538 } 11539 } 11540 if (sendAdded) { 11541 sendPackageAddedForUser(packageName, pkgSetting, userId); 11542 return true; 11543 } 11544 if (sendRemoved) { 11545 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11546 "hiding pkg"); 11547 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11548 return true; 11549 } 11550 } finally { 11551 Binder.restoreCallingIdentity(callingId); 11552 } 11553 return false; 11554 } 11555 11556 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11557 int userId) { 11558 final PackageRemovedInfo info = new PackageRemovedInfo(); 11559 info.removedPackage = packageName; 11560 info.removedUsers = new int[] {userId}; 11561 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11562 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11563 } 11564 11565 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11566 if (pkgList.length > 0) { 11567 Bundle extras = new Bundle(1); 11568 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11569 11570 sendPackageBroadcast( 11571 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11572 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11573 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11574 new int[] {userId}); 11575 } 11576 } 11577 11578 /** 11579 * Returns true if application is not found or there was an error. Otherwise it returns 11580 * the hidden state of the package for the given user. 11581 */ 11582 @Override 11583 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11585 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11586 true /* requireFullPermission */, false /* checkShell */, 11587 "getApplicationHidden for user " + userId); 11588 PackageSetting pkgSetting; 11589 long callingId = Binder.clearCallingIdentity(); 11590 try { 11591 // writer 11592 synchronized (mPackages) { 11593 pkgSetting = mSettings.mPackages.get(packageName); 11594 if (pkgSetting == null) { 11595 return true; 11596 } 11597 return pkgSetting.getHidden(userId); 11598 } 11599 } finally { 11600 Binder.restoreCallingIdentity(callingId); 11601 } 11602 } 11603 11604 /** 11605 * @hide 11606 */ 11607 @Override 11608 public int installExistingPackageAsUser(String packageName, int userId) { 11609 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11610 null); 11611 PackageSetting pkgSetting; 11612 final int uid = Binder.getCallingUid(); 11613 enforceCrossUserPermission(uid, userId, 11614 true /* requireFullPermission */, true /* checkShell */, 11615 "installExistingPackage for user " + userId); 11616 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11617 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11618 } 11619 11620 long callingId = Binder.clearCallingIdentity(); 11621 try { 11622 boolean installed = false; 11623 11624 // writer 11625 synchronized (mPackages) { 11626 pkgSetting = mSettings.mPackages.get(packageName); 11627 if (pkgSetting == null) { 11628 return PackageManager.INSTALL_FAILED_INVALID_URI; 11629 } 11630 if (!pkgSetting.getInstalled(userId)) { 11631 pkgSetting.setInstalled(true, userId); 11632 pkgSetting.setHidden(false, userId); 11633 mSettings.writePackageRestrictionsLPr(userId); 11634 installed = true; 11635 } 11636 } 11637 11638 if (installed) { 11639 if (pkgSetting.pkg != null) { 11640 synchronized (mInstallLock) { 11641 // We don't need to freeze for a brand new install 11642 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11643 } 11644 } 11645 sendPackageAddedForUser(packageName, pkgSetting, userId); 11646 } 11647 } finally { 11648 Binder.restoreCallingIdentity(callingId); 11649 } 11650 11651 return PackageManager.INSTALL_SUCCEEDED; 11652 } 11653 11654 boolean isUserRestricted(int userId, String restrictionKey) { 11655 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11656 if (restrictions.getBoolean(restrictionKey, false)) { 11657 Log.w(TAG, "User is restricted: " + restrictionKey); 11658 return true; 11659 } 11660 return false; 11661 } 11662 11663 @Override 11664 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11665 int userId) { 11666 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11667 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11668 true /* requireFullPermission */, true /* checkShell */, 11669 "setPackagesSuspended for user " + userId); 11670 11671 if (ArrayUtils.isEmpty(packageNames)) { 11672 return packageNames; 11673 } 11674 11675 // List of package names for whom the suspended state has changed. 11676 List<String> changedPackages = new ArrayList<>(packageNames.length); 11677 // List of package names for whom the suspended state is not set as requested in this 11678 // method. 11679 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11680 long callingId = Binder.clearCallingIdentity(); 11681 try { 11682 for (int i = 0; i < packageNames.length; i++) { 11683 String packageName = packageNames[i]; 11684 boolean changed = false; 11685 final int appId; 11686 synchronized (mPackages) { 11687 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11688 if (pkgSetting == null) { 11689 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11690 + "\". Skipping suspending/un-suspending."); 11691 unactionedPackages.add(packageName); 11692 continue; 11693 } 11694 appId = pkgSetting.appId; 11695 if (pkgSetting.getSuspended(userId) != suspended) { 11696 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11697 unactionedPackages.add(packageName); 11698 continue; 11699 } 11700 pkgSetting.setSuspended(suspended, userId); 11701 mSettings.writePackageRestrictionsLPr(userId); 11702 changed = true; 11703 changedPackages.add(packageName); 11704 } 11705 } 11706 11707 if (changed && suspended) { 11708 killApplication(packageName, UserHandle.getUid(userId, appId), 11709 "suspending package"); 11710 } 11711 } 11712 } finally { 11713 Binder.restoreCallingIdentity(callingId); 11714 } 11715 11716 if (!changedPackages.isEmpty()) { 11717 sendPackagesSuspendedForUser(changedPackages.toArray( 11718 new String[changedPackages.size()]), userId, suspended); 11719 } 11720 11721 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11722 } 11723 11724 @Override 11725 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11726 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11727 true /* requireFullPermission */, false /* checkShell */, 11728 "isPackageSuspendedForUser for user " + userId); 11729 synchronized (mPackages) { 11730 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11731 if (pkgSetting == null) { 11732 throw new IllegalArgumentException("Unknown target package: " + packageName); 11733 } 11734 return pkgSetting.getSuspended(userId); 11735 } 11736 } 11737 11738 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11739 if (isPackageDeviceAdmin(packageName, userId)) { 11740 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11741 + "\": has an active device admin"); 11742 return false; 11743 } 11744 11745 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11746 if (packageName.equals(activeLauncherPackageName)) { 11747 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11748 + "\": contains the active launcher"); 11749 return false; 11750 } 11751 11752 if (packageName.equals(mRequiredInstallerPackage)) { 11753 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11754 + "\": required for package installation"); 11755 return false; 11756 } 11757 11758 if (packageName.equals(mRequiredVerifierPackage)) { 11759 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11760 + "\": required for package verification"); 11761 return false; 11762 } 11763 11764 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11765 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11766 + "\": is the default dialer"); 11767 return false; 11768 } 11769 11770 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11771 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11772 + "\": protected package"); 11773 return false; 11774 } 11775 11776 return true; 11777 } 11778 11779 private String getActiveLauncherPackageName(int userId) { 11780 Intent intent = new Intent(Intent.ACTION_MAIN); 11781 intent.addCategory(Intent.CATEGORY_HOME); 11782 ResolveInfo resolveInfo = resolveIntent( 11783 intent, 11784 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11785 PackageManager.MATCH_DEFAULT_ONLY, 11786 userId); 11787 11788 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11789 } 11790 11791 private String getDefaultDialerPackageName(int userId) { 11792 synchronized (mPackages) { 11793 return mSettings.getDefaultDialerPackageNameLPw(userId); 11794 } 11795 } 11796 11797 @Override 11798 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11799 mContext.enforceCallingOrSelfPermission( 11800 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11801 "Only package verification agents can verify applications"); 11802 11803 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11804 final PackageVerificationResponse response = new PackageVerificationResponse( 11805 verificationCode, Binder.getCallingUid()); 11806 msg.arg1 = id; 11807 msg.obj = response; 11808 mHandler.sendMessage(msg); 11809 } 11810 11811 @Override 11812 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11813 long millisecondsToDelay) { 11814 mContext.enforceCallingOrSelfPermission( 11815 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11816 "Only package verification agents can extend verification timeouts"); 11817 11818 final PackageVerificationState state = mPendingVerification.get(id); 11819 final PackageVerificationResponse response = new PackageVerificationResponse( 11820 verificationCodeAtTimeout, Binder.getCallingUid()); 11821 11822 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11823 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11824 } 11825 if (millisecondsToDelay < 0) { 11826 millisecondsToDelay = 0; 11827 } 11828 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11829 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11830 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11831 } 11832 11833 if ((state != null) && !state.timeoutExtended()) { 11834 state.extendTimeout(); 11835 11836 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11837 msg.arg1 = id; 11838 msg.obj = response; 11839 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11840 } 11841 } 11842 11843 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11844 int verificationCode, UserHandle user) { 11845 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11846 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11847 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11848 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11849 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11850 11851 mContext.sendBroadcastAsUser(intent, user, 11852 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11853 } 11854 11855 private ComponentName matchComponentForVerifier(String packageName, 11856 List<ResolveInfo> receivers) { 11857 ActivityInfo targetReceiver = null; 11858 11859 final int NR = receivers.size(); 11860 for (int i = 0; i < NR; i++) { 11861 final ResolveInfo info = receivers.get(i); 11862 if (info.activityInfo == null) { 11863 continue; 11864 } 11865 11866 if (packageName.equals(info.activityInfo.packageName)) { 11867 targetReceiver = info.activityInfo; 11868 break; 11869 } 11870 } 11871 11872 if (targetReceiver == null) { 11873 return null; 11874 } 11875 11876 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11877 } 11878 11879 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11880 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11881 if (pkgInfo.verifiers.length == 0) { 11882 return null; 11883 } 11884 11885 final int N = pkgInfo.verifiers.length; 11886 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11887 for (int i = 0; i < N; i++) { 11888 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11889 11890 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11891 receivers); 11892 if (comp == null) { 11893 continue; 11894 } 11895 11896 final int verifierUid = getUidForVerifier(verifierInfo); 11897 if (verifierUid == -1) { 11898 continue; 11899 } 11900 11901 if (DEBUG_VERIFY) { 11902 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11903 + " with the correct signature"); 11904 } 11905 sufficientVerifiers.add(comp); 11906 verificationState.addSufficientVerifier(verifierUid); 11907 } 11908 11909 return sufficientVerifiers; 11910 } 11911 11912 private int getUidForVerifier(VerifierInfo verifierInfo) { 11913 synchronized (mPackages) { 11914 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11915 if (pkg == null) { 11916 return -1; 11917 } else if (pkg.mSignatures.length != 1) { 11918 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11919 + " has more than one signature; ignoring"); 11920 return -1; 11921 } 11922 11923 /* 11924 * If the public key of the package's signature does not match 11925 * our expected public key, then this is a different package and 11926 * we should skip. 11927 */ 11928 11929 final byte[] expectedPublicKey; 11930 try { 11931 final Signature verifierSig = pkg.mSignatures[0]; 11932 final PublicKey publicKey = verifierSig.getPublicKey(); 11933 expectedPublicKey = publicKey.getEncoded(); 11934 } catch (CertificateException e) { 11935 return -1; 11936 } 11937 11938 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11939 11940 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11941 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11942 + " does not have the expected public key; ignoring"); 11943 return -1; 11944 } 11945 11946 return pkg.applicationInfo.uid; 11947 } 11948 } 11949 11950 @Override 11951 public void finishPackageInstall(int token, boolean didLaunch) { 11952 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11953 11954 if (DEBUG_INSTALL) { 11955 Slog.v(TAG, "BM finishing package install for " + token); 11956 } 11957 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11958 11959 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11960 mHandler.sendMessage(msg); 11961 } 11962 11963 /** 11964 * Get the verification agent timeout. 11965 * 11966 * @return verification timeout in milliseconds 11967 */ 11968 private long getVerificationTimeout() { 11969 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11970 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11971 DEFAULT_VERIFICATION_TIMEOUT); 11972 } 11973 11974 /** 11975 * Get the default verification agent response code. 11976 * 11977 * @return default verification response code 11978 */ 11979 private int getDefaultVerificationResponse() { 11980 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11981 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11982 DEFAULT_VERIFICATION_RESPONSE); 11983 } 11984 11985 /** 11986 * Check whether or not package verification has been enabled. 11987 * 11988 * @return true if verification should be performed 11989 */ 11990 private boolean isVerificationEnabled(int userId, int installFlags) { 11991 if (!DEFAULT_VERIFY_ENABLE) { 11992 return false; 11993 } 11994 // Ephemeral apps don't get the full verification treatment 11995 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11996 if (DEBUG_EPHEMERAL) { 11997 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11998 } 11999 return false; 12000 } 12001 12002 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12003 12004 // Check if installing from ADB 12005 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12006 // Do not run verification in a test harness environment 12007 if (ActivityManager.isRunningInTestHarness()) { 12008 return false; 12009 } 12010 if (ensureVerifyAppsEnabled) { 12011 return true; 12012 } 12013 // Check if the developer does not want package verification for ADB installs 12014 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12015 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12016 return false; 12017 } 12018 } 12019 12020 if (ensureVerifyAppsEnabled) { 12021 return true; 12022 } 12023 12024 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12025 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12026 } 12027 12028 @Override 12029 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12030 throws RemoteException { 12031 mContext.enforceCallingOrSelfPermission( 12032 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12033 "Only intentfilter verification agents can verify applications"); 12034 12035 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12036 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12037 Binder.getCallingUid(), verificationCode, failedDomains); 12038 msg.arg1 = id; 12039 msg.obj = response; 12040 mHandler.sendMessage(msg); 12041 } 12042 12043 @Override 12044 public int getIntentVerificationStatus(String packageName, int userId) { 12045 synchronized (mPackages) { 12046 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12047 } 12048 } 12049 12050 @Override 12051 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12052 mContext.enforceCallingOrSelfPermission( 12053 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12054 12055 boolean result = false; 12056 synchronized (mPackages) { 12057 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12058 } 12059 if (result) { 12060 scheduleWritePackageRestrictionsLocked(userId); 12061 } 12062 return result; 12063 } 12064 12065 @Override 12066 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12067 String packageName) { 12068 synchronized (mPackages) { 12069 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12070 } 12071 } 12072 12073 @Override 12074 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12075 if (TextUtils.isEmpty(packageName)) { 12076 return ParceledListSlice.emptyList(); 12077 } 12078 synchronized (mPackages) { 12079 PackageParser.Package pkg = mPackages.get(packageName); 12080 if (pkg == null || pkg.activities == null) { 12081 return ParceledListSlice.emptyList(); 12082 } 12083 final int count = pkg.activities.size(); 12084 ArrayList<IntentFilter> result = new ArrayList<>(); 12085 for (int n=0; n<count; n++) { 12086 PackageParser.Activity activity = pkg.activities.get(n); 12087 if (activity.intents != null && activity.intents.size() > 0) { 12088 result.addAll(activity.intents); 12089 } 12090 } 12091 return new ParceledListSlice<>(result); 12092 } 12093 } 12094 12095 @Override 12096 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12097 mContext.enforceCallingOrSelfPermission( 12098 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12099 12100 synchronized (mPackages) { 12101 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12102 if (packageName != null) { 12103 result |= updateIntentVerificationStatus(packageName, 12104 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12105 userId); 12106 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12107 packageName, userId); 12108 } 12109 return result; 12110 } 12111 } 12112 12113 @Override 12114 public String getDefaultBrowserPackageName(int userId) { 12115 synchronized (mPackages) { 12116 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12117 } 12118 } 12119 12120 /** 12121 * Get the "allow unknown sources" setting. 12122 * 12123 * @return the current "allow unknown sources" setting 12124 */ 12125 private int getUnknownSourcesSettings() { 12126 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12127 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12128 -1); 12129 } 12130 12131 @Override 12132 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12133 final int uid = Binder.getCallingUid(); 12134 // writer 12135 synchronized (mPackages) { 12136 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12137 if (targetPackageSetting == null) { 12138 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12139 } 12140 12141 PackageSetting installerPackageSetting; 12142 if (installerPackageName != null) { 12143 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12144 if (installerPackageSetting == null) { 12145 throw new IllegalArgumentException("Unknown installer package: " 12146 + installerPackageName); 12147 } 12148 } else { 12149 installerPackageSetting = null; 12150 } 12151 12152 Signature[] callerSignature; 12153 Object obj = mSettings.getUserIdLPr(uid); 12154 if (obj != null) { 12155 if (obj instanceof SharedUserSetting) { 12156 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12157 } else if (obj instanceof PackageSetting) { 12158 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12159 } else { 12160 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12161 } 12162 } else { 12163 throw new SecurityException("Unknown calling UID: " + uid); 12164 } 12165 12166 // Verify: can't set installerPackageName to a package that is 12167 // not signed with the same cert as the caller. 12168 if (installerPackageSetting != null) { 12169 if (compareSignatures(callerSignature, 12170 installerPackageSetting.signatures.mSignatures) 12171 != PackageManager.SIGNATURE_MATCH) { 12172 throw new SecurityException( 12173 "Caller does not have same cert as new installer package " 12174 + installerPackageName); 12175 } 12176 } 12177 12178 // Verify: if target already has an installer package, it must 12179 // be signed with the same cert as the caller. 12180 if (targetPackageSetting.installerPackageName != null) { 12181 PackageSetting setting = mSettings.mPackages.get( 12182 targetPackageSetting.installerPackageName); 12183 // If the currently set package isn't valid, then it's always 12184 // okay to change it. 12185 if (setting != null) { 12186 if (compareSignatures(callerSignature, 12187 setting.signatures.mSignatures) 12188 != PackageManager.SIGNATURE_MATCH) { 12189 throw new SecurityException( 12190 "Caller does not have same cert as old installer package " 12191 + targetPackageSetting.installerPackageName); 12192 } 12193 } 12194 } 12195 12196 // Okay! 12197 targetPackageSetting.installerPackageName = installerPackageName; 12198 if (installerPackageName != null) { 12199 mSettings.mInstallerPackages.add(installerPackageName); 12200 } 12201 scheduleWriteSettingsLocked(); 12202 } 12203 } 12204 12205 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12206 // Queue up an async operation since the package installation may take a little while. 12207 mHandler.post(new Runnable() { 12208 public void run() { 12209 mHandler.removeCallbacks(this); 12210 // Result object to be returned 12211 PackageInstalledInfo res = new PackageInstalledInfo(); 12212 res.setReturnCode(currentStatus); 12213 res.uid = -1; 12214 res.pkg = null; 12215 res.removedInfo = null; 12216 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12217 args.doPreInstall(res.returnCode); 12218 synchronized (mInstallLock) { 12219 installPackageTracedLI(args, res); 12220 } 12221 args.doPostInstall(res.returnCode, res.uid); 12222 } 12223 12224 // A restore should be performed at this point if (a) the install 12225 // succeeded, (b) the operation is not an update, and (c) the new 12226 // package has not opted out of backup participation. 12227 final boolean update = res.removedInfo != null 12228 && res.removedInfo.removedPackage != null; 12229 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12230 boolean doRestore = !update 12231 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12232 12233 // Set up the post-install work request bookkeeping. This will be used 12234 // and cleaned up by the post-install event handling regardless of whether 12235 // there's a restore pass performed. Token values are >= 1. 12236 int token; 12237 if (mNextInstallToken < 0) mNextInstallToken = 1; 12238 token = mNextInstallToken++; 12239 12240 PostInstallData data = new PostInstallData(args, res); 12241 mRunningInstalls.put(token, data); 12242 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12243 12244 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12245 // Pass responsibility to the Backup Manager. It will perform a 12246 // restore if appropriate, then pass responsibility back to the 12247 // Package Manager to run the post-install observer callbacks 12248 // and broadcasts. 12249 IBackupManager bm = IBackupManager.Stub.asInterface( 12250 ServiceManager.getService(Context.BACKUP_SERVICE)); 12251 if (bm != null) { 12252 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12253 + " to BM for possible restore"); 12254 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12255 try { 12256 // TODO: http://b/22388012 12257 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12258 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12259 } else { 12260 doRestore = false; 12261 } 12262 } catch (RemoteException e) { 12263 // can't happen; the backup manager is local 12264 } catch (Exception e) { 12265 Slog.e(TAG, "Exception trying to enqueue restore", e); 12266 doRestore = false; 12267 } 12268 } else { 12269 Slog.e(TAG, "Backup Manager not found!"); 12270 doRestore = false; 12271 } 12272 } 12273 12274 if (!doRestore) { 12275 // No restore possible, or the Backup Manager was mysteriously not 12276 // available -- just fire the post-install work request directly. 12277 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12278 12279 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12280 12281 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12282 mHandler.sendMessage(msg); 12283 } 12284 } 12285 }); 12286 } 12287 12288 /** 12289 * Callback from PackageSettings whenever an app is first transitioned out of the 12290 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12291 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12292 * here whether the app is the target of an ongoing install, and only send the 12293 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12294 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12295 * handling. 12296 */ 12297 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12298 // Serialize this with the rest of the install-process message chain. In the 12299 // restore-at-install case, this Runnable will necessarily run before the 12300 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12301 // are coherent. In the non-restore case, the app has already completed install 12302 // and been launched through some other means, so it is not in a problematic 12303 // state for observers to see the FIRST_LAUNCH signal. 12304 mHandler.post(new Runnable() { 12305 @Override 12306 public void run() { 12307 for (int i = 0; i < mRunningInstalls.size(); i++) { 12308 final PostInstallData data = mRunningInstalls.valueAt(i); 12309 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12310 continue; 12311 } 12312 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12313 // right package; but is it for the right user? 12314 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12315 if (userId == data.res.newUsers[uIndex]) { 12316 if (DEBUG_BACKUP) { 12317 Slog.i(TAG, "Package " + pkgName 12318 + " being restored so deferring FIRST_LAUNCH"); 12319 } 12320 return; 12321 } 12322 } 12323 } 12324 } 12325 // didn't find it, so not being restored 12326 if (DEBUG_BACKUP) { 12327 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12328 } 12329 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12330 } 12331 }); 12332 } 12333 12334 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12335 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12336 installerPkg, null, userIds); 12337 } 12338 12339 private abstract class HandlerParams { 12340 private static final int MAX_RETRIES = 4; 12341 12342 /** 12343 * Number of times startCopy() has been attempted and had a non-fatal 12344 * error. 12345 */ 12346 private int mRetries = 0; 12347 12348 /** User handle for the user requesting the information or installation. */ 12349 private final UserHandle mUser; 12350 String traceMethod; 12351 int traceCookie; 12352 12353 HandlerParams(UserHandle user) { 12354 mUser = user; 12355 } 12356 12357 UserHandle getUser() { 12358 return mUser; 12359 } 12360 12361 HandlerParams setTraceMethod(String traceMethod) { 12362 this.traceMethod = traceMethod; 12363 return this; 12364 } 12365 12366 HandlerParams setTraceCookie(int traceCookie) { 12367 this.traceCookie = traceCookie; 12368 return this; 12369 } 12370 12371 final boolean startCopy() { 12372 boolean res; 12373 try { 12374 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12375 12376 if (++mRetries > MAX_RETRIES) { 12377 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12378 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12379 handleServiceError(); 12380 return false; 12381 } else { 12382 handleStartCopy(); 12383 res = true; 12384 } 12385 } catch (RemoteException e) { 12386 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12387 mHandler.sendEmptyMessage(MCS_RECONNECT); 12388 res = false; 12389 } 12390 handleReturnCode(); 12391 return res; 12392 } 12393 12394 final void serviceError() { 12395 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12396 handleServiceError(); 12397 handleReturnCode(); 12398 } 12399 12400 abstract void handleStartCopy() throws RemoteException; 12401 abstract void handleServiceError(); 12402 abstract void handleReturnCode(); 12403 } 12404 12405 class MeasureParams extends HandlerParams { 12406 private final PackageStats mStats; 12407 private boolean mSuccess; 12408 12409 private final IPackageStatsObserver mObserver; 12410 12411 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12412 super(new UserHandle(stats.userHandle)); 12413 mObserver = observer; 12414 mStats = stats; 12415 } 12416 12417 @Override 12418 public String toString() { 12419 return "MeasureParams{" 12420 + Integer.toHexString(System.identityHashCode(this)) 12421 + " " + mStats.packageName + "}"; 12422 } 12423 12424 @Override 12425 void handleStartCopy() throws RemoteException { 12426 synchronized (mInstallLock) { 12427 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12428 } 12429 12430 if (mSuccess) { 12431 boolean mounted = false; 12432 try { 12433 final String status = Environment.getExternalStorageState(); 12434 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12435 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12436 } catch (Exception e) { 12437 } 12438 12439 if (mounted) { 12440 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12441 12442 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12443 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12444 12445 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12446 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12447 12448 // Always subtract cache size, since it's a subdirectory 12449 mStats.externalDataSize -= mStats.externalCacheSize; 12450 12451 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12452 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12453 12454 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12455 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12456 } 12457 } 12458 } 12459 12460 @Override 12461 void handleReturnCode() { 12462 if (mObserver != null) { 12463 try { 12464 mObserver.onGetStatsCompleted(mStats, mSuccess); 12465 } catch (RemoteException e) { 12466 Slog.i(TAG, "Observer no longer exists."); 12467 } 12468 } 12469 } 12470 12471 @Override 12472 void handleServiceError() { 12473 Slog.e(TAG, "Could not measure application " + mStats.packageName 12474 + " external storage"); 12475 } 12476 } 12477 12478 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12479 throws RemoteException { 12480 long result = 0; 12481 for (File path : paths) { 12482 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12483 } 12484 return result; 12485 } 12486 12487 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12488 for (File path : paths) { 12489 try { 12490 mcs.clearDirectory(path.getAbsolutePath()); 12491 } catch (RemoteException e) { 12492 } 12493 } 12494 } 12495 12496 static class OriginInfo { 12497 /** 12498 * Location where install is coming from, before it has been 12499 * copied/renamed into place. This could be a single monolithic APK 12500 * file, or a cluster directory. This location may be untrusted. 12501 */ 12502 final File file; 12503 final String cid; 12504 12505 /** 12506 * Flag indicating that {@link #file} or {@link #cid} has already been 12507 * staged, meaning downstream users don't need to defensively copy the 12508 * contents. 12509 */ 12510 final boolean staged; 12511 12512 /** 12513 * Flag indicating that {@link #file} or {@link #cid} is an already 12514 * installed app that is being moved. 12515 */ 12516 final boolean existing; 12517 12518 final String resolvedPath; 12519 final File resolvedFile; 12520 12521 static OriginInfo fromNothing() { 12522 return new OriginInfo(null, null, false, false); 12523 } 12524 12525 static OriginInfo fromUntrustedFile(File file) { 12526 return new OriginInfo(file, null, false, false); 12527 } 12528 12529 static OriginInfo fromExistingFile(File file) { 12530 return new OriginInfo(file, null, false, true); 12531 } 12532 12533 static OriginInfo fromStagedFile(File file) { 12534 return new OriginInfo(file, null, true, false); 12535 } 12536 12537 static OriginInfo fromStagedContainer(String cid) { 12538 return new OriginInfo(null, cid, true, false); 12539 } 12540 12541 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12542 this.file = file; 12543 this.cid = cid; 12544 this.staged = staged; 12545 this.existing = existing; 12546 12547 if (cid != null) { 12548 resolvedPath = PackageHelper.getSdDir(cid); 12549 resolvedFile = new File(resolvedPath); 12550 } else if (file != null) { 12551 resolvedPath = file.getAbsolutePath(); 12552 resolvedFile = file; 12553 } else { 12554 resolvedPath = null; 12555 resolvedFile = null; 12556 } 12557 } 12558 } 12559 12560 static class MoveInfo { 12561 final int moveId; 12562 final String fromUuid; 12563 final String toUuid; 12564 final String packageName; 12565 final String dataAppName; 12566 final int appId; 12567 final String seinfo; 12568 final int targetSdkVersion; 12569 12570 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12571 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12572 this.moveId = moveId; 12573 this.fromUuid = fromUuid; 12574 this.toUuid = toUuid; 12575 this.packageName = packageName; 12576 this.dataAppName = dataAppName; 12577 this.appId = appId; 12578 this.seinfo = seinfo; 12579 this.targetSdkVersion = targetSdkVersion; 12580 } 12581 } 12582 12583 static class VerificationInfo { 12584 /** A constant used to indicate that a uid value is not present. */ 12585 public static final int NO_UID = -1; 12586 12587 /** URI referencing where the package was downloaded from. */ 12588 final Uri originatingUri; 12589 12590 /** HTTP referrer URI associated with the originatingURI. */ 12591 final Uri referrer; 12592 12593 /** UID of the application that the install request originated from. */ 12594 final int originatingUid; 12595 12596 /** UID of application requesting the install */ 12597 final int installerUid; 12598 12599 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12600 this.originatingUri = originatingUri; 12601 this.referrer = referrer; 12602 this.originatingUid = originatingUid; 12603 this.installerUid = installerUid; 12604 } 12605 } 12606 12607 class InstallParams extends HandlerParams { 12608 final OriginInfo origin; 12609 final MoveInfo move; 12610 final IPackageInstallObserver2 observer; 12611 int installFlags; 12612 final String installerPackageName; 12613 final String volumeUuid; 12614 private InstallArgs mArgs; 12615 private int mRet; 12616 final String packageAbiOverride; 12617 final String[] grantedRuntimePermissions; 12618 final VerificationInfo verificationInfo; 12619 final Certificate[][] certificates; 12620 12621 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12622 int installFlags, String installerPackageName, String volumeUuid, 12623 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12624 String[] grantedPermissions, Certificate[][] certificates) { 12625 super(user); 12626 this.origin = origin; 12627 this.move = move; 12628 this.observer = observer; 12629 this.installFlags = installFlags; 12630 this.installerPackageName = installerPackageName; 12631 this.volumeUuid = volumeUuid; 12632 this.verificationInfo = verificationInfo; 12633 this.packageAbiOverride = packageAbiOverride; 12634 this.grantedRuntimePermissions = grantedPermissions; 12635 this.certificates = certificates; 12636 } 12637 12638 @Override 12639 public String toString() { 12640 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12641 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12642 } 12643 12644 private int installLocationPolicy(PackageInfoLite pkgLite) { 12645 String packageName = pkgLite.packageName; 12646 int installLocation = pkgLite.installLocation; 12647 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12648 // reader 12649 synchronized (mPackages) { 12650 // Currently installed package which the new package is attempting to replace or 12651 // null if no such package is installed. 12652 PackageParser.Package installedPkg = mPackages.get(packageName); 12653 // Package which currently owns the data which the new package will own if installed. 12654 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12655 // will be null whereas dataOwnerPkg will contain information about the package 12656 // which was uninstalled while keeping its data. 12657 PackageParser.Package dataOwnerPkg = installedPkg; 12658 if (dataOwnerPkg == null) { 12659 PackageSetting ps = mSettings.mPackages.get(packageName); 12660 if (ps != null) { 12661 dataOwnerPkg = ps.pkg; 12662 } 12663 } 12664 12665 if (dataOwnerPkg != null) { 12666 // If installed, the package will get access to data left on the device by its 12667 // predecessor. As a security measure, this is permited only if this is not a 12668 // version downgrade or if the predecessor package is marked as debuggable and 12669 // a downgrade is explicitly requested. 12670 // 12671 // On debuggable platform builds, downgrades are permitted even for 12672 // non-debuggable packages to make testing easier. Debuggable platform builds do 12673 // not offer security guarantees and thus it's OK to disable some security 12674 // mechanisms to make debugging/testing easier on those builds. However, even on 12675 // debuggable builds downgrades of packages are permitted only if requested via 12676 // installFlags. This is because we aim to keep the behavior of debuggable 12677 // platform builds as close as possible to the behavior of non-debuggable 12678 // platform builds. 12679 final boolean downgradeRequested = 12680 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12681 final boolean packageDebuggable = 12682 (dataOwnerPkg.applicationInfo.flags 12683 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12684 final boolean downgradePermitted = 12685 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12686 if (!downgradePermitted) { 12687 try { 12688 checkDowngrade(dataOwnerPkg, pkgLite); 12689 } catch (PackageManagerException e) { 12690 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12691 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12692 } 12693 } 12694 } 12695 12696 if (installedPkg != null) { 12697 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12698 // Check for updated system application. 12699 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12700 if (onSd) { 12701 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12702 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12703 } 12704 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12705 } else { 12706 if (onSd) { 12707 // Install flag overrides everything. 12708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12709 } 12710 // If current upgrade specifies particular preference 12711 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12712 // Application explicitly specified internal. 12713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12714 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12715 // App explictly prefers external. Let policy decide 12716 } else { 12717 // Prefer previous location 12718 if (isExternal(installedPkg)) { 12719 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12720 } 12721 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12722 } 12723 } 12724 } else { 12725 // Invalid install. Return error code 12726 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12727 } 12728 } 12729 } 12730 // All the special cases have been taken care of. 12731 // Return result based on recommended install location. 12732 if (onSd) { 12733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12734 } 12735 return pkgLite.recommendedInstallLocation; 12736 } 12737 12738 /* 12739 * Invoke remote method to get package information and install 12740 * location values. Override install location based on default 12741 * policy if needed and then create install arguments based 12742 * on the install location. 12743 */ 12744 public void handleStartCopy() throws RemoteException { 12745 int ret = PackageManager.INSTALL_SUCCEEDED; 12746 12747 // If we're already staged, we've firmly committed to an install location 12748 if (origin.staged) { 12749 if (origin.file != null) { 12750 installFlags |= PackageManager.INSTALL_INTERNAL; 12751 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12752 } else if (origin.cid != null) { 12753 installFlags |= PackageManager.INSTALL_EXTERNAL; 12754 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12755 } else { 12756 throw new IllegalStateException("Invalid stage location"); 12757 } 12758 } 12759 12760 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12761 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12762 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12763 PackageInfoLite pkgLite = null; 12764 12765 if (onInt && onSd) { 12766 // Check if both bits are set. 12767 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12768 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12769 } else if (onSd && ephemeral) { 12770 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12771 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12772 } else { 12773 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12774 packageAbiOverride); 12775 12776 if (DEBUG_EPHEMERAL && ephemeral) { 12777 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12778 } 12779 12780 /* 12781 * If we have too little free space, try to free cache 12782 * before giving up. 12783 */ 12784 if (!origin.staged && pkgLite.recommendedInstallLocation 12785 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12786 // TODO: focus freeing disk space on the target device 12787 final StorageManager storage = StorageManager.from(mContext); 12788 final long lowThreshold = storage.getStorageLowBytes( 12789 Environment.getDataDirectory()); 12790 12791 final long sizeBytes = mContainerService.calculateInstalledSize( 12792 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12793 12794 try { 12795 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12796 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12797 installFlags, packageAbiOverride); 12798 } catch (InstallerException e) { 12799 Slog.w(TAG, "Failed to free cache", e); 12800 } 12801 12802 /* 12803 * The cache free must have deleted the file we 12804 * downloaded to install. 12805 * 12806 * TODO: fix the "freeCache" call to not delete 12807 * the file we care about. 12808 */ 12809 if (pkgLite.recommendedInstallLocation 12810 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12811 pkgLite.recommendedInstallLocation 12812 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12813 } 12814 } 12815 } 12816 12817 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12818 int loc = pkgLite.recommendedInstallLocation; 12819 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12820 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12821 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12822 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12823 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12824 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12825 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12826 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12827 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12828 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12829 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12830 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12831 } else { 12832 // Override with defaults if needed. 12833 loc = installLocationPolicy(pkgLite); 12834 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12835 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12836 } else if (!onSd && !onInt) { 12837 // Override install location with flags 12838 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12839 // Set the flag to install on external media. 12840 installFlags |= PackageManager.INSTALL_EXTERNAL; 12841 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12842 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12843 if (DEBUG_EPHEMERAL) { 12844 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12845 } 12846 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12847 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12848 |PackageManager.INSTALL_INTERNAL); 12849 } else { 12850 // Make sure the flag for installing on external 12851 // media is unset 12852 installFlags |= PackageManager.INSTALL_INTERNAL; 12853 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12854 } 12855 } 12856 } 12857 } 12858 12859 final InstallArgs args = createInstallArgs(this); 12860 mArgs = args; 12861 12862 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12863 // TODO: http://b/22976637 12864 // Apps installed for "all" users use the device owner to verify the app 12865 UserHandle verifierUser = getUser(); 12866 if (verifierUser == UserHandle.ALL) { 12867 verifierUser = UserHandle.SYSTEM; 12868 } 12869 12870 /* 12871 * Determine if we have any installed package verifiers. If we 12872 * do, then we'll defer to them to verify the packages. 12873 */ 12874 final int requiredUid = mRequiredVerifierPackage == null ? -1 12875 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12876 verifierUser.getIdentifier()); 12877 if (!origin.existing && requiredUid != -1 12878 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12879 final Intent verification = new Intent( 12880 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12881 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12882 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12883 PACKAGE_MIME_TYPE); 12884 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12885 12886 // Query all live verifiers based on current user state 12887 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12888 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12889 12890 if (DEBUG_VERIFY) { 12891 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12892 + verification.toString() + " with " + pkgLite.verifiers.length 12893 + " optional verifiers"); 12894 } 12895 12896 final int verificationId = mPendingVerificationToken++; 12897 12898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12899 12900 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12901 installerPackageName); 12902 12903 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12904 installFlags); 12905 12906 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12907 pkgLite.packageName); 12908 12909 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12910 pkgLite.versionCode); 12911 12912 if (verificationInfo != null) { 12913 if (verificationInfo.originatingUri != null) { 12914 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12915 verificationInfo.originatingUri); 12916 } 12917 if (verificationInfo.referrer != null) { 12918 verification.putExtra(Intent.EXTRA_REFERRER, 12919 verificationInfo.referrer); 12920 } 12921 if (verificationInfo.originatingUid >= 0) { 12922 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12923 verificationInfo.originatingUid); 12924 } 12925 if (verificationInfo.installerUid >= 0) { 12926 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12927 verificationInfo.installerUid); 12928 } 12929 } 12930 12931 final PackageVerificationState verificationState = new PackageVerificationState( 12932 requiredUid, args); 12933 12934 mPendingVerification.append(verificationId, verificationState); 12935 12936 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12937 receivers, verificationState); 12938 12939 /* 12940 * If any sufficient verifiers were listed in the package 12941 * manifest, attempt to ask them. 12942 */ 12943 if (sufficientVerifiers != null) { 12944 final int N = sufficientVerifiers.size(); 12945 if (N == 0) { 12946 Slog.i(TAG, "Additional verifiers required, but none installed."); 12947 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12948 } else { 12949 for (int i = 0; i < N; i++) { 12950 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12951 12952 final Intent sufficientIntent = new Intent(verification); 12953 sufficientIntent.setComponent(verifierComponent); 12954 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12955 } 12956 } 12957 } 12958 12959 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12960 mRequiredVerifierPackage, receivers); 12961 if (ret == PackageManager.INSTALL_SUCCEEDED 12962 && mRequiredVerifierPackage != null) { 12963 Trace.asyncTraceBegin( 12964 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12965 /* 12966 * Send the intent to the required verification agent, 12967 * but only start the verification timeout after the 12968 * target BroadcastReceivers have run. 12969 */ 12970 verification.setComponent(requiredVerifierComponent); 12971 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12973 new BroadcastReceiver() { 12974 @Override 12975 public void onReceive(Context context, Intent intent) { 12976 final Message msg = mHandler 12977 .obtainMessage(CHECK_PENDING_VERIFICATION); 12978 msg.arg1 = verificationId; 12979 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12980 } 12981 }, null, 0, null, null); 12982 12983 /* 12984 * We don't want the copy to proceed until verification 12985 * succeeds, so null out this field. 12986 */ 12987 mArgs = null; 12988 } 12989 } else { 12990 /* 12991 * No package verification is enabled, so immediately start 12992 * the remote call to initiate copy using temporary file. 12993 */ 12994 ret = args.copyApk(mContainerService, true); 12995 } 12996 } 12997 12998 mRet = ret; 12999 } 13000 13001 @Override 13002 void handleReturnCode() { 13003 // If mArgs is null, then MCS couldn't be reached. When it 13004 // reconnects, it will try again to install. At that point, this 13005 // will succeed. 13006 if (mArgs != null) { 13007 processPendingInstall(mArgs, mRet); 13008 } 13009 } 13010 13011 @Override 13012 void handleServiceError() { 13013 mArgs = createInstallArgs(this); 13014 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13015 } 13016 13017 public boolean isForwardLocked() { 13018 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13019 } 13020 } 13021 13022 /** 13023 * Used during creation of InstallArgs 13024 * 13025 * @param installFlags package installation flags 13026 * @return true if should be installed on external storage 13027 */ 13028 private static boolean installOnExternalAsec(int installFlags) { 13029 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13030 return false; 13031 } 13032 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13033 return true; 13034 } 13035 return false; 13036 } 13037 13038 /** 13039 * Used during creation of InstallArgs 13040 * 13041 * @param installFlags package installation flags 13042 * @return true if should be installed as forward locked 13043 */ 13044 private static boolean installForwardLocked(int installFlags) { 13045 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13046 } 13047 13048 private InstallArgs createInstallArgs(InstallParams params) { 13049 if (params.move != null) { 13050 return new MoveInstallArgs(params); 13051 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13052 return new AsecInstallArgs(params); 13053 } else { 13054 return new FileInstallArgs(params); 13055 } 13056 } 13057 13058 /** 13059 * Create args that describe an existing installed package. Typically used 13060 * when cleaning up old installs, or used as a move source. 13061 */ 13062 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13063 String resourcePath, String[] instructionSets) { 13064 final boolean isInAsec; 13065 if (installOnExternalAsec(installFlags)) { 13066 /* Apps on SD card are always in ASEC containers. */ 13067 isInAsec = true; 13068 } else if (installForwardLocked(installFlags) 13069 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13070 /* 13071 * Forward-locked apps are only in ASEC containers if they're the 13072 * new style 13073 */ 13074 isInAsec = true; 13075 } else { 13076 isInAsec = false; 13077 } 13078 13079 if (isInAsec) { 13080 return new AsecInstallArgs(codePath, instructionSets, 13081 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13082 } else { 13083 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13084 } 13085 } 13086 13087 static abstract class InstallArgs { 13088 /** @see InstallParams#origin */ 13089 final OriginInfo origin; 13090 /** @see InstallParams#move */ 13091 final MoveInfo move; 13092 13093 final IPackageInstallObserver2 observer; 13094 // Always refers to PackageManager flags only 13095 final int installFlags; 13096 final String installerPackageName; 13097 final String volumeUuid; 13098 final UserHandle user; 13099 final String abiOverride; 13100 final String[] installGrantPermissions; 13101 /** If non-null, drop an async trace when the install completes */ 13102 final String traceMethod; 13103 final int traceCookie; 13104 final Certificate[][] certificates; 13105 13106 // The list of instruction sets supported by this app. This is currently 13107 // only used during the rmdex() phase to clean up resources. We can get rid of this 13108 // if we move dex files under the common app path. 13109 /* nullable */ String[] instructionSets; 13110 13111 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13112 int installFlags, String installerPackageName, String volumeUuid, 13113 UserHandle user, String[] instructionSets, 13114 String abiOverride, String[] installGrantPermissions, 13115 String traceMethod, int traceCookie, Certificate[][] certificates) { 13116 this.origin = origin; 13117 this.move = move; 13118 this.installFlags = installFlags; 13119 this.observer = observer; 13120 this.installerPackageName = installerPackageName; 13121 this.volumeUuid = volumeUuid; 13122 this.user = user; 13123 this.instructionSets = instructionSets; 13124 this.abiOverride = abiOverride; 13125 this.installGrantPermissions = installGrantPermissions; 13126 this.traceMethod = traceMethod; 13127 this.traceCookie = traceCookie; 13128 this.certificates = certificates; 13129 } 13130 13131 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13132 abstract int doPreInstall(int status); 13133 13134 /** 13135 * Rename package into final resting place. All paths on the given 13136 * scanned package should be updated to reflect the rename. 13137 */ 13138 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13139 abstract int doPostInstall(int status, int uid); 13140 13141 /** @see PackageSettingBase#codePathString */ 13142 abstract String getCodePath(); 13143 /** @see PackageSettingBase#resourcePathString */ 13144 abstract String getResourcePath(); 13145 13146 // Need installer lock especially for dex file removal. 13147 abstract void cleanUpResourcesLI(); 13148 abstract boolean doPostDeleteLI(boolean delete); 13149 13150 /** 13151 * Called before the source arguments are copied. This is used mostly 13152 * for MoveParams when it needs to read the source file to put it in the 13153 * destination. 13154 */ 13155 int doPreCopy() { 13156 return PackageManager.INSTALL_SUCCEEDED; 13157 } 13158 13159 /** 13160 * Called after the source arguments are copied. This is used mostly for 13161 * MoveParams when it needs to read the source file to put it in the 13162 * destination. 13163 */ 13164 int doPostCopy(int uid) { 13165 return PackageManager.INSTALL_SUCCEEDED; 13166 } 13167 13168 protected boolean isFwdLocked() { 13169 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13170 } 13171 13172 protected boolean isExternalAsec() { 13173 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13174 } 13175 13176 protected boolean isEphemeral() { 13177 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13178 } 13179 13180 UserHandle getUser() { 13181 return user; 13182 } 13183 } 13184 13185 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13186 if (!allCodePaths.isEmpty()) { 13187 if (instructionSets == null) { 13188 throw new IllegalStateException("instructionSet == null"); 13189 } 13190 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13191 for (String codePath : allCodePaths) { 13192 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13193 try { 13194 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13195 } catch (InstallerException ignored) { 13196 } 13197 } 13198 } 13199 } 13200 } 13201 13202 /** 13203 * Logic to handle installation of non-ASEC applications, including copying 13204 * and renaming logic. 13205 */ 13206 class FileInstallArgs extends InstallArgs { 13207 private File codeFile; 13208 private File resourceFile; 13209 13210 // Example topology: 13211 // /data/app/com.example/base.apk 13212 // /data/app/com.example/split_foo.apk 13213 // /data/app/com.example/lib/arm/libfoo.so 13214 // /data/app/com.example/lib/arm64/libfoo.so 13215 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13216 13217 /** New install */ 13218 FileInstallArgs(InstallParams params) { 13219 super(params.origin, params.move, params.observer, params.installFlags, 13220 params.installerPackageName, params.volumeUuid, 13221 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13222 params.grantedRuntimePermissions, 13223 params.traceMethod, params.traceCookie, params.certificates); 13224 if (isFwdLocked()) { 13225 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13226 } 13227 } 13228 13229 /** Existing install */ 13230 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13231 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13232 null, null, null, 0, null /*certificates*/); 13233 this.codeFile = (codePath != null) ? new File(codePath) : null; 13234 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13235 } 13236 13237 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13239 try { 13240 return doCopyApk(imcs, temp); 13241 } finally { 13242 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13243 } 13244 } 13245 13246 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13247 if (origin.staged) { 13248 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13249 codeFile = origin.file; 13250 resourceFile = origin.file; 13251 return PackageManager.INSTALL_SUCCEEDED; 13252 } 13253 13254 try { 13255 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13256 final File tempDir = 13257 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13258 codeFile = tempDir; 13259 resourceFile = tempDir; 13260 } catch (IOException e) { 13261 Slog.w(TAG, "Failed to create copy file: " + e); 13262 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13263 } 13264 13265 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13266 @Override 13267 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13268 if (!FileUtils.isValidExtFilename(name)) { 13269 throw new IllegalArgumentException("Invalid filename: " + name); 13270 } 13271 try { 13272 final File file = new File(codeFile, name); 13273 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13274 O_RDWR | O_CREAT, 0644); 13275 Os.chmod(file.getAbsolutePath(), 0644); 13276 return new ParcelFileDescriptor(fd); 13277 } catch (ErrnoException e) { 13278 throw new RemoteException("Failed to open: " + e.getMessage()); 13279 } 13280 } 13281 }; 13282 13283 int ret = PackageManager.INSTALL_SUCCEEDED; 13284 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13285 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13286 Slog.e(TAG, "Failed to copy package"); 13287 return ret; 13288 } 13289 13290 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13291 NativeLibraryHelper.Handle handle = null; 13292 try { 13293 handle = NativeLibraryHelper.Handle.create(codeFile); 13294 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13295 abiOverride); 13296 } catch (IOException e) { 13297 Slog.e(TAG, "Copying native libraries failed", e); 13298 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13299 } finally { 13300 IoUtils.closeQuietly(handle); 13301 } 13302 13303 return ret; 13304 } 13305 13306 int doPreInstall(int status) { 13307 if (status != PackageManager.INSTALL_SUCCEEDED) { 13308 cleanUp(); 13309 } 13310 return status; 13311 } 13312 13313 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13314 if (status != PackageManager.INSTALL_SUCCEEDED) { 13315 cleanUp(); 13316 return false; 13317 } 13318 13319 final File targetDir = codeFile.getParentFile(); 13320 final File beforeCodeFile = codeFile; 13321 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13322 13323 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13324 try { 13325 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13326 } catch (ErrnoException e) { 13327 Slog.w(TAG, "Failed to rename", e); 13328 return false; 13329 } 13330 13331 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13332 Slog.w(TAG, "Failed to restorecon"); 13333 return false; 13334 } 13335 13336 // Reflect the rename internally 13337 codeFile = afterCodeFile; 13338 resourceFile = afterCodeFile; 13339 13340 // Reflect the rename in scanned details 13341 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13342 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13343 afterCodeFile, pkg.baseCodePath)); 13344 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13345 afterCodeFile, pkg.splitCodePaths)); 13346 13347 // Reflect the rename in app info 13348 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13349 pkg.setApplicationInfoCodePath(pkg.codePath); 13350 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13351 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13352 pkg.setApplicationInfoResourcePath(pkg.codePath); 13353 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13354 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13355 13356 return true; 13357 } 13358 13359 int doPostInstall(int status, int uid) { 13360 if (status != PackageManager.INSTALL_SUCCEEDED) { 13361 cleanUp(); 13362 } 13363 return status; 13364 } 13365 13366 @Override 13367 String getCodePath() { 13368 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13369 } 13370 13371 @Override 13372 String getResourcePath() { 13373 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13374 } 13375 13376 private boolean cleanUp() { 13377 if (codeFile == null || !codeFile.exists()) { 13378 return false; 13379 } 13380 13381 removeCodePathLI(codeFile); 13382 13383 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13384 resourceFile.delete(); 13385 } 13386 13387 return true; 13388 } 13389 13390 void cleanUpResourcesLI() { 13391 // Try enumerating all code paths before deleting 13392 List<String> allCodePaths = Collections.EMPTY_LIST; 13393 if (codeFile != null && codeFile.exists()) { 13394 try { 13395 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13396 allCodePaths = pkg.getAllCodePaths(); 13397 } catch (PackageParserException e) { 13398 // Ignored; we tried our best 13399 } 13400 } 13401 13402 cleanUp(); 13403 removeDexFiles(allCodePaths, instructionSets); 13404 } 13405 13406 boolean doPostDeleteLI(boolean delete) { 13407 // XXX err, shouldn't we respect the delete flag? 13408 cleanUpResourcesLI(); 13409 return true; 13410 } 13411 } 13412 13413 private boolean isAsecExternal(String cid) { 13414 final String asecPath = PackageHelper.getSdFilesystem(cid); 13415 return !asecPath.startsWith(mAsecInternalPath); 13416 } 13417 13418 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13419 PackageManagerException { 13420 if (copyRet < 0) { 13421 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13422 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13423 throw new PackageManagerException(copyRet, message); 13424 } 13425 } 13426 } 13427 13428 /** 13429 * Extract the MountService "container ID" from the full code path of an 13430 * .apk. 13431 */ 13432 static String cidFromCodePath(String fullCodePath) { 13433 int eidx = fullCodePath.lastIndexOf("/"); 13434 String subStr1 = fullCodePath.substring(0, eidx); 13435 int sidx = subStr1.lastIndexOf("/"); 13436 return subStr1.substring(sidx+1, eidx); 13437 } 13438 13439 /** 13440 * Logic to handle installation of ASEC applications, including copying and 13441 * renaming logic. 13442 */ 13443 class AsecInstallArgs extends InstallArgs { 13444 static final String RES_FILE_NAME = "pkg.apk"; 13445 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13446 13447 String cid; 13448 String packagePath; 13449 String resourcePath; 13450 13451 /** New install */ 13452 AsecInstallArgs(InstallParams params) { 13453 super(params.origin, params.move, params.observer, params.installFlags, 13454 params.installerPackageName, params.volumeUuid, 13455 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13456 params.grantedRuntimePermissions, 13457 params.traceMethod, params.traceCookie, params.certificates); 13458 } 13459 13460 /** Existing install */ 13461 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13462 boolean isExternal, boolean isForwardLocked) { 13463 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13464 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13465 instructionSets, null, null, null, 0, null /*certificates*/); 13466 // Hackily pretend we're still looking at a full code path 13467 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13468 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13469 } 13470 13471 // Extract cid from fullCodePath 13472 int eidx = fullCodePath.lastIndexOf("/"); 13473 String subStr1 = fullCodePath.substring(0, eidx); 13474 int sidx = subStr1.lastIndexOf("/"); 13475 cid = subStr1.substring(sidx+1, eidx); 13476 setMountPath(subStr1); 13477 } 13478 13479 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13480 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13481 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13482 instructionSets, null, null, null, 0, null /*certificates*/); 13483 this.cid = cid; 13484 setMountPath(PackageHelper.getSdDir(cid)); 13485 } 13486 13487 void createCopyFile() { 13488 cid = mInstallerService.allocateExternalStageCidLegacy(); 13489 } 13490 13491 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13492 if (origin.staged && origin.cid != null) { 13493 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13494 cid = origin.cid; 13495 setMountPath(PackageHelper.getSdDir(cid)); 13496 return PackageManager.INSTALL_SUCCEEDED; 13497 } 13498 13499 if (temp) { 13500 createCopyFile(); 13501 } else { 13502 /* 13503 * Pre-emptively destroy the container since it's destroyed if 13504 * copying fails due to it existing anyway. 13505 */ 13506 PackageHelper.destroySdDir(cid); 13507 } 13508 13509 final String newMountPath = imcs.copyPackageToContainer( 13510 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13511 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13512 13513 if (newMountPath != null) { 13514 setMountPath(newMountPath); 13515 return PackageManager.INSTALL_SUCCEEDED; 13516 } else { 13517 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13518 } 13519 } 13520 13521 @Override 13522 String getCodePath() { 13523 return packagePath; 13524 } 13525 13526 @Override 13527 String getResourcePath() { 13528 return resourcePath; 13529 } 13530 13531 int doPreInstall(int status) { 13532 if (status != PackageManager.INSTALL_SUCCEEDED) { 13533 // Destroy container 13534 PackageHelper.destroySdDir(cid); 13535 } else { 13536 boolean mounted = PackageHelper.isContainerMounted(cid); 13537 if (!mounted) { 13538 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13539 Process.SYSTEM_UID); 13540 if (newMountPath != null) { 13541 setMountPath(newMountPath); 13542 } else { 13543 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13544 } 13545 } 13546 } 13547 return status; 13548 } 13549 13550 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13551 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13552 String newMountPath = null; 13553 if (PackageHelper.isContainerMounted(cid)) { 13554 // Unmount the container 13555 if (!PackageHelper.unMountSdDir(cid)) { 13556 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13557 return false; 13558 } 13559 } 13560 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13561 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13562 " which might be stale. Will try to clean up."); 13563 // Clean up the stale container and proceed to recreate. 13564 if (!PackageHelper.destroySdDir(newCacheId)) { 13565 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13566 return false; 13567 } 13568 // Successfully cleaned up stale container. Try to rename again. 13569 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13570 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13571 + " inspite of cleaning it up."); 13572 return false; 13573 } 13574 } 13575 if (!PackageHelper.isContainerMounted(newCacheId)) { 13576 Slog.w(TAG, "Mounting container " + newCacheId); 13577 newMountPath = PackageHelper.mountSdDir(newCacheId, 13578 getEncryptKey(), Process.SYSTEM_UID); 13579 } else { 13580 newMountPath = PackageHelper.getSdDir(newCacheId); 13581 } 13582 if (newMountPath == null) { 13583 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13584 return false; 13585 } 13586 Log.i(TAG, "Succesfully renamed " + cid + 13587 " to " + newCacheId + 13588 " at new path: " + newMountPath); 13589 cid = newCacheId; 13590 13591 final File beforeCodeFile = new File(packagePath); 13592 setMountPath(newMountPath); 13593 final File afterCodeFile = new File(packagePath); 13594 13595 // Reflect the rename in scanned details 13596 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13597 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13598 afterCodeFile, pkg.baseCodePath)); 13599 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13600 afterCodeFile, pkg.splitCodePaths)); 13601 13602 // Reflect the rename in app info 13603 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13604 pkg.setApplicationInfoCodePath(pkg.codePath); 13605 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13606 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13607 pkg.setApplicationInfoResourcePath(pkg.codePath); 13608 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13609 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13610 13611 return true; 13612 } 13613 13614 private void setMountPath(String mountPath) { 13615 final File mountFile = new File(mountPath); 13616 13617 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13618 if (monolithicFile.exists()) { 13619 packagePath = monolithicFile.getAbsolutePath(); 13620 if (isFwdLocked()) { 13621 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13622 } else { 13623 resourcePath = packagePath; 13624 } 13625 } else { 13626 packagePath = mountFile.getAbsolutePath(); 13627 resourcePath = packagePath; 13628 } 13629 } 13630 13631 int doPostInstall(int status, int uid) { 13632 if (status != PackageManager.INSTALL_SUCCEEDED) { 13633 cleanUp(); 13634 } else { 13635 final int groupOwner; 13636 final String protectedFile; 13637 if (isFwdLocked()) { 13638 groupOwner = UserHandle.getSharedAppGid(uid); 13639 protectedFile = RES_FILE_NAME; 13640 } else { 13641 groupOwner = -1; 13642 protectedFile = null; 13643 } 13644 13645 if (uid < Process.FIRST_APPLICATION_UID 13646 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13647 Slog.e(TAG, "Failed to finalize " + cid); 13648 PackageHelper.destroySdDir(cid); 13649 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13650 } 13651 13652 boolean mounted = PackageHelper.isContainerMounted(cid); 13653 if (!mounted) { 13654 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13655 } 13656 } 13657 return status; 13658 } 13659 13660 private void cleanUp() { 13661 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13662 13663 // Destroy secure container 13664 PackageHelper.destroySdDir(cid); 13665 } 13666 13667 private List<String> getAllCodePaths() { 13668 final File codeFile = new File(getCodePath()); 13669 if (codeFile != null && codeFile.exists()) { 13670 try { 13671 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13672 return pkg.getAllCodePaths(); 13673 } catch (PackageParserException e) { 13674 // Ignored; we tried our best 13675 } 13676 } 13677 return Collections.EMPTY_LIST; 13678 } 13679 13680 void cleanUpResourcesLI() { 13681 // Enumerate all code paths before deleting 13682 cleanUpResourcesLI(getAllCodePaths()); 13683 } 13684 13685 private void cleanUpResourcesLI(List<String> allCodePaths) { 13686 cleanUp(); 13687 removeDexFiles(allCodePaths, instructionSets); 13688 } 13689 13690 String getPackageName() { 13691 return getAsecPackageName(cid); 13692 } 13693 13694 boolean doPostDeleteLI(boolean delete) { 13695 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13696 final List<String> allCodePaths = getAllCodePaths(); 13697 boolean mounted = PackageHelper.isContainerMounted(cid); 13698 if (mounted) { 13699 // Unmount first 13700 if (PackageHelper.unMountSdDir(cid)) { 13701 mounted = false; 13702 } 13703 } 13704 if (!mounted && delete) { 13705 cleanUpResourcesLI(allCodePaths); 13706 } 13707 return !mounted; 13708 } 13709 13710 @Override 13711 int doPreCopy() { 13712 if (isFwdLocked()) { 13713 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13714 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13715 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13716 } 13717 } 13718 13719 return PackageManager.INSTALL_SUCCEEDED; 13720 } 13721 13722 @Override 13723 int doPostCopy(int uid) { 13724 if (isFwdLocked()) { 13725 if (uid < Process.FIRST_APPLICATION_UID 13726 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13727 RES_FILE_NAME)) { 13728 Slog.e(TAG, "Failed to finalize " + cid); 13729 PackageHelper.destroySdDir(cid); 13730 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13731 } 13732 } 13733 13734 return PackageManager.INSTALL_SUCCEEDED; 13735 } 13736 } 13737 13738 /** 13739 * Logic to handle movement of existing installed applications. 13740 */ 13741 class MoveInstallArgs extends InstallArgs { 13742 private File codeFile; 13743 private File resourceFile; 13744 13745 /** New install */ 13746 MoveInstallArgs(InstallParams params) { 13747 super(params.origin, params.move, params.observer, params.installFlags, 13748 params.installerPackageName, params.volumeUuid, 13749 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13750 params.grantedRuntimePermissions, 13751 params.traceMethod, params.traceCookie, params.certificates); 13752 } 13753 13754 int copyApk(IMediaContainerService imcs, boolean temp) { 13755 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13756 + move.fromUuid + " to " + move.toUuid); 13757 synchronized (mInstaller) { 13758 try { 13759 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13760 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13761 } catch (InstallerException e) { 13762 Slog.w(TAG, "Failed to move app", e); 13763 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13764 } 13765 } 13766 13767 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13768 resourceFile = codeFile; 13769 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13770 13771 return PackageManager.INSTALL_SUCCEEDED; 13772 } 13773 13774 int doPreInstall(int status) { 13775 if (status != PackageManager.INSTALL_SUCCEEDED) { 13776 cleanUp(move.toUuid); 13777 } 13778 return status; 13779 } 13780 13781 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13782 if (status != PackageManager.INSTALL_SUCCEEDED) { 13783 cleanUp(move.toUuid); 13784 return false; 13785 } 13786 13787 // Reflect the move in app info 13788 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13789 pkg.setApplicationInfoCodePath(pkg.codePath); 13790 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13791 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13792 pkg.setApplicationInfoResourcePath(pkg.codePath); 13793 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13794 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13795 13796 return true; 13797 } 13798 13799 int doPostInstall(int status, int uid) { 13800 if (status == PackageManager.INSTALL_SUCCEEDED) { 13801 cleanUp(move.fromUuid); 13802 } else { 13803 cleanUp(move.toUuid); 13804 } 13805 return status; 13806 } 13807 13808 @Override 13809 String getCodePath() { 13810 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13811 } 13812 13813 @Override 13814 String getResourcePath() { 13815 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13816 } 13817 13818 private boolean cleanUp(String volumeUuid) { 13819 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13820 move.dataAppName); 13821 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13822 final int[] userIds = sUserManager.getUserIds(); 13823 synchronized (mInstallLock) { 13824 // Clean up both app data and code 13825 // All package moves are frozen until finished 13826 for (int userId : userIds) { 13827 try { 13828 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13829 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13830 } catch (InstallerException e) { 13831 Slog.w(TAG, String.valueOf(e)); 13832 } 13833 } 13834 removeCodePathLI(codeFile); 13835 } 13836 return true; 13837 } 13838 13839 void cleanUpResourcesLI() { 13840 throw new UnsupportedOperationException(); 13841 } 13842 13843 boolean doPostDeleteLI(boolean delete) { 13844 throw new UnsupportedOperationException(); 13845 } 13846 } 13847 13848 static String getAsecPackageName(String packageCid) { 13849 int idx = packageCid.lastIndexOf("-"); 13850 if (idx == -1) { 13851 return packageCid; 13852 } 13853 return packageCid.substring(0, idx); 13854 } 13855 13856 // Utility method used to create code paths based on package name and available index. 13857 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13858 String idxStr = ""; 13859 int idx = 1; 13860 // Fall back to default value of idx=1 if prefix is not 13861 // part of oldCodePath 13862 if (oldCodePath != null) { 13863 String subStr = oldCodePath; 13864 // Drop the suffix right away 13865 if (suffix != null && subStr.endsWith(suffix)) { 13866 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13867 } 13868 // If oldCodePath already contains prefix find out the 13869 // ending index to either increment or decrement. 13870 int sidx = subStr.lastIndexOf(prefix); 13871 if (sidx != -1) { 13872 subStr = subStr.substring(sidx + prefix.length()); 13873 if (subStr != null) { 13874 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13875 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13876 } 13877 try { 13878 idx = Integer.parseInt(subStr); 13879 if (idx <= 1) { 13880 idx++; 13881 } else { 13882 idx--; 13883 } 13884 } catch(NumberFormatException e) { 13885 } 13886 } 13887 } 13888 } 13889 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13890 return prefix + idxStr; 13891 } 13892 13893 private File getNextCodePath(File targetDir, String packageName) { 13894 int suffix = 1; 13895 File result; 13896 do { 13897 result = new File(targetDir, packageName + "-" + suffix); 13898 suffix++; 13899 } while (result.exists()); 13900 return result; 13901 } 13902 13903 // Utility method that returns the relative package path with respect 13904 // to the installation directory. Like say for /data/data/com.test-1.apk 13905 // string com.test-1 is returned. 13906 static String deriveCodePathName(String codePath) { 13907 if (codePath == null) { 13908 return null; 13909 } 13910 final File codeFile = new File(codePath); 13911 final String name = codeFile.getName(); 13912 if (codeFile.isDirectory()) { 13913 return name; 13914 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13915 final int lastDot = name.lastIndexOf('.'); 13916 return name.substring(0, lastDot); 13917 } else { 13918 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13919 return null; 13920 } 13921 } 13922 13923 static class PackageInstalledInfo { 13924 String name; 13925 int uid; 13926 // The set of users that originally had this package installed. 13927 int[] origUsers; 13928 // The set of users that now have this package installed. 13929 int[] newUsers; 13930 PackageParser.Package pkg; 13931 int returnCode; 13932 String returnMsg; 13933 PackageRemovedInfo removedInfo; 13934 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13935 13936 public void setError(int code, String msg) { 13937 setReturnCode(code); 13938 setReturnMessage(msg); 13939 Slog.w(TAG, msg); 13940 } 13941 13942 public void setError(String msg, PackageParserException e) { 13943 setReturnCode(e.error); 13944 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13945 Slog.w(TAG, msg, e); 13946 } 13947 13948 public void setError(String msg, PackageManagerException e) { 13949 returnCode = e.error; 13950 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13951 Slog.w(TAG, msg, e); 13952 } 13953 13954 public void setReturnCode(int returnCode) { 13955 this.returnCode = returnCode; 13956 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13957 for (int i = 0; i < childCount; i++) { 13958 addedChildPackages.valueAt(i).returnCode = returnCode; 13959 } 13960 } 13961 13962 private void setReturnMessage(String returnMsg) { 13963 this.returnMsg = returnMsg; 13964 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13965 for (int i = 0; i < childCount; i++) { 13966 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13967 } 13968 } 13969 13970 // In some error cases we want to convey more info back to the observer 13971 String origPackage; 13972 String origPermission; 13973 } 13974 13975 /* 13976 * Install a non-existing package. 13977 */ 13978 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13979 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13980 PackageInstalledInfo res) { 13981 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13982 13983 // Remember this for later, in case we need to rollback this install 13984 String pkgName = pkg.packageName; 13985 13986 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13987 13988 synchronized(mPackages) { 13989 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13990 // A package with the same name is already installed, though 13991 // it has been renamed to an older name. The package we 13992 // are trying to install should be installed as an update to 13993 // the existing one, but that has not been requested, so bail. 13994 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13995 + " without first uninstalling package running as " 13996 + mSettings.mRenamedPackages.get(pkgName)); 13997 return; 13998 } 13999 if (mPackages.containsKey(pkgName)) { 14000 // Don't allow installation over an existing package with the same name. 14001 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14002 + " without first uninstalling."); 14003 return; 14004 } 14005 } 14006 14007 try { 14008 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14009 System.currentTimeMillis(), user); 14010 14011 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14012 14013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14014 prepareAppDataAfterInstallLIF(newPackage); 14015 14016 } else { 14017 // Remove package from internal structures, but keep around any 14018 // data that might have already existed 14019 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14020 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14021 } 14022 } catch (PackageManagerException e) { 14023 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14024 } 14025 14026 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14027 } 14028 14029 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14030 // Can't rotate keys during boot or if sharedUser. 14031 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14032 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14033 return false; 14034 } 14035 // app is using upgradeKeySets; make sure all are valid 14036 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14037 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14038 for (int i = 0; i < upgradeKeySets.length; i++) { 14039 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14040 Slog.wtf(TAG, "Package " 14041 + (oldPs.name != null ? oldPs.name : "<null>") 14042 + " contains upgrade-key-set reference to unknown key-set: " 14043 + upgradeKeySets[i] 14044 + " reverting to signatures check."); 14045 return false; 14046 } 14047 } 14048 return true; 14049 } 14050 14051 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14052 // Upgrade keysets are being used. Determine if new package has a superset of the 14053 // required keys. 14054 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14055 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14056 for (int i = 0; i < upgradeKeySets.length; i++) { 14057 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14058 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14059 return true; 14060 } 14061 } 14062 return false; 14063 } 14064 14065 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14066 try (DigestInputStream digestStream = 14067 new DigestInputStream(new FileInputStream(file), digest)) { 14068 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14069 } 14070 } 14071 14072 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14073 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14074 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14075 14076 final PackageParser.Package oldPackage; 14077 final String pkgName = pkg.packageName; 14078 final int[] allUsers; 14079 final int[] installedUsers; 14080 14081 synchronized(mPackages) { 14082 oldPackage = mPackages.get(pkgName); 14083 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14084 14085 // don't allow upgrade to target a release SDK from a pre-release SDK 14086 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14087 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14088 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14089 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14090 if (oldTargetsPreRelease 14091 && !newTargetsPreRelease 14092 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14093 Slog.w(TAG, "Can't install package targeting released sdk"); 14094 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14095 return; 14096 } 14097 14098 // don't allow an upgrade from full to ephemeral 14099 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14100 if (isEphemeral && !oldIsEphemeral) { 14101 // can't downgrade from full to ephemeral 14102 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14103 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14104 return; 14105 } 14106 14107 // verify signatures are valid 14108 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14109 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14110 if (!checkUpgradeKeySetLP(ps, pkg)) { 14111 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14112 "New package not signed by keys specified by upgrade-keysets: " 14113 + pkgName); 14114 return; 14115 } 14116 } else { 14117 // default to original signature matching 14118 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14119 != PackageManager.SIGNATURE_MATCH) { 14120 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14121 "New package has a different signature: " + pkgName); 14122 return; 14123 } 14124 } 14125 14126 // don't allow a system upgrade unless the upgrade hash matches 14127 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14128 byte[] digestBytes = null; 14129 try { 14130 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14131 updateDigest(digest, new File(pkg.baseCodePath)); 14132 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14133 for (String path : pkg.splitCodePaths) { 14134 updateDigest(digest, new File(path)); 14135 } 14136 } 14137 digestBytes = digest.digest(); 14138 } catch (NoSuchAlgorithmException | IOException e) { 14139 res.setError(INSTALL_FAILED_INVALID_APK, 14140 "Could not compute hash: " + pkgName); 14141 return; 14142 } 14143 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14144 res.setError(INSTALL_FAILED_INVALID_APK, 14145 "New package fails restrict-update check: " + pkgName); 14146 return; 14147 } 14148 // retain upgrade restriction 14149 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14150 } 14151 14152 // Check for shared user id changes 14153 String invalidPackageName = 14154 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14155 if (invalidPackageName != null) { 14156 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14157 "Package " + invalidPackageName + " tried to change user " 14158 + oldPackage.mSharedUserId); 14159 return; 14160 } 14161 14162 // In case of rollback, remember per-user/profile install state 14163 allUsers = sUserManager.getUserIds(); 14164 installedUsers = ps.queryInstalledUsers(allUsers, true); 14165 } 14166 14167 // Update what is removed 14168 res.removedInfo = new PackageRemovedInfo(); 14169 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14170 res.removedInfo.removedPackage = oldPackage.packageName; 14171 res.removedInfo.isUpdate = true; 14172 res.removedInfo.origUsers = installedUsers; 14173 final int childCount = (oldPackage.childPackages != null) 14174 ? oldPackage.childPackages.size() : 0; 14175 for (int i = 0; i < childCount; i++) { 14176 boolean childPackageUpdated = false; 14177 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14178 if (res.addedChildPackages != null) { 14179 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14180 if (childRes != null) { 14181 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14182 childRes.removedInfo.removedPackage = childPkg.packageName; 14183 childRes.removedInfo.isUpdate = true; 14184 childPackageUpdated = true; 14185 } 14186 } 14187 if (!childPackageUpdated) { 14188 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14189 childRemovedRes.removedPackage = childPkg.packageName; 14190 childRemovedRes.isUpdate = false; 14191 childRemovedRes.dataRemoved = true; 14192 synchronized (mPackages) { 14193 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14194 if (childPs != null) { 14195 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14196 } 14197 } 14198 if (res.removedInfo.removedChildPackages == null) { 14199 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14200 } 14201 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14202 } 14203 } 14204 14205 boolean sysPkg = (isSystemApp(oldPackage)); 14206 if (sysPkg) { 14207 // Set the system/privileged flags as needed 14208 final boolean privileged = 14209 (oldPackage.applicationInfo.privateFlags 14210 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14211 final int systemPolicyFlags = policyFlags 14212 | PackageParser.PARSE_IS_SYSTEM 14213 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14214 14215 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14216 user, allUsers, installerPackageName, res); 14217 } else { 14218 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14219 user, allUsers, installerPackageName, res); 14220 } 14221 } 14222 14223 public List<String> getPreviousCodePaths(String packageName) { 14224 final PackageSetting ps = mSettings.mPackages.get(packageName); 14225 final List<String> result = new ArrayList<String>(); 14226 if (ps != null && ps.oldCodePaths != null) { 14227 result.addAll(ps.oldCodePaths); 14228 } 14229 return result; 14230 } 14231 14232 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14233 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14234 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14235 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14236 + deletedPackage); 14237 14238 String pkgName = deletedPackage.packageName; 14239 boolean deletedPkg = true; 14240 boolean addedPkg = false; 14241 boolean updatedSettings = false; 14242 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14243 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14244 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14245 14246 final long origUpdateTime = (pkg.mExtras != null) 14247 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14248 14249 // First delete the existing package while retaining the data directory 14250 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14251 res.removedInfo, true, pkg)) { 14252 // If the existing package wasn't successfully deleted 14253 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14254 deletedPkg = false; 14255 } else { 14256 // Successfully deleted the old package; proceed with replace. 14257 14258 // If deleted package lived in a container, give users a chance to 14259 // relinquish resources before killing. 14260 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14261 if (DEBUG_INSTALL) { 14262 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14263 } 14264 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14265 final ArrayList<String> pkgList = new ArrayList<String>(1); 14266 pkgList.add(deletedPackage.applicationInfo.packageName); 14267 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14268 } 14269 14270 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14271 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14272 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14273 14274 try { 14275 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14276 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14277 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14278 14279 // Update the in-memory copy of the previous code paths. 14280 PackageSetting ps = mSettings.mPackages.get(pkgName); 14281 if (!killApp) { 14282 if (ps.oldCodePaths == null) { 14283 ps.oldCodePaths = new ArraySet<>(); 14284 } 14285 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14286 if (deletedPackage.splitCodePaths != null) { 14287 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14288 } 14289 } else { 14290 ps.oldCodePaths = null; 14291 } 14292 if (ps.childPackageNames != null) { 14293 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14294 final String childPkgName = ps.childPackageNames.get(i); 14295 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14296 childPs.oldCodePaths = ps.oldCodePaths; 14297 } 14298 } 14299 prepareAppDataAfterInstallLIF(newPackage); 14300 addedPkg = true; 14301 } catch (PackageManagerException e) { 14302 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14303 } 14304 } 14305 14306 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14307 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14308 14309 // Revert all internal state mutations and added folders for the failed install 14310 if (addedPkg) { 14311 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14312 res.removedInfo, true, null); 14313 } 14314 14315 // Restore the old package 14316 if (deletedPkg) { 14317 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14318 File restoreFile = new File(deletedPackage.codePath); 14319 // Parse old package 14320 boolean oldExternal = isExternal(deletedPackage); 14321 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14322 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14323 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14324 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14325 try { 14326 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14327 null); 14328 } catch (PackageManagerException e) { 14329 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14330 + e.getMessage()); 14331 return; 14332 } 14333 14334 synchronized (mPackages) { 14335 // Ensure the installer package name up to date 14336 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14337 14338 // Update permissions for restored package 14339 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14340 14341 mSettings.writeLPr(); 14342 } 14343 14344 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14345 } 14346 } else { 14347 synchronized (mPackages) { 14348 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14349 if (ps != null) { 14350 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14351 if (res.removedInfo.removedChildPackages != null) { 14352 final int childCount = res.removedInfo.removedChildPackages.size(); 14353 // Iterate in reverse as we may modify the collection 14354 for (int i = childCount - 1; i >= 0; i--) { 14355 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14356 if (res.addedChildPackages.containsKey(childPackageName)) { 14357 res.removedInfo.removedChildPackages.removeAt(i); 14358 } else { 14359 PackageRemovedInfo childInfo = res.removedInfo 14360 .removedChildPackages.valueAt(i); 14361 childInfo.removedForAllUsers = mPackages.get( 14362 childInfo.removedPackage) == null; 14363 } 14364 } 14365 } 14366 } 14367 } 14368 } 14369 } 14370 14371 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14372 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14373 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14374 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14375 + ", old=" + deletedPackage); 14376 14377 final boolean disabledSystem; 14378 14379 // Remove existing system package 14380 removePackageLI(deletedPackage, true); 14381 14382 synchronized (mPackages) { 14383 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14384 } 14385 if (!disabledSystem) { 14386 // We didn't need to disable the .apk as a current system package, 14387 // which means we are replacing another update that is already 14388 // installed. We need to make sure to delete the older one's .apk. 14389 res.removedInfo.args = createInstallArgsForExisting(0, 14390 deletedPackage.applicationInfo.getCodePath(), 14391 deletedPackage.applicationInfo.getResourcePath(), 14392 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14393 } else { 14394 res.removedInfo.args = null; 14395 } 14396 14397 // Successfully disabled the old package. Now proceed with re-installation 14398 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14399 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14400 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14401 14402 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14403 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14404 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14405 14406 PackageParser.Package newPackage = null; 14407 try { 14408 // Add the package to the internal data structures 14409 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14410 14411 // Set the update and install times 14412 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14413 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14414 System.currentTimeMillis()); 14415 14416 // Update the package dynamic state if succeeded 14417 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14418 // Now that the install succeeded make sure we remove data 14419 // directories for any child package the update removed. 14420 final int deletedChildCount = (deletedPackage.childPackages != null) 14421 ? deletedPackage.childPackages.size() : 0; 14422 final int newChildCount = (newPackage.childPackages != null) 14423 ? newPackage.childPackages.size() : 0; 14424 for (int i = 0; i < deletedChildCount; i++) { 14425 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14426 boolean childPackageDeleted = true; 14427 for (int j = 0; j < newChildCount; j++) { 14428 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14429 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14430 childPackageDeleted = false; 14431 break; 14432 } 14433 } 14434 if (childPackageDeleted) { 14435 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14436 deletedChildPkg.packageName); 14437 if (ps != null && res.removedInfo.removedChildPackages != null) { 14438 PackageRemovedInfo removedChildRes = res.removedInfo 14439 .removedChildPackages.get(deletedChildPkg.packageName); 14440 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14441 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14442 } 14443 } 14444 } 14445 14446 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14447 prepareAppDataAfterInstallLIF(newPackage); 14448 } 14449 } catch (PackageManagerException e) { 14450 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14451 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14452 } 14453 14454 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14455 // Re installation failed. Restore old information 14456 // Remove new pkg information 14457 if (newPackage != null) { 14458 removeInstalledPackageLI(newPackage, true); 14459 } 14460 // Add back the old system package 14461 try { 14462 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14463 } catch (PackageManagerException e) { 14464 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14465 } 14466 14467 synchronized (mPackages) { 14468 if (disabledSystem) { 14469 enableSystemPackageLPw(deletedPackage); 14470 } 14471 14472 // Ensure the installer package name up to date 14473 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14474 14475 // Update permissions for restored package 14476 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14477 14478 mSettings.writeLPr(); 14479 } 14480 14481 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14482 + " after failed upgrade"); 14483 } 14484 } 14485 14486 /** 14487 * Checks whether the parent or any of the child packages have a change shared 14488 * user. For a package to be a valid update the shred users of the parent and 14489 * the children should match. We may later support changing child shared users. 14490 * @param oldPkg The updated package. 14491 * @param newPkg The update package. 14492 * @return The shared user that change between the versions. 14493 */ 14494 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14495 PackageParser.Package newPkg) { 14496 // Check parent shared user 14497 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14498 return newPkg.packageName; 14499 } 14500 // Check child shared users 14501 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14502 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14503 for (int i = 0; i < newChildCount; i++) { 14504 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14505 // If this child was present, did it have the same shared user? 14506 for (int j = 0; j < oldChildCount; j++) { 14507 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14508 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14509 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14510 return newChildPkg.packageName; 14511 } 14512 } 14513 } 14514 return null; 14515 } 14516 14517 private void removeNativeBinariesLI(PackageSetting ps) { 14518 // Remove the lib path for the parent package 14519 if (ps != null) { 14520 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14521 // Remove the lib path for the child packages 14522 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14523 for (int i = 0; i < childCount; i++) { 14524 PackageSetting childPs = null; 14525 synchronized (mPackages) { 14526 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14527 } 14528 if (childPs != null) { 14529 NativeLibraryHelper.removeNativeBinariesLI(childPs 14530 .legacyNativeLibraryPathString); 14531 } 14532 } 14533 } 14534 } 14535 14536 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14537 // Enable the parent package 14538 mSettings.enableSystemPackageLPw(pkg.packageName); 14539 // Enable the child packages 14540 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14541 for (int i = 0; i < childCount; i++) { 14542 PackageParser.Package childPkg = pkg.childPackages.get(i); 14543 mSettings.enableSystemPackageLPw(childPkg.packageName); 14544 } 14545 } 14546 14547 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14548 PackageParser.Package newPkg) { 14549 // Disable the parent package (parent always replaced) 14550 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14551 // Disable the child packages 14552 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14553 for (int i = 0; i < childCount; i++) { 14554 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14555 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14556 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14557 } 14558 return disabled; 14559 } 14560 14561 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14562 String installerPackageName) { 14563 // Enable the parent package 14564 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14565 // Enable the child packages 14566 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14567 for (int i = 0; i < childCount; i++) { 14568 PackageParser.Package childPkg = pkg.childPackages.get(i); 14569 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14570 } 14571 } 14572 14573 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14574 // Collect all used permissions in the UID 14575 ArraySet<String> usedPermissions = new ArraySet<>(); 14576 final int packageCount = su.packages.size(); 14577 for (int i = 0; i < packageCount; i++) { 14578 PackageSetting ps = su.packages.valueAt(i); 14579 if (ps.pkg == null) { 14580 continue; 14581 } 14582 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14583 for (int j = 0; j < requestedPermCount; j++) { 14584 String permission = ps.pkg.requestedPermissions.get(j); 14585 BasePermission bp = mSettings.mPermissions.get(permission); 14586 if (bp != null) { 14587 usedPermissions.add(permission); 14588 } 14589 } 14590 } 14591 14592 PermissionsState permissionsState = su.getPermissionsState(); 14593 // Prune install permissions 14594 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14595 final int installPermCount = installPermStates.size(); 14596 for (int i = installPermCount - 1; i >= 0; i--) { 14597 PermissionState permissionState = installPermStates.get(i); 14598 if (!usedPermissions.contains(permissionState.getName())) { 14599 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14600 if (bp != null) { 14601 permissionsState.revokeInstallPermission(bp); 14602 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14603 PackageManager.MASK_PERMISSION_FLAGS, 0); 14604 } 14605 } 14606 } 14607 14608 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14609 14610 // Prune runtime permissions 14611 for (int userId : allUserIds) { 14612 List<PermissionState> runtimePermStates = permissionsState 14613 .getRuntimePermissionStates(userId); 14614 final int runtimePermCount = runtimePermStates.size(); 14615 for (int i = runtimePermCount - 1; i >= 0; i--) { 14616 PermissionState permissionState = runtimePermStates.get(i); 14617 if (!usedPermissions.contains(permissionState.getName())) { 14618 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14619 if (bp != null) { 14620 permissionsState.revokeRuntimePermission(bp, userId); 14621 permissionsState.updatePermissionFlags(bp, userId, 14622 PackageManager.MASK_PERMISSION_FLAGS, 0); 14623 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14624 runtimePermissionChangedUserIds, userId); 14625 } 14626 } 14627 } 14628 } 14629 14630 return runtimePermissionChangedUserIds; 14631 } 14632 14633 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14634 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14635 // Update the parent package setting 14636 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14637 res, user); 14638 // Update the child packages setting 14639 final int childCount = (newPackage.childPackages != null) 14640 ? newPackage.childPackages.size() : 0; 14641 for (int i = 0; i < childCount; i++) { 14642 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14643 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14644 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14645 childRes.origUsers, childRes, user); 14646 } 14647 } 14648 14649 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14650 String installerPackageName, int[] allUsers, int[] installedForUsers, 14651 PackageInstalledInfo res, UserHandle user) { 14652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14653 14654 String pkgName = newPackage.packageName; 14655 synchronized (mPackages) { 14656 //write settings. the installStatus will be incomplete at this stage. 14657 //note that the new package setting would have already been 14658 //added to mPackages. It hasn't been persisted yet. 14659 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14661 mSettings.writeLPr(); 14662 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14663 } 14664 14665 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14666 synchronized (mPackages) { 14667 updatePermissionsLPw(newPackage.packageName, newPackage, 14668 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14669 ? UPDATE_PERMISSIONS_ALL : 0)); 14670 // For system-bundled packages, we assume that installing an upgraded version 14671 // of the package implies that the user actually wants to run that new code, 14672 // so we enable the package. 14673 PackageSetting ps = mSettings.mPackages.get(pkgName); 14674 final int userId = user.getIdentifier(); 14675 if (ps != null) { 14676 if (isSystemApp(newPackage)) { 14677 if (DEBUG_INSTALL) { 14678 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14679 } 14680 // Enable system package for requested users 14681 if (res.origUsers != null) { 14682 for (int origUserId : res.origUsers) { 14683 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14684 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14685 origUserId, installerPackageName); 14686 } 14687 } 14688 } 14689 // Also convey the prior install/uninstall state 14690 if (allUsers != null && installedForUsers != null) { 14691 for (int currentUserId : allUsers) { 14692 final boolean installed = ArrayUtils.contains( 14693 installedForUsers, currentUserId); 14694 if (DEBUG_INSTALL) { 14695 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14696 } 14697 ps.setInstalled(installed, currentUserId); 14698 } 14699 // these install state changes will be persisted in the 14700 // upcoming call to mSettings.writeLPr(). 14701 } 14702 } 14703 // It's implied that when a user requests installation, they want the app to be 14704 // installed and enabled. 14705 if (userId != UserHandle.USER_ALL) { 14706 ps.setInstalled(true, userId); 14707 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14708 } 14709 } 14710 res.name = pkgName; 14711 res.uid = newPackage.applicationInfo.uid; 14712 res.pkg = newPackage; 14713 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14714 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14715 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14716 //to update install status 14717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14718 mSettings.writeLPr(); 14719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14720 } 14721 14722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14723 } 14724 14725 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14726 try { 14727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14728 installPackageLI(args, res); 14729 } finally { 14730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14731 } 14732 } 14733 14734 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14735 final int installFlags = args.installFlags; 14736 final String installerPackageName = args.installerPackageName; 14737 final String volumeUuid = args.volumeUuid; 14738 final File tmpPackageFile = new File(args.getCodePath()); 14739 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14740 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14741 || (args.volumeUuid != null)); 14742 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14743 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14744 boolean replace = false; 14745 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14746 if (args.move != null) { 14747 // moving a complete application; perform an initial scan on the new install location 14748 scanFlags |= SCAN_INITIAL; 14749 } 14750 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14751 scanFlags |= SCAN_DONT_KILL_APP; 14752 } 14753 14754 // Result object to be returned 14755 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14756 14757 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14758 14759 // Sanity check 14760 if (ephemeral && (forwardLocked || onExternal)) { 14761 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14762 + " external=" + onExternal); 14763 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14764 return; 14765 } 14766 14767 // Retrieve PackageSettings and parse package 14768 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14769 | PackageParser.PARSE_ENFORCE_CODE 14770 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14771 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14772 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14773 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14774 PackageParser pp = new PackageParser(); 14775 pp.setSeparateProcesses(mSeparateProcesses); 14776 pp.setDisplayMetrics(mMetrics); 14777 14778 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14779 final PackageParser.Package pkg; 14780 try { 14781 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14782 } catch (PackageParserException e) { 14783 res.setError("Failed parse during installPackageLI", e); 14784 return; 14785 } finally { 14786 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14787 } 14788 14789 // If we are installing a clustered package add results for the children 14790 if (pkg.childPackages != null) { 14791 synchronized (mPackages) { 14792 final int childCount = pkg.childPackages.size(); 14793 for (int i = 0; i < childCount; i++) { 14794 PackageParser.Package childPkg = pkg.childPackages.get(i); 14795 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14796 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14797 childRes.pkg = childPkg; 14798 childRes.name = childPkg.packageName; 14799 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14800 if (childPs != null) { 14801 childRes.origUsers = childPs.queryInstalledUsers( 14802 sUserManager.getUserIds(), true); 14803 } 14804 if ((mPackages.containsKey(childPkg.packageName))) { 14805 childRes.removedInfo = new PackageRemovedInfo(); 14806 childRes.removedInfo.removedPackage = childPkg.packageName; 14807 } 14808 if (res.addedChildPackages == null) { 14809 res.addedChildPackages = new ArrayMap<>(); 14810 } 14811 res.addedChildPackages.put(childPkg.packageName, childRes); 14812 } 14813 } 14814 } 14815 14816 // If package doesn't declare API override, mark that we have an install 14817 // time CPU ABI override. 14818 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14819 pkg.cpuAbiOverride = args.abiOverride; 14820 } 14821 14822 String pkgName = res.name = pkg.packageName; 14823 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14824 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14825 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14826 return; 14827 } 14828 } 14829 14830 try { 14831 // either use what we've been given or parse directly from the APK 14832 if (args.certificates != null) { 14833 try { 14834 PackageParser.populateCertificates(pkg, args.certificates); 14835 } catch (PackageParserException e) { 14836 // there was something wrong with the certificates we were given; 14837 // try to pull them from the APK 14838 PackageParser.collectCertificates(pkg, parseFlags); 14839 } 14840 } else { 14841 PackageParser.collectCertificates(pkg, parseFlags); 14842 } 14843 } catch (PackageParserException e) { 14844 res.setError("Failed collect during installPackageLI", e); 14845 return; 14846 } 14847 14848 // Get rid of all references to package scan path via parser. 14849 pp = null; 14850 String oldCodePath = null; 14851 boolean systemApp = false; 14852 synchronized (mPackages) { 14853 // Check if installing already existing package 14854 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14855 String oldName = mSettings.mRenamedPackages.get(pkgName); 14856 if (pkg.mOriginalPackages != null 14857 && pkg.mOriginalPackages.contains(oldName) 14858 && mPackages.containsKey(oldName)) { 14859 // This package is derived from an original package, 14860 // and this device has been updating from that original 14861 // name. We must continue using the original name, so 14862 // rename the new package here. 14863 pkg.setPackageName(oldName); 14864 pkgName = pkg.packageName; 14865 replace = true; 14866 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14867 + oldName + " pkgName=" + pkgName); 14868 } else if (mPackages.containsKey(pkgName)) { 14869 // This package, under its official name, already exists 14870 // on the device; we should replace it. 14871 replace = true; 14872 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14873 } 14874 14875 // Child packages are installed through the parent package 14876 if (pkg.parentPackage != null) { 14877 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14878 "Package " + pkg.packageName + " is child of package " 14879 + pkg.parentPackage.parentPackage + ". Child packages " 14880 + "can be updated only through the parent package."); 14881 return; 14882 } 14883 14884 if (replace) { 14885 // Prevent apps opting out from runtime permissions 14886 PackageParser.Package oldPackage = mPackages.get(pkgName); 14887 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14888 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14889 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14890 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14891 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14892 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14893 + " doesn't support runtime permissions but the old" 14894 + " target SDK " + oldTargetSdk + " does."); 14895 return; 14896 } 14897 14898 // Prevent installing of child packages 14899 if (oldPackage.parentPackage != null) { 14900 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14901 "Package " + pkg.packageName + " is child of package " 14902 + oldPackage.parentPackage + ". Child packages " 14903 + "can be updated only through the parent package."); 14904 return; 14905 } 14906 } 14907 } 14908 14909 PackageSetting ps = mSettings.mPackages.get(pkgName); 14910 if (ps != null) { 14911 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14912 14913 // Quick sanity check that we're signed correctly if updating; 14914 // we'll check this again later when scanning, but we want to 14915 // bail early here before tripping over redefined permissions. 14916 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14917 if (!checkUpgradeKeySetLP(ps, pkg)) { 14918 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14919 + pkg.packageName + " upgrade keys do not match the " 14920 + "previously installed version"); 14921 return; 14922 } 14923 } else { 14924 try { 14925 verifySignaturesLP(ps, pkg); 14926 } catch (PackageManagerException e) { 14927 res.setError(e.error, e.getMessage()); 14928 return; 14929 } 14930 } 14931 14932 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14933 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14934 systemApp = (ps.pkg.applicationInfo.flags & 14935 ApplicationInfo.FLAG_SYSTEM) != 0; 14936 } 14937 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14938 } 14939 14940 // Check whether the newly-scanned package wants to define an already-defined perm 14941 int N = pkg.permissions.size(); 14942 for (int i = N-1; i >= 0; i--) { 14943 PackageParser.Permission perm = pkg.permissions.get(i); 14944 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14945 if (bp != null) { 14946 // If the defining package is signed with our cert, it's okay. This 14947 // also includes the "updating the same package" case, of course. 14948 // "updating same package" could also involve key-rotation. 14949 final boolean sigsOk; 14950 if (bp.sourcePackage.equals(pkg.packageName) 14951 && (bp.packageSetting instanceof PackageSetting) 14952 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14953 scanFlags))) { 14954 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14955 } else { 14956 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14957 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14958 } 14959 if (!sigsOk) { 14960 // If the owning package is the system itself, we log but allow 14961 // install to proceed; we fail the install on all other permission 14962 // redefinitions. 14963 if (!bp.sourcePackage.equals("android")) { 14964 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14965 + pkg.packageName + " attempting to redeclare permission " 14966 + perm.info.name + " already owned by " + bp.sourcePackage); 14967 res.origPermission = perm.info.name; 14968 res.origPackage = bp.sourcePackage; 14969 return; 14970 } else { 14971 Slog.w(TAG, "Package " + pkg.packageName 14972 + " attempting to redeclare system permission " 14973 + perm.info.name + "; ignoring new declaration"); 14974 pkg.permissions.remove(i); 14975 } 14976 } 14977 } 14978 } 14979 } 14980 14981 if (systemApp) { 14982 if (onExternal) { 14983 // Abort update; system app can't be replaced with app on sdcard 14984 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14985 "Cannot install updates to system apps on sdcard"); 14986 return; 14987 } else if (ephemeral) { 14988 // Abort update; system app can't be replaced with an ephemeral app 14989 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14990 "Cannot update a system app with an ephemeral app"); 14991 return; 14992 } 14993 } 14994 14995 if (args.move != null) { 14996 // We did an in-place move, so dex is ready to roll 14997 scanFlags |= SCAN_NO_DEX; 14998 scanFlags |= SCAN_MOVE; 14999 15000 synchronized (mPackages) { 15001 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15002 if (ps == null) { 15003 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15004 "Missing settings for moved package " + pkgName); 15005 } 15006 15007 // We moved the entire application as-is, so bring over the 15008 // previously derived ABI information. 15009 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15010 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15011 } 15012 15013 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15014 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15015 scanFlags |= SCAN_NO_DEX; 15016 15017 try { 15018 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15019 args.abiOverride : pkg.cpuAbiOverride); 15020 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15021 true /* extract libs */); 15022 } catch (PackageManagerException pme) { 15023 Slog.e(TAG, "Error deriving application ABI", pme); 15024 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15025 return; 15026 } 15027 15028 // Shared libraries for the package need to be updated. 15029 synchronized (mPackages) { 15030 try { 15031 updateSharedLibrariesLPw(pkg, null); 15032 } catch (PackageManagerException e) { 15033 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15034 } 15035 } 15036 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15037 // Do not run PackageDexOptimizer through the local performDexOpt 15038 // method because `pkg` may not be in `mPackages` yet. 15039 // 15040 // Also, don't fail application installs if the dexopt step fails. 15041 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15042 null /* instructionSets */, false /* checkProfiles */, 15043 getCompilerFilterForReason(REASON_INSTALL), 15044 getOrCreateCompilerPackageStats(pkg)); 15045 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15046 15047 // Notify BackgroundDexOptService that the package has been changed. 15048 // If this is an update of a package which used to fail to compile, 15049 // BDOS will remove it from its blacklist. 15050 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15051 } 15052 15053 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15054 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15055 return; 15056 } 15057 15058 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15059 15060 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15061 "installPackageLI")) { 15062 if (replace) { 15063 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15064 installerPackageName, res); 15065 } else { 15066 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15067 args.user, installerPackageName, volumeUuid, res); 15068 } 15069 } 15070 synchronized (mPackages) { 15071 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15072 if (ps != null) { 15073 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15074 } 15075 15076 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15077 for (int i = 0; i < childCount; i++) { 15078 PackageParser.Package childPkg = pkg.childPackages.get(i); 15079 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15080 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15081 if (childPs != null) { 15082 childRes.newUsers = childPs.queryInstalledUsers( 15083 sUserManager.getUserIds(), true); 15084 } 15085 } 15086 } 15087 } 15088 15089 private void startIntentFilterVerifications(int userId, boolean replacing, 15090 PackageParser.Package pkg) { 15091 if (mIntentFilterVerifierComponent == null) { 15092 Slog.w(TAG, "No IntentFilter verification will not be done as " 15093 + "there is no IntentFilterVerifier available!"); 15094 return; 15095 } 15096 15097 final int verifierUid = getPackageUid( 15098 mIntentFilterVerifierComponent.getPackageName(), 15099 MATCH_DEBUG_TRIAGED_MISSING, 15100 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15101 15102 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15103 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15104 mHandler.sendMessage(msg); 15105 15106 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15107 for (int i = 0; i < childCount; i++) { 15108 PackageParser.Package childPkg = pkg.childPackages.get(i); 15109 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15110 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15111 mHandler.sendMessage(msg); 15112 } 15113 } 15114 15115 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15116 PackageParser.Package pkg) { 15117 int size = pkg.activities.size(); 15118 if (size == 0) { 15119 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15120 "No activity, so no need to verify any IntentFilter!"); 15121 return; 15122 } 15123 15124 final boolean hasDomainURLs = hasDomainURLs(pkg); 15125 if (!hasDomainURLs) { 15126 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15127 "No domain URLs, so no need to verify any IntentFilter!"); 15128 return; 15129 } 15130 15131 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15132 + " if any IntentFilter from the " + size 15133 + " Activities needs verification ..."); 15134 15135 int count = 0; 15136 final String packageName = pkg.packageName; 15137 15138 synchronized (mPackages) { 15139 // If this is a new install and we see that we've already run verification for this 15140 // package, we have nothing to do: it means the state was restored from backup. 15141 if (!replacing) { 15142 IntentFilterVerificationInfo ivi = 15143 mSettings.getIntentFilterVerificationLPr(packageName); 15144 if (ivi != null) { 15145 if (DEBUG_DOMAIN_VERIFICATION) { 15146 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15147 + ivi.getStatusString()); 15148 } 15149 return; 15150 } 15151 } 15152 15153 // If any filters need to be verified, then all need to be. 15154 boolean needToVerify = false; 15155 for (PackageParser.Activity a : pkg.activities) { 15156 for (ActivityIntentInfo filter : a.intents) { 15157 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15158 if (DEBUG_DOMAIN_VERIFICATION) { 15159 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15160 } 15161 needToVerify = true; 15162 break; 15163 } 15164 } 15165 } 15166 15167 if (needToVerify) { 15168 final int verificationId = mIntentFilterVerificationToken++; 15169 for (PackageParser.Activity a : pkg.activities) { 15170 for (ActivityIntentInfo filter : a.intents) { 15171 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15172 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15173 "Verification needed for IntentFilter:" + filter.toString()); 15174 mIntentFilterVerifier.addOneIntentFilterVerification( 15175 verifierUid, userId, verificationId, filter, packageName); 15176 count++; 15177 } 15178 } 15179 } 15180 } 15181 } 15182 15183 if (count > 0) { 15184 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15185 + " IntentFilter verification" + (count > 1 ? "s" : "") 15186 + " for userId:" + userId); 15187 mIntentFilterVerifier.startVerifications(userId); 15188 } else { 15189 if (DEBUG_DOMAIN_VERIFICATION) { 15190 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15191 } 15192 } 15193 } 15194 15195 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15196 final ComponentName cn = filter.activity.getComponentName(); 15197 final String packageName = cn.getPackageName(); 15198 15199 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15200 packageName); 15201 if (ivi == null) { 15202 return true; 15203 } 15204 int status = ivi.getStatus(); 15205 switch (status) { 15206 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15207 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15208 return true; 15209 15210 default: 15211 // Nothing to do 15212 return false; 15213 } 15214 } 15215 15216 private static boolean isMultiArch(ApplicationInfo info) { 15217 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15218 } 15219 15220 private static boolean isExternal(PackageParser.Package pkg) { 15221 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15222 } 15223 15224 private static boolean isExternal(PackageSetting ps) { 15225 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15226 } 15227 15228 private static boolean isEphemeral(PackageParser.Package pkg) { 15229 return pkg.applicationInfo.isEphemeralApp(); 15230 } 15231 15232 private static boolean isEphemeral(PackageSetting ps) { 15233 return ps.pkg != null && isEphemeral(ps.pkg); 15234 } 15235 15236 private static boolean isSystemApp(PackageParser.Package pkg) { 15237 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15238 } 15239 15240 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15241 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15242 } 15243 15244 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15245 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15246 } 15247 15248 private static boolean isSystemApp(PackageSetting ps) { 15249 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15250 } 15251 15252 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15253 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15254 } 15255 15256 private int packageFlagsToInstallFlags(PackageSetting ps) { 15257 int installFlags = 0; 15258 if (isEphemeral(ps)) { 15259 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15260 } 15261 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15262 // This existing package was an external ASEC install when we have 15263 // the external flag without a UUID 15264 installFlags |= PackageManager.INSTALL_EXTERNAL; 15265 } 15266 if (ps.isForwardLocked()) { 15267 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15268 } 15269 return installFlags; 15270 } 15271 15272 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15273 if (isExternal(pkg)) { 15274 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15275 return StorageManager.UUID_PRIMARY_PHYSICAL; 15276 } else { 15277 return pkg.volumeUuid; 15278 } 15279 } else { 15280 return StorageManager.UUID_PRIVATE_INTERNAL; 15281 } 15282 } 15283 15284 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15285 if (isExternal(pkg)) { 15286 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15287 return mSettings.getExternalVersion(); 15288 } else { 15289 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15290 } 15291 } else { 15292 return mSettings.getInternalVersion(); 15293 } 15294 } 15295 15296 private void deleteTempPackageFiles() { 15297 final FilenameFilter filter = new FilenameFilter() { 15298 public boolean accept(File dir, String name) { 15299 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15300 } 15301 }; 15302 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15303 file.delete(); 15304 } 15305 } 15306 15307 @Override 15308 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15309 int flags) { 15310 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15311 flags); 15312 } 15313 15314 @Override 15315 public void deletePackage(final String packageName, 15316 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15317 mContext.enforceCallingOrSelfPermission( 15318 android.Manifest.permission.DELETE_PACKAGES, null); 15319 Preconditions.checkNotNull(packageName); 15320 Preconditions.checkNotNull(observer); 15321 final int uid = Binder.getCallingUid(); 15322 if (uid != Process.SHELL_UID && uid != Process.ROOT_UID && uid != Process.SYSTEM_UID 15323 && uid != getPackageUid(mRequiredInstallerPackage, 0, UserHandle.getUserId(uid)) 15324 && !isOrphaned(packageName) 15325 && !isCallerSameAsInstaller(uid, packageName)) { 15326 try { 15327 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15328 intent.setData(Uri.fromParts("package", packageName, null)); 15329 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15330 observer.onUserActionRequired(intent); 15331 } catch (RemoteException re) { 15332 } 15333 return; 15334 } 15335 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15336 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15337 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15338 mContext.enforceCallingOrSelfPermission( 15339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15340 "deletePackage for user " + userId); 15341 } 15342 15343 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15344 try { 15345 observer.onPackageDeleted(packageName, 15346 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15347 } catch (RemoteException re) { 15348 } 15349 return; 15350 } 15351 15352 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15353 try { 15354 observer.onPackageDeleted(packageName, 15355 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15356 } catch (RemoteException re) { 15357 } 15358 return; 15359 } 15360 15361 if (DEBUG_REMOVE) { 15362 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15363 + " deleteAllUsers: " + deleteAllUsers ); 15364 } 15365 // Queue up an async operation since the package deletion may take a little while. 15366 mHandler.post(new Runnable() { 15367 public void run() { 15368 mHandler.removeCallbacks(this); 15369 int returnCode; 15370 if (!deleteAllUsers) { 15371 returnCode = deletePackageX(packageName, userId, deleteFlags); 15372 } else { 15373 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15374 // If nobody is blocking uninstall, proceed with delete for all users 15375 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15376 returnCode = deletePackageX(packageName, userId, deleteFlags); 15377 } else { 15378 // Otherwise uninstall individually for users with blockUninstalls=false 15379 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15380 for (int userId : users) { 15381 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15382 returnCode = deletePackageX(packageName, userId, userFlags); 15383 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15384 Slog.w(TAG, "Package delete failed for user " + userId 15385 + ", returnCode " + returnCode); 15386 } 15387 } 15388 } 15389 // The app has only been marked uninstalled for certain users. 15390 // We still need to report that delete was blocked 15391 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15392 } 15393 } 15394 try { 15395 observer.onPackageDeleted(packageName, returnCode, null); 15396 } catch (RemoteException e) { 15397 Log.i(TAG, "Observer no longer exists."); 15398 } //end catch 15399 } //end run 15400 }); 15401 } 15402 15403 private boolean isCallerSameAsInstaller(int callingUid, String pkgName) { 15404 final int installerPkgUid = getPackageUid(getInstallerPackageName(pkgName), 15405 0 /* flags */, UserHandle.getUserId(callingUid)); 15406 return installerPkgUid == callingUid; 15407 } 15408 15409 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15410 int[] result = EMPTY_INT_ARRAY; 15411 for (int userId : userIds) { 15412 if (getBlockUninstallForUser(packageName, userId)) { 15413 result = ArrayUtils.appendInt(result, userId); 15414 } 15415 } 15416 return result; 15417 } 15418 15419 @Override 15420 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15421 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15422 } 15423 15424 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15425 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15426 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15427 try { 15428 if (dpm != null) { 15429 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15430 /* callingUserOnly =*/ false); 15431 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15432 : deviceOwnerComponentName.getPackageName(); 15433 // Does the package contains the device owner? 15434 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15435 // this check is probably not needed, since DO should be registered as a device 15436 // admin on some user too. (Original bug for this: b/17657954) 15437 if (packageName.equals(deviceOwnerPackageName)) { 15438 return true; 15439 } 15440 // Does it contain a device admin for any user? 15441 int[] users; 15442 if (userId == UserHandle.USER_ALL) { 15443 users = sUserManager.getUserIds(); 15444 } else { 15445 users = new int[]{userId}; 15446 } 15447 for (int i = 0; i < users.length; ++i) { 15448 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15449 return true; 15450 } 15451 } 15452 } 15453 } catch (RemoteException e) { 15454 } 15455 return false; 15456 } 15457 15458 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15459 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15460 } 15461 15462 /** 15463 * This method is an internal method that could be get invoked either 15464 * to delete an installed package or to clean up a failed installation. 15465 * After deleting an installed package, a broadcast is sent to notify any 15466 * listeners that the package has been removed. For cleaning up a failed 15467 * installation, the broadcast is not necessary since the package's 15468 * installation wouldn't have sent the initial broadcast either 15469 * The key steps in deleting a package are 15470 * deleting the package information in internal structures like mPackages, 15471 * deleting the packages base directories through installd 15472 * updating mSettings to reflect current status 15473 * persisting settings for later use 15474 * sending a broadcast if necessary 15475 */ 15476 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15477 final PackageRemovedInfo info = new PackageRemovedInfo(); 15478 final boolean res; 15479 15480 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15481 ? UserHandle.USER_ALL : userId; 15482 15483 if (isPackageDeviceAdmin(packageName, removeUser)) { 15484 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15485 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15486 } 15487 15488 PackageSetting uninstalledPs = null; 15489 15490 // for the uninstall-updates case and restricted profiles, remember the per- 15491 // user handle installed state 15492 int[] allUsers; 15493 synchronized (mPackages) { 15494 uninstalledPs = mSettings.mPackages.get(packageName); 15495 if (uninstalledPs == null) { 15496 Slog.w(TAG, "Not removing non-existent package " + packageName); 15497 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15498 } 15499 allUsers = sUserManager.getUserIds(); 15500 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15501 } 15502 15503 final int freezeUser; 15504 if (isUpdatedSystemApp(uninstalledPs) 15505 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15506 // We're downgrading a system app, which will apply to all users, so 15507 // freeze them all during the downgrade 15508 freezeUser = UserHandle.USER_ALL; 15509 } else { 15510 freezeUser = removeUser; 15511 } 15512 15513 synchronized (mInstallLock) { 15514 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15515 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15516 deleteFlags, "deletePackageX")) { 15517 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15518 deleteFlags | REMOVE_CHATTY, info, true, null); 15519 } 15520 synchronized (mPackages) { 15521 if (res) { 15522 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15523 } 15524 } 15525 } 15526 15527 if (res) { 15528 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15529 info.sendPackageRemovedBroadcasts(killApp); 15530 info.sendSystemPackageUpdatedBroadcasts(); 15531 info.sendSystemPackageAppearedBroadcasts(); 15532 } 15533 // Force a gc here. 15534 Runtime.getRuntime().gc(); 15535 // Delete the resources here after sending the broadcast to let 15536 // other processes clean up before deleting resources. 15537 if (info.args != null) { 15538 synchronized (mInstallLock) { 15539 info.args.doPostDeleteLI(true); 15540 } 15541 } 15542 15543 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15544 } 15545 15546 class PackageRemovedInfo { 15547 String removedPackage; 15548 int uid = -1; 15549 int removedAppId = -1; 15550 int[] origUsers; 15551 int[] removedUsers = null; 15552 boolean isRemovedPackageSystemUpdate = false; 15553 boolean isUpdate; 15554 boolean dataRemoved; 15555 boolean removedForAllUsers; 15556 // Clean up resources deleted packages. 15557 InstallArgs args = null; 15558 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15559 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15560 15561 void sendPackageRemovedBroadcasts(boolean killApp) { 15562 sendPackageRemovedBroadcastInternal(killApp); 15563 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15564 for (int i = 0; i < childCount; i++) { 15565 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15566 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15567 } 15568 } 15569 15570 void sendSystemPackageUpdatedBroadcasts() { 15571 if (isRemovedPackageSystemUpdate) { 15572 sendSystemPackageUpdatedBroadcastsInternal(); 15573 final int childCount = (removedChildPackages != null) 15574 ? removedChildPackages.size() : 0; 15575 for (int i = 0; i < childCount; i++) { 15576 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15577 if (childInfo.isRemovedPackageSystemUpdate) { 15578 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15579 } 15580 } 15581 } 15582 } 15583 15584 void sendSystemPackageAppearedBroadcasts() { 15585 final int packageCount = (appearedChildPackages != null) 15586 ? appearedChildPackages.size() : 0; 15587 for (int i = 0; i < packageCount; i++) { 15588 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15589 for (int userId : installedInfo.newUsers) { 15590 sendPackageAddedForUser(installedInfo.name, true, 15591 UserHandle.getAppId(installedInfo.uid), userId); 15592 } 15593 } 15594 } 15595 15596 private void sendSystemPackageUpdatedBroadcastsInternal() { 15597 Bundle extras = new Bundle(2); 15598 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15599 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15601 extras, 0, null, null, null); 15602 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15603 extras, 0, null, null, null); 15604 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15605 null, 0, removedPackage, null, null); 15606 } 15607 15608 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15609 Bundle extras = new Bundle(2); 15610 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15611 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15612 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15613 if (isUpdate || isRemovedPackageSystemUpdate) { 15614 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15615 } 15616 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15617 if (removedPackage != null) { 15618 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15619 extras, 0, null, null, removedUsers); 15620 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15621 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15622 removedPackage, extras, 0, null, null, removedUsers); 15623 } 15624 } 15625 if (removedAppId >= 0) { 15626 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15627 removedUsers); 15628 } 15629 } 15630 } 15631 15632 /* 15633 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15634 * flag is not set, the data directory is removed as well. 15635 * make sure this flag is set for partially installed apps. If not its meaningless to 15636 * delete a partially installed application. 15637 */ 15638 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15639 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15640 String packageName = ps.name; 15641 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15642 // Retrieve object to delete permissions for shared user later on 15643 final PackageParser.Package deletedPkg; 15644 final PackageSetting deletedPs; 15645 // reader 15646 synchronized (mPackages) { 15647 deletedPkg = mPackages.get(packageName); 15648 deletedPs = mSettings.mPackages.get(packageName); 15649 if (outInfo != null) { 15650 outInfo.removedPackage = packageName; 15651 outInfo.removedUsers = deletedPs != null 15652 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15653 : null; 15654 } 15655 } 15656 15657 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15658 15659 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15660 final PackageParser.Package resolvedPkg; 15661 if (deletedPkg != null) { 15662 resolvedPkg = deletedPkg; 15663 } else { 15664 // We don't have a parsed package when it lives on an ejected 15665 // adopted storage device, so fake something together 15666 resolvedPkg = new PackageParser.Package(ps.name); 15667 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15668 } 15669 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15670 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15671 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15672 if (outInfo != null) { 15673 outInfo.dataRemoved = true; 15674 } 15675 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15676 } 15677 15678 // writer 15679 synchronized (mPackages) { 15680 if (deletedPs != null) { 15681 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15682 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15683 clearDefaultBrowserIfNeeded(packageName); 15684 if (outInfo != null) { 15685 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15686 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15687 } 15688 updatePermissionsLPw(deletedPs.name, null, 0); 15689 if (deletedPs.sharedUser != null) { 15690 // Remove permissions associated with package. Since runtime 15691 // permissions are per user we have to kill the removed package 15692 // or packages running under the shared user of the removed 15693 // package if revoking the permissions requested only by the removed 15694 // package is successful and this causes a change in gids. 15695 for (int userId : UserManagerService.getInstance().getUserIds()) { 15696 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15697 userId); 15698 if (userIdToKill == UserHandle.USER_ALL 15699 || userIdToKill >= UserHandle.USER_SYSTEM) { 15700 // If gids changed for this user, kill all affected packages. 15701 mHandler.post(new Runnable() { 15702 @Override 15703 public void run() { 15704 // This has to happen with no lock held. 15705 killApplication(deletedPs.name, deletedPs.appId, 15706 KILL_APP_REASON_GIDS_CHANGED); 15707 } 15708 }); 15709 break; 15710 } 15711 } 15712 } 15713 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15714 } 15715 // make sure to preserve per-user disabled state if this removal was just 15716 // a downgrade of a system app to the factory package 15717 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15718 if (DEBUG_REMOVE) { 15719 Slog.d(TAG, "Propagating install state across downgrade"); 15720 } 15721 for (int userId : allUserHandles) { 15722 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15723 if (DEBUG_REMOVE) { 15724 Slog.d(TAG, " user " + userId + " => " + installed); 15725 } 15726 ps.setInstalled(installed, userId); 15727 } 15728 } 15729 } 15730 // can downgrade to reader 15731 if (writeSettings) { 15732 // Save settings now 15733 mSettings.writeLPr(); 15734 } 15735 } 15736 if (outInfo != null) { 15737 // A user ID was deleted here. Go through all users and remove it 15738 // from KeyStore. 15739 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15740 } 15741 } 15742 15743 static boolean locationIsPrivileged(File path) { 15744 try { 15745 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15746 .getCanonicalPath(); 15747 return path.getCanonicalPath().startsWith(privilegedAppDir); 15748 } catch (IOException e) { 15749 Slog.e(TAG, "Unable to access code path " + path); 15750 } 15751 return false; 15752 } 15753 15754 /* 15755 * Tries to delete system package. 15756 */ 15757 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15758 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15759 boolean writeSettings) { 15760 if (deletedPs.parentPackageName != null) { 15761 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15762 return false; 15763 } 15764 15765 final boolean applyUserRestrictions 15766 = (allUserHandles != null) && (outInfo.origUsers != null); 15767 final PackageSetting disabledPs; 15768 // Confirm if the system package has been updated 15769 // An updated system app can be deleted. This will also have to restore 15770 // the system pkg from system partition 15771 // reader 15772 synchronized (mPackages) { 15773 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15774 } 15775 15776 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15777 + " disabledPs=" + disabledPs); 15778 15779 if (disabledPs == null) { 15780 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15781 return false; 15782 } else if (DEBUG_REMOVE) { 15783 Slog.d(TAG, "Deleting system pkg from data partition"); 15784 } 15785 15786 if (DEBUG_REMOVE) { 15787 if (applyUserRestrictions) { 15788 Slog.d(TAG, "Remembering install states:"); 15789 for (int userId : allUserHandles) { 15790 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15791 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15792 } 15793 } 15794 } 15795 15796 // Delete the updated package 15797 outInfo.isRemovedPackageSystemUpdate = true; 15798 if (outInfo.removedChildPackages != null) { 15799 final int childCount = (deletedPs.childPackageNames != null) 15800 ? deletedPs.childPackageNames.size() : 0; 15801 for (int i = 0; i < childCount; i++) { 15802 String childPackageName = deletedPs.childPackageNames.get(i); 15803 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15804 .contains(childPackageName)) { 15805 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15806 childPackageName); 15807 if (childInfo != null) { 15808 childInfo.isRemovedPackageSystemUpdate = true; 15809 } 15810 } 15811 } 15812 } 15813 15814 if (disabledPs.versionCode < deletedPs.versionCode) { 15815 // Delete data for downgrades 15816 flags &= ~PackageManager.DELETE_KEEP_DATA; 15817 } else { 15818 // Preserve data by setting flag 15819 flags |= PackageManager.DELETE_KEEP_DATA; 15820 } 15821 15822 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15823 outInfo, writeSettings, disabledPs.pkg); 15824 if (!ret) { 15825 return false; 15826 } 15827 15828 // writer 15829 synchronized (mPackages) { 15830 // Reinstate the old system package 15831 enableSystemPackageLPw(disabledPs.pkg); 15832 // Remove any native libraries from the upgraded package. 15833 removeNativeBinariesLI(deletedPs); 15834 } 15835 15836 // Install the system package 15837 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15838 int parseFlags = mDefParseFlags 15839 | PackageParser.PARSE_MUST_BE_APK 15840 | PackageParser.PARSE_IS_SYSTEM 15841 | PackageParser.PARSE_IS_SYSTEM_DIR; 15842 if (locationIsPrivileged(disabledPs.codePath)) { 15843 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15844 } 15845 15846 final PackageParser.Package newPkg; 15847 try { 15848 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15849 } catch (PackageManagerException e) { 15850 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15851 + e.getMessage()); 15852 return false; 15853 } 15854 try { 15855 // update shared libraries for the newly re-installed system package 15856 updateSharedLibrariesLPw(newPkg, null); 15857 } catch (PackageManagerException e) { 15858 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 15859 } 15860 15861 prepareAppDataAfterInstallLIF(newPkg); 15862 15863 // writer 15864 synchronized (mPackages) { 15865 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15866 15867 // Propagate the permissions state as we do not want to drop on the floor 15868 // runtime permissions. The update permissions method below will take 15869 // care of removing obsolete permissions and grant install permissions. 15870 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15871 updatePermissionsLPw(newPkg.packageName, newPkg, 15872 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15873 15874 if (applyUserRestrictions) { 15875 if (DEBUG_REMOVE) { 15876 Slog.d(TAG, "Propagating install state across reinstall"); 15877 } 15878 for (int userId : allUserHandles) { 15879 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15880 if (DEBUG_REMOVE) { 15881 Slog.d(TAG, " user " + userId + " => " + installed); 15882 } 15883 ps.setInstalled(installed, userId); 15884 15885 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15886 } 15887 // Regardless of writeSettings we need to ensure that this restriction 15888 // state propagation is persisted 15889 mSettings.writeAllUsersPackageRestrictionsLPr(); 15890 } 15891 // can downgrade to reader here 15892 if (writeSettings) { 15893 mSettings.writeLPr(); 15894 } 15895 } 15896 return true; 15897 } 15898 15899 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15900 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15901 PackageRemovedInfo outInfo, boolean writeSettings, 15902 PackageParser.Package replacingPackage) { 15903 synchronized (mPackages) { 15904 if (outInfo != null) { 15905 outInfo.uid = ps.appId; 15906 } 15907 15908 if (outInfo != null && outInfo.removedChildPackages != null) { 15909 final int childCount = (ps.childPackageNames != null) 15910 ? ps.childPackageNames.size() : 0; 15911 for (int i = 0; i < childCount; i++) { 15912 String childPackageName = ps.childPackageNames.get(i); 15913 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15914 if (childPs == null) { 15915 return false; 15916 } 15917 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15918 childPackageName); 15919 if (childInfo != null) { 15920 childInfo.uid = childPs.appId; 15921 } 15922 } 15923 } 15924 } 15925 15926 // Delete package data from internal structures and also remove data if flag is set 15927 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15928 15929 // Delete the child packages data 15930 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15931 for (int i = 0; i < childCount; i++) { 15932 PackageSetting childPs; 15933 synchronized (mPackages) { 15934 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15935 } 15936 if (childPs != null) { 15937 PackageRemovedInfo childOutInfo = (outInfo != null 15938 && outInfo.removedChildPackages != null) 15939 ? outInfo.removedChildPackages.get(childPs.name) : null; 15940 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15941 && (replacingPackage != null 15942 && !replacingPackage.hasChildPackage(childPs.name)) 15943 ? flags & ~DELETE_KEEP_DATA : flags; 15944 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15945 deleteFlags, writeSettings); 15946 } 15947 } 15948 15949 // Delete application code and resources only for parent packages 15950 if (ps.parentPackageName == null) { 15951 if (deleteCodeAndResources && (outInfo != null)) { 15952 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15953 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15954 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15955 } 15956 } 15957 15958 return true; 15959 } 15960 15961 @Override 15962 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15963 int userId) { 15964 mContext.enforceCallingOrSelfPermission( 15965 android.Manifest.permission.DELETE_PACKAGES, null); 15966 synchronized (mPackages) { 15967 PackageSetting ps = mSettings.mPackages.get(packageName); 15968 if (ps == null) { 15969 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15970 return false; 15971 } 15972 if (!ps.getInstalled(userId)) { 15973 // Can't block uninstall for an app that is not installed or enabled. 15974 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15975 return false; 15976 } 15977 ps.setBlockUninstall(blockUninstall, userId); 15978 mSettings.writePackageRestrictionsLPr(userId); 15979 } 15980 return true; 15981 } 15982 15983 @Override 15984 public boolean getBlockUninstallForUser(String packageName, int userId) { 15985 synchronized (mPackages) { 15986 PackageSetting ps = mSettings.mPackages.get(packageName); 15987 if (ps == null) { 15988 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15989 return false; 15990 } 15991 return ps.getBlockUninstall(userId); 15992 } 15993 } 15994 15995 @Override 15996 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15997 int callingUid = Binder.getCallingUid(); 15998 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15999 throw new SecurityException( 16000 "setRequiredForSystemUser can only be run by the system or root"); 16001 } 16002 synchronized (mPackages) { 16003 PackageSetting ps = mSettings.mPackages.get(packageName); 16004 if (ps == null) { 16005 Log.w(TAG, "Package doesn't exist: " + packageName); 16006 return false; 16007 } 16008 if (systemUserApp) { 16009 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16010 } else { 16011 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16012 } 16013 mSettings.writeLPr(); 16014 } 16015 return true; 16016 } 16017 16018 /* 16019 * This method handles package deletion in general 16020 */ 16021 private boolean deletePackageLIF(String packageName, UserHandle user, 16022 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16023 PackageRemovedInfo outInfo, boolean writeSettings, 16024 PackageParser.Package replacingPackage) { 16025 if (packageName == null) { 16026 Slog.w(TAG, "Attempt to delete null packageName."); 16027 return false; 16028 } 16029 16030 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16031 16032 PackageSetting ps; 16033 16034 synchronized (mPackages) { 16035 ps = mSettings.mPackages.get(packageName); 16036 if (ps == null) { 16037 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16038 return false; 16039 } 16040 16041 if (ps.parentPackageName != null && (!isSystemApp(ps) 16042 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16043 if (DEBUG_REMOVE) { 16044 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16045 + ((user == null) ? UserHandle.USER_ALL : user)); 16046 } 16047 final int removedUserId = (user != null) ? user.getIdentifier() 16048 : UserHandle.USER_ALL; 16049 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16050 return false; 16051 } 16052 markPackageUninstalledForUserLPw(ps, user); 16053 scheduleWritePackageRestrictionsLocked(user); 16054 return true; 16055 } 16056 } 16057 16058 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16059 && user.getIdentifier() != UserHandle.USER_ALL)) { 16060 // The caller is asking that the package only be deleted for a single 16061 // user. To do this, we just mark its uninstalled state and delete 16062 // its data. If this is a system app, we only allow this to happen if 16063 // they have set the special DELETE_SYSTEM_APP which requests different 16064 // semantics than normal for uninstalling system apps. 16065 markPackageUninstalledForUserLPw(ps, user); 16066 16067 if (!isSystemApp(ps)) { 16068 // Do not uninstall the APK if an app should be cached 16069 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16070 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16071 // Other user still have this package installed, so all 16072 // we need to do is clear this user's data and save that 16073 // it is uninstalled. 16074 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16075 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16076 return false; 16077 } 16078 scheduleWritePackageRestrictionsLocked(user); 16079 return true; 16080 } else { 16081 // We need to set it back to 'installed' so the uninstall 16082 // broadcasts will be sent correctly. 16083 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16084 ps.setInstalled(true, user.getIdentifier()); 16085 } 16086 } else { 16087 // This is a system app, so we assume that the 16088 // other users still have this package installed, so all 16089 // we need to do is clear this user's data and save that 16090 // it is uninstalled. 16091 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16092 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16093 return false; 16094 } 16095 scheduleWritePackageRestrictionsLocked(user); 16096 return true; 16097 } 16098 } 16099 16100 // If we are deleting a composite package for all users, keep track 16101 // of result for each child. 16102 if (ps.childPackageNames != null && outInfo != null) { 16103 synchronized (mPackages) { 16104 final int childCount = ps.childPackageNames.size(); 16105 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16106 for (int i = 0; i < childCount; i++) { 16107 String childPackageName = ps.childPackageNames.get(i); 16108 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16109 childInfo.removedPackage = childPackageName; 16110 outInfo.removedChildPackages.put(childPackageName, childInfo); 16111 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16112 if (childPs != null) { 16113 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16114 } 16115 } 16116 } 16117 } 16118 16119 boolean ret = false; 16120 if (isSystemApp(ps)) { 16121 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16122 // When an updated system application is deleted we delete the existing resources 16123 // as well and fall back to existing code in system partition 16124 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16125 } else { 16126 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16127 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16128 outInfo, writeSettings, replacingPackage); 16129 } 16130 16131 // Take a note whether we deleted the package for all users 16132 if (outInfo != null) { 16133 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16134 if (outInfo.removedChildPackages != null) { 16135 synchronized (mPackages) { 16136 final int childCount = outInfo.removedChildPackages.size(); 16137 for (int i = 0; i < childCount; i++) { 16138 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16139 if (childInfo != null) { 16140 childInfo.removedForAllUsers = mPackages.get( 16141 childInfo.removedPackage) == null; 16142 } 16143 } 16144 } 16145 } 16146 // If we uninstalled an update to a system app there may be some 16147 // child packages that appeared as they are declared in the system 16148 // app but were not declared in the update. 16149 if (isSystemApp(ps)) { 16150 synchronized (mPackages) { 16151 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16152 final int childCount = (updatedPs.childPackageNames != null) 16153 ? updatedPs.childPackageNames.size() : 0; 16154 for (int i = 0; i < childCount; i++) { 16155 String childPackageName = updatedPs.childPackageNames.get(i); 16156 if (outInfo.removedChildPackages == null 16157 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16158 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16159 if (childPs == null) { 16160 continue; 16161 } 16162 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16163 installRes.name = childPackageName; 16164 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16165 installRes.pkg = mPackages.get(childPackageName); 16166 installRes.uid = childPs.pkg.applicationInfo.uid; 16167 if (outInfo.appearedChildPackages == null) { 16168 outInfo.appearedChildPackages = new ArrayMap<>(); 16169 } 16170 outInfo.appearedChildPackages.put(childPackageName, installRes); 16171 } 16172 } 16173 } 16174 } 16175 } 16176 16177 return ret; 16178 } 16179 16180 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16181 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16182 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16183 for (int nextUserId : userIds) { 16184 if (DEBUG_REMOVE) { 16185 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16186 } 16187 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16188 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16189 false /*hidden*/, false /*suspended*/, null, null, null, 16190 false /*blockUninstall*/, 16191 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16192 } 16193 } 16194 16195 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16196 PackageRemovedInfo outInfo) { 16197 final PackageParser.Package pkg; 16198 synchronized (mPackages) { 16199 pkg = mPackages.get(ps.name); 16200 } 16201 16202 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16203 : new int[] {userId}; 16204 for (int nextUserId : userIds) { 16205 if (DEBUG_REMOVE) { 16206 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16207 + nextUserId); 16208 } 16209 16210 destroyAppDataLIF(pkg, userId, 16211 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16212 destroyAppProfilesLIF(pkg, userId); 16213 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16214 schedulePackageCleaning(ps.name, nextUserId, false); 16215 synchronized (mPackages) { 16216 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16217 scheduleWritePackageRestrictionsLocked(nextUserId); 16218 } 16219 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16220 } 16221 } 16222 16223 if (outInfo != null) { 16224 outInfo.removedPackage = ps.name; 16225 outInfo.removedAppId = ps.appId; 16226 outInfo.removedUsers = userIds; 16227 } 16228 16229 return true; 16230 } 16231 16232 private final class ClearStorageConnection implements ServiceConnection { 16233 IMediaContainerService mContainerService; 16234 16235 @Override 16236 public void onServiceConnected(ComponentName name, IBinder service) { 16237 synchronized (this) { 16238 mContainerService = IMediaContainerService.Stub.asInterface(service); 16239 notifyAll(); 16240 } 16241 } 16242 16243 @Override 16244 public void onServiceDisconnected(ComponentName name) { 16245 } 16246 } 16247 16248 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16249 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16250 16251 final boolean mounted; 16252 if (Environment.isExternalStorageEmulated()) { 16253 mounted = true; 16254 } else { 16255 final String status = Environment.getExternalStorageState(); 16256 16257 mounted = status.equals(Environment.MEDIA_MOUNTED) 16258 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16259 } 16260 16261 if (!mounted) { 16262 return; 16263 } 16264 16265 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16266 int[] users; 16267 if (userId == UserHandle.USER_ALL) { 16268 users = sUserManager.getUserIds(); 16269 } else { 16270 users = new int[] { userId }; 16271 } 16272 final ClearStorageConnection conn = new ClearStorageConnection(); 16273 if (mContext.bindServiceAsUser( 16274 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16275 try { 16276 for (int curUser : users) { 16277 long timeout = SystemClock.uptimeMillis() + 5000; 16278 synchronized (conn) { 16279 long now; 16280 while (conn.mContainerService == null && 16281 (now = SystemClock.uptimeMillis()) < timeout) { 16282 try { 16283 conn.wait(timeout - now); 16284 } catch (InterruptedException e) { 16285 } 16286 } 16287 } 16288 if (conn.mContainerService == null) { 16289 return; 16290 } 16291 16292 final UserEnvironment userEnv = new UserEnvironment(curUser); 16293 clearDirectory(conn.mContainerService, 16294 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16295 if (allData) { 16296 clearDirectory(conn.mContainerService, 16297 userEnv.buildExternalStorageAppDataDirs(packageName)); 16298 clearDirectory(conn.mContainerService, 16299 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16300 } 16301 } 16302 } finally { 16303 mContext.unbindService(conn); 16304 } 16305 } 16306 } 16307 16308 @Override 16309 public void clearApplicationProfileData(String packageName) { 16310 enforceSystemOrRoot("Only the system can clear all profile data"); 16311 16312 final PackageParser.Package pkg; 16313 synchronized (mPackages) { 16314 pkg = mPackages.get(packageName); 16315 } 16316 16317 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16318 synchronized (mInstallLock) { 16319 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16320 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16321 true /* removeBaseMarker */); 16322 } 16323 } 16324 } 16325 16326 @Override 16327 public void clearApplicationUserData(final String packageName, 16328 final IPackageDataObserver observer, final int userId) { 16329 mContext.enforceCallingOrSelfPermission( 16330 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16331 16332 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16333 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16334 16335 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16336 throw new SecurityException("Cannot clear data for a protected package: " 16337 + packageName); 16338 } 16339 // Queue up an async operation since the package deletion may take a little while. 16340 mHandler.post(new Runnable() { 16341 public void run() { 16342 mHandler.removeCallbacks(this); 16343 final boolean succeeded; 16344 try (PackageFreezer freezer = freezePackage(packageName, 16345 "clearApplicationUserData")) { 16346 synchronized (mInstallLock) { 16347 succeeded = clearApplicationUserDataLIF(packageName, userId); 16348 } 16349 clearExternalStorageDataSync(packageName, userId, true); 16350 } 16351 if (succeeded) { 16352 // invoke DeviceStorageMonitor's update method to clear any notifications 16353 DeviceStorageMonitorInternal dsm = LocalServices 16354 .getService(DeviceStorageMonitorInternal.class); 16355 if (dsm != null) { 16356 dsm.checkMemory(); 16357 } 16358 } 16359 if(observer != null) { 16360 try { 16361 observer.onRemoveCompleted(packageName, succeeded); 16362 } catch (RemoteException e) { 16363 Log.i(TAG, "Observer no longer exists."); 16364 } 16365 } //end if observer 16366 } //end run 16367 }); 16368 } 16369 16370 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16371 if (packageName == null) { 16372 Slog.w(TAG, "Attempt to delete null packageName."); 16373 return false; 16374 } 16375 16376 // Try finding details about the requested package 16377 PackageParser.Package pkg; 16378 synchronized (mPackages) { 16379 pkg = mPackages.get(packageName); 16380 if (pkg == null) { 16381 final PackageSetting ps = mSettings.mPackages.get(packageName); 16382 if (ps != null) { 16383 pkg = ps.pkg; 16384 } 16385 } 16386 16387 if (pkg == null) { 16388 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16389 return false; 16390 } 16391 16392 PackageSetting ps = (PackageSetting) pkg.mExtras; 16393 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16394 } 16395 16396 clearAppDataLIF(pkg, userId, 16397 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16398 16399 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16400 removeKeystoreDataIfNeeded(userId, appId); 16401 16402 UserManagerInternal umInternal = getUserManagerInternal(); 16403 final int flags; 16404 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16405 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16406 } else if (umInternal.isUserRunning(userId)) { 16407 flags = StorageManager.FLAG_STORAGE_DE; 16408 } else { 16409 flags = 0; 16410 } 16411 prepareAppDataContentsLIF(pkg, userId, flags); 16412 16413 return true; 16414 } 16415 16416 /** 16417 * Reverts user permission state changes (permissions and flags) in 16418 * all packages for a given user. 16419 * 16420 * @param userId The device user for which to do a reset. 16421 */ 16422 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16423 final int packageCount = mPackages.size(); 16424 for (int i = 0; i < packageCount; i++) { 16425 PackageParser.Package pkg = mPackages.valueAt(i); 16426 PackageSetting ps = (PackageSetting) pkg.mExtras; 16427 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16428 } 16429 } 16430 16431 private void resetNetworkPolicies(int userId) { 16432 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16433 } 16434 16435 /** 16436 * Reverts user permission state changes (permissions and flags). 16437 * 16438 * @param ps The package for which to reset. 16439 * @param userId The device user for which to do a reset. 16440 */ 16441 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16442 final PackageSetting ps, final int userId) { 16443 if (ps.pkg == null) { 16444 return; 16445 } 16446 16447 // These are flags that can change base on user actions. 16448 final int userSettableMask = FLAG_PERMISSION_USER_SET 16449 | FLAG_PERMISSION_USER_FIXED 16450 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16451 | FLAG_PERMISSION_REVIEW_REQUIRED; 16452 16453 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16454 | FLAG_PERMISSION_POLICY_FIXED; 16455 16456 boolean writeInstallPermissions = false; 16457 boolean writeRuntimePermissions = false; 16458 16459 final int permissionCount = ps.pkg.requestedPermissions.size(); 16460 for (int i = 0; i < permissionCount; i++) { 16461 String permission = ps.pkg.requestedPermissions.get(i); 16462 16463 BasePermission bp = mSettings.mPermissions.get(permission); 16464 if (bp == null) { 16465 continue; 16466 } 16467 16468 // If shared user we just reset the state to which only this app contributed. 16469 if (ps.sharedUser != null) { 16470 boolean used = false; 16471 final int packageCount = ps.sharedUser.packages.size(); 16472 for (int j = 0; j < packageCount; j++) { 16473 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16474 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16475 && pkg.pkg.requestedPermissions.contains(permission)) { 16476 used = true; 16477 break; 16478 } 16479 } 16480 if (used) { 16481 continue; 16482 } 16483 } 16484 16485 PermissionsState permissionsState = ps.getPermissionsState(); 16486 16487 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16488 16489 // Always clear the user settable flags. 16490 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16491 bp.name) != null; 16492 // If permission review is enabled and this is a legacy app, mark the 16493 // permission as requiring a review as this is the initial state. 16494 int flags = 0; 16495 if (Build.PERMISSIONS_REVIEW_REQUIRED 16496 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16497 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16498 } 16499 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16500 if (hasInstallState) { 16501 writeInstallPermissions = true; 16502 } else { 16503 writeRuntimePermissions = true; 16504 } 16505 } 16506 16507 // Below is only runtime permission handling. 16508 if (!bp.isRuntime()) { 16509 continue; 16510 } 16511 16512 // Never clobber system or policy. 16513 if ((oldFlags & policyOrSystemFlags) != 0) { 16514 continue; 16515 } 16516 16517 // If this permission was granted by default, make sure it is. 16518 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16519 if (permissionsState.grantRuntimePermission(bp, userId) 16520 != PERMISSION_OPERATION_FAILURE) { 16521 writeRuntimePermissions = true; 16522 } 16523 // If permission review is enabled the permissions for a legacy apps 16524 // are represented as constantly granted runtime ones, so don't revoke. 16525 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16526 // Otherwise, reset the permission. 16527 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16528 switch (revokeResult) { 16529 case PERMISSION_OPERATION_SUCCESS: 16530 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16531 writeRuntimePermissions = true; 16532 final int appId = ps.appId; 16533 mHandler.post(new Runnable() { 16534 @Override 16535 public void run() { 16536 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16537 } 16538 }); 16539 } break; 16540 } 16541 } 16542 } 16543 16544 // Synchronously write as we are taking permissions away. 16545 if (writeRuntimePermissions) { 16546 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16547 } 16548 16549 // Synchronously write as we are taking permissions away. 16550 if (writeInstallPermissions) { 16551 mSettings.writeLPr(); 16552 } 16553 } 16554 16555 /** 16556 * Remove entries from the keystore daemon. Will only remove it if the 16557 * {@code appId} is valid. 16558 */ 16559 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16560 if (appId < 0) { 16561 return; 16562 } 16563 16564 final KeyStore keyStore = KeyStore.getInstance(); 16565 if (keyStore != null) { 16566 if (userId == UserHandle.USER_ALL) { 16567 for (final int individual : sUserManager.getUserIds()) { 16568 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16569 } 16570 } else { 16571 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16572 } 16573 } else { 16574 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16575 } 16576 } 16577 16578 @Override 16579 public void deleteApplicationCacheFiles(final String packageName, 16580 final IPackageDataObserver observer) { 16581 final int userId = UserHandle.getCallingUserId(); 16582 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16583 } 16584 16585 @Override 16586 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16587 final IPackageDataObserver observer) { 16588 mContext.enforceCallingOrSelfPermission( 16589 android.Manifest.permission.DELETE_CACHE_FILES, null); 16590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16591 /* requireFullPermission= */ true, /* checkShell= */ false, 16592 "delete application cache files"); 16593 16594 final PackageParser.Package pkg; 16595 synchronized (mPackages) { 16596 pkg = mPackages.get(packageName); 16597 } 16598 16599 // Queue up an async operation since the package deletion may take a little while. 16600 mHandler.post(new Runnable() { 16601 public void run() { 16602 synchronized (mInstallLock) { 16603 final int flags = StorageManager.FLAG_STORAGE_DE 16604 | StorageManager.FLAG_STORAGE_CE; 16605 // We're only clearing cache files, so we don't care if the 16606 // app is unfrozen and still able to run 16607 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16608 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16609 } 16610 clearExternalStorageDataSync(packageName, userId, false); 16611 if (observer != null) { 16612 try { 16613 observer.onRemoveCompleted(packageName, true); 16614 } catch (RemoteException e) { 16615 Log.i(TAG, "Observer no longer exists."); 16616 } 16617 } 16618 } 16619 }); 16620 } 16621 16622 @Override 16623 public void getPackageSizeInfo(final String packageName, int userHandle, 16624 final IPackageStatsObserver observer) { 16625 mContext.enforceCallingOrSelfPermission( 16626 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16627 if (packageName == null) { 16628 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16629 } 16630 16631 PackageStats stats = new PackageStats(packageName, userHandle); 16632 16633 /* 16634 * Queue up an async operation since the package measurement may take a 16635 * little while. 16636 */ 16637 Message msg = mHandler.obtainMessage(INIT_COPY); 16638 msg.obj = new MeasureParams(stats, observer); 16639 mHandler.sendMessage(msg); 16640 } 16641 16642 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16643 final PackageSetting ps; 16644 synchronized (mPackages) { 16645 ps = mSettings.mPackages.get(packageName); 16646 if (ps == null) { 16647 Slog.w(TAG, "Failed to find settings for " + packageName); 16648 return false; 16649 } 16650 } 16651 try { 16652 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16653 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16654 ps.getCeDataInode(userId), ps.codePathString, stats); 16655 } catch (InstallerException e) { 16656 Slog.w(TAG, String.valueOf(e)); 16657 return false; 16658 } 16659 16660 // For now, ignore code size of packages on system partition 16661 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16662 stats.codeSize = 0; 16663 } 16664 16665 return true; 16666 } 16667 16668 private int getUidTargetSdkVersionLockedLPr(int uid) { 16669 Object obj = mSettings.getUserIdLPr(uid); 16670 if (obj instanceof SharedUserSetting) { 16671 final SharedUserSetting sus = (SharedUserSetting) obj; 16672 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16673 final Iterator<PackageSetting> it = sus.packages.iterator(); 16674 while (it.hasNext()) { 16675 final PackageSetting ps = it.next(); 16676 if (ps.pkg != null) { 16677 int v = ps.pkg.applicationInfo.targetSdkVersion; 16678 if (v < vers) vers = v; 16679 } 16680 } 16681 return vers; 16682 } else if (obj instanceof PackageSetting) { 16683 final PackageSetting ps = (PackageSetting) obj; 16684 if (ps.pkg != null) { 16685 return ps.pkg.applicationInfo.targetSdkVersion; 16686 } 16687 } 16688 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16689 } 16690 16691 @Override 16692 public void addPreferredActivity(IntentFilter filter, int match, 16693 ComponentName[] set, ComponentName activity, int userId) { 16694 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16695 "Adding preferred"); 16696 } 16697 16698 private void addPreferredActivityInternal(IntentFilter filter, int match, 16699 ComponentName[] set, ComponentName activity, boolean always, int userId, 16700 String opname) { 16701 // writer 16702 int callingUid = Binder.getCallingUid(); 16703 enforceCrossUserPermission(callingUid, userId, 16704 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16705 if (filter.countActions() == 0) { 16706 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16707 return; 16708 } 16709 synchronized (mPackages) { 16710 if (mContext.checkCallingOrSelfPermission( 16711 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16712 != PackageManager.PERMISSION_GRANTED) { 16713 if (getUidTargetSdkVersionLockedLPr(callingUid) 16714 < Build.VERSION_CODES.FROYO) { 16715 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16716 + callingUid); 16717 return; 16718 } 16719 mContext.enforceCallingOrSelfPermission( 16720 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16721 } 16722 16723 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16724 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16725 + userId + ":"); 16726 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16727 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16728 scheduleWritePackageRestrictionsLocked(userId); 16729 postPreferredActivityChangedBroadcast(userId); 16730 } 16731 } 16732 16733 private void postPreferredActivityChangedBroadcast(int userId) { 16734 mHandler.post(() -> { 16735 final IActivityManager am = ActivityManagerNative.getDefault(); 16736 if (am == null) { 16737 return; 16738 } 16739 16740 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16741 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16742 try { 16743 am.broadcastIntent(null, intent, null, null, 16744 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16745 null, false, false, userId); 16746 } catch (RemoteException e) { 16747 } 16748 }); 16749 } 16750 16751 @Override 16752 public void replacePreferredActivity(IntentFilter filter, int match, 16753 ComponentName[] set, ComponentName activity, int userId) { 16754 if (filter.countActions() != 1) { 16755 throw new IllegalArgumentException( 16756 "replacePreferredActivity expects filter to have only 1 action."); 16757 } 16758 if (filter.countDataAuthorities() != 0 16759 || filter.countDataPaths() != 0 16760 || filter.countDataSchemes() > 1 16761 || filter.countDataTypes() != 0) { 16762 throw new IllegalArgumentException( 16763 "replacePreferredActivity expects filter to have no data authorities, " + 16764 "paths, or types; and at most one scheme."); 16765 } 16766 16767 final int callingUid = Binder.getCallingUid(); 16768 enforceCrossUserPermission(callingUid, userId, 16769 true /* requireFullPermission */, false /* checkShell */, 16770 "replace preferred activity"); 16771 synchronized (mPackages) { 16772 if (mContext.checkCallingOrSelfPermission( 16773 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16774 != PackageManager.PERMISSION_GRANTED) { 16775 if (getUidTargetSdkVersionLockedLPr(callingUid) 16776 < Build.VERSION_CODES.FROYO) { 16777 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16778 + Binder.getCallingUid()); 16779 return; 16780 } 16781 mContext.enforceCallingOrSelfPermission( 16782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16783 } 16784 16785 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16786 if (pir != null) { 16787 // Get all of the existing entries that exactly match this filter. 16788 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16789 if (existing != null && existing.size() == 1) { 16790 PreferredActivity cur = existing.get(0); 16791 if (DEBUG_PREFERRED) { 16792 Slog.i(TAG, "Checking replace of preferred:"); 16793 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16794 if (!cur.mPref.mAlways) { 16795 Slog.i(TAG, " -- CUR; not mAlways!"); 16796 } else { 16797 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16798 Slog.i(TAG, " -- CUR: mSet=" 16799 + Arrays.toString(cur.mPref.mSetComponents)); 16800 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16801 Slog.i(TAG, " -- NEW: mMatch=" 16802 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16803 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16804 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16805 } 16806 } 16807 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16808 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16809 && cur.mPref.sameSet(set)) { 16810 // Setting the preferred activity to what it happens to be already 16811 if (DEBUG_PREFERRED) { 16812 Slog.i(TAG, "Replacing with same preferred activity " 16813 + cur.mPref.mShortComponent + " for user " 16814 + userId + ":"); 16815 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16816 } 16817 return; 16818 } 16819 } 16820 16821 if (existing != null) { 16822 if (DEBUG_PREFERRED) { 16823 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16824 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16825 } 16826 for (int i = 0; i < existing.size(); i++) { 16827 PreferredActivity pa = existing.get(i); 16828 if (DEBUG_PREFERRED) { 16829 Slog.i(TAG, "Removing existing preferred activity " 16830 + pa.mPref.mComponent + ":"); 16831 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16832 } 16833 pir.removeFilter(pa); 16834 } 16835 } 16836 } 16837 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16838 "Replacing preferred"); 16839 } 16840 } 16841 16842 @Override 16843 public void clearPackagePreferredActivities(String packageName) { 16844 final int uid = Binder.getCallingUid(); 16845 // writer 16846 synchronized (mPackages) { 16847 PackageParser.Package pkg = mPackages.get(packageName); 16848 if (pkg == null || pkg.applicationInfo.uid != uid) { 16849 if (mContext.checkCallingOrSelfPermission( 16850 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16851 != PackageManager.PERMISSION_GRANTED) { 16852 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16853 < Build.VERSION_CODES.FROYO) { 16854 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16855 + Binder.getCallingUid()); 16856 return; 16857 } 16858 mContext.enforceCallingOrSelfPermission( 16859 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16860 } 16861 } 16862 16863 int user = UserHandle.getCallingUserId(); 16864 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16865 scheduleWritePackageRestrictionsLocked(user); 16866 } 16867 } 16868 } 16869 16870 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16871 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16872 ArrayList<PreferredActivity> removed = null; 16873 boolean changed = false; 16874 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16875 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16876 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16877 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16878 continue; 16879 } 16880 Iterator<PreferredActivity> it = pir.filterIterator(); 16881 while (it.hasNext()) { 16882 PreferredActivity pa = it.next(); 16883 // Mark entry for removal only if it matches the package name 16884 // and the entry is of type "always". 16885 if (packageName == null || 16886 (pa.mPref.mComponent.getPackageName().equals(packageName) 16887 && pa.mPref.mAlways)) { 16888 if (removed == null) { 16889 removed = new ArrayList<PreferredActivity>(); 16890 } 16891 removed.add(pa); 16892 } 16893 } 16894 if (removed != null) { 16895 for (int j=0; j<removed.size(); j++) { 16896 PreferredActivity pa = removed.get(j); 16897 pir.removeFilter(pa); 16898 } 16899 changed = true; 16900 } 16901 } 16902 if (changed) { 16903 postPreferredActivityChangedBroadcast(userId); 16904 } 16905 return changed; 16906 } 16907 16908 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16909 private void clearIntentFilterVerificationsLPw(int userId) { 16910 final int packageCount = mPackages.size(); 16911 for (int i = 0; i < packageCount; i++) { 16912 PackageParser.Package pkg = mPackages.valueAt(i); 16913 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16914 } 16915 } 16916 16917 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16918 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16919 if (userId == UserHandle.USER_ALL) { 16920 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16921 sUserManager.getUserIds())) { 16922 for (int oneUserId : sUserManager.getUserIds()) { 16923 scheduleWritePackageRestrictionsLocked(oneUserId); 16924 } 16925 } 16926 } else { 16927 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16928 scheduleWritePackageRestrictionsLocked(userId); 16929 } 16930 } 16931 } 16932 16933 void clearDefaultBrowserIfNeeded(String packageName) { 16934 for (int oneUserId : sUserManager.getUserIds()) { 16935 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16936 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16937 if (packageName.equals(defaultBrowserPackageName)) { 16938 setDefaultBrowserPackageName(null, oneUserId); 16939 } 16940 } 16941 } 16942 16943 @Override 16944 public void resetApplicationPreferences(int userId) { 16945 mContext.enforceCallingOrSelfPermission( 16946 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16947 final long identity = Binder.clearCallingIdentity(); 16948 // writer 16949 try { 16950 synchronized (mPackages) { 16951 clearPackagePreferredActivitiesLPw(null, userId); 16952 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16953 // TODO: We have to reset the default SMS and Phone. This requires 16954 // significant refactoring to keep all default apps in the package 16955 // manager (cleaner but more work) or have the services provide 16956 // callbacks to the package manager to request a default app reset. 16957 applyFactoryDefaultBrowserLPw(userId); 16958 clearIntentFilterVerificationsLPw(userId); 16959 primeDomainVerificationsLPw(userId); 16960 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16961 scheduleWritePackageRestrictionsLocked(userId); 16962 } 16963 resetNetworkPolicies(userId); 16964 } finally { 16965 Binder.restoreCallingIdentity(identity); 16966 } 16967 } 16968 16969 @Override 16970 public int getPreferredActivities(List<IntentFilter> outFilters, 16971 List<ComponentName> outActivities, String packageName) { 16972 16973 int num = 0; 16974 final int userId = UserHandle.getCallingUserId(); 16975 // reader 16976 synchronized (mPackages) { 16977 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16978 if (pir != null) { 16979 final Iterator<PreferredActivity> it = pir.filterIterator(); 16980 while (it.hasNext()) { 16981 final PreferredActivity pa = it.next(); 16982 if (packageName == null 16983 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16984 && pa.mPref.mAlways)) { 16985 if (outFilters != null) { 16986 outFilters.add(new IntentFilter(pa)); 16987 } 16988 if (outActivities != null) { 16989 outActivities.add(pa.mPref.mComponent); 16990 } 16991 } 16992 } 16993 } 16994 } 16995 16996 return num; 16997 } 16998 16999 @Override 17000 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17001 int userId) { 17002 int callingUid = Binder.getCallingUid(); 17003 if (callingUid != Process.SYSTEM_UID) { 17004 throw new SecurityException( 17005 "addPersistentPreferredActivity can only be run by the system"); 17006 } 17007 if (filter.countActions() == 0) { 17008 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17009 return; 17010 } 17011 synchronized (mPackages) { 17012 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17013 ":"); 17014 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17015 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17016 new PersistentPreferredActivity(filter, activity)); 17017 scheduleWritePackageRestrictionsLocked(userId); 17018 postPreferredActivityChangedBroadcast(userId); 17019 } 17020 } 17021 17022 @Override 17023 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17024 int callingUid = Binder.getCallingUid(); 17025 if (callingUid != Process.SYSTEM_UID) { 17026 throw new SecurityException( 17027 "clearPackagePersistentPreferredActivities can only be run by the system"); 17028 } 17029 ArrayList<PersistentPreferredActivity> removed = null; 17030 boolean changed = false; 17031 synchronized (mPackages) { 17032 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17033 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17034 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17035 .valueAt(i); 17036 if (userId != thisUserId) { 17037 continue; 17038 } 17039 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17040 while (it.hasNext()) { 17041 PersistentPreferredActivity ppa = it.next(); 17042 // Mark entry for removal only if it matches the package name. 17043 if (ppa.mComponent.getPackageName().equals(packageName)) { 17044 if (removed == null) { 17045 removed = new ArrayList<PersistentPreferredActivity>(); 17046 } 17047 removed.add(ppa); 17048 } 17049 } 17050 if (removed != null) { 17051 for (int j=0; j<removed.size(); j++) { 17052 PersistentPreferredActivity ppa = removed.get(j); 17053 ppir.removeFilter(ppa); 17054 } 17055 changed = true; 17056 } 17057 } 17058 17059 if (changed) { 17060 scheduleWritePackageRestrictionsLocked(userId); 17061 postPreferredActivityChangedBroadcast(userId); 17062 } 17063 } 17064 } 17065 17066 /** 17067 * Common machinery for picking apart a restored XML blob and passing 17068 * it to a caller-supplied functor to be applied to the running system. 17069 */ 17070 private void restoreFromXml(XmlPullParser parser, int userId, 17071 String expectedStartTag, BlobXmlRestorer functor) 17072 throws IOException, XmlPullParserException { 17073 int type; 17074 while ((type = parser.next()) != XmlPullParser.START_TAG 17075 && type != XmlPullParser.END_DOCUMENT) { 17076 } 17077 if (type != XmlPullParser.START_TAG) { 17078 // oops didn't find a start tag?! 17079 if (DEBUG_BACKUP) { 17080 Slog.e(TAG, "Didn't find start tag during restore"); 17081 } 17082 return; 17083 } 17084Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17085 // this is supposed to be TAG_PREFERRED_BACKUP 17086 if (!expectedStartTag.equals(parser.getName())) { 17087 if (DEBUG_BACKUP) { 17088 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17089 } 17090 return; 17091 } 17092 17093 // skip interfering stuff, then we're aligned with the backing implementation 17094 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17095Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17096 functor.apply(parser, userId); 17097 } 17098 17099 private interface BlobXmlRestorer { 17100 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17101 } 17102 17103 /** 17104 * Non-Binder method, support for the backup/restore mechanism: write the 17105 * full set of preferred activities in its canonical XML format. Returns the 17106 * XML output as a byte array, or null if there is none. 17107 */ 17108 @Override 17109 public byte[] getPreferredActivityBackup(int userId) { 17110 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17111 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17112 } 17113 17114 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17115 try { 17116 final XmlSerializer serializer = new FastXmlSerializer(); 17117 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17118 serializer.startDocument(null, true); 17119 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17120 17121 synchronized (mPackages) { 17122 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17123 } 17124 17125 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17126 serializer.endDocument(); 17127 serializer.flush(); 17128 } catch (Exception e) { 17129 if (DEBUG_BACKUP) { 17130 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17131 } 17132 return null; 17133 } 17134 17135 return dataStream.toByteArray(); 17136 } 17137 17138 @Override 17139 public void restorePreferredActivities(byte[] backup, int userId) { 17140 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17141 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17142 } 17143 17144 try { 17145 final XmlPullParser parser = Xml.newPullParser(); 17146 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17147 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17148 new BlobXmlRestorer() { 17149 @Override 17150 public void apply(XmlPullParser parser, int userId) 17151 throws XmlPullParserException, IOException { 17152 synchronized (mPackages) { 17153 mSettings.readPreferredActivitiesLPw(parser, userId); 17154 } 17155 } 17156 } ); 17157 } catch (Exception e) { 17158 if (DEBUG_BACKUP) { 17159 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17160 } 17161 } 17162 } 17163 17164 /** 17165 * Non-Binder method, support for the backup/restore mechanism: write the 17166 * default browser (etc) settings in its canonical XML format. Returns the default 17167 * browser XML representation as a byte array, or null if there is none. 17168 */ 17169 @Override 17170 public byte[] getDefaultAppsBackup(int userId) { 17171 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17172 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17173 } 17174 17175 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17176 try { 17177 final XmlSerializer serializer = new FastXmlSerializer(); 17178 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17179 serializer.startDocument(null, true); 17180 serializer.startTag(null, TAG_DEFAULT_APPS); 17181 17182 synchronized (mPackages) { 17183 mSettings.writeDefaultAppsLPr(serializer, userId); 17184 } 17185 17186 serializer.endTag(null, TAG_DEFAULT_APPS); 17187 serializer.endDocument(); 17188 serializer.flush(); 17189 } catch (Exception e) { 17190 if (DEBUG_BACKUP) { 17191 Slog.e(TAG, "Unable to write default apps for backup", e); 17192 } 17193 return null; 17194 } 17195 17196 return dataStream.toByteArray(); 17197 } 17198 17199 @Override 17200 public void restoreDefaultApps(byte[] backup, int userId) { 17201 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17202 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17203 } 17204 17205 try { 17206 final XmlPullParser parser = Xml.newPullParser(); 17207 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17208 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17209 new BlobXmlRestorer() { 17210 @Override 17211 public void apply(XmlPullParser parser, int userId) 17212 throws XmlPullParserException, IOException { 17213 synchronized (mPackages) { 17214 mSettings.readDefaultAppsLPw(parser, userId); 17215 } 17216 } 17217 } ); 17218 } catch (Exception e) { 17219 if (DEBUG_BACKUP) { 17220 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17221 } 17222 } 17223 } 17224 17225 @Override 17226 public byte[] getIntentFilterVerificationBackup(int userId) { 17227 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17228 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17229 } 17230 17231 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17232 try { 17233 final XmlSerializer serializer = new FastXmlSerializer(); 17234 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17235 serializer.startDocument(null, true); 17236 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17237 17238 synchronized (mPackages) { 17239 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17240 } 17241 17242 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17243 serializer.endDocument(); 17244 serializer.flush(); 17245 } catch (Exception e) { 17246 if (DEBUG_BACKUP) { 17247 Slog.e(TAG, "Unable to write default apps for backup", e); 17248 } 17249 return null; 17250 } 17251 17252 return dataStream.toByteArray(); 17253 } 17254 17255 @Override 17256 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17257 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17258 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17259 } 17260 17261 try { 17262 final XmlPullParser parser = Xml.newPullParser(); 17263 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17264 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17265 new BlobXmlRestorer() { 17266 @Override 17267 public void apply(XmlPullParser parser, int userId) 17268 throws XmlPullParserException, IOException { 17269 synchronized (mPackages) { 17270 mSettings.readAllDomainVerificationsLPr(parser, userId); 17271 mSettings.writeLPr(); 17272 } 17273 } 17274 } ); 17275 } catch (Exception e) { 17276 if (DEBUG_BACKUP) { 17277 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17278 } 17279 } 17280 } 17281 17282 @Override 17283 public byte[] getPermissionGrantBackup(int userId) { 17284 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17285 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17286 } 17287 17288 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17289 try { 17290 final XmlSerializer serializer = new FastXmlSerializer(); 17291 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17292 serializer.startDocument(null, true); 17293 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17294 17295 synchronized (mPackages) { 17296 serializeRuntimePermissionGrantsLPr(serializer, userId); 17297 } 17298 17299 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17300 serializer.endDocument(); 17301 serializer.flush(); 17302 } catch (Exception e) { 17303 if (DEBUG_BACKUP) { 17304 Slog.e(TAG, "Unable to write default apps for backup", e); 17305 } 17306 return null; 17307 } 17308 17309 return dataStream.toByteArray(); 17310 } 17311 17312 @Override 17313 public void restorePermissionGrants(byte[] backup, int userId) { 17314 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17315 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17316 } 17317 17318 try { 17319 final XmlPullParser parser = Xml.newPullParser(); 17320 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17321 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17322 new BlobXmlRestorer() { 17323 @Override 17324 public void apply(XmlPullParser parser, int userId) 17325 throws XmlPullParserException, IOException { 17326 synchronized (mPackages) { 17327 processRestoredPermissionGrantsLPr(parser, userId); 17328 } 17329 } 17330 } ); 17331 } catch (Exception e) { 17332 if (DEBUG_BACKUP) { 17333 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17334 } 17335 } 17336 } 17337 17338 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17339 throws IOException { 17340 serializer.startTag(null, TAG_ALL_GRANTS); 17341 17342 final int N = mSettings.mPackages.size(); 17343 for (int i = 0; i < N; i++) { 17344 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17345 boolean pkgGrantsKnown = false; 17346 17347 PermissionsState packagePerms = ps.getPermissionsState(); 17348 17349 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17350 final int grantFlags = state.getFlags(); 17351 // only look at grants that are not system/policy fixed 17352 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17353 final boolean isGranted = state.isGranted(); 17354 // And only back up the user-twiddled state bits 17355 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17356 final String packageName = mSettings.mPackages.keyAt(i); 17357 if (!pkgGrantsKnown) { 17358 serializer.startTag(null, TAG_GRANT); 17359 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17360 pkgGrantsKnown = true; 17361 } 17362 17363 final boolean userSet = 17364 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17365 final boolean userFixed = 17366 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17367 final boolean revoke = 17368 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17369 17370 serializer.startTag(null, TAG_PERMISSION); 17371 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17372 if (isGranted) { 17373 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17374 } 17375 if (userSet) { 17376 serializer.attribute(null, ATTR_USER_SET, "true"); 17377 } 17378 if (userFixed) { 17379 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17380 } 17381 if (revoke) { 17382 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17383 } 17384 serializer.endTag(null, TAG_PERMISSION); 17385 } 17386 } 17387 } 17388 17389 if (pkgGrantsKnown) { 17390 serializer.endTag(null, TAG_GRANT); 17391 } 17392 } 17393 17394 serializer.endTag(null, TAG_ALL_GRANTS); 17395 } 17396 17397 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17398 throws XmlPullParserException, IOException { 17399 String pkgName = null; 17400 int outerDepth = parser.getDepth(); 17401 int type; 17402 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17403 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17404 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17405 continue; 17406 } 17407 17408 final String tagName = parser.getName(); 17409 if (tagName.equals(TAG_GRANT)) { 17410 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17411 if (DEBUG_BACKUP) { 17412 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17413 } 17414 } else if (tagName.equals(TAG_PERMISSION)) { 17415 17416 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17417 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17418 17419 int newFlagSet = 0; 17420 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17421 newFlagSet |= FLAG_PERMISSION_USER_SET; 17422 } 17423 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17424 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17425 } 17426 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17427 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17428 } 17429 if (DEBUG_BACKUP) { 17430 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17431 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17432 } 17433 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17434 if (ps != null) { 17435 // Already installed so we apply the grant immediately 17436 if (DEBUG_BACKUP) { 17437 Slog.v(TAG, " + already installed; applying"); 17438 } 17439 PermissionsState perms = ps.getPermissionsState(); 17440 BasePermission bp = mSettings.mPermissions.get(permName); 17441 if (bp != null) { 17442 if (isGranted) { 17443 perms.grantRuntimePermission(bp, userId); 17444 } 17445 if (newFlagSet != 0) { 17446 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17447 } 17448 } 17449 } else { 17450 // Need to wait for post-restore install to apply the grant 17451 if (DEBUG_BACKUP) { 17452 Slog.v(TAG, " - not yet installed; saving for later"); 17453 } 17454 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17455 isGranted, newFlagSet, userId); 17456 } 17457 } else { 17458 PackageManagerService.reportSettingsProblem(Log.WARN, 17459 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17460 XmlUtils.skipCurrentTag(parser); 17461 } 17462 } 17463 17464 scheduleWriteSettingsLocked(); 17465 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17466 } 17467 17468 @Override 17469 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17470 int sourceUserId, int targetUserId, int flags) { 17471 mContext.enforceCallingOrSelfPermission( 17472 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17473 int callingUid = Binder.getCallingUid(); 17474 enforceOwnerRights(ownerPackage, callingUid); 17475 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17476 if (intentFilter.countActions() == 0) { 17477 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17478 return; 17479 } 17480 synchronized (mPackages) { 17481 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17482 ownerPackage, targetUserId, flags); 17483 CrossProfileIntentResolver resolver = 17484 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17485 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17486 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17487 if (existing != null) { 17488 int size = existing.size(); 17489 for (int i = 0; i < size; i++) { 17490 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17491 return; 17492 } 17493 } 17494 } 17495 resolver.addFilter(newFilter); 17496 scheduleWritePackageRestrictionsLocked(sourceUserId); 17497 } 17498 } 17499 17500 @Override 17501 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17502 mContext.enforceCallingOrSelfPermission( 17503 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17504 int callingUid = Binder.getCallingUid(); 17505 enforceOwnerRights(ownerPackage, callingUid); 17506 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17507 synchronized (mPackages) { 17508 CrossProfileIntentResolver resolver = 17509 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17510 ArraySet<CrossProfileIntentFilter> set = 17511 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17512 for (CrossProfileIntentFilter filter : set) { 17513 if (filter.getOwnerPackage().equals(ownerPackage)) { 17514 resolver.removeFilter(filter); 17515 } 17516 } 17517 scheduleWritePackageRestrictionsLocked(sourceUserId); 17518 } 17519 } 17520 17521 // Enforcing that callingUid is owning pkg on userId 17522 private void enforceOwnerRights(String pkg, int callingUid) { 17523 // The system owns everything. 17524 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17525 return; 17526 } 17527 int callingUserId = UserHandle.getUserId(callingUid); 17528 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17529 if (pi == null) { 17530 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17531 + callingUserId); 17532 } 17533 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17534 throw new SecurityException("Calling uid " + callingUid 17535 + " does not own package " + pkg); 17536 } 17537 } 17538 17539 @Override 17540 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17541 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17542 } 17543 17544 private Intent getHomeIntent() { 17545 Intent intent = new Intent(Intent.ACTION_MAIN); 17546 intent.addCategory(Intent.CATEGORY_HOME); 17547 intent.addCategory(Intent.CATEGORY_DEFAULT); 17548 return intent; 17549 } 17550 17551 private IntentFilter getHomeFilter() { 17552 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17553 filter.addCategory(Intent.CATEGORY_HOME); 17554 filter.addCategory(Intent.CATEGORY_DEFAULT); 17555 return filter; 17556 } 17557 17558 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17559 int userId) { 17560 Intent intent = getHomeIntent(); 17561 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17562 PackageManager.GET_META_DATA, userId); 17563 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17564 true, false, false, userId); 17565 17566 allHomeCandidates.clear(); 17567 if (list != null) { 17568 for (ResolveInfo ri : list) { 17569 allHomeCandidates.add(ri); 17570 } 17571 } 17572 return (preferred == null || preferred.activityInfo == null) 17573 ? null 17574 : new ComponentName(preferred.activityInfo.packageName, 17575 preferred.activityInfo.name); 17576 } 17577 17578 @Override 17579 public void setHomeActivity(ComponentName comp, int userId) { 17580 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17581 getHomeActivitiesAsUser(homeActivities, userId); 17582 17583 boolean found = false; 17584 17585 final int size = homeActivities.size(); 17586 final ComponentName[] set = new ComponentName[size]; 17587 for (int i = 0; i < size; i++) { 17588 final ResolveInfo candidate = homeActivities.get(i); 17589 final ActivityInfo info = candidate.activityInfo; 17590 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17591 set[i] = activityName; 17592 if (!found && activityName.equals(comp)) { 17593 found = true; 17594 } 17595 } 17596 if (!found) { 17597 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17598 + userId); 17599 } 17600 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17601 set, comp, userId); 17602 } 17603 17604 private @Nullable String getSetupWizardPackageName() { 17605 final Intent intent = new Intent(Intent.ACTION_MAIN); 17606 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17607 17608 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17609 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17610 | MATCH_DISABLED_COMPONENTS, 17611 UserHandle.myUserId()); 17612 if (matches.size() == 1) { 17613 return matches.get(0).getComponentInfo().packageName; 17614 } else { 17615 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17616 + ": matches=" + matches); 17617 return null; 17618 } 17619 } 17620 17621 @Override 17622 public void setApplicationEnabledSetting(String appPackageName, 17623 int newState, int flags, int userId, String callingPackage) { 17624 if (!sUserManager.exists(userId)) return; 17625 if (callingPackage == null) { 17626 callingPackage = Integer.toString(Binder.getCallingUid()); 17627 } 17628 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17629 } 17630 17631 @Override 17632 public void setComponentEnabledSetting(ComponentName componentName, 17633 int newState, int flags, int userId) { 17634 if (!sUserManager.exists(userId)) return; 17635 setEnabledSetting(componentName.getPackageName(), 17636 componentName.getClassName(), newState, flags, userId, null); 17637 } 17638 17639 private void setEnabledSetting(final String packageName, String className, int newState, 17640 final int flags, int userId, String callingPackage) { 17641 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17642 || newState == COMPONENT_ENABLED_STATE_ENABLED 17643 || newState == COMPONENT_ENABLED_STATE_DISABLED 17644 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17645 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17646 throw new IllegalArgumentException("Invalid new component state: " 17647 + newState); 17648 } 17649 PackageSetting pkgSetting; 17650 final int uid = Binder.getCallingUid(); 17651 final int permission; 17652 if (uid == Process.SYSTEM_UID) { 17653 permission = PackageManager.PERMISSION_GRANTED; 17654 } else { 17655 permission = mContext.checkCallingOrSelfPermission( 17656 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17657 } 17658 enforceCrossUserPermission(uid, userId, 17659 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17660 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17661 boolean sendNow = false; 17662 boolean isApp = (className == null); 17663 String componentName = isApp ? packageName : className; 17664 int packageUid = -1; 17665 ArrayList<String> components; 17666 17667 // writer 17668 synchronized (mPackages) { 17669 pkgSetting = mSettings.mPackages.get(packageName); 17670 if (pkgSetting == null) { 17671 if (className == null) { 17672 throw new IllegalArgumentException("Unknown package: " + packageName); 17673 } 17674 throw new IllegalArgumentException( 17675 "Unknown component: " + packageName + "/" + className); 17676 } 17677 } 17678 17679 // Limit who can change which apps 17680 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17681 // Don't allow apps that don't have permission to modify other apps 17682 if (!allowedByPermission) { 17683 throw new SecurityException( 17684 "Permission Denial: attempt to change component state from pid=" 17685 + Binder.getCallingPid() 17686 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17687 } 17688 // Don't allow changing protected packages. 17689 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17690 throw new SecurityException("Cannot disable a protected package: " + packageName); 17691 } 17692 } 17693 17694 synchronized (mPackages) { 17695 if (uid == Process.SHELL_UID) { 17696 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17697 int oldState = pkgSetting.getEnabled(userId); 17698 if (className == null 17699 && 17700 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17701 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17702 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17703 && 17704 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17705 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17706 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17707 // ok 17708 } else { 17709 throw new SecurityException( 17710 "Shell cannot change component state for " + packageName + "/" 17711 + className + " to " + newState); 17712 } 17713 } 17714 if (className == null) { 17715 // We're dealing with an application/package level state change 17716 if (pkgSetting.getEnabled(userId) == newState) { 17717 // Nothing to do 17718 return; 17719 } 17720 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17721 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17722 // Don't care about who enables an app. 17723 callingPackage = null; 17724 } 17725 pkgSetting.setEnabled(newState, userId, callingPackage); 17726 // pkgSetting.pkg.mSetEnabled = newState; 17727 } else { 17728 // We're dealing with a component level state change 17729 // First, verify that this is a valid class name. 17730 PackageParser.Package pkg = pkgSetting.pkg; 17731 if (pkg == null || !pkg.hasComponentClassName(className)) { 17732 if (pkg != null && 17733 pkg.applicationInfo.targetSdkVersion >= 17734 Build.VERSION_CODES.JELLY_BEAN) { 17735 throw new IllegalArgumentException("Component class " + className 17736 + " does not exist in " + packageName); 17737 } else { 17738 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17739 + className + " does not exist in " + packageName); 17740 } 17741 } 17742 switch (newState) { 17743 case COMPONENT_ENABLED_STATE_ENABLED: 17744 if (!pkgSetting.enableComponentLPw(className, userId)) { 17745 return; 17746 } 17747 break; 17748 case COMPONENT_ENABLED_STATE_DISABLED: 17749 if (!pkgSetting.disableComponentLPw(className, userId)) { 17750 return; 17751 } 17752 break; 17753 case COMPONENT_ENABLED_STATE_DEFAULT: 17754 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17755 return; 17756 } 17757 break; 17758 default: 17759 Slog.e(TAG, "Invalid new component state: " + newState); 17760 return; 17761 } 17762 } 17763 scheduleWritePackageRestrictionsLocked(userId); 17764 components = mPendingBroadcasts.get(userId, packageName); 17765 final boolean newPackage = components == null; 17766 if (newPackage) { 17767 components = new ArrayList<String>(); 17768 } 17769 if (!components.contains(componentName)) { 17770 components.add(componentName); 17771 } 17772 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17773 sendNow = true; 17774 // Purge entry from pending broadcast list if another one exists already 17775 // since we are sending one right away. 17776 mPendingBroadcasts.remove(userId, packageName); 17777 } else { 17778 if (newPackage) { 17779 mPendingBroadcasts.put(userId, packageName, components); 17780 } 17781 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17782 // Schedule a message 17783 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17784 } 17785 } 17786 } 17787 17788 long callingId = Binder.clearCallingIdentity(); 17789 try { 17790 if (sendNow) { 17791 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17792 sendPackageChangedBroadcast(packageName, 17793 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17794 } 17795 } finally { 17796 Binder.restoreCallingIdentity(callingId); 17797 } 17798 } 17799 17800 @Override 17801 public void flushPackageRestrictionsAsUser(int userId) { 17802 if (!sUserManager.exists(userId)) { 17803 return; 17804 } 17805 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17806 false /* checkShell */, "flushPackageRestrictions"); 17807 synchronized (mPackages) { 17808 mSettings.writePackageRestrictionsLPr(userId); 17809 mDirtyUsers.remove(userId); 17810 if (mDirtyUsers.isEmpty()) { 17811 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17812 } 17813 } 17814 } 17815 17816 private void sendPackageChangedBroadcast(String packageName, 17817 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17818 if (DEBUG_INSTALL) 17819 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17820 + componentNames); 17821 Bundle extras = new Bundle(4); 17822 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17823 String nameList[] = new String[componentNames.size()]; 17824 componentNames.toArray(nameList); 17825 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17826 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17827 extras.putInt(Intent.EXTRA_UID, packageUid); 17828 // If this is not reporting a change of the overall package, then only send it 17829 // to registered receivers. We don't want to launch a swath of apps for every 17830 // little component state change. 17831 final int flags = !componentNames.contains(packageName) 17832 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17833 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17834 new int[] {UserHandle.getUserId(packageUid)}); 17835 } 17836 17837 @Override 17838 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17839 if (!sUserManager.exists(userId)) return; 17840 final int uid = Binder.getCallingUid(); 17841 final int permission = mContext.checkCallingOrSelfPermission( 17842 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17843 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17844 enforceCrossUserPermission(uid, userId, 17845 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17846 // writer 17847 synchronized (mPackages) { 17848 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17849 allowedByPermission, uid, userId)) { 17850 scheduleWritePackageRestrictionsLocked(userId); 17851 } 17852 } 17853 } 17854 17855 @Override 17856 public String getInstallerPackageName(String packageName) { 17857 // reader 17858 synchronized (mPackages) { 17859 return mSettings.getInstallerPackageNameLPr(packageName); 17860 } 17861 } 17862 17863 public boolean isOrphaned(String packageName) { 17864 // reader 17865 synchronized (mPackages) { 17866 return mSettings.isOrphaned(packageName); 17867 } 17868 } 17869 17870 @Override 17871 public int getApplicationEnabledSetting(String packageName, int userId) { 17872 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17873 int uid = Binder.getCallingUid(); 17874 enforceCrossUserPermission(uid, userId, 17875 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17876 // reader 17877 synchronized (mPackages) { 17878 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17879 } 17880 } 17881 17882 @Override 17883 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17884 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17885 int uid = Binder.getCallingUid(); 17886 enforceCrossUserPermission(uid, userId, 17887 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17888 // reader 17889 synchronized (mPackages) { 17890 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17891 } 17892 } 17893 17894 @Override 17895 public void enterSafeMode() { 17896 enforceSystemOrRoot("Only the system can request entering safe mode"); 17897 17898 if (!mSystemReady) { 17899 mSafeMode = true; 17900 } 17901 } 17902 17903 @Override 17904 public void systemReady() { 17905 mSystemReady = true; 17906 17907 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 17908 // disabled after already being started. 17909 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 17910 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 17911 17912 // Read the compatibilty setting when the system is ready. 17913 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17914 mContext.getContentResolver(), 17915 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17916 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17917 if (DEBUG_SETTINGS) { 17918 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17919 } 17920 17921 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17922 17923 synchronized (mPackages) { 17924 // Verify that all of the preferred activity components actually 17925 // exist. It is possible for applications to be updated and at 17926 // that point remove a previously declared activity component that 17927 // had been set as a preferred activity. We try to clean this up 17928 // the next time we encounter that preferred activity, but it is 17929 // possible for the user flow to never be able to return to that 17930 // situation so here we do a sanity check to make sure we haven't 17931 // left any junk around. 17932 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17933 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17934 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17935 removed.clear(); 17936 for (PreferredActivity pa : pir.filterSet()) { 17937 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17938 removed.add(pa); 17939 } 17940 } 17941 if (removed.size() > 0) { 17942 for (int r=0; r<removed.size(); r++) { 17943 PreferredActivity pa = removed.get(r); 17944 Slog.w(TAG, "Removing dangling preferred activity: " 17945 + pa.mPref.mComponent); 17946 pir.removeFilter(pa); 17947 } 17948 mSettings.writePackageRestrictionsLPr( 17949 mSettings.mPreferredActivities.keyAt(i)); 17950 } 17951 } 17952 17953 for (int userId : UserManagerService.getInstance().getUserIds()) { 17954 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17955 grantPermissionsUserIds = ArrayUtils.appendInt( 17956 grantPermissionsUserIds, userId); 17957 } 17958 } 17959 } 17960 sUserManager.systemReady(); 17961 17962 // If we upgraded grant all default permissions before kicking off. 17963 for (int userId : grantPermissionsUserIds) { 17964 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17965 } 17966 17967 // If we did not grant default permissions, we preload from this the 17968 // default permission exceptions lazily to ensure we don't hit the 17969 // disk on a new user creation. 17970 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 17971 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 17972 } 17973 17974 // Kick off any messages waiting for system ready 17975 if (mPostSystemReadyMessages != null) { 17976 for (Message msg : mPostSystemReadyMessages) { 17977 msg.sendToTarget(); 17978 } 17979 mPostSystemReadyMessages = null; 17980 } 17981 17982 // Watch for external volumes that come and go over time 17983 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17984 storage.registerListener(mStorageListener); 17985 17986 mInstallerService.systemReady(); 17987 mPackageDexOptimizer.systemReady(); 17988 17989 MountServiceInternal mountServiceInternal = LocalServices.getService( 17990 MountServiceInternal.class); 17991 mountServiceInternal.addExternalStoragePolicy( 17992 new MountServiceInternal.ExternalStorageMountPolicy() { 17993 @Override 17994 public int getMountMode(int uid, String packageName) { 17995 if (Process.isIsolated(uid)) { 17996 return Zygote.MOUNT_EXTERNAL_NONE; 17997 } 17998 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17999 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18000 } 18001 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18002 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18003 } 18004 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18005 return Zygote.MOUNT_EXTERNAL_READ; 18006 } 18007 return Zygote.MOUNT_EXTERNAL_WRITE; 18008 } 18009 18010 @Override 18011 public boolean hasExternalStorage(int uid, String packageName) { 18012 return true; 18013 } 18014 }); 18015 18016 // Now that we're mostly running, clean up stale users and apps 18017 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18018 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18019 } 18020 18021 @Override 18022 public boolean isSafeMode() { 18023 return mSafeMode; 18024 } 18025 18026 @Override 18027 public boolean hasSystemUidErrors() { 18028 return mHasSystemUidErrors; 18029 } 18030 18031 static String arrayToString(int[] array) { 18032 StringBuffer buf = new StringBuffer(128); 18033 buf.append('['); 18034 if (array != null) { 18035 for (int i=0; i<array.length; i++) { 18036 if (i > 0) buf.append(", "); 18037 buf.append(array[i]); 18038 } 18039 } 18040 buf.append(']'); 18041 return buf.toString(); 18042 } 18043 18044 static class DumpState { 18045 public static final int DUMP_LIBS = 1 << 0; 18046 public static final int DUMP_FEATURES = 1 << 1; 18047 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18048 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18049 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18050 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18051 public static final int DUMP_PERMISSIONS = 1 << 6; 18052 public static final int DUMP_PACKAGES = 1 << 7; 18053 public static final int DUMP_SHARED_USERS = 1 << 8; 18054 public static final int DUMP_MESSAGES = 1 << 9; 18055 public static final int DUMP_PROVIDERS = 1 << 10; 18056 public static final int DUMP_VERIFIERS = 1 << 11; 18057 public static final int DUMP_PREFERRED = 1 << 12; 18058 public static final int DUMP_PREFERRED_XML = 1 << 13; 18059 public static final int DUMP_KEYSETS = 1 << 14; 18060 public static final int DUMP_VERSION = 1 << 15; 18061 public static final int DUMP_INSTALLS = 1 << 16; 18062 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18063 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18064 public static final int DUMP_FROZEN = 1 << 19; 18065 public static final int DUMP_DEXOPT = 1 << 20; 18066 public static final int DUMP_COMPILER_STATS = 1 << 21; 18067 18068 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18069 18070 private int mTypes; 18071 18072 private int mOptions; 18073 18074 private boolean mTitlePrinted; 18075 18076 private SharedUserSetting mSharedUser; 18077 18078 public boolean isDumping(int type) { 18079 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18080 return true; 18081 } 18082 18083 return (mTypes & type) != 0; 18084 } 18085 18086 public void setDump(int type) { 18087 mTypes |= type; 18088 } 18089 18090 public boolean isOptionEnabled(int option) { 18091 return (mOptions & option) != 0; 18092 } 18093 18094 public void setOptionEnabled(int option) { 18095 mOptions |= option; 18096 } 18097 18098 public boolean onTitlePrinted() { 18099 final boolean printed = mTitlePrinted; 18100 mTitlePrinted = true; 18101 return printed; 18102 } 18103 18104 public boolean getTitlePrinted() { 18105 return mTitlePrinted; 18106 } 18107 18108 public void setTitlePrinted(boolean enabled) { 18109 mTitlePrinted = enabled; 18110 } 18111 18112 public SharedUserSetting getSharedUser() { 18113 return mSharedUser; 18114 } 18115 18116 public void setSharedUser(SharedUserSetting user) { 18117 mSharedUser = user; 18118 } 18119 } 18120 18121 @Override 18122 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18123 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18124 (new PackageManagerShellCommand(this)).exec( 18125 this, in, out, err, args, resultReceiver); 18126 } 18127 18128 @Override 18129 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18130 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18131 != PackageManager.PERMISSION_GRANTED) { 18132 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18133 + Binder.getCallingPid() 18134 + ", uid=" + Binder.getCallingUid() 18135 + " without permission " 18136 + android.Manifest.permission.DUMP); 18137 return; 18138 } 18139 18140 DumpState dumpState = new DumpState(); 18141 boolean fullPreferred = false; 18142 boolean checkin = false; 18143 18144 String packageName = null; 18145 ArraySet<String> permissionNames = null; 18146 18147 int opti = 0; 18148 while (opti < args.length) { 18149 String opt = args[opti]; 18150 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18151 break; 18152 } 18153 opti++; 18154 18155 if ("-a".equals(opt)) { 18156 // Right now we only know how to print all. 18157 } else if ("-h".equals(opt)) { 18158 pw.println("Package manager dump options:"); 18159 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18160 pw.println(" --checkin: dump for a checkin"); 18161 pw.println(" -f: print details of intent filters"); 18162 pw.println(" -h: print this help"); 18163 pw.println(" cmd may be one of:"); 18164 pw.println(" l[ibraries]: list known shared libraries"); 18165 pw.println(" f[eatures]: list device features"); 18166 pw.println(" k[eysets]: print known keysets"); 18167 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18168 pw.println(" perm[issions]: dump permissions"); 18169 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18170 pw.println(" pref[erred]: print preferred package settings"); 18171 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18172 pw.println(" prov[iders]: dump content providers"); 18173 pw.println(" p[ackages]: dump installed packages"); 18174 pw.println(" s[hared-users]: dump shared user IDs"); 18175 pw.println(" m[essages]: print collected runtime messages"); 18176 pw.println(" v[erifiers]: print package verifier info"); 18177 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18178 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18179 pw.println(" version: print database version info"); 18180 pw.println(" write: write current settings now"); 18181 pw.println(" installs: details about install sessions"); 18182 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18183 pw.println(" dexopt: dump dexopt state"); 18184 pw.println(" compiler-stats: dump compiler statistics"); 18185 pw.println(" <package.name>: info about given package"); 18186 return; 18187 } else if ("--checkin".equals(opt)) { 18188 checkin = true; 18189 } else if ("-f".equals(opt)) { 18190 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18191 } else { 18192 pw.println("Unknown argument: " + opt + "; use -h for help"); 18193 } 18194 } 18195 18196 // Is the caller requesting to dump a particular piece of data? 18197 if (opti < args.length) { 18198 String cmd = args[opti]; 18199 opti++; 18200 // Is this a package name? 18201 if ("android".equals(cmd) || cmd.contains(".")) { 18202 packageName = cmd; 18203 // When dumping a single package, we always dump all of its 18204 // filter information since the amount of data will be reasonable. 18205 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18206 } else if ("check-permission".equals(cmd)) { 18207 if (opti >= args.length) { 18208 pw.println("Error: check-permission missing permission argument"); 18209 return; 18210 } 18211 String perm = args[opti]; 18212 opti++; 18213 if (opti >= args.length) { 18214 pw.println("Error: check-permission missing package argument"); 18215 return; 18216 } 18217 String pkg = args[opti]; 18218 opti++; 18219 int user = UserHandle.getUserId(Binder.getCallingUid()); 18220 if (opti < args.length) { 18221 try { 18222 user = Integer.parseInt(args[opti]); 18223 } catch (NumberFormatException e) { 18224 pw.println("Error: check-permission user argument is not a number: " 18225 + args[opti]); 18226 return; 18227 } 18228 } 18229 pw.println(checkPermission(perm, pkg, user)); 18230 return; 18231 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18232 dumpState.setDump(DumpState.DUMP_LIBS); 18233 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18234 dumpState.setDump(DumpState.DUMP_FEATURES); 18235 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18236 if (opti >= args.length) { 18237 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18238 | DumpState.DUMP_SERVICE_RESOLVERS 18239 | DumpState.DUMP_RECEIVER_RESOLVERS 18240 | DumpState.DUMP_CONTENT_RESOLVERS); 18241 } else { 18242 while (opti < args.length) { 18243 String name = args[opti]; 18244 if ("a".equals(name) || "activity".equals(name)) { 18245 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18246 } else if ("s".equals(name) || "service".equals(name)) { 18247 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18248 } else if ("r".equals(name) || "receiver".equals(name)) { 18249 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18250 } else if ("c".equals(name) || "content".equals(name)) { 18251 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18252 } else { 18253 pw.println("Error: unknown resolver table type: " + name); 18254 return; 18255 } 18256 opti++; 18257 } 18258 } 18259 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18260 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18261 } else if ("permission".equals(cmd)) { 18262 if (opti >= args.length) { 18263 pw.println("Error: permission requires permission name"); 18264 return; 18265 } 18266 permissionNames = new ArraySet<>(); 18267 while (opti < args.length) { 18268 permissionNames.add(args[opti]); 18269 opti++; 18270 } 18271 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18272 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18273 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18274 dumpState.setDump(DumpState.DUMP_PREFERRED); 18275 } else if ("preferred-xml".equals(cmd)) { 18276 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18277 if (opti < args.length && "--full".equals(args[opti])) { 18278 fullPreferred = true; 18279 opti++; 18280 } 18281 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18282 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18283 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18284 dumpState.setDump(DumpState.DUMP_PACKAGES); 18285 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18286 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18287 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18288 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18289 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18290 dumpState.setDump(DumpState.DUMP_MESSAGES); 18291 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18292 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18293 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18294 || "intent-filter-verifiers".equals(cmd)) { 18295 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18296 } else if ("version".equals(cmd)) { 18297 dumpState.setDump(DumpState.DUMP_VERSION); 18298 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18299 dumpState.setDump(DumpState.DUMP_KEYSETS); 18300 } else if ("installs".equals(cmd)) { 18301 dumpState.setDump(DumpState.DUMP_INSTALLS); 18302 } else if ("frozen".equals(cmd)) { 18303 dumpState.setDump(DumpState.DUMP_FROZEN); 18304 } else if ("dexopt".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_DEXOPT); 18306 } else if ("compiler-stats".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18308 } else if ("write".equals(cmd)) { 18309 synchronized (mPackages) { 18310 mSettings.writeLPr(); 18311 pw.println("Settings written."); 18312 return; 18313 } 18314 } 18315 } 18316 18317 if (checkin) { 18318 pw.println("vers,1"); 18319 } 18320 18321 // reader 18322 synchronized (mPackages) { 18323 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18324 if (!checkin) { 18325 if (dumpState.onTitlePrinted()) 18326 pw.println(); 18327 pw.println("Database versions:"); 18328 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18329 } 18330 } 18331 18332 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18333 if (!checkin) { 18334 if (dumpState.onTitlePrinted()) 18335 pw.println(); 18336 pw.println("Verifiers:"); 18337 pw.print(" Required: "); 18338 pw.print(mRequiredVerifierPackage); 18339 pw.print(" (uid="); 18340 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18341 UserHandle.USER_SYSTEM)); 18342 pw.println(")"); 18343 } else if (mRequiredVerifierPackage != null) { 18344 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18345 pw.print(","); 18346 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18347 UserHandle.USER_SYSTEM)); 18348 } 18349 } 18350 18351 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18352 packageName == null) { 18353 if (mIntentFilterVerifierComponent != null) { 18354 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18355 if (!checkin) { 18356 if (dumpState.onTitlePrinted()) 18357 pw.println(); 18358 pw.println("Intent Filter Verifier:"); 18359 pw.print(" Using: "); 18360 pw.print(verifierPackageName); 18361 pw.print(" (uid="); 18362 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18363 UserHandle.USER_SYSTEM)); 18364 pw.println(")"); 18365 } else if (verifierPackageName != null) { 18366 pw.print("ifv,"); pw.print(verifierPackageName); 18367 pw.print(","); 18368 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18369 UserHandle.USER_SYSTEM)); 18370 } 18371 } else { 18372 pw.println(); 18373 pw.println("No Intent Filter Verifier available!"); 18374 } 18375 } 18376 18377 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18378 boolean printedHeader = false; 18379 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18380 while (it.hasNext()) { 18381 String name = it.next(); 18382 SharedLibraryEntry ent = mSharedLibraries.get(name); 18383 if (!checkin) { 18384 if (!printedHeader) { 18385 if (dumpState.onTitlePrinted()) 18386 pw.println(); 18387 pw.println("Libraries:"); 18388 printedHeader = true; 18389 } 18390 pw.print(" "); 18391 } else { 18392 pw.print("lib,"); 18393 } 18394 pw.print(name); 18395 if (!checkin) { 18396 pw.print(" -> "); 18397 } 18398 if (ent.path != null) { 18399 if (!checkin) { 18400 pw.print("(jar) "); 18401 pw.print(ent.path); 18402 } else { 18403 pw.print(",jar,"); 18404 pw.print(ent.path); 18405 } 18406 } else { 18407 if (!checkin) { 18408 pw.print("(apk) "); 18409 pw.print(ent.apk); 18410 } else { 18411 pw.print(",apk,"); 18412 pw.print(ent.apk); 18413 } 18414 } 18415 pw.println(); 18416 } 18417 } 18418 18419 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18420 if (dumpState.onTitlePrinted()) 18421 pw.println(); 18422 if (!checkin) { 18423 pw.println("Features:"); 18424 } 18425 18426 for (FeatureInfo feat : mAvailableFeatures.values()) { 18427 if (checkin) { 18428 pw.print("feat,"); 18429 pw.print(feat.name); 18430 pw.print(","); 18431 pw.println(feat.version); 18432 } else { 18433 pw.print(" "); 18434 pw.print(feat.name); 18435 if (feat.version > 0) { 18436 pw.print(" version="); 18437 pw.print(feat.version); 18438 } 18439 pw.println(); 18440 } 18441 } 18442 } 18443 18444 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18445 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18446 : "Activity Resolver Table:", " ", packageName, 18447 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18448 dumpState.setTitlePrinted(true); 18449 } 18450 } 18451 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18452 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18453 : "Receiver Resolver Table:", " ", packageName, 18454 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18455 dumpState.setTitlePrinted(true); 18456 } 18457 } 18458 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18459 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18460 : "Service Resolver Table:", " ", packageName, 18461 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18462 dumpState.setTitlePrinted(true); 18463 } 18464 } 18465 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18466 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18467 : "Provider Resolver Table:", " ", packageName, 18468 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18469 dumpState.setTitlePrinted(true); 18470 } 18471 } 18472 18473 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18474 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18475 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18476 int user = mSettings.mPreferredActivities.keyAt(i); 18477 if (pir.dump(pw, 18478 dumpState.getTitlePrinted() 18479 ? "\nPreferred Activities User " + user + ":" 18480 : "Preferred Activities User " + user + ":", " ", 18481 packageName, true, false)) { 18482 dumpState.setTitlePrinted(true); 18483 } 18484 } 18485 } 18486 18487 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18488 pw.flush(); 18489 FileOutputStream fout = new FileOutputStream(fd); 18490 BufferedOutputStream str = new BufferedOutputStream(fout); 18491 XmlSerializer serializer = new FastXmlSerializer(); 18492 try { 18493 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18494 serializer.startDocument(null, true); 18495 serializer.setFeature( 18496 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18497 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18498 serializer.endDocument(); 18499 serializer.flush(); 18500 } catch (IllegalArgumentException e) { 18501 pw.println("Failed writing: " + e); 18502 } catch (IllegalStateException e) { 18503 pw.println("Failed writing: " + e); 18504 } catch (IOException e) { 18505 pw.println("Failed writing: " + e); 18506 } 18507 } 18508 18509 if (!checkin 18510 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18511 && packageName == null) { 18512 pw.println(); 18513 int count = mSettings.mPackages.size(); 18514 if (count == 0) { 18515 pw.println("No applications!"); 18516 pw.println(); 18517 } else { 18518 final String prefix = " "; 18519 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18520 if (allPackageSettings.size() == 0) { 18521 pw.println("No domain preferred apps!"); 18522 pw.println(); 18523 } else { 18524 pw.println("App verification status:"); 18525 pw.println(); 18526 count = 0; 18527 for (PackageSetting ps : allPackageSettings) { 18528 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18529 if (ivi == null || ivi.getPackageName() == null) continue; 18530 pw.println(prefix + "Package: " + ivi.getPackageName()); 18531 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18532 pw.println(prefix + "Status: " + ivi.getStatusString()); 18533 pw.println(); 18534 count++; 18535 } 18536 if (count == 0) { 18537 pw.println(prefix + "No app verification established."); 18538 pw.println(); 18539 } 18540 for (int userId : sUserManager.getUserIds()) { 18541 pw.println("App linkages for user " + userId + ":"); 18542 pw.println(); 18543 count = 0; 18544 for (PackageSetting ps : allPackageSettings) { 18545 final long status = ps.getDomainVerificationStatusForUser(userId); 18546 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18547 continue; 18548 } 18549 pw.println(prefix + "Package: " + ps.name); 18550 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18551 String statusStr = IntentFilterVerificationInfo. 18552 getStatusStringFromValue(status); 18553 pw.println(prefix + "Status: " + statusStr); 18554 pw.println(); 18555 count++; 18556 } 18557 if (count == 0) { 18558 pw.println(prefix + "No configured app linkages."); 18559 pw.println(); 18560 } 18561 } 18562 } 18563 } 18564 } 18565 18566 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18567 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18568 if (packageName == null && permissionNames == null) { 18569 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18570 if (iperm == 0) { 18571 if (dumpState.onTitlePrinted()) 18572 pw.println(); 18573 pw.println("AppOp Permissions:"); 18574 } 18575 pw.print(" AppOp Permission "); 18576 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18577 pw.println(":"); 18578 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18579 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18580 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18581 } 18582 } 18583 } 18584 } 18585 18586 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18587 boolean printedSomething = false; 18588 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18589 if (packageName != null && !packageName.equals(p.info.packageName)) { 18590 continue; 18591 } 18592 if (!printedSomething) { 18593 if (dumpState.onTitlePrinted()) 18594 pw.println(); 18595 pw.println("Registered ContentProviders:"); 18596 printedSomething = true; 18597 } 18598 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18599 pw.print(" "); pw.println(p.toString()); 18600 } 18601 printedSomething = false; 18602 for (Map.Entry<String, PackageParser.Provider> entry : 18603 mProvidersByAuthority.entrySet()) { 18604 PackageParser.Provider p = entry.getValue(); 18605 if (packageName != null && !packageName.equals(p.info.packageName)) { 18606 continue; 18607 } 18608 if (!printedSomething) { 18609 if (dumpState.onTitlePrinted()) 18610 pw.println(); 18611 pw.println("ContentProvider Authorities:"); 18612 printedSomething = true; 18613 } 18614 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18615 pw.print(" "); pw.println(p.toString()); 18616 if (p.info != null && p.info.applicationInfo != null) { 18617 final String appInfo = p.info.applicationInfo.toString(); 18618 pw.print(" applicationInfo="); pw.println(appInfo); 18619 } 18620 } 18621 } 18622 18623 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18624 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18625 } 18626 18627 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18628 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18629 } 18630 18631 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18632 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18633 } 18634 18635 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18636 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18637 } 18638 18639 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18640 // XXX should handle packageName != null by dumping only install data that 18641 // the given package is involved with. 18642 if (dumpState.onTitlePrinted()) pw.println(); 18643 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18644 } 18645 18646 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18647 // XXX should handle packageName != null by dumping only install data that 18648 // the given package is involved with. 18649 if (dumpState.onTitlePrinted()) pw.println(); 18650 18651 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18652 ipw.println(); 18653 ipw.println("Frozen packages:"); 18654 ipw.increaseIndent(); 18655 if (mFrozenPackages.size() == 0) { 18656 ipw.println("(none)"); 18657 } else { 18658 for (int i = 0; i < mFrozenPackages.size(); i++) { 18659 ipw.println(mFrozenPackages.valueAt(i)); 18660 } 18661 } 18662 ipw.decreaseIndent(); 18663 } 18664 18665 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18666 if (dumpState.onTitlePrinted()) pw.println(); 18667 dumpDexoptStateLPr(pw, packageName); 18668 } 18669 18670 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18671 if (dumpState.onTitlePrinted()) pw.println(); 18672 dumpCompilerStatsLPr(pw, packageName); 18673 } 18674 18675 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18676 if (dumpState.onTitlePrinted()) pw.println(); 18677 mSettings.dumpReadMessagesLPr(pw, dumpState); 18678 18679 pw.println(); 18680 pw.println("Package warning messages:"); 18681 BufferedReader in = null; 18682 String line = null; 18683 try { 18684 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18685 while ((line = in.readLine()) != null) { 18686 if (line.contains("ignored: updated version")) continue; 18687 pw.println(line); 18688 } 18689 } catch (IOException ignored) { 18690 } finally { 18691 IoUtils.closeQuietly(in); 18692 } 18693 } 18694 18695 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18696 BufferedReader in = null; 18697 String line = null; 18698 try { 18699 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18700 while ((line = in.readLine()) != null) { 18701 if (line.contains("ignored: updated version")) continue; 18702 pw.print("msg,"); 18703 pw.println(line); 18704 } 18705 } catch (IOException ignored) { 18706 } finally { 18707 IoUtils.closeQuietly(in); 18708 } 18709 } 18710 } 18711 } 18712 18713 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18714 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18715 ipw.println(); 18716 ipw.println("Dexopt state:"); 18717 ipw.increaseIndent(); 18718 Collection<PackageParser.Package> packages = null; 18719 if (packageName != null) { 18720 PackageParser.Package targetPackage = mPackages.get(packageName); 18721 if (targetPackage != null) { 18722 packages = Collections.singletonList(targetPackage); 18723 } else { 18724 ipw.println("Unable to find package: " + packageName); 18725 return; 18726 } 18727 } else { 18728 packages = mPackages.values(); 18729 } 18730 18731 for (PackageParser.Package pkg : packages) { 18732 ipw.println("[" + pkg.packageName + "]"); 18733 ipw.increaseIndent(); 18734 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18735 ipw.decreaseIndent(); 18736 } 18737 } 18738 18739 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18740 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18741 ipw.println(); 18742 ipw.println("Compiler stats:"); 18743 ipw.increaseIndent(); 18744 Collection<PackageParser.Package> packages = null; 18745 if (packageName != null) { 18746 PackageParser.Package targetPackage = mPackages.get(packageName); 18747 if (targetPackage != null) { 18748 packages = Collections.singletonList(targetPackage); 18749 } else { 18750 ipw.println("Unable to find package: " + packageName); 18751 return; 18752 } 18753 } else { 18754 packages = mPackages.values(); 18755 } 18756 18757 for (PackageParser.Package pkg : packages) { 18758 ipw.println("[" + pkg.packageName + "]"); 18759 ipw.increaseIndent(); 18760 18761 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18762 if (stats == null) { 18763 ipw.println("(No recorded stats)"); 18764 } else { 18765 stats.dump(ipw); 18766 } 18767 ipw.decreaseIndent(); 18768 } 18769 } 18770 18771 private String dumpDomainString(String packageName) { 18772 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18773 .getList(); 18774 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18775 18776 ArraySet<String> result = new ArraySet<>(); 18777 if (iviList.size() > 0) { 18778 for (IntentFilterVerificationInfo ivi : iviList) { 18779 for (String host : ivi.getDomains()) { 18780 result.add(host); 18781 } 18782 } 18783 } 18784 if (filters != null && filters.size() > 0) { 18785 for (IntentFilter filter : filters) { 18786 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18787 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18788 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18789 result.addAll(filter.getHostsList()); 18790 } 18791 } 18792 } 18793 18794 StringBuilder sb = new StringBuilder(result.size() * 16); 18795 for (String domain : result) { 18796 if (sb.length() > 0) sb.append(" "); 18797 sb.append(domain); 18798 } 18799 return sb.toString(); 18800 } 18801 18802 // ------- apps on sdcard specific code ------- 18803 static final boolean DEBUG_SD_INSTALL = false; 18804 18805 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18806 18807 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18808 18809 private boolean mMediaMounted = false; 18810 18811 static String getEncryptKey() { 18812 try { 18813 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18814 SD_ENCRYPTION_KEYSTORE_NAME); 18815 if (sdEncKey == null) { 18816 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18817 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18818 if (sdEncKey == null) { 18819 Slog.e(TAG, "Failed to create encryption keys"); 18820 return null; 18821 } 18822 } 18823 return sdEncKey; 18824 } catch (NoSuchAlgorithmException nsae) { 18825 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18826 return null; 18827 } catch (IOException ioe) { 18828 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18829 return null; 18830 } 18831 } 18832 18833 /* 18834 * Update media status on PackageManager. 18835 */ 18836 @Override 18837 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18838 int callingUid = Binder.getCallingUid(); 18839 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18840 throw new SecurityException("Media status can only be updated by the system"); 18841 } 18842 // reader; this apparently protects mMediaMounted, but should probably 18843 // be a different lock in that case. 18844 synchronized (mPackages) { 18845 Log.i(TAG, "Updating external media status from " 18846 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18847 + (mediaStatus ? "mounted" : "unmounted")); 18848 if (DEBUG_SD_INSTALL) 18849 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18850 + ", mMediaMounted=" + mMediaMounted); 18851 if (mediaStatus == mMediaMounted) { 18852 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18853 : 0, -1); 18854 mHandler.sendMessage(msg); 18855 return; 18856 } 18857 mMediaMounted = mediaStatus; 18858 } 18859 // Queue up an async operation since the package installation may take a 18860 // little while. 18861 mHandler.post(new Runnable() { 18862 public void run() { 18863 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18864 } 18865 }); 18866 } 18867 18868 /** 18869 * Called by MountService when the initial ASECs to scan are available. 18870 * Should block until all the ASEC containers are finished being scanned. 18871 */ 18872 public void scanAvailableAsecs() { 18873 updateExternalMediaStatusInner(true, false, false); 18874 } 18875 18876 /* 18877 * Collect information of applications on external media, map them against 18878 * existing containers and update information based on current mount status. 18879 * Please note that we always have to report status if reportStatus has been 18880 * set to true especially when unloading packages. 18881 */ 18882 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18883 boolean externalStorage) { 18884 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18885 int[] uidArr = EmptyArray.INT; 18886 18887 final String[] list = PackageHelper.getSecureContainerList(); 18888 if (ArrayUtils.isEmpty(list)) { 18889 Log.i(TAG, "No secure containers found"); 18890 } else { 18891 // Process list of secure containers and categorize them 18892 // as active or stale based on their package internal state. 18893 18894 // reader 18895 synchronized (mPackages) { 18896 for (String cid : list) { 18897 // Leave stages untouched for now; installer service owns them 18898 if (PackageInstallerService.isStageName(cid)) continue; 18899 18900 if (DEBUG_SD_INSTALL) 18901 Log.i(TAG, "Processing container " + cid); 18902 String pkgName = getAsecPackageName(cid); 18903 if (pkgName == null) { 18904 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18905 continue; 18906 } 18907 if (DEBUG_SD_INSTALL) 18908 Log.i(TAG, "Looking for pkg : " + pkgName); 18909 18910 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18911 if (ps == null) { 18912 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18913 continue; 18914 } 18915 18916 /* 18917 * Skip packages that are not external if we're unmounting 18918 * external storage. 18919 */ 18920 if (externalStorage && !isMounted && !isExternal(ps)) { 18921 continue; 18922 } 18923 18924 final AsecInstallArgs args = new AsecInstallArgs(cid, 18925 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18926 // The package status is changed only if the code path 18927 // matches between settings and the container id. 18928 if (ps.codePathString != null 18929 && ps.codePathString.startsWith(args.getCodePath())) { 18930 if (DEBUG_SD_INSTALL) { 18931 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18932 + " at code path: " + ps.codePathString); 18933 } 18934 18935 // We do have a valid package installed on sdcard 18936 processCids.put(args, ps.codePathString); 18937 final int uid = ps.appId; 18938 if (uid != -1) { 18939 uidArr = ArrayUtils.appendInt(uidArr, uid); 18940 } 18941 } else { 18942 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18943 + ps.codePathString); 18944 } 18945 } 18946 } 18947 18948 Arrays.sort(uidArr); 18949 } 18950 18951 // Process packages with valid entries. 18952 if (isMounted) { 18953 if (DEBUG_SD_INSTALL) 18954 Log.i(TAG, "Loading packages"); 18955 loadMediaPackages(processCids, uidArr, externalStorage); 18956 startCleaningPackages(); 18957 mInstallerService.onSecureContainersAvailable(); 18958 } else { 18959 if (DEBUG_SD_INSTALL) 18960 Log.i(TAG, "Unloading packages"); 18961 unloadMediaPackages(processCids, uidArr, reportStatus); 18962 } 18963 } 18964 18965 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18966 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18967 final int size = infos.size(); 18968 final String[] packageNames = new String[size]; 18969 final int[] packageUids = new int[size]; 18970 for (int i = 0; i < size; i++) { 18971 final ApplicationInfo info = infos.get(i); 18972 packageNames[i] = info.packageName; 18973 packageUids[i] = info.uid; 18974 } 18975 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18976 finishedReceiver); 18977 } 18978 18979 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18980 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18981 sendResourcesChangedBroadcast(mediaStatus, replacing, 18982 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18983 } 18984 18985 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18986 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18987 int size = pkgList.length; 18988 if (size > 0) { 18989 // Send broadcasts here 18990 Bundle extras = new Bundle(); 18991 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18992 if (uidArr != null) { 18993 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18994 } 18995 if (replacing) { 18996 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18997 } 18998 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18999 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19000 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19001 } 19002 } 19003 19004 /* 19005 * Look at potentially valid container ids from processCids If package 19006 * information doesn't match the one on record or package scanning fails, 19007 * the cid is added to list of removeCids. We currently don't delete stale 19008 * containers. 19009 */ 19010 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19011 boolean externalStorage) { 19012 ArrayList<String> pkgList = new ArrayList<String>(); 19013 Set<AsecInstallArgs> keys = processCids.keySet(); 19014 19015 for (AsecInstallArgs args : keys) { 19016 String codePath = processCids.get(args); 19017 if (DEBUG_SD_INSTALL) 19018 Log.i(TAG, "Loading container : " + args.cid); 19019 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19020 try { 19021 // Make sure there are no container errors first. 19022 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19023 Slog.e(TAG, "Failed to mount cid : " + args.cid 19024 + " when installing from sdcard"); 19025 continue; 19026 } 19027 // Check code path here. 19028 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19029 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19030 + " does not match one in settings " + codePath); 19031 continue; 19032 } 19033 // Parse package 19034 int parseFlags = mDefParseFlags; 19035 if (args.isExternalAsec()) { 19036 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19037 } 19038 if (args.isFwdLocked()) { 19039 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19040 } 19041 19042 synchronized (mInstallLock) { 19043 PackageParser.Package pkg = null; 19044 try { 19045 // Sadly we don't know the package name yet to freeze it 19046 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19047 SCAN_IGNORE_FROZEN, 0, null); 19048 } catch (PackageManagerException e) { 19049 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19050 } 19051 // Scan the package 19052 if (pkg != null) { 19053 /* 19054 * TODO why is the lock being held? doPostInstall is 19055 * called in other places without the lock. This needs 19056 * to be straightened out. 19057 */ 19058 // writer 19059 synchronized (mPackages) { 19060 retCode = PackageManager.INSTALL_SUCCEEDED; 19061 pkgList.add(pkg.packageName); 19062 // Post process args 19063 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19064 pkg.applicationInfo.uid); 19065 } 19066 } else { 19067 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19068 } 19069 } 19070 19071 } finally { 19072 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19073 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19074 } 19075 } 19076 } 19077 // writer 19078 synchronized (mPackages) { 19079 // If the platform SDK has changed since the last time we booted, 19080 // we need to re-grant app permission to catch any new ones that 19081 // appear. This is really a hack, and means that apps can in some 19082 // cases get permissions that the user didn't initially explicitly 19083 // allow... it would be nice to have some better way to handle 19084 // this situation. 19085 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19086 : mSettings.getInternalVersion(); 19087 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19088 : StorageManager.UUID_PRIVATE_INTERNAL; 19089 19090 int updateFlags = UPDATE_PERMISSIONS_ALL; 19091 if (ver.sdkVersion != mSdkVersion) { 19092 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19093 + mSdkVersion + "; regranting permissions for external"); 19094 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19095 } 19096 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19097 19098 // Yay, everything is now upgraded 19099 ver.forceCurrent(); 19100 19101 // can downgrade to reader 19102 // Persist settings 19103 mSettings.writeLPr(); 19104 } 19105 // Send a broadcast to let everyone know we are done processing 19106 if (pkgList.size() > 0) { 19107 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19108 } 19109 } 19110 19111 /* 19112 * Utility method to unload a list of specified containers 19113 */ 19114 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19115 // Just unmount all valid containers. 19116 for (AsecInstallArgs arg : cidArgs) { 19117 synchronized (mInstallLock) { 19118 arg.doPostDeleteLI(false); 19119 } 19120 } 19121 } 19122 19123 /* 19124 * Unload packages mounted on external media. This involves deleting package 19125 * data from internal structures, sending broadcasts about disabled packages, 19126 * gc'ing to free up references, unmounting all secure containers 19127 * corresponding to packages on external media, and posting a 19128 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19129 * that we always have to post this message if status has been requested no 19130 * matter what. 19131 */ 19132 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19133 final boolean reportStatus) { 19134 if (DEBUG_SD_INSTALL) 19135 Log.i(TAG, "unloading media packages"); 19136 ArrayList<String> pkgList = new ArrayList<String>(); 19137 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19138 final Set<AsecInstallArgs> keys = processCids.keySet(); 19139 for (AsecInstallArgs args : keys) { 19140 String pkgName = args.getPackageName(); 19141 if (DEBUG_SD_INSTALL) 19142 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19143 // Delete package internally 19144 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19145 synchronized (mInstallLock) { 19146 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19147 final boolean res; 19148 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19149 "unloadMediaPackages")) { 19150 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19151 null); 19152 } 19153 if (res) { 19154 pkgList.add(pkgName); 19155 } else { 19156 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19157 failedList.add(args); 19158 } 19159 } 19160 } 19161 19162 // reader 19163 synchronized (mPackages) { 19164 // We didn't update the settings after removing each package; 19165 // write them now for all packages. 19166 mSettings.writeLPr(); 19167 } 19168 19169 // We have to absolutely send UPDATED_MEDIA_STATUS only 19170 // after confirming that all the receivers processed the ordered 19171 // broadcast when packages get disabled, force a gc to clean things up. 19172 // and unload all the containers. 19173 if (pkgList.size() > 0) { 19174 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19175 new IIntentReceiver.Stub() { 19176 public void performReceive(Intent intent, int resultCode, String data, 19177 Bundle extras, boolean ordered, boolean sticky, 19178 int sendingUser) throws RemoteException { 19179 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19180 reportStatus ? 1 : 0, 1, keys); 19181 mHandler.sendMessage(msg); 19182 } 19183 }); 19184 } else { 19185 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19186 keys); 19187 mHandler.sendMessage(msg); 19188 } 19189 } 19190 19191 private void loadPrivatePackages(final VolumeInfo vol) { 19192 mHandler.post(new Runnable() { 19193 @Override 19194 public void run() { 19195 loadPrivatePackagesInner(vol); 19196 } 19197 }); 19198 } 19199 19200 private void loadPrivatePackagesInner(VolumeInfo vol) { 19201 final String volumeUuid = vol.fsUuid; 19202 if (TextUtils.isEmpty(volumeUuid)) { 19203 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19204 return; 19205 } 19206 19207 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19208 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19209 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19210 19211 final VersionInfo ver; 19212 final List<PackageSetting> packages; 19213 synchronized (mPackages) { 19214 ver = mSettings.findOrCreateVersion(volumeUuid); 19215 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19216 } 19217 19218 for (PackageSetting ps : packages) { 19219 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19220 synchronized (mInstallLock) { 19221 final PackageParser.Package pkg; 19222 try { 19223 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19224 loaded.add(pkg.applicationInfo); 19225 19226 } catch (PackageManagerException e) { 19227 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19228 } 19229 19230 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19231 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19232 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19233 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19234 } 19235 } 19236 } 19237 19238 // Reconcile app data for all started/unlocked users 19239 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19240 final UserManager um = mContext.getSystemService(UserManager.class); 19241 UserManagerInternal umInternal = getUserManagerInternal(); 19242 for (UserInfo user : um.getUsers()) { 19243 final int flags; 19244 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19245 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19246 } else if (umInternal.isUserRunning(user.id)) { 19247 flags = StorageManager.FLAG_STORAGE_DE; 19248 } else { 19249 continue; 19250 } 19251 19252 try { 19253 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19254 synchronized (mInstallLock) { 19255 reconcileAppsDataLI(volumeUuid, user.id, flags); 19256 } 19257 } catch (IllegalStateException e) { 19258 // Device was probably ejected, and we'll process that event momentarily 19259 Slog.w(TAG, "Failed to prepare storage: " + e); 19260 } 19261 } 19262 19263 synchronized (mPackages) { 19264 int updateFlags = UPDATE_PERMISSIONS_ALL; 19265 if (ver.sdkVersion != mSdkVersion) { 19266 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19267 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19268 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19269 } 19270 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19271 19272 // Yay, everything is now upgraded 19273 ver.forceCurrent(); 19274 19275 mSettings.writeLPr(); 19276 } 19277 19278 for (PackageFreezer freezer : freezers) { 19279 freezer.close(); 19280 } 19281 19282 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19283 sendResourcesChangedBroadcast(true, false, loaded, null); 19284 } 19285 19286 private void unloadPrivatePackages(final VolumeInfo vol) { 19287 mHandler.post(new Runnable() { 19288 @Override 19289 public void run() { 19290 unloadPrivatePackagesInner(vol); 19291 } 19292 }); 19293 } 19294 19295 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19296 final String volumeUuid = vol.fsUuid; 19297 if (TextUtils.isEmpty(volumeUuid)) { 19298 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19299 return; 19300 } 19301 19302 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19303 synchronized (mInstallLock) { 19304 synchronized (mPackages) { 19305 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19306 for (PackageSetting ps : packages) { 19307 if (ps.pkg == null) continue; 19308 19309 final ApplicationInfo info = ps.pkg.applicationInfo; 19310 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19311 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19312 19313 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19314 "unloadPrivatePackagesInner")) { 19315 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19316 false, null)) { 19317 unloaded.add(info); 19318 } else { 19319 Slog.w(TAG, "Failed to unload " + ps.codePath); 19320 } 19321 } 19322 19323 // Try very hard to release any references to this package 19324 // so we don't risk the system server being killed due to 19325 // open FDs 19326 AttributeCache.instance().removePackage(ps.name); 19327 } 19328 19329 mSettings.writeLPr(); 19330 } 19331 } 19332 19333 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19334 sendResourcesChangedBroadcast(false, false, unloaded, null); 19335 19336 // Try very hard to release any references to this path so we don't risk 19337 // the system server being killed due to open FDs 19338 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19339 19340 for (int i = 0; i < 3; i++) { 19341 System.gc(); 19342 System.runFinalization(); 19343 } 19344 } 19345 19346 /** 19347 * Prepare storage areas for given user on all mounted devices. 19348 */ 19349 void prepareUserData(int userId, int userSerial, int flags) { 19350 synchronized (mInstallLock) { 19351 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19352 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19353 final String volumeUuid = vol.getFsUuid(); 19354 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19355 } 19356 } 19357 } 19358 19359 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19360 boolean allowRecover) { 19361 // Prepare storage and verify that serial numbers are consistent; if 19362 // there's a mismatch we need to destroy to avoid leaking data 19363 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19364 try { 19365 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19366 19367 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19368 UserManagerService.enforceSerialNumber( 19369 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19370 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19371 UserManagerService.enforceSerialNumber( 19372 Environment.getDataSystemDeDirectory(userId), userSerial); 19373 } 19374 } 19375 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19376 UserManagerService.enforceSerialNumber( 19377 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19378 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19379 UserManagerService.enforceSerialNumber( 19380 Environment.getDataSystemCeDirectory(userId), userSerial); 19381 } 19382 } 19383 19384 synchronized (mInstallLock) { 19385 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19386 } 19387 } catch (Exception e) { 19388 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19389 + " because we failed to prepare: " + e); 19390 destroyUserDataLI(volumeUuid, userId, 19391 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19392 19393 if (allowRecover) { 19394 // Try one last time; if we fail again we're really in trouble 19395 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19396 } 19397 } 19398 } 19399 19400 /** 19401 * Destroy storage areas for given user on all mounted devices. 19402 */ 19403 void destroyUserData(int userId, int flags) { 19404 synchronized (mInstallLock) { 19405 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19406 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19407 final String volumeUuid = vol.getFsUuid(); 19408 destroyUserDataLI(volumeUuid, userId, flags); 19409 } 19410 } 19411 } 19412 19413 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19414 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19415 try { 19416 // Clean up app data, profile data, and media data 19417 mInstaller.destroyUserData(volumeUuid, userId, flags); 19418 19419 // Clean up system data 19420 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19421 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19422 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19423 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19424 } 19425 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19426 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19427 } 19428 } 19429 19430 // Data with special labels is now gone, so finish the job 19431 storage.destroyUserStorage(volumeUuid, userId, flags); 19432 19433 } catch (Exception e) { 19434 logCriticalInfo(Log.WARN, 19435 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19436 } 19437 } 19438 19439 /** 19440 * Examine all users present on given mounted volume, and destroy data 19441 * belonging to users that are no longer valid, or whose user ID has been 19442 * recycled. 19443 */ 19444 private void reconcileUsers(String volumeUuid) { 19445 final List<File> files = new ArrayList<>(); 19446 Collections.addAll(files, FileUtils 19447 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19448 Collections.addAll(files, FileUtils 19449 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19450 Collections.addAll(files, FileUtils 19451 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19452 Collections.addAll(files, FileUtils 19453 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19454 for (File file : files) { 19455 if (!file.isDirectory()) continue; 19456 19457 final int userId; 19458 final UserInfo info; 19459 try { 19460 userId = Integer.parseInt(file.getName()); 19461 info = sUserManager.getUserInfo(userId); 19462 } catch (NumberFormatException e) { 19463 Slog.w(TAG, "Invalid user directory " + file); 19464 continue; 19465 } 19466 19467 boolean destroyUser = false; 19468 if (info == null) { 19469 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19470 + " because no matching user was found"); 19471 destroyUser = true; 19472 } else if (!mOnlyCore) { 19473 try { 19474 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19475 } catch (IOException e) { 19476 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19477 + " because we failed to enforce serial number: " + e); 19478 destroyUser = true; 19479 } 19480 } 19481 19482 if (destroyUser) { 19483 synchronized (mInstallLock) { 19484 destroyUserDataLI(volumeUuid, userId, 19485 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19486 } 19487 } 19488 } 19489 } 19490 19491 private void assertPackageKnown(String volumeUuid, String packageName) 19492 throws PackageManagerException { 19493 synchronized (mPackages) { 19494 final PackageSetting ps = mSettings.mPackages.get(packageName); 19495 if (ps == null) { 19496 throw new PackageManagerException("Package " + packageName + " is unknown"); 19497 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19498 throw new PackageManagerException( 19499 "Package " + packageName + " found on unknown volume " + volumeUuid 19500 + "; expected volume " + ps.volumeUuid); 19501 } 19502 } 19503 } 19504 19505 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19506 throws PackageManagerException { 19507 synchronized (mPackages) { 19508 final PackageSetting ps = mSettings.mPackages.get(packageName); 19509 if (ps == null) { 19510 throw new PackageManagerException("Package " + packageName + " is unknown"); 19511 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19512 throw new PackageManagerException( 19513 "Package " + packageName + " found on unknown volume " + volumeUuid 19514 + "; expected volume " + ps.volumeUuid); 19515 } else if (!ps.getInstalled(userId)) { 19516 throw new PackageManagerException( 19517 "Package " + packageName + " not installed for user " + userId); 19518 } 19519 } 19520 } 19521 19522 /** 19523 * Examine all apps present on given mounted volume, and destroy apps that 19524 * aren't expected, either due to uninstallation or reinstallation on 19525 * another volume. 19526 */ 19527 private void reconcileApps(String volumeUuid) { 19528 final File[] files = FileUtils 19529 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19530 for (File file : files) { 19531 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19532 && !PackageInstallerService.isStageName(file.getName()); 19533 if (!isPackage) { 19534 // Ignore entries which are not packages 19535 continue; 19536 } 19537 19538 try { 19539 final PackageLite pkg = PackageParser.parsePackageLite(file, 19540 PackageParser.PARSE_MUST_BE_APK); 19541 assertPackageKnown(volumeUuid, pkg.packageName); 19542 19543 } catch (PackageParserException | PackageManagerException e) { 19544 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19545 synchronized (mInstallLock) { 19546 removeCodePathLI(file); 19547 } 19548 } 19549 } 19550 } 19551 19552 /** 19553 * Reconcile all app data for the given user. 19554 * <p> 19555 * Verifies that directories exist and that ownership and labeling is 19556 * correct for all installed apps on all mounted volumes. 19557 */ 19558 void reconcileAppsData(int userId, int flags) { 19559 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19560 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19561 final String volumeUuid = vol.getFsUuid(); 19562 synchronized (mInstallLock) { 19563 reconcileAppsDataLI(volumeUuid, userId, flags); 19564 } 19565 } 19566 } 19567 19568 /** 19569 * Reconcile all app data on given mounted volume. 19570 * <p> 19571 * Destroys app data that isn't expected, either due to uninstallation or 19572 * reinstallation on another volume. 19573 * <p> 19574 * Verifies that directories exist and that ownership and labeling is 19575 * correct for all installed apps. 19576 */ 19577 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19578 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19579 + Integer.toHexString(flags)); 19580 19581 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19582 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19583 19584 boolean restoreconNeeded = false; 19585 19586 // First look for stale data that doesn't belong, and check if things 19587 // have changed since we did our last restorecon 19588 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19589 if (StorageManager.isFileEncryptedNativeOrEmulated() 19590 && !StorageManager.isUserKeyUnlocked(userId)) { 19591 throw new RuntimeException( 19592 "Yikes, someone asked us to reconcile CE storage while " + userId 19593 + " was still locked; this would have caused massive data loss!"); 19594 } 19595 19596 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19597 19598 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19599 for (File file : files) { 19600 final String packageName = file.getName(); 19601 try { 19602 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19603 } catch (PackageManagerException e) { 19604 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19605 try { 19606 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19607 StorageManager.FLAG_STORAGE_CE, 0); 19608 } catch (InstallerException e2) { 19609 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19610 } 19611 } 19612 } 19613 } 19614 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19615 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19616 19617 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19618 for (File file : files) { 19619 final String packageName = file.getName(); 19620 try { 19621 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19622 } catch (PackageManagerException e) { 19623 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19624 try { 19625 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19626 StorageManager.FLAG_STORAGE_DE, 0); 19627 } catch (InstallerException e2) { 19628 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19629 } 19630 } 19631 } 19632 } 19633 19634 // Ensure that data directories are ready to roll for all packages 19635 // installed for this volume and user 19636 final List<PackageSetting> packages; 19637 synchronized (mPackages) { 19638 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19639 } 19640 int preparedCount = 0; 19641 for (PackageSetting ps : packages) { 19642 final String packageName = ps.name; 19643 if (ps.pkg == null) { 19644 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19645 // TODO: might be due to legacy ASEC apps; we should circle back 19646 // and reconcile again once they're scanned 19647 continue; 19648 } 19649 19650 if (ps.getInstalled(userId)) { 19651 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19652 19653 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19654 // We may have just shuffled around app data directories, so 19655 // prepare them one more time 19656 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19657 } 19658 19659 preparedCount++; 19660 } 19661 } 19662 19663 if (restoreconNeeded) { 19664 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19665 SELinuxMMAC.setRestoreconDone(ceDir); 19666 } 19667 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19668 SELinuxMMAC.setRestoreconDone(deDir); 19669 } 19670 } 19671 19672 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19673 + " packages; restoreconNeeded was " + restoreconNeeded); 19674 } 19675 19676 /** 19677 * Prepare app data for the given app just after it was installed or 19678 * upgraded. This method carefully only touches users that it's installed 19679 * for, and it forces a restorecon to handle any seinfo changes. 19680 * <p> 19681 * Verifies that directories exist and that ownership and labeling is 19682 * correct for all installed apps. If there is an ownership mismatch, it 19683 * will try recovering system apps by wiping data; third-party app data is 19684 * left intact. 19685 * <p> 19686 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19687 */ 19688 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19689 final PackageSetting ps; 19690 synchronized (mPackages) { 19691 ps = mSettings.mPackages.get(pkg.packageName); 19692 mSettings.writeKernelMappingLPr(ps); 19693 } 19694 19695 final UserManager um = mContext.getSystemService(UserManager.class); 19696 UserManagerInternal umInternal = getUserManagerInternal(); 19697 for (UserInfo user : um.getUsers()) { 19698 final int flags; 19699 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19700 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19701 } else if (umInternal.isUserRunning(user.id)) { 19702 flags = StorageManager.FLAG_STORAGE_DE; 19703 } else { 19704 continue; 19705 } 19706 19707 if (ps.getInstalled(user.id)) { 19708 // Whenever an app changes, force a restorecon of its data 19709 // TODO: when user data is locked, mark that we're still dirty 19710 prepareAppDataLIF(pkg, user.id, flags, true); 19711 } 19712 } 19713 } 19714 19715 /** 19716 * Prepare app data for the given app. 19717 * <p> 19718 * Verifies that directories exist and that ownership and labeling is 19719 * correct for all installed apps. If there is an ownership mismatch, this 19720 * will try recovering system apps by wiping data; third-party app data is 19721 * left intact. 19722 */ 19723 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19724 boolean restoreconNeeded) { 19725 if (pkg == null) { 19726 Slog.wtf(TAG, "Package was null!", new Throwable()); 19727 return; 19728 } 19729 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19730 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19731 for (int i = 0; i < childCount; i++) { 19732 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19733 } 19734 } 19735 19736 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19737 boolean restoreconNeeded) { 19738 if (DEBUG_APP_DATA) { 19739 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19740 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19741 } 19742 19743 final String volumeUuid = pkg.volumeUuid; 19744 final String packageName = pkg.packageName; 19745 final ApplicationInfo app = pkg.applicationInfo; 19746 final int appId = UserHandle.getAppId(app.uid); 19747 19748 Preconditions.checkNotNull(app.seinfo); 19749 19750 try { 19751 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19752 appId, app.seinfo, app.targetSdkVersion); 19753 } catch (InstallerException e) { 19754 if (app.isSystemApp()) { 19755 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19756 + ", but trying to recover: " + e); 19757 destroyAppDataLeafLIF(pkg, userId, flags); 19758 try { 19759 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19760 appId, app.seinfo, app.targetSdkVersion); 19761 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19762 } catch (InstallerException e2) { 19763 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19764 } 19765 } else { 19766 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19767 } 19768 } 19769 19770 if (restoreconNeeded) { 19771 try { 19772 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19773 app.seinfo); 19774 } catch (InstallerException e) { 19775 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19776 } 19777 } 19778 19779 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19780 try { 19781 // CE storage is unlocked right now, so read out the inode and 19782 // remember for use later when it's locked 19783 // TODO: mark this structure as dirty so we persist it! 19784 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19785 StorageManager.FLAG_STORAGE_CE); 19786 synchronized (mPackages) { 19787 final PackageSetting ps = mSettings.mPackages.get(packageName); 19788 if (ps != null) { 19789 ps.setCeDataInode(ceDataInode, userId); 19790 } 19791 } 19792 } catch (InstallerException e) { 19793 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19794 } 19795 } 19796 19797 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19798 } 19799 19800 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19801 if (pkg == null) { 19802 Slog.wtf(TAG, "Package was null!", new Throwable()); 19803 return; 19804 } 19805 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19806 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19807 for (int i = 0; i < childCount; i++) { 19808 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19809 } 19810 } 19811 19812 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19813 final String volumeUuid = pkg.volumeUuid; 19814 final String packageName = pkg.packageName; 19815 final ApplicationInfo app = pkg.applicationInfo; 19816 19817 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19818 // Create a native library symlink only if we have native libraries 19819 // and if the native libraries are 32 bit libraries. We do not provide 19820 // this symlink for 64 bit libraries. 19821 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19822 final String nativeLibPath = app.nativeLibraryDir; 19823 try { 19824 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19825 nativeLibPath, userId); 19826 } catch (InstallerException e) { 19827 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19828 } 19829 } 19830 } 19831 } 19832 19833 /** 19834 * For system apps on non-FBE devices, this method migrates any existing 19835 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19836 * requested by the app. 19837 */ 19838 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19839 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19840 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19841 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19842 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19843 try { 19844 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19845 storageTarget); 19846 } catch (InstallerException e) { 19847 logCriticalInfo(Log.WARN, 19848 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19849 } 19850 return true; 19851 } else { 19852 return false; 19853 } 19854 } 19855 19856 public PackageFreezer freezePackage(String packageName, String killReason) { 19857 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19858 } 19859 19860 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19861 return new PackageFreezer(packageName, userId, killReason); 19862 } 19863 19864 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19865 String killReason) { 19866 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19867 } 19868 19869 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19870 String killReason) { 19871 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19872 return new PackageFreezer(); 19873 } else { 19874 return freezePackage(packageName, userId, killReason); 19875 } 19876 } 19877 19878 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19879 String killReason) { 19880 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19881 } 19882 19883 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19884 String killReason) { 19885 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19886 return new PackageFreezer(); 19887 } else { 19888 return freezePackage(packageName, userId, killReason); 19889 } 19890 } 19891 19892 /** 19893 * Class that freezes and kills the given package upon creation, and 19894 * unfreezes it upon closing. This is typically used when doing surgery on 19895 * app code/data to prevent the app from running while you're working. 19896 */ 19897 private class PackageFreezer implements AutoCloseable { 19898 private final String mPackageName; 19899 private final PackageFreezer[] mChildren; 19900 19901 private final boolean mWeFroze; 19902 19903 private final AtomicBoolean mClosed = new AtomicBoolean(); 19904 private final CloseGuard mCloseGuard = CloseGuard.get(); 19905 19906 /** 19907 * Create and return a stub freezer that doesn't actually do anything, 19908 * typically used when someone requested 19909 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19910 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19911 */ 19912 public PackageFreezer() { 19913 mPackageName = null; 19914 mChildren = null; 19915 mWeFroze = false; 19916 mCloseGuard.open("close"); 19917 } 19918 19919 public PackageFreezer(String packageName, int userId, String killReason) { 19920 synchronized (mPackages) { 19921 mPackageName = packageName; 19922 mWeFroze = mFrozenPackages.add(mPackageName); 19923 19924 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19925 if (ps != null) { 19926 killApplication(ps.name, ps.appId, userId, killReason); 19927 } 19928 19929 final PackageParser.Package p = mPackages.get(packageName); 19930 if (p != null && p.childPackages != null) { 19931 final int N = p.childPackages.size(); 19932 mChildren = new PackageFreezer[N]; 19933 for (int i = 0; i < N; i++) { 19934 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19935 userId, killReason); 19936 } 19937 } else { 19938 mChildren = null; 19939 } 19940 } 19941 mCloseGuard.open("close"); 19942 } 19943 19944 @Override 19945 protected void finalize() throws Throwable { 19946 try { 19947 mCloseGuard.warnIfOpen(); 19948 close(); 19949 } finally { 19950 super.finalize(); 19951 } 19952 } 19953 19954 @Override 19955 public void close() { 19956 mCloseGuard.close(); 19957 if (mClosed.compareAndSet(false, true)) { 19958 synchronized (mPackages) { 19959 if (mWeFroze) { 19960 mFrozenPackages.remove(mPackageName); 19961 } 19962 19963 if (mChildren != null) { 19964 for (PackageFreezer freezer : mChildren) { 19965 freezer.close(); 19966 } 19967 } 19968 } 19969 } 19970 } 19971 } 19972 19973 /** 19974 * Verify that given package is currently frozen. 19975 */ 19976 private void checkPackageFrozen(String packageName) { 19977 synchronized (mPackages) { 19978 if (!mFrozenPackages.contains(packageName)) { 19979 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19980 } 19981 } 19982 } 19983 19984 @Override 19985 public int movePackage(final String packageName, final String volumeUuid) { 19986 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19987 19988 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19989 final int moveId = mNextMoveId.getAndIncrement(); 19990 mHandler.post(new Runnable() { 19991 @Override 19992 public void run() { 19993 try { 19994 movePackageInternal(packageName, volumeUuid, moveId, user); 19995 } catch (PackageManagerException e) { 19996 Slog.w(TAG, "Failed to move " + packageName, e); 19997 mMoveCallbacks.notifyStatusChanged(moveId, 19998 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19999 } 20000 } 20001 }); 20002 return moveId; 20003 } 20004 20005 private void movePackageInternal(final String packageName, final String volumeUuid, 20006 final int moveId, UserHandle user) throws PackageManagerException { 20007 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20008 final PackageManager pm = mContext.getPackageManager(); 20009 20010 final boolean currentAsec; 20011 final String currentVolumeUuid; 20012 final File codeFile; 20013 final String installerPackageName; 20014 final String packageAbiOverride; 20015 final int appId; 20016 final String seinfo; 20017 final String label; 20018 final int targetSdkVersion; 20019 final PackageFreezer freezer; 20020 final int[] installedUserIds; 20021 20022 // reader 20023 synchronized (mPackages) { 20024 final PackageParser.Package pkg = mPackages.get(packageName); 20025 final PackageSetting ps = mSettings.mPackages.get(packageName); 20026 if (pkg == null || ps == null) { 20027 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20028 } 20029 20030 if (pkg.applicationInfo.isSystemApp()) { 20031 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20032 "Cannot move system application"); 20033 } 20034 20035 if (pkg.applicationInfo.isExternalAsec()) { 20036 currentAsec = true; 20037 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20038 } else if (pkg.applicationInfo.isForwardLocked()) { 20039 currentAsec = true; 20040 currentVolumeUuid = "forward_locked"; 20041 } else { 20042 currentAsec = false; 20043 currentVolumeUuid = ps.volumeUuid; 20044 20045 final File probe = new File(pkg.codePath); 20046 final File probeOat = new File(probe, "oat"); 20047 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20048 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20049 "Move only supported for modern cluster style installs"); 20050 } 20051 } 20052 20053 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20054 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20055 "Package already moved to " + volumeUuid); 20056 } 20057 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20058 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20059 "Device admin cannot be moved"); 20060 } 20061 20062 if (mFrozenPackages.contains(packageName)) { 20063 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20064 "Failed to move already frozen package"); 20065 } 20066 20067 codeFile = new File(pkg.codePath); 20068 installerPackageName = ps.installerPackageName; 20069 packageAbiOverride = ps.cpuAbiOverrideString; 20070 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20071 seinfo = pkg.applicationInfo.seinfo; 20072 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20073 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20074 freezer = freezePackage(packageName, "movePackageInternal"); 20075 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20076 } 20077 20078 final Bundle extras = new Bundle(); 20079 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20080 extras.putString(Intent.EXTRA_TITLE, label); 20081 mMoveCallbacks.notifyCreated(moveId, extras); 20082 20083 int installFlags; 20084 final boolean moveCompleteApp; 20085 final File measurePath; 20086 20087 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20088 installFlags = INSTALL_INTERNAL; 20089 moveCompleteApp = !currentAsec; 20090 measurePath = Environment.getDataAppDirectory(volumeUuid); 20091 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20092 installFlags = INSTALL_EXTERNAL; 20093 moveCompleteApp = false; 20094 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20095 } else { 20096 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20097 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20098 || !volume.isMountedWritable()) { 20099 freezer.close(); 20100 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20101 "Move location not mounted private volume"); 20102 } 20103 20104 Preconditions.checkState(!currentAsec); 20105 20106 installFlags = INSTALL_INTERNAL; 20107 moveCompleteApp = true; 20108 measurePath = Environment.getDataAppDirectory(volumeUuid); 20109 } 20110 20111 final PackageStats stats = new PackageStats(null, -1); 20112 synchronized (mInstaller) { 20113 for (int userId : installedUserIds) { 20114 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20115 freezer.close(); 20116 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20117 "Failed to measure package size"); 20118 } 20119 } 20120 } 20121 20122 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20123 + stats.dataSize); 20124 20125 final long startFreeBytes = measurePath.getFreeSpace(); 20126 final long sizeBytes; 20127 if (moveCompleteApp) { 20128 sizeBytes = stats.codeSize + stats.dataSize; 20129 } else { 20130 sizeBytes = stats.codeSize; 20131 } 20132 20133 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20134 freezer.close(); 20135 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20136 "Not enough free space to move"); 20137 } 20138 20139 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20140 20141 final CountDownLatch installedLatch = new CountDownLatch(1); 20142 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20143 @Override 20144 public void onUserActionRequired(Intent intent) throws RemoteException { 20145 throw new IllegalStateException(); 20146 } 20147 20148 @Override 20149 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20150 Bundle extras) throws RemoteException { 20151 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20152 + PackageManager.installStatusToString(returnCode, msg)); 20153 20154 installedLatch.countDown(); 20155 freezer.close(); 20156 20157 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20158 switch (status) { 20159 case PackageInstaller.STATUS_SUCCESS: 20160 mMoveCallbacks.notifyStatusChanged(moveId, 20161 PackageManager.MOVE_SUCCEEDED); 20162 break; 20163 case PackageInstaller.STATUS_FAILURE_STORAGE: 20164 mMoveCallbacks.notifyStatusChanged(moveId, 20165 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20166 break; 20167 default: 20168 mMoveCallbacks.notifyStatusChanged(moveId, 20169 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20170 break; 20171 } 20172 } 20173 }; 20174 20175 final MoveInfo move; 20176 if (moveCompleteApp) { 20177 // Kick off a thread to report progress estimates 20178 new Thread() { 20179 @Override 20180 public void run() { 20181 while (true) { 20182 try { 20183 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20184 break; 20185 } 20186 } catch (InterruptedException ignored) { 20187 } 20188 20189 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20190 final int progress = 10 + (int) MathUtils.constrain( 20191 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20192 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20193 } 20194 } 20195 }.start(); 20196 20197 final String dataAppName = codeFile.getName(); 20198 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20199 dataAppName, appId, seinfo, targetSdkVersion); 20200 } else { 20201 move = null; 20202 } 20203 20204 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20205 20206 final Message msg = mHandler.obtainMessage(INIT_COPY); 20207 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20208 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20209 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20210 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20211 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20212 msg.obj = params; 20213 20214 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20215 System.identityHashCode(msg.obj)); 20216 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20217 System.identityHashCode(msg.obj)); 20218 20219 mHandler.sendMessage(msg); 20220 } 20221 20222 @Override 20223 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20225 20226 final int realMoveId = mNextMoveId.getAndIncrement(); 20227 final Bundle extras = new Bundle(); 20228 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20229 mMoveCallbacks.notifyCreated(realMoveId, extras); 20230 20231 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20232 @Override 20233 public void onCreated(int moveId, Bundle extras) { 20234 // Ignored 20235 } 20236 20237 @Override 20238 public void onStatusChanged(int moveId, int status, long estMillis) { 20239 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20240 } 20241 }; 20242 20243 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20244 storage.setPrimaryStorageUuid(volumeUuid, callback); 20245 return realMoveId; 20246 } 20247 20248 @Override 20249 public int getMoveStatus(int moveId) { 20250 mContext.enforceCallingOrSelfPermission( 20251 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20252 return mMoveCallbacks.mLastStatus.get(moveId); 20253 } 20254 20255 @Override 20256 public void registerMoveCallback(IPackageMoveObserver callback) { 20257 mContext.enforceCallingOrSelfPermission( 20258 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20259 mMoveCallbacks.register(callback); 20260 } 20261 20262 @Override 20263 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20264 mContext.enforceCallingOrSelfPermission( 20265 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20266 mMoveCallbacks.unregister(callback); 20267 } 20268 20269 @Override 20270 public boolean setInstallLocation(int loc) { 20271 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20272 null); 20273 if (getInstallLocation() == loc) { 20274 return true; 20275 } 20276 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20277 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20278 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20279 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20280 return true; 20281 } 20282 return false; 20283 } 20284 20285 @Override 20286 public int getInstallLocation() { 20287 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20288 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20289 PackageHelper.APP_INSTALL_AUTO); 20290 } 20291 20292 /** Called by UserManagerService */ 20293 void cleanUpUser(UserManagerService userManager, int userHandle) { 20294 synchronized (mPackages) { 20295 mDirtyUsers.remove(userHandle); 20296 mUserNeedsBadging.delete(userHandle); 20297 mSettings.removeUserLPw(userHandle); 20298 mPendingBroadcasts.remove(userHandle); 20299 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20300 removeUnusedPackagesLPw(userManager, userHandle); 20301 } 20302 } 20303 20304 /** 20305 * We're removing userHandle and would like to remove any downloaded packages 20306 * that are no longer in use by any other user. 20307 * @param userHandle the user being removed 20308 */ 20309 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20310 final boolean DEBUG_CLEAN_APKS = false; 20311 int [] users = userManager.getUserIds(); 20312 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20313 while (psit.hasNext()) { 20314 PackageSetting ps = psit.next(); 20315 if (ps.pkg == null) { 20316 continue; 20317 } 20318 final String packageName = ps.pkg.packageName; 20319 // Skip over if system app 20320 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20321 continue; 20322 } 20323 if (DEBUG_CLEAN_APKS) { 20324 Slog.i(TAG, "Checking package " + packageName); 20325 } 20326 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20327 if (keep) { 20328 if (DEBUG_CLEAN_APKS) { 20329 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20330 } 20331 } else { 20332 for (int i = 0; i < users.length; i++) { 20333 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20334 keep = true; 20335 if (DEBUG_CLEAN_APKS) { 20336 Slog.i(TAG, " Keeping package " + packageName + " for user " 20337 + users[i]); 20338 } 20339 break; 20340 } 20341 } 20342 } 20343 if (!keep) { 20344 if (DEBUG_CLEAN_APKS) { 20345 Slog.i(TAG, " Removing package " + packageName); 20346 } 20347 mHandler.post(new Runnable() { 20348 public void run() { 20349 deletePackageX(packageName, userHandle, 0); 20350 } //end run 20351 }); 20352 } 20353 } 20354 } 20355 20356 /** Called by UserManagerService */ 20357 void createNewUser(int userId) { 20358 synchronized (mInstallLock) { 20359 mSettings.createNewUserLI(this, mInstaller, userId); 20360 } 20361 synchronized (mPackages) { 20362 scheduleWritePackageRestrictionsLocked(userId); 20363 scheduleWritePackageListLocked(userId); 20364 applyFactoryDefaultBrowserLPw(userId); 20365 primeDomainVerificationsLPw(userId); 20366 } 20367 } 20368 20369 void onNewUserCreated(final int userId) { 20370 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20371 // If permission review for legacy apps is required, we represent 20372 // dagerous permissions for such apps as always granted runtime 20373 // permissions to keep per user flag state whether review is needed. 20374 // Hence, if a new user is added we have to propagate dangerous 20375 // permission grants for these legacy apps. 20376 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20377 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20378 | UPDATE_PERMISSIONS_REPLACE_ALL); 20379 } 20380 } 20381 20382 @Override 20383 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20384 mContext.enforceCallingOrSelfPermission( 20385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20386 "Only package verification agents can read the verifier device identity"); 20387 20388 synchronized (mPackages) { 20389 return mSettings.getVerifierDeviceIdentityLPw(); 20390 } 20391 } 20392 20393 @Override 20394 public void setPermissionEnforced(String permission, boolean enforced) { 20395 // TODO: Now that we no longer change GID for storage, this should to away. 20396 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20397 "setPermissionEnforced"); 20398 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20399 synchronized (mPackages) { 20400 if (mSettings.mReadExternalStorageEnforced == null 20401 || mSettings.mReadExternalStorageEnforced != enforced) { 20402 mSettings.mReadExternalStorageEnforced = enforced; 20403 mSettings.writeLPr(); 20404 } 20405 } 20406 // kill any non-foreground processes so we restart them and 20407 // grant/revoke the GID. 20408 final IActivityManager am = ActivityManagerNative.getDefault(); 20409 if (am != null) { 20410 final long token = Binder.clearCallingIdentity(); 20411 try { 20412 am.killProcessesBelowForeground("setPermissionEnforcement"); 20413 } catch (RemoteException e) { 20414 } finally { 20415 Binder.restoreCallingIdentity(token); 20416 } 20417 } 20418 } else { 20419 throw new IllegalArgumentException("No selective enforcement for " + permission); 20420 } 20421 } 20422 20423 @Override 20424 @Deprecated 20425 public boolean isPermissionEnforced(String permission) { 20426 return true; 20427 } 20428 20429 @Override 20430 public boolean isStorageLow() { 20431 final long token = Binder.clearCallingIdentity(); 20432 try { 20433 final DeviceStorageMonitorInternal 20434 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20435 if (dsm != null) { 20436 return dsm.isMemoryLow(); 20437 } else { 20438 return false; 20439 } 20440 } finally { 20441 Binder.restoreCallingIdentity(token); 20442 } 20443 } 20444 20445 @Override 20446 public IPackageInstaller getPackageInstaller() { 20447 return mInstallerService; 20448 } 20449 20450 private boolean userNeedsBadging(int userId) { 20451 int index = mUserNeedsBadging.indexOfKey(userId); 20452 if (index < 0) { 20453 final UserInfo userInfo; 20454 final long token = Binder.clearCallingIdentity(); 20455 try { 20456 userInfo = sUserManager.getUserInfo(userId); 20457 } finally { 20458 Binder.restoreCallingIdentity(token); 20459 } 20460 final boolean b; 20461 if (userInfo != null && userInfo.isManagedProfile()) { 20462 b = true; 20463 } else { 20464 b = false; 20465 } 20466 mUserNeedsBadging.put(userId, b); 20467 return b; 20468 } 20469 return mUserNeedsBadging.valueAt(index); 20470 } 20471 20472 @Override 20473 public KeySet getKeySetByAlias(String packageName, String alias) { 20474 if (packageName == null || alias == null) { 20475 return null; 20476 } 20477 synchronized(mPackages) { 20478 final PackageParser.Package pkg = mPackages.get(packageName); 20479 if (pkg == null) { 20480 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20481 throw new IllegalArgumentException("Unknown package: " + packageName); 20482 } 20483 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20484 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20485 } 20486 } 20487 20488 @Override 20489 public KeySet getSigningKeySet(String packageName) { 20490 if (packageName == null) { 20491 return null; 20492 } 20493 synchronized(mPackages) { 20494 final PackageParser.Package pkg = mPackages.get(packageName); 20495 if (pkg == null) { 20496 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20497 throw new IllegalArgumentException("Unknown package: " + packageName); 20498 } 20499 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20500 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20501 throw new SecurityException("May not access signing KeySet of other apps."); 20502 } 20503 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20504 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20505 } 20506 } 20507 20508 @Override 20509 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20510 if (packageName == null || ks == null) { 20511 return false; 20512 } 20513 synchronized(mPackages) { 20514 final PackageParser.Package pkg = mPackages.get(packageName); 20515 if (pkg == null) { 20516 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20517 throw new IllegalArgumentException("Unknown package: " + packageName); 20518 } 20519 IBinder ksh = ks.getToken(); 20520 if (ksh instanceof KeySetHandle) { 20521 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20522 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20523 } 20524 return false; 20525 } 20526 } 20527 20528 @Override 20529 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20530 if (packageName == null || ks == null) { 20531 return false; 20532 } 20533 synchronized(mPackages) { 20534 final PackageParser.Package pkg = mPackages.get(packageName); 20535 if (pkg == null) { 20536 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20537 throw new IllegalArgumentException("Unknown package: " + packageName); 20538 } 20539 IBinder ksh = ks.getToken(); 20540 if (ksh instanceof KeySetHandle) { 20541 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20542 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20543 } 20544 return false; 20545 } 20546 } 20547 20548 private void deletePackageIfUnusedLPr(final String packageName) { 20549 PackageSetting ps = mSettings.mPackages.get(packageName); 20550 if (ps == null) { 20551 return; 20552 } 20553 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20554 // TODO Implement atomic delete if package is unused 20555 // It is currently possible that the package will be deleted even if it is installed 20556 // after this method returns. 20557 mHandler.post(new Runnable() { 20558 public void run() { 20559 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20560 } 20561 }); 20562 } 20563 } 20564 20565 /** 20566 * Check and throw if the given before/after packages would be considered a 20567 * downgrade. 20568 */ 20569 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20570 throws PackageManagerException { 20571 if (after.versionCode < before.mVersionCode) { 20572 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20573 "Update version code " + after.versionCode + " is older than current " 20574 + before.mVersionCode); 20575 } else if (after.versionCode == before.mVersionCode) { 20576 if (after.baseRevisionCode < before.baseRevisionCode) { 20577 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20578 "Update base revision code " + after.baseRevisionCode 20579 + " is older than current " + before.baseRevisionCode); 20580 } 20581 20582 if (!ArrayUtils.isEmpty(after.splitNames)) { 20583 for (int i = 0; i < after.splitNames.length; i++) { 20584 final String splitName = after.splitNames[i]; 20585 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20586 if (j != -1) { 20587 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20588 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20589 "Update split " + splitName + " revision code " 20590 + after.splitRevisionCodes[i] + " is older than current " 20591 + before.splitRevisionCodes[j]); 20592 } 20593 } 20594 } 20595 } 20596 } 20597 } 20598 20599 private static class MoveCallbacks extends Handler { 20600 private static final int MSG_CREATED = 1; 20601 private static final int MSG_STATUS_CHANGED = 2; 20602 20603 private final RemoteCallbackList<IPackageMoveObserver> 20604 mCallbacks = new RemoteCallbackList<>(); 20605 20606 private final SparseIntArray mLastStatus = new SparseIntArray(); 20607 20608 public MoveCallbacks(Looper looper) { 20609 super(looper); 20610 } 20611 20612 public void register(IPackageMoveObserver callback) { 20613 mCallbacks.register(callback); 20614 } 20615 20616 public void unregister(IPackageMoveObserver callback) { 20617 mCallbacks.unregister(callback); 20618 } 20619 20620 @Override 20621 public void handleMessage(Message msg) { 20622 final SomeArgs args = (SomeArgs) msg.obj; 20623 final int n = mCallbacks.beginBroadcast(); 20624 for (int i = 0; i < n; i++) { 20625 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20626 try { 20627 invokeCallback(callback, msg.what, args); 20628 } catch (RemoteException ignored) { 20629 } 20630 } 20631 mCallbacks.finishBroadcast(); 20632 args.recycle(); 20633 } 20634 20635 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20636 throws RemoteException { 20637 switch (what) { 20638 case MSG_CREATED: { 20639 callback.onCreated(args.argi1, (Bundle) args.arg2); 20640 break; 20641 } 20642 case MSG_STATUS_CHANGED: { 20643 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20644 break; 20645 } 20646 } 20647 } 20648 20649 private void notifyCreated(int moveId, Bundle extras) { 20650 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20651 20652 final SomeArgs args = SomeArgs.obtain(); 20653 args.argi1 = moveId; 20654 args.arg2 = extras; 20655 obtainMessage(MSG_CREATED, args).sendToTarget(); 20656 } 20657 20658 private void notifyStatusChanged(int moveId, int status) { 20659 notifyStatusChanged(moveId, status, -1); 20660 } 20661 20662 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20663 Slog.v(TAG, "Move " + moveId + " status " + status); 20664 20665 final SomeArgs args = SomeArgs.obtain(); 20666 args.argi1 = moveId; 20667 args.argi2 = status; 20668 args.arg3 = estMillis; 20669 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20670 20671 synchronized (mLastStatus) { 20672 mLastStatus.put(moveId, status); 20673 } 20674 } 20675 } 20676 20677 private final static class OnPermissionChangeListeners extends Handler { 20678 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20679 20680 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20681 new RemoteCallbackList<>(); 20682 20683 public OnPermissionChangeListeners(Looper looper) { 20684 super(looper); 20685 } 20686 20687 @Override 20688 public void handleMessage(Message msg) { 20689 switch (msg.what) { 20690 case MSG_ON_PERMISSIONS_CHANGED: { 20691 final int uid = msg.arg1; 20692 handleOnPermissionsChanged(uid); 20693 } break; 20694 } 20695 } 20696 20697 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20698 mPermissionListeners.register(listener); 20699 20700 } 20701 20702 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20703 mPermissionListeners.unregister(listener); 20704 } 20705 20706 public void onPermissionsChanged(int uid) { 20707 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20708 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20709 } 20710 } 20711 20712 private void handleOnPermissionsChanged(int uid) { 20713 final int count = mPermissionListeners.beginBroadcast(); 20714 try { 20715 for (int i = 0; i < count; i++) { 20716 IOnPermissionsChangeListener callback = mPermissionListeners 20717 .getBroadcastItem(i); 20718 try { 20719 callback.onPermissionsChanged(uid); 20720 } catch (RemoteException e) { 20721 Log.e(TAG, "Permission listener is dead", e); 20722 } 20723 } 20724 } finally { 20725 mPermissionListeners.finishBroadcast(); 20726 } 20727 } 20728 } 20729 20730 private class PackageManagerInternalImpl extends PackageManagerInternal { 20731 @Override 20732 public void setLocationPackagesProvider(PackagesProvider provider) { 20733 synchronized (mPackages) { 20734 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20735 } 20736 } 20737 20738 @Override 20739 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20740 synchronized (mPackages) { 20741 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20742 } 20743 } 20744 20745 @Override 20746 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20747 synchronized (mPackages) { 20748 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20749 } 20750 } 20751 20752 @Override 20753 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20754 synchronized (mPackages) { 20755 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20756 } 20757 } 20758 20759 @Override 20760 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20761 synchronized (mPackages) { 20762 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20763 } 20764 } 20765 20766 @Override 20767 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20768 synchronized (mPackages) { 20769 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20770 } 20771 } 20772 20773 @Override 20774 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20775 synchronized (mPackages) { 20776 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20777 packageName, userId); 20778 } 20779 } 20780 20781 @Override 20782 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20783 synchronized (mPackages) { 20784 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20785 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20786 packageName, userId); 20787 } 20788 } 20789 20790 @Override 20791 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20792 synchronized (mPackages) { 20793 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20794 packageName, userId); 20795 } 20796 } 20797 20798 @Override 20799 public void setKeepUninstalledPackages(final List<String> packageList) { 20800 Preconditions.checkNotNull(packageList); 20801 List<String> removedFromList = null; 20802 synchronized (mPackages) { 20803 if (mKeepUninstalledPackages != null) { 20804 final int packagesCount = mKeepUninstalledPackages.size(); 20805 for (int i = 0; i < packagesCount; i++) { 20806 String oldPackage = mKeepUninstalledPackages.get(i); 20807 if (packageList != null && packageList.contains(oldPackage)) { 20808 continue; 20809 } 20810 if (removedFromList == null) { 20811 removedFromList = new ArrayList<>(); 20812 } 20813 removedFromList.add(oldPackage); 20814 } 20815 } 20816 mKeepUninstalledPackages = new ArrayList<>(packageList); 20817 if (removedFromList != null) { 20818 final int removedCount = removedFromList.size(); 20819 for (int i = 0; i < removedCount; i++) { 20820 deletePackageIfUnusedLPr(removedFromList.get(i)); 20821 } 20822 } 20823 } 20824 } 20825 20826 @Override 20827 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20828 synchronized (mPackages) { 20829 // If we do not support permission review, done. 20830 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20831 return false; 20832 } 20833 20834 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20835 if (packageSetting == null) { 20836 return false; 20837 } 20838 20839 // Permission review applies only to apps not supporting the new permission model. 20840 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20841 return false; 20842 } 20843 20844 // Legacy apps have the permission and get user consent on launch. 20845 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20846 return permissionsState.isPermissionReviewRequired(userId); 20847 } 20848 } 20849 20850 @Override 20851 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20852 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20853 } 20854 20855 @Override 20856 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20857 int userId) { 20858 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20859 } 20860 20861 @Override 20862 public void setDeviceAndProfileOwnerPackages( 20863 int deviceOwnerUserId, String deviceOwnerPackage, 20864 SparseArray<String> profileOwnerPackages) { 20865 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20866 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20867 } 20868 20869 @Override 20870 public boolean isPackageDataProtected(int userId, String packageName) { 20871 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20872 } 20873 } 20874 20875 @Override 20876 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20877 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20878 synchronized (mPackages) { 20879 final long identity = Binder.clearCallingIdentity(); 20880 try { 20881 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20882 packageNames, userId); 20883 } finally { 20884 Binder.restoreCallingIdentity(identity); 20885 } 20886 } 20887 } 20888 20889 private static void enforceSystemOrPhoneCaller(String tag) { 20890 int callingUid = Binder.getCallingUid(); 20891 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20892 throw new SecurityException( 20893 "Cannot call " + tag + " from UID " + callingUid); 20894 } 20895 } 20896 20897 boolean isHistoricalPackageUsageAvailable() { 20898 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20899 } 20900 20901 /** 20902 * Return a <b>copy</b> of the collection of packages known to the package manager. 20903 * @return A copy of the values of mPackages. 20904 */ 20905 Collection<PackageParser.Package> getPackages() { 20906 synchronized (mPackages) { 20907 return new ArrayList<>(mPackages.values()); 20908 } 20909 } 20910 20911 /** 20912 * Logs process start information (including base APK hash) to the security log. 20913 * @hide 20914 */ 20915 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20916 String apkFile, int pid) { 20917 if (!SecurityLog.isLoggingEnabled()) { 20918 return; 20919 } 20920 Bundle data = new Bundle(); 20921 data.putLong("startTimestamp", System.currentTimeMillis()); 20922 data.putString("processName", processName); 20923 data.putInt("uid", uid); 20924 data.putString("seinfo", seinfo); 20925 data.putString("apkFile", apkFile); 20926 data.putInt("pid", pid); 20927 Message msg = mProcessLoggingHandler.obtainMessage( 20928 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20929 msg.setData(data); 20930 mProcessLoggingHandler.sendMessage(msg); 20931 } 20932 20933 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20934 return mCompilerStats.getPackageStats(pkgName); 20935 } 20936 20937 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20938 return getOrCreateCompilerPackageStats(pkg.packageName); 20939 } 20940 20941 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20942 return mCompilerStats.getOrCreatePackageStats(pkgName); 20943 } 20944 20945 public void deleteCompilerPackageStats(String pkgName) { 20946 mCompilerStats.deletePackageStats(pkgName); 20947 } 20948} 20949