PackageManagerService.java revision 72de4ddb461e132f381aad7386f815581fd2aad5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 80import static android.system.OsConstants.O_CREAT; 81import static android.system.OsConstants.O_RDWR; 82 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.annotation.UserIdInt; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 369 370 private static final int RADIO_UID = Process.PHONE_UID; 371 private static final int LOG_UID = Process.LOG_UID; 372 private static final int NFC_UID = Process.NFC_UID; 373 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 374 private static final int SHELL_UID = Process.SHELL_UID; 375 376 // Cap the size of permission trees that 3rd party apps can define 377 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 378 379 // Suffix used during package installation when copying/moving 380 // package apks to install directory. 381 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 382 383 static final int SCAN_NO_DEX = 1<<1; 384 static final int SCAN_FORCE_DEX = 1<<2; 385 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 386 static final int SCAN_NEW_INSTALL = 1<<4; 387 static final int SCAN_NO_PATHS = 1<<5; 388 static final int SCAN_UPDATE_TIME = 1<<6; 389 static final int SCAN_DEFER_DEX = 1<<7; 390 static final int SCAN_BOOTING = 1<<8; 391 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 392 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 393 static final int SCAN_REPLACING = 1<<11; 394 static final int SCAN_REQUIRE_KNOWN = 1<<12; 395 static final int SCAN_MOVE = 1<<13; 396 static final int SCAN_INITIAL = 1<<14; 397 static final int SCAN_CHECK_ONLY = 1<<15; 398 static final int SCAN_DONT_KILL_APP = 1<<17; 399 static final int SCAN_IGNORE_FROZEN = 1<<18; 400 401 static final int REMOVE_CHATTY = 1<<16; 402 403 private static final int[] EMPTY_INT_ARRAY = new int[0]; 404 405 /** 406 * Timeout (in milliseconds) after which the watchdog should declare that 407 * our handler thread is wedged. The usual default for such things is one 408 * minute but we sometimes do very lengthy I/O operations on this thread, 409 * such as installing multi-gigabyte applications, so ours needs to be longer. 410 */ 411 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 412 413 /** 414 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 415 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 416 * settings entry if available, otherwise we use the hardcoded default. If it's been 417 * more than this long since the last fstrim, we force one during the boot sequence. 418 * 419 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 420 * one gets run at the next available charging+idle time. This final mandatory 421 * no-fstrim check kicks in only of the other scheduling criteria is never met. 422 */ 423 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 424 425 /** 426 * Whether verification is enabled by default. 427 */ 428 private static final boolean DEFAULT_VERIFY_ENABLE = true; 429 430 /** 431 * The default maximum time to wait for the verification agent to return in 432 * milliseconds. 433 */ 434 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 435 436 /** 437 * The default response for package verification timeout. 438 * 439 * This can be either PackageManager.VERIFICATION_ALLOW or 440 * PackageManager.VERIFICATION_REJECT. 441 */ 442 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 443 444 static final String PLATFORM_PACKAGE_NAME = "android"; 445 446 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 447 448 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 449 DEFAULT_CONTAINER_PACKAGE, 450 "com.android.defcontainer.DefaultContainerService"); 451 452 private static final String KILL_APP_REASON_GIDS_CHANGED = 453 "permission grant or revoke changed gids"; 454 455 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 456 "permissions revoked"; 457 458 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 459 460 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 461 462 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 463 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 public static final int REASON_CORE_APP = 8; 508 509 public static final int REASON_LAST = REASON_CORE_APP; 510 511 /** Special library name that skips shared libraries check during compilation. */ 512 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 513 514 final ServiceThread mHandlerThread; 515 516 final PackageHandler mHandler; 517 518 private final ProcessLoggingHandler mProcessLoggingHandler; 519 520 /** 521 * Messages for {@link #mHandler} that need to wait for system ready before 522 * being dispatched. 523 */ 524 private ArrayList<Message> mPostSystemReadyMessages; 525 526 final int mSdkVersion = Build.VERSION.SDK_INT; 527 528 final Context mContext; 529 final boolean mFactoryTest; 530 final boolean mOnlyCore; 531 final DisplayMetrics mMetrics; 532 final int mDefParseFlags; 533 final String[] mSeparateProcesses; 534 final boolean mIsUpgrade; 535 final boolean mIsPreNUpgrade; 536 537 /** The location for ASEC container files on internal storage. */ 538 final String mAsecInternalPath; 539 540 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 541 // LOCK HELD. Can be called with mInstallLock held. 542 @GuardedBy("mInstallLock") 543 final Installer mInstaller; 544 545 /** Directory where installed third-party apps stored */ 546 final File mAppInstallDir; 547 final File mEphemeralInstallDir; 548 549 /** 550 * Directory to which applications installed internally have their 551 * 32 bit native libraries copied. 552 */ 553 private File mAppLib32InstallDir; 554 555 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 556 // apps. 557 final File mDrmAppPrivateInstallDir; 558 559 // ---------------------------------------------------------------- 560 561 // Lock for state used when installing and doing other long running 562 // operations. Methods that must be called with this lock held have 563 // the suffix "LI". 564 final Object mInstallLock = new Object(); 565 566 // ---------------------------------------------------------------- 567 568 // Keys are String (package name), values are Package. This also serves 569 // as the lock for the global state. Methods that must be called with 570 // this lock held have the prefix "LP". 571 @GuardedBy("mPackages") 572 final ArrayMap<String, PackageParser.Package> mPackages = 573 new ArrayMap<String, PackageParser.Package>(); 574 575 final ArrayMap<String, Set<String>> mKnownCodebase = 576 new ArrayMap<String, Set<String>>(); 577 578 // Tracks available target package names -> overlay package paths. 579 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 580 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 581 582 /** 583 * Tracks new system packages [received in an OTA] that we expect to 584 * find updated user-installed versions. Keys are package name, values 585 * are package location. 586 */ 587 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 588 /** 589 * Tracks high priority intent filters for protected actions. During boot, certain 590 * filter actions are protected and should never be allowed to have a high priority 591 * intent filter for them. However, there is one, and only one exception -- the 592 * setup wizard. It must be able to define a high priority intent filter for these 593 * actions to ensure there are no escapes from the wizard. We need to delay processing 594 * of these during boot as we need to look at all of the system packages in order 595 * to know which component is the setup wizard. 596 */ 597 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 598 /** 599 * Whether or not processing protected filters should be deferred. 600 */ 601 private boolean mDeferProtectedFilters = true; 602 603 /** 604 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 605 */ 606 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 607 /** 608 * Whether or not system app permissions should be promoted from install to runtime. 609 */ 610 boolean mPromoteSystemApps; 611 612 @GuardedBy("mPackages") 613 final Settings mSettings; 614 615 /** 616 * Set of package names that are currently "frozen", which means active 617 * surgery is being done on the code/data for that package. The platform 618 * will refuse to launch frozen packages to avoid race conditions. 619 * 620 * @see PackageFreezer 621 */ 622 @GuardedBy("mPackages") 623 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 624 625 final ProtectedPackages mProtectedPackages; 626 627 boolean mFirstBoot; 628 629 // System configuration read by SystemConfig. 630 final int[] mGlobalGids; 631 final SparseArray<ArraySet<String>> mSystemPermissions; 632 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 633 634 // If mac_permissions.xml was found for seinfo labeling. 635 boolean mFoundPolicyFile; 636 637 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 638 639 public static final class SharedLibraryEntry { 640 public final String path; 641 public final String apk; 642 643 SharedLibraryEntry(String _path, String _apk) { 644 path = _path; 645 apk = _apk; 646 } 647 } 648 649 // Currently known shared libraries. 650 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 651 new ArrayMap<String, SharedLibraryEntry>(); 652 653 // All available activities, for your resolving pleasure. 654 final ActivityIntentResolver mActivities = 655 new ActivityIntentResolver(); 656 657 // All available receivers, for your resolving pleasure. 658 final ActivityIntentResolver mReceivers = 659 new ActivityIntentResolver(); 660 661 // All available services, for your resolving pleasure. 662 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 663 664 // All available providers, for your resolving pleasure. 665 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 666 667 // Mapping from provider base names (first directory in content URI codePath) 668 // to the provider information. 669 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 670 new ArrayMap<String, PackageParser.Provider>(); 671 672 // Mapping from instrumentation class names to info about them. 673 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 674 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 675 676 // Mapping from permission names to info about them. 677 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 678 new ArrayMap<String, PackageParser.PermissionGroup>(); 679 680 // Packages whose data we have transfered into another package, thus 681 // should no longer exist. 682 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 683 684 // Broadcast actions that are only available to the system. 685 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 686 687 /** List of packages waiting for verification. */ 688 final SparseArray<PackageVerificationState> mPendingVerification 689 = new SparseArray<PackageVerificationState>(); 690 691 /** Set of packages associated with each app op permission. */ 692 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 693 694 final PackageInstallerService mInstallerService; 695 696 private final PackageDexOptimizer mPackageDexOptimizer; 697 698 private AtomicInteger mNextMoveId = new AtomicInteger(); 699 private final MoveCallbacks mMoveCallbacks; 700 701 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 702 703 // Cache of users who need badging. 704 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 705 706 /** Token for keys in mPendingVerification. */ 707 private int mPendingVerificationToken = 0; 708 709 volatile boolean mSystemReady; 710 volatile boolean mSafeMode; 711 volatile boolean mHasSystemUidErrors; 712 713 ApplicationInfo mAndroidApplication; 714 final ActivityInfo mResolveActivity = new ActivityInfo(); 715 final ResolveInfo mResolveInfo = new ResolveInfo(); 716 ComponentName mResolveComponentName; 717 PackageParser.Package mPlatformPackage; 718 ComponentName mCustomResolverComponentName; 719 720 boolean mResolverReplaced = false; 721 722 private final @Nullable ComponentName mIntentFilterVerifierComponent; 723 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 724 725 private int mIntentFilterVerificationToken = 0; 726 727 /** Component that knows whether or not an ephemeral application exists */ 728 final ComponentName mEphemeralResolverComponent; 729 /** The service connection to the ephemeral resolver */ 730 final EphemeralResolverConnection mEphemeralResolverConnection; 731 732 /** Component used to install ephemeral applications */ 733 final ComponentName mEphemeralInstallerComponent; 734 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 735 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 736 737 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 738 = new SparseArray<IntentFilterVerificationState>(); 739 740 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 741 new DefaultPermissionGrantPolicy(this); 742 743 // List of packages names to keep cached, even if they are uninstalled for all users 744 private List<String> mKeepUninstalledPackages; 745 746 private UserManagerInternal mUserManagerInternal; 747 748 private static class IFVerificationParams { 749 PackageParser.Package pkg; 750 boolean replacing; 751 int userId; 752 int verifierUid; 753 754 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 755 int _userId, int _verifierUid) { 756 pkg = _pkg; 757 replacing = _replacing; 758 userId = _userId; 759 replacing = _replacing; 760 verifierUid = _verifierUid; 761 } 762 } 763 764 private interface IntentFilterVerifier<T extends IntentFilter> { 765 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 766 T filter, String packageName); 767 void startVerifications(int userId); 768 void receiveVerificationResponse(int verificationId); 769 } 770 771 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 772 private Context mContext; 773 private ComponentName mIntentFilterVerifierComponent; 774 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 775 776 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 777 mContext = context; 778 mIntentFilterVerifierComponent = verifierComponent; 779 } 780 781 private String getDefaultScheme() { 782 return IntentFilter.SCHEME_HTTPS; 783 } 784 785 @Override 786 public void startVerifications(int userId) { 787 // Launch verifications requests 788 int count = mCurrentIntentFilterVerifications.size(); 789 for (int n=0; n<count; n++) { 790 int verificationId = mCurrentIntentFilterVerifications.get(n); 791 final IntentFilterVerificationState ivs = 792 mIntentFilterVerificationStates.get(verificationId); 793 794 String packageName = ivs.getPackageName(); 795 796 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 797 final int filterCount = filters.size(); 798 ArraySet<String> domainsSet = new ArraySet<>(); 799 for (int m=0; m<filterCount; m++) { 800 PackageParser.ActivityIntentInfo filter = filters.get(m); 801 domainsSet.addAll(filter.getHostsList()); 802 } 803 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 804 synchronized (mPackages) { 805 if (mSettings.createIntentFilterVerificationIfNeededLPw( 806 packageName, domainsList) != null) { 807 scheduleWriteSettingsLocked(); 808 } 809 } 810 sendVerificationRequest(userId, verificationId, ivs); 811 } 812 mCurrentIntentFilterVerifications.clear(); 813 } 814 815 private void sendVerificationRequest(int userId, int verificationId, 816 IntentFilterVerificationState ivs) { 817 818 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 821 verificationId); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 824 getDefaultScheme()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 827 ivs.getHostsString()); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 830 ivs.getPackageName()); 831 verificationIntent.setComponent(mIntentFilterVerifierComponent); 832 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 833 834 UserHandle user = new UserHandle(userId); 835 mContext.sendBroadcastAsUser(verificationIntent, user); 836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 837 "Sending IntentFilter verification broadcast"); 838 } 839 840 public void receiveVerificationResponse(int verificationId) { 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 843 final boolean verified = ivs.isVerified(); 844 845 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 846 final int count = filters.size(); 847 if (DEBUG_DOMAIN_VERIFICATION) { 848 Slog.i(TAG, "Received verification response " + verificationId 849 + " for " + count + " filters, verified=" + verified); 850 } 851 for (int n=0; n<count; n++) { 852 PackageParser.ActivityIntentInfo filter = filters.get(n); 853 filter.setVerified(verified); 854 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 856 + " verified with result:" + verified + " and hosts:" 857 + ivs.getHostsString()); 858 } 859 860 mIntentFilterVerificationStates.remove(verificationId); 861 862 final String packageName = ivs.getPackageName(); 863 IntentFilterVerificationInfo ivi = null; 864 865 synchronized (mPackages) { 866 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 867 } 868 if (ivi == null) { 869 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 870 + verificationId + " packageName:" + packageName); 871 return; 872 } 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 874 "Updating IntentFilterVerificationInfo for package " + packageName 875 +" verificationId:" + verificationId); 876 877 synchronized (mPackages) { 878 if (verified) { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 880 } else { 881 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 882 } 883 scheduleWriteSettingsLocked(); 884 885 final int userId = ivs.getUserId(); 886 if (userId != UserHandle.USER_ALL) { 887 final int userStatus = 888 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 889 890 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 891 boolean needUpdate = false; 892 893 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 894 // already been set by the User thru the Disambiguation dialog 895 switch (userStatus) { 896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 897 if (verified) { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 899 } else { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 901 } 902 needUpdate = true; 903 break; 904 905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 906 if (verified) { 907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 908 needUpdate = true; 909 } 910 break; 911 912 default: 913 // Nothing to do 914 } 915 916 if (needUpdate) { 917 mSettings.updateIntentFilterVerificationStatusLPw( 918 packageName, updatedStatus, userId); 919 scheduleWritePackageRestrictionsLocked(userId); 920 } 921 } 922 } 923 } 924 925 @Override 926 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 927 ActivityIntentInfo filter, String packageName) { 928 if (!hasValidDomains(filter)) { 929 return false; 930 } 931 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 932 if (ivs == null) { 933 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 934 packageName); 935 } 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 938 } 939 ivs.addFilter(filter); 940 return true; 941 } 942 943 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 944 int userId, int verificationId, String packageName) { 945 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 946 verifierUid, userId, packageName); 947 ivs.setPendingState(); 948 synchronized (mPackages) { 949 mIntentFilterVerificationStates.append(verificationId, ivs); 950 mCurrentIntentFilterVerifications.add(verificationId); 951 } 952 return ivs; 953 } 954 } 955 956 private static boolean hasValidDomains(ActivityIntentInfo filter) { 957 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 960 } 961 962 // Set of pending broadcasts for aggregating enable/disable of components. 963 static class PendingPackageBroadcasts { 964 // for each user id, a map of <package name -> components within that package> 965 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 966 967 public PendingPackageBroadcasts() { 968 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 969 } 970 971 public ArrayList<String> get(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 return packages.get(packageName); 974 } 975 976 public void put(int userId, String packageName, ArrayList<String> components) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 packages.put(packageName, components); 979 } 980 981 public void remove(int userId, String packageName) { 982 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 983 if (packages != null) { 984 packages.remove(packageName); 985 } 986 } 987 988 public void remove(int userId) { 989 mUidMap.remove(userId); 990 } 991 992 public int userIdCount() { 993 return mUidMap.size(); 994 } 995 996 public int userIdAt(int n) { 997 return mUidMap.keyAt(n); 998 } 999 1000 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1001 return mUidMap.get(userId); 1002 } 1003 1004 public int size() { 1005 // total number of pending broadcast entries across all userIds 1006 int num = 0; 1007 for (int i = 0; i< mUidMap.size(); i++) { 1008 num += mUidMap.valueAt(i).size(); 1009 } 1010 return num; 1011 } 1012 1013 public void clear() { 1014 mUidMap.clear(); 1015 } 1016 1017 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1018 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1019 if (map == null) { 1020 map = new ArrayMap<String, ArrayList<String>>(); 1021 mUidMap.put(userId, map); 1022 } 1023 return map; 1024 } 1025 } 1026 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1027 1028 // Service Connection to remote media container service to copy 1029 // package uri's from external media onto secure containers 1030 // or internal storage. 1031 private IMediaContainerService mContainerService = null; 1032 1033 static final int SEND_PENDING_BROADCAST = 1; 1034 static final int MCS_BOUND = 3; 1035 static final int END_COPY = 4; 1036 static final int INIT_COPY = 5; 1037 static final int MCS_UNBIND = 6; 1038 static final int START_CLEANING_PACKAGE = 7; 1039 static final int FIND_INSTALL_LOC = 8; 1040 static final int POST_INSTALL = 9; 1041 static final int MCS_RECONNECT = 10; 1042 static final int MCS_GIVE_UP = 11; 1043 static final int UPDATED_MEDIA_STATUS = 12; 1044 static final int WRITE_SETTINGS = 13; 1045 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1046 static final int PACKAGE_VERIFIED = 15; 1047 static final int CHECK_PENDING_VERIFICATION = 16; 1048 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1049 static final int INTENT_FILTER_VERIFIED = 18; 1050 static final int WRITE_PACKAGE_LIST = 19; 1051 1052 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1053 1054 // Delay time in millisecs 1055 static final int BROADCAST_DELAY = 10 * 1000; 1056 1057 static UserManagerService sUserManager; 1058 1059 // Stores a list of users whose package restrictions file needs to be updated 1060 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1061 1062 final private DefaultContainerConnection mDefContainerConn = 1063 new DefaultContainerConnection(); 1064 class DefaultContainerConnection implements ServiceConnection { 1065 public void onServiceConnected(ComponentName name, IBinder service) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1067 IMediaContainerService imcs = 1068 IMediaContainerService.Stub.asInterface(service); 1069 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1070 } 1071 1072 public void onServiceDisconnected(ComponentName name) { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1074 } 1075 } 1076 1077 // Recordkeeping of restore-after-install operations that are currently in flight 1078 // between the Package Manager and the Backup Manager 1079 static class PostInstallData { 1080 public InstallArgs args; 1081 public PackageInstalledInfo res; 1082 1083 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1084 args = _a; 1085 res = _r; 1086 } 1087 } 1088 1089 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1090 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1091 1092 // XML tags for backup/restore of various bits of state 1093 private static final String TAG_PREFERRED_BACKUP = "pa"; 1094 private static final String TAG_DEFAULT_APPS = "da"; 1095 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1096 1097 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1098 private static final String TAG_ALL_GRANTS = "rt-grants"; 1099 private static final String TAG_GRANT = "grant"; 1100 private static final String ATTR_PACKAGE_NAME = "pkg"; 1101 1102 private static final String TAG_PERMISSION = "perm"; 1103 private static final String ATTR_PERMISSION_NAME = "name"; 1104 private static final String ATTR_IS_GRANTED = "g"; 1105 private static final String ATTR_USER_SET = "set"; 1106 private static final String ATTR_USER_FIXED = "fixed"; 1107 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1108 1109 // System/policy permission grants are not backed up 1110 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1111 FLAG_PERMISSION_POLICY_FIXED 1112 | FLAG_PERMISSION_SYSTEM_FIXED 1113 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1114 1115 // And we back up these user-adjusted states 1116 private static final int USER_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_USER_SET 1118 | FLAG_PERMISSION_USER_FIXED 1119 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1120 1121 final @Nullable String mRequiredVerifierPackage; 1122 final @NonNull String mRequiredInstallerPackage; 1123 final @Nullable String mSetupWizardPackage; 1124 final @NonNull String mServicesSystemSharedLibraryPackageName; 1125 final @NonNull String mSharedSystemSharedLibraryPackageName; 1126 1127 private final PackageUsage mPackageUsage = new PackageUsage(); 1128 private final CompilerStats mCompilerStats = new CompilerStats(); 1129 1130 class PackageHandler extends Handler { 1131 private boolean mBound = false; 1132 final ArrayList<HandlerParams> mPendingInstalls = 1133 new ArrayList<HandlerParams>(); 1134 1135 private boolean connectToService() { 1136 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1137 " DefaultContainerService"); 1138 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1141 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1143 mBound = true; 1144 return true; 1145 } 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1147 return false; 1148 } 1149 1150 private void disconnectService() { 1151 mContainerService = null; 1152 mBound = false; 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1154 mContext.unbindService(mDefContainerConn); 1155 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1156 } 1157 1158 PackageHandler(Looper looper) { 1159 super(looper); 1160 } 1161 1162 public void handleMessage(Message msg) { 1163 try { 1164 doHandleMessage(msg); 1165 } finally { 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 } 1168 } 1169 1170 void doHandleMessage(Message msg) { 1171 switch (msg.what) { 1172 case INIT_COPY: { 1173 HandlerParams params = (HandlerParams) msg.obj; 1174 int idx = mPendingInstalls.size(); 1175 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1176 // If a bind was already initiated we dont really 1177 // need to do anything. The pending install 1178 // will be processed later on. 1179 if (!mBound) { 1180 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1181 System.identityHashCode(mHandler)); 1182 // If this is the only one pending we might 1183 // have to bind to the service again. 1184 if (!connectToService()) { 1185 Slog.e(TAG, "Failed to bind to media container service"); 1186 params.serviceError(); 1187 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1188 System.identityHashCode(mHandler)); 1189 if (params.traceMethod != null) { 1190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1191 params.traceCookie); 1192 } 1193 return; 1194 } else { 1195 // Once we bind to the service, the first 1196 // pending request will be processed. 1197 mPendingInstalls.add(idx, params); 1198 } 1199 } else { 1200 mPendingInstalls.add(idx, params); 1201 // Already bound to the service. Just make 1202 // sure we trigger off processing the first request. 1203 if (idx == 0) { 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 break; 1208 } 1209 case MCS_BOUND: { 1210 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1211 if (msg.obj != null) { 1212 mContainerService = (IMediaContainerService) msg.obj; 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1214 System.identityHashCode(mHandler)); 1215 } 1216 if (mContainerService == null) { 1217 if (!mBound) { 1218 // Something seriously wrong since we are not bound and we are not 1219 // waiting for connection. Bail out. 1220 Slog.e(TAG, "Cannot bind to media container service"); 1221 for (HandlerParams params : mPendingInstalls) { 1222 // Indicate service bind error 1223 params.serviceError(); 1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1225 System.identityHashCode(params)); 1226 if (params.traceMethod != null) { 1227 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1228 params.traceMethod, params.traceCookie); 1229 } 1230 return; 1231 } 1232 mPendingInstalls.clear(); 1233 } else { 1234 Slog.w(TAG, "Waiting to connect to media container service"); 1235 } 1236 } else if (mPendingInstalls.size() > 0) { 1237 HandlerParams params = mPendingInstalls.get(0); 1238 if (params != null) { 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1240 System.identityHashCode(params)); 1241 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1242 if (params.startCopy()) { 1243 // We are done... look for more work or to 1244 // go idle. 1245 if (DEBUG_SD_INSTALL) Log.i(TAG, 1246 "Checking for more work or unbind..."); 1247 // Delete pending install 1248 if (mPendingInstalls.size() > 0) { 1249 mPendingInstalls.remove(0); 1250 } 1251 if (mPendingInstalls.size() == 0) { 1252 if (mBound) { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, 1254 "Posting delayed MCS_UNBIND"); 1255 removeMessages(MCS_UNBIND); 1256 Message ubmsg = obtainMessage(MCS_UNBIND); 1257 // Unbind after a little delay, to avoid 1258 // continual thrashing. 1259 sendMessageDelayed(ubmsg, 10000); 1260 } 1261 } else { 1262 // There are more pending requests in queue. 1263 // Just post MCS_BOUND message to trigger processing 1264 // of next pending install. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Posting MCS_BOUND for next work"); 1267 mHandler.sendEmptyMessage(MCS_BOUND); 1268 } 1269 } 1270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1271 } 1272 } else { 1273 // Should never happen ideally. 1274 Slog.w(TAG, "Empty queue"); 1275 } 1276 break; 1277 } 1278 case MCS_RECONNECT: { 1279 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1280 if (mPendingInstalls.size() > 0) { 1281 if (mBound) { 1282 disconnectService(); 1283 } 1284 if (!connectToService()) { 1285 Slog.e(TAG, "Failed to bind to media container service"); 1286 for (HandlerParams params : mPendingInstalls) { 1287 // Indicate service bind error 1288 params.serviceError(); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 } 1292 mPendingInstalls.clear(); 1293 } 1294 } 1295 break; 1296 } 1297 case MCS_UNBIND: { 1298 // If there is no actual work left, then time to unbind. 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1300 1301 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1302 if (mBound) { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1304 1305 disconnectService(); 1306 } 1307 } else if (mPendingInstalls.size() > 0) { 1308 // There are more pending requests in queue. 1309 // Just post MCS_BOUND message to trigger processing 1310 // of next pending install. 1311 mHandler.sendEmptyMessage(MCS_BOUND); 1312 } 1313 1314 break; 1315 } 1316 case MCS_GIVE_UP: { 1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1318 HandlerParams params = mPendingInstalls.remove(0); 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 break; 1322 } 1323 case SEND_PENDING_BROADCAST: { 1324 String packages[]; 1325 ArrayList<String> components[]; 1326 int size = 0; 1327 int uids[]; 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1329 synchronized (mPackages) { 1330 if (mPendingBroadcasts == null) { 1331 return; 1332 } 1333 size = mPendingBroadcasts.size(); 1334 if (size <= 0) { 1335 // Nothing to be done. Just return 1336 return; 1337 } 1338 packages = new String[size]; 1339 components = new ArrayList[size]; 1340 uids = new int[size]; 1341 int i = 0; // filling out the above arrays 1342 1343 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1344 int packageUserId = mPendingBroadcasts.userIdAt(n); 1345 Iterator<Map.Entry<String, ArrayList<String>>> it 1346 = mPendingBroadcasts.packagesForUserId(packageUserId) 1347 .entrySet().iterator(); 1348 while (it.hasNext() && i < size) { 1349 Map.Entry<String, ArrayList<String>> ent = it.next(); 1350 packages[i] = ent.getKey(); 1351 components[i] = ent.getValue(); 1352 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1353 uids[i] = (ps != null) 1354 ? UserHandle.getUid(packageUserId, ps.appId) 1355 : -1; 1356 i++; 1357 } 1358 } 1359 size = i; 1360 mPendingBroadcasts.clear(); 1361 } 1362 // Send broadcasts 1363 for (int i = 0; i < size; i++) { 1364 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1365 } 1366 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1367 break; 1368 } 1369 case START_CLEANING_PACKAGE: { 1370 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1371 final String packageName = (String)msg.obj; 1372 final int userId = msg.arg1; 1373 final boolean andCode = msg.arg2 != 0; 1374 synchronized (mPackages) { 1375 if (userId == UserHandle.USER_ALL) { 1376 int[] users = sUserManager.getUserIds(); 1377 for (int user : users) { 1378 mSettings.addPackageToCleanLPw( 1379 new PackageCleanItem(user, packageName, andCode)); 1380 } 1381 } else { 1382 mSettings.addPackageToCleanLPw( 1383 new PackageCleanItem(userId, packageName, andCode)); 1384 } 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 startCleaningPackages(); 1388 } break; 1389 case POST_INSTALL: { 1390 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1391 1392 PostInstallData data = mRunningInstalls.get(msg.arg1); 1393 final boolean didRestore = (msg.arg2 != 0); 1394 mRunningInstalls.delete(msg.arg1); 1395 1396 if (data != null) { 1397 InstallArgs args = data.args; 1398 PackageInstalledInfo parentRes = data.res; 1399 1400 final boolean grantPermissions = (args.installFlags 1401 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1402 final boolean killApp = (args.installFlags 1403 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1404 final String[] grantedPermissions = args.installGrantPermissions; 1405 1406 // Handle the parent package 1407 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1408 grantedPermissions, didRestore, args.installerPackageName, 1409 args.observer); 1410 1411 // Handle the child packages 1412 final int childCount = (parentRes.addedChildPackages != null) 1413 ? parentRes.addedChildPackages.size() : 0; 1414 for (int i = 0; i < childCount; i++) { 1415 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1416 handlePackagePostInstall(childRes, grantPermissions, killApp, 1417 grantedPermissions, false, args.installerPackageName, 1418 args.observer); 1419 } 1420 1421 // Log tracing if needed 1422 if (args.traceMethod != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1424 args.traceCookie); 1425 } 1426 } else { 1427 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1428 } 1429 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1431 } break; 1432 case UPDATED_MEDIA_STATUS: { 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1434 boolean reportStatus = msg.arg1 == 1; 1435 boolean doGc = msg.arg2 == 1; 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1437 if (doGc) { 1438 // Force a gc to clear up stale containers. 1439 Runtime.getRuntime().gc(); 1440 } 1441 if (msg.obj != null) { 1442 @SuppressWarnings("unchecked") 1443 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1445 // Unload containers 1446 unloadAllContainers(args); 1447 } 1448 if (reportStatus) { 1449 try { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1451 PackageHelper.getMountService().finishMediaUpdate(); 1452 } catch (RemoteException e) { 1453 Log.e(TAG, "MountService not running?"); 1454 } 1455 } 1456 } break; 1457 case WRITE_SETTINGS: { 1458 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1459 synchronized (mPackages) { 1460 removeMessages(WRITE_SETTINGS); 1461 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1462 mSettings.writeLPr(); 1463 mDirtyUsers.clear(); 1464 } 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1466 } break; 1467 case WRITE_PACKAGE_RESTRICTIONS: { 1468 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1469 synchronized (mPackages) { 1470 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1471 for (int userId : mDirtyUsers) { 1472 mSettings.writePackageRestrictionsLPr(userId); 1473 } 1474 mDirtyUsers.clear(); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 } break; 1478 case WRITE_PACKAGE_LIST: { 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1480 synchronized (mPackages) { 1481 removeMessages(WRITE_PACKAGE_LIST); 1482 mSettings.writePackageListLPr(msg.arg1); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 } break; 1486 case CHECK_PENDING_VERIFICATION: { 1487 final int verificationId = msg.arg1; 1488 final PackageVerificationState state = mPendingVerification.get(verificationId); 1489 1490 if ((state != null) && !state.timeoutExtended()) { 1491 final InstallArgs args = state.getInstallArgs(); 1492 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1493 1494 Slog.i(TAG, "Verification timed out for " + originUri); 1495 mPendingVerification.remove(verificationId); 1496 1497 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1498 1499 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1500 Slog.i(TAG, "Continuing with installation of " + originUri); 1501 state.setVerifierResponse(Binder.getCallingUid(), 1502 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1503 broadcastPackageVerified(verificationId, originUri, 1504 PackageManager.VERIFICATION_ALLOW, 1505 state.getInstallArgs().getUser()); 1506 try { 1507 ret = args.copyApk(mContainerService, true); 1508 } catch (RemoteException e) { 1509 Slog.e(TAG, "Could not contact the ContainerService"); 1510 } 1511 } else { 1512 broadcastPackageVerified(verificationId, originUri, 1513 PackageManager.VERIFICATION_REJECT, 1514 state.getInstallArgs().getUser()); 1515 } 1516 1517 Trace.asyncTraceEnd( 1518 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1519 1520 processPendingInstall(args, ret); 1521 mHandler.sendEmptyMessage(MCS_UNBIND); 1522 } 1523 break; 1524 } 1525 case PACKAGE_VERIFIED: { 1526 final int verificationId = msg.arg1; 1527 1528 final PackageVerificationState state = mPendingVerification.get(verificationId); 1529 if (state == null) { 1530 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1531 break; 1532 } 1533 1534 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1535 1536 state.setVerifierResponse(response.callerUid, response.code); 1537 1538 if (state.isVerificationComplete()) { 1539 mPendingVerification.remove(verificationId); 1540 1541 final InstallArgs args = state.getInstallArgs(); 1542 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1543 1544 int ret; 1545 if (state.isInstallAllowed()) { 1546 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1547 broadcastPackageVerified(verificationId, originUri, 1548 response.code, state.getInstallArgs().getUser()); 1549 try { 1550 ret = args.copyApk(mContainerService, true); 1551 } catch (RemoteException e) { 1552 Slog.e(TAG, "Could not contact the ContainerService"); 1553 } 1554 } else { 1555 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1556 } 1557 1558 Trace.asyncTraceEnd( 1559 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1560 1561 processPendingInstall(args, ret); 1562 mHandler.sendEmptyMessage(MCS_UNBIND); 1563 } 1564 1565 break; 1566 } 1567 case START_INTENT_FILTER_VERIFICATIONS: { 1568 IFVerificationParams params = (IFVerificationParams) msg.obj; 1569 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1570 params.replacing, params.pkg); 1571 break; 1572 } 1573 case INTENT_FILTER_VERIFIED: { 1574 final int verificationId = msg.arg1; 1575 1576 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1577 verificationId); 1578 if (state == null) { 1579 Slog.w(TAG, "Invalid IntentFilter verification token " 1580 + verificationId + " received"); 1581 break; 1582 } 1583 1584 final int userId = state.getUserId(); 1585 1586 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1587 "Processing IntentFilter verification with token:" 1588 + verificationId + " and userId:" + userId); 1589 1590 final IntentFilterVerificationResponse response = 1591 (IntentFilterVerificationResponse) msg.obj; 1592 1593 state.setVerifierResponse(response.callerUid, response.code); 1594 1595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1596 "IntentFilter verification with token:" + verificationId 1597 + " and userId:" + userId 1598 + " is settings verifier response with response code:" 1599 + response.code); 1600 1601 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1603 + response.getFailedDomainsString()); 1604 } 1605 1606 if (state.isVerificationComplete()) { 1607 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1608 } else { 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " was not said to be complete"); 1612 } 1613 1614 break; 1615 } 1616 } 1617 } 1618 } 1619 1620 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1621 boolean killApp, String[] grantedPermissions, 1622 boolean launchedForRestore, String installerPackage, 1623 IPackageInstallObserver2 installObserver) { 1624 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1625 // Send the removed broadcasts 1626 if (res.removedInfo != null) { 1627 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1628 } 1629 1630 // Now that we successfully installed the package, grant runtime 1631 // permissions if requested before broadcasting the install. 1632 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1633 >= Build.VERSION_CODES.M) { 1634 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1635 } 1636 1637 final boolean update = res.removedInfo != null 1638 && res.removedInfo.removedPackage != null; 1639 1640 // If this is the first time we have child packages for a disabled privileged 1641 // app that had no children, we grant requested runtime permissions to the new 1642 // children if the parent on the system image had them already granted. 1643 if (res.pkg.parentPackage != null) { 1644 synchronized (mPackages) { 1645 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1646 } 1647 } 1648 1649 synchronized (mPackages) { 1650 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1651 } 1652 1653 final String packageName = res.pkg.applicationInfo.packageName; 1654 Bundle extras = new Bundle(1); 1655 extras.putInt(Intent.EXTRA_UID, res.uid); 1656 1657 // Determine the set of users who are adding this package for 1658 // the first time vs. those who are seeing an update. 1659 int[] firstUsers = EMPTY_INT_ARRAY; 1660 int[] updateUsers = EMPTY_INT_ARRAY; 1661 if (res.origUsers == null || res.origUsers.length == 0) { 1662 firstUsers = res.newUsers; 1663 } else { 1664 for (int newUser : res.newUsers) { 1665 boolean isNew = true; 1666 for (int origUser : res.origUsers) { 1667 if (origUser == newUser) { 1668 isNew = false; 1669 break; 1670 } 1671 } 1672 if (isNew) { 1673 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1674 } else { 1675 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1676 } 1677 } 1678 } 1679 1680 // Send installed broadcasts if the install/update is not ephemeral 1681 if (!isEphemeral(res.pkg)) { 1682 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1683 1684 // Send added for users that see the package for the first time 1685 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1686 extras, 0 /*flags*/, null /*targetPackage*/, 1687 null /*finishedReceiver*/, firstUsers); 1688 1689 // Send added for users that don't see the package for the first time 1690 if (update) { 1691 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1692 } 1693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1694 extras, 0 /*flags*/, null /*targetPackage*/, 1695 null /*finishedReceiver*/, updateUsers); 1696 1697 // Send replaced for users that don't see the package for the first time 1698 if (update) { 1699 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1700 packageName, extras, 0 /*flags*/, 1701 null /*targetPackage*/, null /*finishedReceiver*/, 1702 updateUsers); 1703 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1704 null /*package*/, null /*extras*/, 0 /*flags*/, 1705 packageName /*targetPackage*/, 1706 null /*finishedReceiver*/, updateUsers); 1707 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1708 // First-install and we did a restore, so we're responsible for the 1709 // first-launch broadcast. 1710 if (DEBUG_BACKUP) { 1711 Slog.i(TAG, "Post-restore of " + packageName 1712 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1713 } 1714 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1715 } 1716 1717 // Send broadcast package appeared if forward locked/external for all users 1718 // treat asec-hosted packages like removable media on upgrade 1719 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1720 if (DEBUG_INSTALL) { 1721 Slog.i(TAG, "upgrading pkg " + res.pkg 1722 + " is ASEC-hosted -> AVAILABLE"); 1723 } 1724 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1725 ArrayList<String> pkgList = new ArrayList<>(1); 1726 pkgList.add(packageName); 1727 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1728 } 1729 } 1730 1731 // Work that needs to happen on first install within each user 1732 if (firstUsers != null && firstUsers.length > 0) { 1733 synchronized (mPackages) { 1734 for (int userId : firstUsers) { 1735 // If this app is a browser and it's newly-installed for some 1736 // users, clear any default-browser state in those users. The 1737 // app's nature doesn't depend on the user, so we can just check 1738 // its browser nature in any user and generalize. 1739 if (packageIsBrowser(packageName, userId)) { 1740 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1741 } 1742 1743 // We may also need to apply pending (restored) runtime 1744 // permission grants within these users. 1745 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1746 } 1747 } 1748 } 1749 1750 // Log current value of "unknown sources" setting 1751 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1752 getUnknownSourcesSettings()); 1753 1754 // Force a gc to clear up things 1755 Runtime.getRuntime().gc(); 1756 1757 // Remove the replaced package's older resources safely now 1758 // We delete after a gc for applications on sdcard. 1759 if (res.removedInfo != null && res.removedInfo.args != null) { 1760 synchronized (mInstallLock) { 1761 res.removedInfo.args.doPostDeleteLI(true); 1762 } 1763 } 1764 } 1765 1766 // If someone is watching installs - notify them 1767 if (installObserver != null) { 1768 try { 1769 Bundle extras = extrasForInstallResult(res); 1770 installObserver.onPackageInstalled(res.name, res.returnCode, 1771 res.returnMsg, extras); 1772 } catch (RemoteException e) { 1773 Slog.i(TAG, "Observer no longer exists."); 1774 } 1775 } 1776 } 1777 1778 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1779 PackageParser.Package pkg) { 1780 if (pkg.parentPackage == null) { 1781 return; 1782 } 1783 if (pkg.requestedPermissions == null) { 1784 return; 1785 } 1786 final PackageSetting disabledSysParentPs = mSettings 1787 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1788 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1789 || !disabledSysParentPs.isPrivileged() 1790 || (disabledSysParentPs.childPackageNames != null 1791 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1792 return; 1793 } 1794 final int[] allUserIds = sUserManager.getUserIds(); 1795 final int permCount = pkg.requestedPermissions.size(); 1796 for (int i = 0; i < permCount; i++) { 1797 String permission = pkg.requestedPermissions.get(i); 1798 BasePermission bp = mSettings.mPermissions.get(permission); 1799 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1800 continue; 1801 } 1802 for (int userId : allUserIds) { 1803 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1804 permission, userId)) { 1805 grantRuntimePermission(pkg.packageName, permission, userId); 1806 } 1807 } 1808 } 1809 } 1810 1811 private StorageEventListener mStorageListener = new StorageEventListener() { 1812 @Override 1813 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1814 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1815 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1816 final String volumeUuid = vol.getFsUuid(); 1817 1818 // Clean up any users or apps that were removed or recreated 1819 // while this volume was missing 1820 reconcileUsers(volumeUuid); 1821 reconcileApps(volumeUuid); 1822 1823 // Clean up any install sessions that expired or were 1824 // cancelled while this volume was missing 1825 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1826 1827 loadPrivatePackages(vol); 1828 1829 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1830 unloadPrivatePackages(vol); 1831 } 1832 } 1833 1834 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1835 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1836 updateExternalMediaStatus(true, false); 1837 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1838 updateExternalMediaStatus(false, false); 1839 } 1840 } 1841 } 1842 1843 @Override 1844 public void onVolumeForgotten(String fsUuid) { 1845 if (TextUtils.isEmpty(fsUuid)) { 1846 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1847 return; 1848 } 1849 1850 // Remove any apps installed on the forgotten volume 1851 synchronized (mPackages) { 1852 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1853 for (PackageSetting ps : packages) { 1854 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1855 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1856 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1857 } 1858 1859 mSettings.onVolumeForgotten(fsUuid); 1860 mSettings.writeLPr(); 1861 } 1862 } 1863 }; 1864 1865 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1866 String[] grantedPermissions) { 1867 for (int userId : userIds) { 1868 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1869 } 1870 1871 // We could have touched GID membership, so flush out packages.list 1872 synchronized (mPackages) { 1873 mSettings.writePackageListLPr(); 1874 } 1875 } 1876 1877 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1878 String[] grantedPermissions) { 1879 SettingBase sb = (SettingBase) pkg.mExtras; 1880 if (sb == null) { 1881 return; 1882 } 1883 1884 PermissionsState permissionsState = sb.getPermissionsState(); 1885 1886 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1887 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1888 1889 for (String permission : pkg.requestedPermissions) { 1890 final BasePermission bp; 1891 synchronized (mPackages) { 1892 bp = mSettings.mPermissions.get(permission); 1893 } 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 1906 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1907 Bundle extras = null; 1908 switch (res.returnCode) { 1909 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1910 extras = new Bundle(); 1911 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1912 res.origPermission); 1913 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1914 res.origPackage); 1915 break; 1916 } 1917 case PackageManager.INSTALL_SUCCEEDED: { 1918 extras = new Bundle(); 1919 extras.putBoolean(Intent.EXTRA_REPLACING, 1920 res.removedInfo != null && res.removedInfo.removedPackage != null); 1921 break; 1922 } 1923 } 1924 return extras; 1925 } 1926 1927 void scheduleWriteSettingsLocked() { 1928 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1929 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1930 } 1931 } 1932 1933 void scheduleWritePackageListLocked(int userId) { 1934 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1935 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1936 msg.arg1 = userId; 1937 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1938 } 1939 } 1940 1941 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1942 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1943 scheduleWritePackageRestrictionsLocked(userId); 1944 } 1945 1946 void scheduleWritePackageRestrictionsLocked(int userId) { 1947 final int[] userIds = (userId == UserHandle.USER_ALL) 1948 ? sUserManager.getUserIds() : new int[]{userId}; 1949 for (int nextUserId : userIds) { 1950 if (!sUserManager.exists(nextUserId)) return; 1951 mDirtyUsers.add(nextUserId); 1952 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1953 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1954 } 1955 } 1956 } 1957 1958 public static PackageManagerService main(Context context, Installer installer, 1959 boolean factoryTest, boolean onlyCore) { 1960 // Self-check for initial settings. 1961 PackageManagerServiceCompilerMapping.checkProperties(); 1962 1963 PackageManagerService m = new PackageManagerService(context, installer, 1964 factoryTest, onlyCore); 1965 m.enableSystemUserPackages(); 1966 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 1967 // disabled after already being started. 1968 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 1969 UserHandle.USER_SYSTEM); 1970 ServiceManager.addService("package", m); 1971 return m; 1972 } 1973 1974 private void enableSystemUserPackages() { 1975 if (!UserManager.isSplitSystemUser()) { 1976 return; 1977 } 1978 // For system user, enable apps based on the following conditions: 1979 // - app is whitelisted or belong to one of these groups: 1980 // -- system app which has no launcher icons 1981 // -- system app which has INTERACT_ACROSS_USERS permission 1982 // -- system IME app 1983 // - app is not in the blacklist 1984 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1985 Set<String> enableApps = new ArraySet<>(); 1986 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1987 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1988 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1989 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1990 enableApps.addAll(wlApps); 1991 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1992 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1993 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1994 enableApps.removeAll(blApps); 1995 Log.i(TAG, "Applications installed for system user: " + enableApps); 1996 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1997 UserHandle.SYSTEM); 1998 final int allAppsSize = allAps.size(); 1999 synchronized (mPackages) { 2000 for (int i = 0; i < allAppsSize; i++) { 2001 String pName = allAps.get(i); 2002 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2003 // Should not happen, but we shouldn't be failing if it does 2004 if (pkgSetting == null) { 2005 continue; 2006 } 2007 boolean install = enableApps.contains(pName); 2008 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2009 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2010 + " for system user"); 2011 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2012 } 2013 } 2014 } 2015 } 2016 2017 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2018 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2019 Context.DISPLAY_SERVICE); 2020 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2021 } 2022 2023 /** 2024 * Requests that files preopted on a secondary system partition be copied to the data partition 2025 * if possible. Note that the actual copying of the files is accomplished by init for security 2026 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2027 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2028 */ 2029 private static void requestCopyPreoptedFiles() { 2030 final int WAIT_TIME_MS = 100; 2031 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2032 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2033 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2034 // We will wait for up to 100 seconds. 2035 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2036 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2037 try { 2038 Thread.sleep(WAIT_TIME_MS); 2039 } catch (InterruptedException e) { 2040 // Do nothing 2041 } 2042 if (SystemClock.uptimeMillis() > timeEnd) { 2043 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2044 Slog.wtf(TAG, "cppreopt did not finish!"); 2045 break; 2046 } 2047 } 2048 } 2049 } 2050 2051 public PackageManagerService(Context context, Installer installer, 2052 boolean factoryTest, boolean onlyCore) { 2053 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2054 SystemClock.uptimeMillis()); 2055 2056 if (mSdkVersion <= 0) { 2057 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2058 } 2059 2060 mContext = context; 2061 mFactoryTest = factoryTest; 2062 mOnlyCore = onlyCore; 2063 mMetrics = new DisplayMetrics(); 2064 mSettings = new Settings(mPackages); 2065 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2066 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2067 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2068 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2069 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2070 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2071 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2072 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2073 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2074 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2075 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2076 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2077 2078 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2079 if (separateProcesses != null && separateProcesses.length() > 0) { 2080 if ("*".equals(separateProcesses)) { 2081 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2082 mSeparateProcesses = null; 2083 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2084 } else { 2085 mDefParseFlags = 0; 2086 mSeparateProcesses = separateProcesses.split(","); 2087 Slog.w(TAG, "Running with debug.separate_processes: " 2088 + separateProcesses); 2089 } 2090 } else { 2091 mDefParseFlags = 0; 2092 mSeparateProcesses = null; 2093 } 2094 2095 mInstaller = installer; 2096 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2097 "*dexopt*"); 2098 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2099 2100 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2101 FgThread.get().getLooper()); 2102 2103 getDefaultDisplayMetrics(context, mMetrics); 2104 2105 SystemConfig systemConfig = SystemConfig.getInstance(); 2106 mGlobalGids = systemConfig.getGlobalGids(); 2107 mSystemPermissions = systemConfig.getSystemPermissions(); 2108 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2109 2110 mProtectedPackages = new ProtectedPackages(mContext); 2111 2112 synchronized (mInstallLock) { 2113 // writer 2114 synchronized (mPackages) { 2115 mHandlerThread = new ServiceThread(TAG, 2116 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2117 mHandlerThread.start(); 2118 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2119 mProcessLoggingHandler = new ProcessLoggingHandler(); 2120 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2121 2122 File dataDir = Environment.getDataDirectory(); 2123 mAppInstallDir = new File(dataDir, "app"); 2124 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2125 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2126 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2127 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2128 2129 sUserManager = new UserManagerService(context, this, mPackages); 2130 2131 // Propagate permission configuration in to package manager. 2132 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2133 = systemConfig.getPermissions(); 2134 for (int i=0; i<permConfig.size(); i++) { 2135 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2136 BasePermission bp = mSettings.mPermissions.get(perm.name); 2137 if (bp == null) { 2138 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2139 mSettings.mPermissions.put(perm.name, bp); 2140 } 2141 if (perm.gids != null) { 2142 bp.setGids(perm.gids, perm.perUser); 2143 } 2144 } 2145 2146 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2147 for (int i=0; i<libConfig.size(); i++) { 2148 mSharedLibraries.put(libConfig.keyAt(i), 2149 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2150 } 2151 2152 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2153 2154 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2155 2156 if (mFirstBoot) { 2157 requestCopyPreoptedFiles(); 2158 } 2159 2160 String customResolverActivity = Resources.getSystem().getString( 2161 R.string.config_customResolverActivity); 2162 if (TextUtils.isEmpty(customResolverActivity)) { 2163 customResolverActivity = null; 2164 } else { 2165 mCustomResolverComponentName = ComponentName.unflattenFromString( 2166 customResolverActivity); 2167 } 2168 2169 long startTime = SystemClock.uptimeMillis(); 2170 2171 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2172 startTime); 2173 2174 // Set flag to monitor and not change apk file paths when 2175 // scanning install directories. 2176 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2177 2178 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2179 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2180 2181 if (bootClassPath == null) { 2182 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2183 } 2184 2185 if (systemServerClassPath == null) { 2186 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2187 } 2188 2189 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2190 final String[] dexCodeInstructionSets = 2191 getDexCodeInstructionSets( 2192 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2193 2194 /** 2195 * Ensure all external libraries have had dexopt run on them. 2196 */ 2197 if (mSharedLibraries.size() > 0) { 2198 // NOTE: For now, we're compiling these system "shared libraries" 2199 // (and framework jars) into all available architectures. It's possible 2200 // to compile them only when we come across an app that uses them (there's 2201 // already logic for that in scanPackageLI) but that adds some complexity. 2202 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2203 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2204 final String lib = libEntry.path; 2205 if (lib == null) { 2206 continue; 2207 } 2208 2209 try { 2210 // Shared libraries do not have profiles so we perform a full 2211 // AOT compilation (if needed). 2212 int dexoptNeeded = DexFile.getDexOptNeeded( 2213 lib, dexCodeInstructionSet, 2214 getCompilerFilterForReason(REASON_SHARED_APK), 2215 false /* newProfile */); 2216 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2217 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2218 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2219 getCompilerFilterForReason(REASON_SHARED_APK), 2220 StorageManager.UUID_PRIVATE_INTERNAL, 2221 SKIP_SHARED_LIBRARY_CHECK); 2222 } 2223 } catch (FileNotFoundException e) { 2224 Slog.w(TAG, "Library not found: " + lib); 2225 } catch (IOException | InstallerException e) { 2226 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2227 + e.getMessage()); 2228 } 2229 } 2230 } 2231 } 2232 2233 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2234 2235 final VersionInfo ver = mSettings.getInternalVersion(); 2236 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2237 2238 // when upgrading from pre-M, promote system app permissions from install to runtime 2239 mPromoteSystemApps = 2240 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2241 2242 // When upgrading from pre-N, we need to handle package extraction like first boot, 2243 // as there is no profiling data available. 2244 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2245 2246 // save off the names of pre-existing system packages prior to scanning; we don't 2247 // want to automatically grant runtime permissions for new system apps 2248 if (mPromoteSystemApps) { 2249 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2250 while (pkgSettingIter.hasNext()) { 2251 PackageSetting ps = pkgSettingIter.next(); 2252 if (isSystemApp(ps)) { 2253 mExistingSystemPackages.add(ps.name); 2254 } 2255 } 2256 } 2257 2258 // Collect vendor overlay packages. 2259 // (Do this before scanning any apps.) 2260 // For security and version matching reason, only consider 2261 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2262 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2263 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2264 | PackageParser.PARSE_IS_SYSTEM 2265 | PackageParser.PARSE_IS_SYSTEM_DIR 2266 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2267 2268 // Find base frameworks (resource packages without code). 2269 scanDirTracedLI(frameworkDir, mDefParseFlags 2270 | PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR 2272 | PackageParser.PARSE_IS_PRIVILEGED, 2273 scanFlags | SCAN_NO_DEX, 0); 2274 2275 // Collected privileged system packages. 2276 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2277 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2278 | PackageParser.PARSE_IS_SYSTEM 2279 | PackageParser.PARSE_IS_SYSTEM_DIR 2280 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2281 2282 // Collect ordinary system packages. 2283 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2284 scanDirTracedLI(systemAppDir, mDefParseFlags 2285 | PackageParser.PARSE_IS_SYSTEM 2286 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2287 2288 // Collect all vendor packages. 2289 File vendorAppDir = new File("/vendor/app"); 2290 try { 2291 vendorAppDir = vendorAppDir.getCanonicalFile(); 2292 } catch (IOException e) { 2293 // failed to look up canonical path, continue with original one 2294 } 2295 scanDirTracedLI(vendorAppDir, mDefParseFlags 2296 | PackageParser.PARSE_IS_SYSTEM 2297 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2298 2299 // Collect all OEM packages. 2300 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2301 scanDirTracedLI(oemAppDir, mDefParseFlags 2302 | PackageParser.PARSE_IS_SYSTEM 2303 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2304 2305 // Prune any system packages that no longer exist. 2306 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2307 if (!mOnlyCore) { 2308 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2309 while (psit.hasNext()) { 2310 PackageSetting ps = psit.next(); 2311 2312 /* 2313 * If this is not a system app, it can't be a 2314 * disable system app. 2315 */ 2316 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2317 continue; 2318 } 2319 2320 /* 2321 * If the package is scanned, it's not erased. 2322 */ 2323 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2324 if (scannedPkg != null) { 2325 /* 2326 * If the system app is both scanned and in the 2327 * disabled packages list, then it must have been 2328 * added via OTA. Remove it from the currently 2329 * scanned package so the previously user-installed 2330 * application can be scanned. 2331 */ 2332 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2333 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2334 + ps.name + "; removing system app. Last known codePath=" 2335 + ps.codePathString + ", installStatus=" + ps.installStatus 2336 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2337 + scannedPkg.mVersionCode); 2338 removePackageLI(scannedPkg, true); 2339 mExpectingBetter.put(ps.name, ps.codePath); 2340 } 2341 2342 continue; 2343 } 2344 2345 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2346 psit.remove(); 2347 logCriticalInfo(Log.WARN, "System package " + ps.name 2348 + " no longer exists; it's data will be wiped"); 2349 // Actual deletion of code and data will be handled by later 2350 // reconciliation step 2351 } else { 2352 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2353 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2354 possiblyDeletedUpdatedSystemApps.add(ps.name); 2355 } 2356 } 2357 } 2358 } 2359 2360 //look for any incomplete package installations 2361 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2362 for (int i = 0; i < deletePkgsList.size(); i++) { 2363 // Actual deletion of code and data will be handled by later 2364 // reconciliation step 2365 final String packageName = deletePkgsList.get(i).name; 2366 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2367 synchronized (mPackages) { 2368 mSettings.removePackageLPw(packageName); 2369 } 2370 } 2371 2372 //delete tmp files 2373 deleteTempPackageFiles(); 2374 2375 // Remove any shared userIDs that have no associated packages 2376 mSettings.pruneSharedUsersLPw(); 2377 2378 if (!mOnlyCore) { 2379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2380 SystemClock.uptimeMillis()); 2381 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2382 2383 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2384 | PackageParser.PARSE_FORWARD_LOCK, 2385 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2386 2387 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2388 | PackageParser.PARSE_IS_EPHEMERAL, 2389 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2390 2391 /** 2392 * Remove disable package settings for any updated system 2393 * apps that were removed via an OTA. If they're not a 2394 * previously-updated app, remove them completely. 2395 * Otherwise, just revoke their system-level permissions. 2396 */ 2397 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2398 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2399 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2400 2401 String msg; 2402 if (deletedPkg == null) { 2403 msg = "Updated system package " + deletedAppName 2404 + " no longer exists; it's data will be wiped"; 2405 // Actual deletion of code and data will be handled by later 2406 // reconciliation step 2407 } else { 2408 msg = "Updated system app + " + deletedAppName 2409 + " no longer present; removing system privileges for " 2410 + deletedAppName; 2411 2412 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2413 2414 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2415 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2416 } 2417 logCriticalInfo(Log.WARN, msg); 2418 } 2419 2420 /** 2421 * Make sure all system apps that we expected to appear on 2422 * the userdata partition actually showed up. If they never 2423 * appeared, crawl back and revive the system version. 2424 */ 2425 for (int i = 0; i < mExpectingBetter.size(); i++) { 2426 final String packageName = mExpectingBetter.keyAt(i); 2427 if (!mPackages.containsKey(packageName)) { 2428 final File scanFile = mExpectingBetter.valueAt(i); 2429 2430 logCriticalInfo(Log.WARN, "Expected better " + packageName 2431 + " but never showed up; reverting to system"); 2432 2433 int reparseFlags = mDefParseFlags; 2434 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2435 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED; 2438 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2439 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR; 2441 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2442 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR; 2444 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2445 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2446 | PackageParser.PARSE_IS_SYSTEM_DIR; 2447 } else { 2448 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2449 continue; 2450 } 2451 2452 mSettings.enableSystemPackageLPw(packageName); 2453 2454 try { 2455 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2456 } catch (PackageManagerException e) { 2457 Slog.e(TAG, "Failed to parse original system package: " 2458 + e.getMessage()); 2459 } 2460 } 2461 } 2462 } 2463 mExpectingBetter.clear(); 2464 2465 // Resolve protected action filters. Only the setup wizard is allowed to 2466 // have a high priority filter for these actions. 2467 mSetupWizardPackage = getSetupWizardPackageName(); 2468 if (mProtectedFilters.size() > 0) { 2469 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2470 Slog.i(TAG, "No setup wizard;" 2471 + " All protected intents capped to priority 0"); 2472 } 2473 for (ActivityIntentInfo filter : mProtectedFilters) { 2474 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2475 if (DEBUG_FILTERS) { 2476 Slog.i(TAG, "Found setup wizard;" 2477 + " allow priority " + filter.getPriority() + ";" 2478 + " package: " + filter.activity.info.packageName 2479 + " activity: " + filter.activity.className 2480 + " priority: " + filter.getPriority()); 2481 } 2482 // skip setup wizard; allow it to keep the high priority filter 2483 continue; 2484 } 2485 Slog.w(TAG, "Protected action; cap priority to 0;" 2486 + " package: " + filter.activity.info.packageName 2487 + " activity: " + filter.activity.className 2488 + " origPrio: " + filter.getPriority()); 2489 filter.setPriority(0); 2490 } 2491 } 2492 mDeferProtectedFilters = false; 2493 mProtectedFilters.clear(); 2494 2495 // Now that we know all of the shared libraries, update all clients to have 2496 // the correct library paths. 2497 updateAllSharedLibrariesLPw(); 2498 2499 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2500 // NOTE: We ignore potential failures here during a system scan (like 2501 // the rest of the commands above) because there's precious little we 2502 // can do about it. A settings error is reported, though. 2503 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2504 false /* boot complete */); 2505 } 2506 2507 // Now that we know all the packages we are keeping, 2508 // read and update their last usage times. 2509 mPackageUsage.read(mPackages); 2510 mCompilerStats.read(); 2511 2512 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2513 SystemClock.uptimeMillis()); 2514 Slog.i(TAG, "Time to scan packages: " 2515 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2516 + " seconds"); 2517 2518 // If the platform SDK has changed since the last time we booted, 2519 // we need to re-grant app permission to catch any new ones that 2520 // appear. This is really a hack, and means that apps can in some 2521 // cases get permissions that the user didn't initially explicitly 2522 // allow... it would be nice to have some better way to handle 2523 // this situation. 2524 int updateFlags = UPDATE_PERMISSIONS_ALL; 2525 if (ver.sdkVersion != mSdkVersion) { 2526 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2527 + mSdkVersion + "; regranting permissions for internal storage"); 2528 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2529 } 2530 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2531 ver.sdkVersion = mSdkVersion; 2532 2533 // If this is the first boot or an update from pre-M, and it is a normal 2534 // boot, then we need to initialize the default preferred apps across 2535 // all defined users. 2536 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2537 for (UserInfo user : sUserManager.getUsers(true)) { 2538 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2539 applyFactoryDefaultBrowserLPw(user.id); 2540 primeDomainVerificationsLPw(user.id); 2541 } 2542 } 2543 2544 // Prepare storage for system user really early during boot, 2545 // since core system apps like SettingsProvider and SystemUI 2546 // can't wait for user to start 2547 final int storageFlags; 2548 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2549 storageFlags = StorageManager.FLAG_STORAGE_DE; 2550 } else { 2551 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2552 } 2553 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2554 storageFlags); 2555 2556 // If this is first boot after an OTA, and a normal boot, then 2557 // we need to clear code cache directories. 2558 // Note that we do *not* clear the application profiles. These remain valid 2559 // across OTAs and are used to drive profile verification (post OTA) and 2560 // profile compilation (without waiting to collect a fresh set of profiles). 2561 if (mIsUpgrade && !onlyCore) { 2562 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2563 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2564 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2565 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2566 // No apps are running this early, so no need to freeze 2567 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2568 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2569 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2570 } 2571 } 2572 ver.fingerprint = Build.FINGERPRINT; 2573 } 2574 2575 checkDefaultBrowser(); 2576 2577 // clear only after permissions and other defaults have been updated 2578 mExistingSystemPackages.clear(); 2579 mPromoteSystemApps = false; 2580 2581 // All the changes are done during package scanning. 2582 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2583 2584 // can downgrade to reader 2585 mSettings.writeLPr(); 2586 2587 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2588 // early on (before the package manager declares itself as early) because other 2589 // components in the system server might ask for package contexts for these apps. 2590 // 2591 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2592 // (i.e, that the data partition is unavailable). 2593 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2594 long start = System.nanoTime(); 2595 List<PackageParser.Package> coreApps = new ArrayList<>(); 2596 for (PackageParser.Package pkg : mPackages.values()) { 2597 if (pkg.coreApp) { 2598 coreApps.add(pkg); 2599 } 2600 } 2601 2602 int[] stats = performDexOptUpgrade(coreApps, false, 2603 getCompilerFilterForReason(REASON_CORE_APP)); 2604 2605 final int elapsedTimeSeconds = 2606 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2607 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2608 2609 if (DEBUG_DEXOPT) { 2610 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2611 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2612 } 2613 2614 2615 // TODO: Should we log these stats to tron too ? 2616 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2617 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2618 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2619 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2620 } 2621 2622 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2623 SystemClock.uptimeMillis()); 2624 2625 if (!mOnlyCore) { 2626 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2627 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2628 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2629 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2630 mIntentFilterVerifierComponent); 2631 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2632 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2633 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2634 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2635 } else { 2636 mRequiredVerifierPackage = null; 2637 mRequiredInstallerPackage = null; 2638 mIntentFilterVerifierComponent = null; 2639 mIntentFilterVerifier = null; 2640 mServicesSystemSharedLibraryPackageName = null; 2641 mSharedSystemSharedLibraryPackageName = null; 2642 } 2643 2644 mInstallerService = new PackageInstallerService(context, this); 2645 2646 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2647 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2648 // both the installer and resolver must be present to enable ephemeral 2649 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2650 if (DEBUG_EPHEMERAL) { 2651 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2652 + " installer:" + ephemeralInstallerComponent); 2653 } 2654 mEphemeralResolverComponent = ephemeralResolverComponent; 2655 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2656 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2657 mEphemeralResolverConnection = 2658 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2659 } else { 2660 if (DEBUG_EPHEMERAL) { 2661 final String missingComponent = 2662 (ephemeralResolverComponent == null) 2663 ? (ephemeralInstallerComponent == null) 2664 ? "resolver and installer" 2665 : "resolver" 2666 : "installer"; 2667 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2668 } 2669 mEphemeralResolverComponent = null; 2670 mEphemeralInstallerComponent = null; 2671 mEphemeralResolverConnection = null; 2672 } 2673 2674 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2675 } // synchronized (mPackages) 2676 } // synchronized (mInstallLock) 2677 2678 // Now after opening every single application zip, make sure they 2679 // are all flushed. Not really needed, but keeps things nice and 2680 // tidy. 2681 Runtime.getRuntime().gc(); 2682 2683 // The initial scanning above does many calls into installd while 2684 // holding the mPackages lock, but we're mostly interested in yelling 2685 // once we have a booted system. 2686 mInstaller.setWarnIfHeld(mPackages); 2687 2688 // Expose private service for system components to use. 2689 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2690 } 2691 2692 @Override 2693 public boolean isFirstBoot() { 2694 return mFirstBoot; 2695 } 2696 2697 @Override 2698 public boolean isOnlyCoreApps() { 2699 return mOnlyCore; 2700 } 2701 2702 @Override 2703 public boolean isUpgrade() { 2704 return mIsUpgrade; 2705 } 2706 2707 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2708 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2709 2710 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2711 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2712 UserHandle.USER_SYSTEM); 2713 if (matches.size() == 1) { 2714 return matches.get(0).getComponentInfo().packageName; 2715 } else { 2716 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2717 return null; 2718 } 2719 } 2720 2721 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2722 synchronized (mPackages) { 2723 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2724 if (libraryEntry == null) { 2725 throw new IllegalStateException("Missing required shared library:" + libraryName); 2726 } 2727 return libraryEntry.apk; 2728 } 2729 } 2730 2731 private @NonNull String getRequiredInstallerLPr() { 2732 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2733 intent.addCategory(Intent.CATEGORY_DEFAULT); 2734 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2735 2736 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2737 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2738 UserHandle.USER_SYSTEM); 2739 if (matches.size() == 1) { 2740 ResolveInfo resolveInfo = matches.get(0); 2741 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2742 throw new RuntimeException("The installer must be a privileged app"); 2743 } 2744 return matches.get(0).getComponentInfo().packageName; 2745 } else { 2746 throw new RuntimeException("There must be exactly one installer; found " + matches); 2747 } 2748 } 2749 2750 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2751 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2752 2753 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2754 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2755 UserHandle.USER_SYSTEM); 2756 ResolveInfo best = null; 2757 final int N = matches.size(); 2758 for (int i = 0; i < N; i++) { 2759 final ResolveInfo cur = matches.get(i); 2760 final String packageName = cur.getComponentInfo().packageName; 2761 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2762 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2763 continue; 2764 } 2765 2766 if (best == null || cur.priority > best.priority) { 2767 best = cur; 2768 } 2769 } 2770 2771 if (best != null) { 2772 return best.getComponentInfo().getComponentName(); 2773 } else { 2774 throw new RuntimeException("There must be at least one intent filter verifier"); 2775 } 2776 } 2777 2778 private @Nullable ComponentName getEphemeralResolverLPr() { 2779 final String[] packageArray = 2780 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2781 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2782 if (DEBUG_EPHEMERAL) { 2783 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2784 } 2785 return null; 2786 } 2787 2788 final int resolveFlags = 2789 MATCH_DIRECT_BOOT_AWARE 2790 | MATCH_DIRECT_BOOT_UNAWARE 2791 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2792 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2793 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2794 resolveFlags, UserHandle.USER_SYSTEM); 2795 2796 final int N = resolvers.size(); 2797 if (N == 0) { 2798 if (DEBUG_EPHEMERAL) { 2799 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2800 } 2801 return null; 2802 } 2803 2804 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2805 for (int i = 0; i < N; i++) { 2806 final ResolveInfo info = resolvers.get(i); 2807 2808 if (info.serviceInfo == null) { 2809 continue; 2810 } 2811 2812 final String packageName = info.serviceInfo.packageName; 2813 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2814 if (DEBUG_EPHEMERAL) { 2815 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2816 + " pkg: " + packageName + ", info:" + info); 2817 } 2818 continue; 2819 } 2820 2821 if (DEBUG_EPHEMERAL) { 2822 Slog.v(TAG, "Ephemeral resolver found;" 2823 + " pkg: " + packageName + ", info:" + info); 2824 } 2825 return new ComponentName(packageName, info.serviceInfo.name); 2826 } 2827 if (DEBUG_EPHEMERAL) { 2828 Slog.v(TAG, "Ephemeral resolver NOT found"); 2829 } 2830 return null; 2831 } 2832 2833 private @Nullable ComponentName getEphemeralInstallerLPr() { 2834 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2835 intent.addCategory(Intent.CATEGORY_DEFAULT); 2836 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2837 2838 final int resolveFlags = 2839 MATCH_DIRECT_BOOT_AWARE 2840 | MATCH_DIRECT_BOOT_UNAWARE 2841 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2842 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2843 resolveFlags, UserHandle.USER_SYSTEM); 2844 if (matches.size() == 0) { 2845 return null; 2846 } else if (matches.size() == 1) { 2847 return matches.get(0).getComponentInfo().getComponentName(); 2848 } else { 2849 throw new RuntimeException( 2850 "There must be at most one ephemeral installer; found " + matches); 2851 } 2852 } 2853 2854 private void primeDomainVerificationsLPw(int userId) { 2855 if (DEBUG_DOMAIN_VERIFICATION) { 2856 Slog.d(TAG, "Priming domain verifications in user " + userId); 2857 } 2858 2859 SystemConfig systemConfig = SystemConfig.getInstance(); 2860 ArraySet<String> packages = systemConfig.getLinkedApps(); 2861 ArraySet<String> domains = new ArraySet<String>(); 2862 2863 for (String packageName : packages) { 2864 PackageParser.Package pkg = mPackages.get(packageName); 2865 if (pkg != null) { 2866 if (!pkg.isSystemApp()) { 2867 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2868 continue; 2869 } 2870 2871 domains.clear(); 2872 for (PackageParser.Activity a : pkg.activities) { 2873 for (ActivityIntentInfo filter : a.intents) { 2874 if (hasValidDomains(filter)) { 2875 domains.addAll(filter.getHostsList()); 2876 } 2877 } 2878 } 2879 2880 if (domains.size() > 0) { 2881 if (DEBUG_DOMAIN_VERIFICATION) { 2882 Slog.v(TAG, " + " + packageName); 2883 } 2884 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2885 // state w.r.t. the formal app-linkage "no verification attempted" state; 2886 // and then 'always' in the per-user state actually used for intent resolution. 2887 final IntentFilterVerificationInfo ivi; 2888 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2889 new ArrayList<String>(domains)); 2890 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2891 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2892 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2893 } else { 2894 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2895 + "' does not handle web links"); 2896 } 2897 } else { 2898 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2899 } 2900 } 2901 2902 scheduleWritePackageRestrictionsLocked(userId); 2903 scheduleWriteSettingsLocked(); 2904 } 2905 2906 private void applyFactoryDefaultBrowserLPw(int userId) { 2907 // The default browser app's package name is stored in a string resource, 2908 // with a product-specific overlay used for vendor customization. 2909 String browserPkg = mContext.getResources().getString( 2910 com.android.internal.R.string.default_browser); 2911 if (!TextUtils.isEmpty(browserPkg)) { 2912 // non-empty string => required to be a known package 2913 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2914 if (ps == null) { 2915 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2916 browserPkg = null; 2917 } else { 2918 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2919 } 2920 } 2921 2922 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2923 // default. If there's more than one, just leave everything alone. 2924 if (browserPkg == null) { 2925 calculateDefaultBrowserLPw(userId); 2926 } 2927 } 2928 2929 private void calculateDefaultBrowserLPw(int userId) { 2930 List<String> allBrowsers = resolveAllBrowserApps(userId); 2931 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2932 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2933 } 2934 2935 private List<String> resolveAllBrowserApps(int userId) { 2936 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2937 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2938 PackageManager.MATCH_ALL, userId); 2939 2940 final int count = list.size(); 2941 List<String> result = new ArrayList<String>(count); 2942 for (int i=0; i<count; i++) { 2943 ResolveInfo info = list.get(i); 2944 if (info.activityInfo == null 2945 || !info.handleAllWebDataURI 2946 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2947 || result.contains(info.activityInfo.packageName)) { 2948 continue; 2949 } 2950 result.add(info.activityInfo.packageName); 2951 } 2952 2953 return result; 2954 } 2955 2956 private boolean packageIsBrowser(String packageName, int userId) { 2957 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2958 PackageManager.MATCH_ALL, userId); 2959 final int N = list.size(); 2960 for (int i = 0; i < N; i++) { 2961 ResolveInfo info = list.get(i); 2962 if (packageName.equals(info.activityInfo.packageName)) { 2963 return true; 2964 } 2965 } 2966 return false; 2967 } 2968 2969 private void checkDefaultBrowser() { 2970 final int myUserId = UserHandle.myUserId(); 2971 final String packageName = getDefaultBrowserPackageName(myUserId); 2972 if (packageName != null) { 2973 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2974 if (info == null) { 2975 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2976 synchronized (mPackages) { 2977 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2978 } 2979 } 2980 } 2981 } 2982 2983 @Override 2984 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2985 throws RemoteException { 2986 try { 2987 return super.onTransact(code, data, reply, flags); 2988 } catch (RuntimeException e) { 2989 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2990 Slog.wtf(TAG, "Package Manager Crash", e); 2991 } 2992 throw e; 2993 } 2994 } 2995 2996 static int[] appendInts(int[] cur, int[] add) { 2997 if (add == null) return cur; 2998 if (cur == null) return add; 2999 final int N = add.length; 3000 for (int i=0; i<N; i++) { 3001 cur = appendInt(cur, add[i]); 3002 } 3003 return cur; 3004 } 3005 3006 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3007 if (!sUserManager.exists(userId)) return null; 3008 if (ps == null) { 3009 return null; 3010 } 3011 final PackageParser.Package p = ps.pkg; 3012 if (p == null) { 3013 return null; 3014 } 3015 3016 final PermissionsState permissionsState = ps.getPermissionsState(); 3017 3018 // Compute GIDs only if requested 3019 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3020 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3021 // Compute granted permissions only if package has requested permissions 3022 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3023 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3024 final PackageUserState state = ps.readUserState(userId); 3025 3026 return PackageParser.generatePackageInfo(p, gids, flags, 3027 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3028 } 3029 3030 @Override 3031 public void checkPackageStartable(String packageName, int userId) { 3032 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3033 3034 synchronized (mPackages) { 3035 final PackageSetting ps = mSettings.mPackages.get(packageName); 3036 if (ps == null) { 3037 throw new SecurityException("Package " + packageName + " was not found!"); 3038 } 3039 3040 if (!ps.getInstalled(userId)) { 3041 throw new SecurityException( 3042 "Package " + packageName + " was not installed for user " + userId + "!"); 3043 } 3044 3045 if (mSafeMode && !ps.isSystem()) { 3046 throw new SecurityException("Package " + packageName + " not a system app!"); 3047 } 3048 3049 if (mFrozenPackages.contains(packageName)) { 3050 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3051 } 3052 3053 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3054 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3055 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3056 } 3057 } 3058 } 3059 3060 @Override 3061 public boolean isPackageAvailable(String packageName, int userId) { 3062 if (!sUserManager.exists(userId)) return false; 3063 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3064 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3065 synchronized (mPackages) { 3066 PackageParser.Package p = mPackages.get(packageName); 3067 if (p != null) { 3068 final PackageSetting ps = (PackageSetting) p.mExtras; 3069 if (ps != null) { 3070 final PackageUserState state = ps.readUserState(userId); 3071 if (state != null) { 3072 return PackageParser.isAvailable(state); 3073 } 3074 } 3075 } 3076 } 3077 return false; 3078 } 3079 3080 @Override 3081 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3082 if (!sUserManager.exists(userId)) return null; 3083 flags = updateFlagsForPackage(flags, userId, packageName); 3084 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3085 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3086 // reader 3087 synchronized (mPackages) { 3088 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3089 PackageParser.Package p = null; 3090 if (matchFactoryOnly) { 3091 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3092 if (ps != null) { 3093 return generatePackageInfo(ps, flags, userId); 3094 } 3095 } 3096 if (p == null) { 3097 p = mPackages.get(packageName); 3098 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3099 return null; 3100 } 3101 } 3102 if (DEBUG_PACKAGE_INFO) 3103 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3104 if (p != null) { 3105 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3106 } 3107 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3108 final PackageSetting ps = mSettings.mPackages.get(packageName); 3109 return generatePackageInfo(ps, flags, userId); 3110 } 3111 } 3112 return null; 3113 } 3114 3115 @Override 3116 public String[] currentToCanonicalPackageNames(String[] names) { 3117 String[] out = new String[names.length]; 3118 // reader 3119 synchronized (mPackages) { 3120 for (int i=names.length-1; i>=0; i--) { 3121 PackageSetting ps = mSettings.mPackages.get(names[i]); 3122 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3123 } 3124 } 3125 return out; 3126 } 3127 3128 @Override 3129 public String[] canonicalToCurrentPackageNames(String[] names) { 3130 String[] out = new String[names.length]; 3131 // reader 3132 synchronized (mPackages) { 3133 for (int i=names.length-1; i>=0; i--) { 3134 String cur = mSettings.mRenamedPackages.get(names[i]); 3135 out[i] = cur != null ? cur : names[i]; 3136 } 3137 } 3138 return out; 3139 } 3140 3141 @Override 3142 public int getPackageUid(String packageName, int flags, int userId) { 3143 if (!sUserManager.exists(userId)) return -1; 3144 flags = updateFlagsForPackage(flags, userId, packageName); 3145 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3146 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3147 3148 // reader 3149 synchronized (mPackages) { 3150 final PackageParser.Package p = mPackages.get(packageName); 3151 if (p != null && p.isMatch(flags)) { 3152 return UserHandle.getUid(userId, p.applicationInfo.uid); 3153 } 3154 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3155 final PackageSetting ps = mSettings.mPackages.get(packageName); 3156 if (ps != null && ps.isMatch(flags)) { 3157 return UserHandle.getUid(userId, ps.appId); 3158 } 3159 } 3160 } 3161 3162 return -1; 3163 } 3164 3165 @Override 3166 public int[] getPackageGids(String packageName, int flags, int userId) { 3167 if (!sUserManager.exists(userId)) return null; 3168 flags = updateFlagsForPackage(flags, userId, packageName); 3169 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3170 false /* requireFullPermission */, false /* checkShell */, 3171 "getPackageGids"); 3172 3173 // reader 3174 synchronized (mPackages) { 3175 final PackageParser.Package p = mPackages.get(packageName); 3176 if (p != null && p.isMatch(flags)) { 3177 PackageSetting ps = (PackageSetting) p.mExtras; 3178 return ps.getPermissionsState().computeGids(userId); 3179 } 3180 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3181 final PackageSetting ps = mSettings.mPackages.get(packageName); 3182 if (ps != null && ps.isMatch(flags)) { 3183 return ps.getPermissionsState().computeGids(userId); 3184 } 3185 } 3186 } 3187 3188 return null; 3189 } 3190 3191 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3192 if (bp.perm != null) { 3193 return PackageParser.generatePermissionInfo(bp.perm, flags); 3194 } 3195 PermissionInfo pi = new PermissionInfo(); 3196 pi.name = bp.name; 3197 pi.packageName = bp.sourcePackage; 3198 pi.nonLocalizedLabel = bp.name; 3199 pi.protectionLevel = bp.protectionLevel; 3200 return pi; 3201 } 3202 3203 @Override 3204 public PermissionInfo getPermissionInfo(String name, int flags) { 3205 // reader 3206 synchronized (mPackages) { 3207 final BasePermission p = mSettings.mPermissions.get(name); 3208 if (p != null) { 3209 return generatePermissionInfo(p, flags); 3210 } 3211 return null; 3212 } 3213 } 3214 3215 @Override 3216 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3217 int flags) { 3218 // reader 3219 synchronized (mPackages) { 3220 if (group != null && !mPermissionGroups.containsKey(group)) { 3221 // This is thrown as NameNotFoundException 3222 return null; 3223 } 3224 3225 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3226 for (BasePermission p : mSettings.mPermissions.values()) { 3227 if (group == null) { 3228 if (p.perm == null || p.perm.info.group == null) { 3229 out.add(generatePermissionInfo(p, flags)); 3230 } 3231 } else { 3232 if (p.perm != null && group.equals(p.perm.info.group)) { 3233 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3234 } 3235 } 3236 } 3237 return new ParceledListSlice<>(out); 3238 } 3239 } 3240 3241 @Override 3242 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3243 // reader 3244 synchronized (mPackages) { 3245 return PackageParser.generatePermissionGroupInfo( 3246 mPermissionGroups.get(name), flags); 3247 } 3248 } 3249 3250 @Override 3251 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3252 // reader 3253 synchronized (mPackages) { 3254 final int N = mPermissionGroups.size(); 3255 ArrayList<PermissionGroupInfo> out 3256 = new ArrayList<PermissionGroupInfo>(N); 3257 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3258 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3259 } 3260 return new ParceledListSlice<>(out); 3261 } 3262 } 3263 3264 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3265 int userId) { 3266 if (!sUserManager.exists(userId)) return null; 3267 PackageSetting ps = mSettings.mPackages.get(packageName); 3268 if (ps != null) { 3269 if (ps.pkg == null) { 3270 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3271 if (pInfo != null) { 3272 return pInfo.applicationInfo; 3273 } 3274 return null; 3275 } 3276 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3277 ps.readUserState(userId), userId); 3278 } 3279 return null; 3280 } 3281 3282 @Override 3283 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3284 if (!sUserManager.exists(userId)) return null; 3285 flags = updateFlagsForApplication(flags, userId, packageName); 3286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3287 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3288 // writer 3289 synchronized (mPackages) { 3290 PackageParser.Package p = mPackages.get(packageName); 3291 if (DEBUG_PACKAGE_INFO) Log.v( 3292 TAG, "getApplicationInfo " + packageName 3293 + ": " + p); 3294 if (p != null) { 3295 PackageSetting ps = mSettings.mPackages.get(packageName); 3296 if (ps == null) return null; 3297 // Note: isEnabledLP() does not apply here - always return info 3298 return PackageParser.generateApplicationInfo( 3299 p, flags, ps.readUserState(userId), userId); 3300 } 3301 if ("android".equals(packageName)||"system".equals(packageName)) { 3302 return mAndroidApplication; 3303 } 3304 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3305 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3306 } 3307 } 3308 return null; 3309 } 3310 3311 @Override 3312 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3313 final IPackageDataObserver observer) { 3314 mContext.enforceCallingOrSelfPermission( 3315 android.Manifest.permission.CLEAR_APP_CACHE, null); 3316 // Queue up an async operation since clearing cache may take a little while. 3317 mHandler.post(new Runnable() { 3318 public void run() { 3319 mHandler.removeCallbacks(this); 3320 boolean success = true; 3321 synchronized (mInstallLock) { 3322 try { 3323 mInstaller.freeCache(volumeUuid, freeStorageSize); 3324 } catch (InstallerException e) { 3325 Slog.w(TAG, "Couldn't clear application caches: " + e); 3326 success = false; 3327 } 3328 } 3329 if (observer != null) { 3330 try { 3331 observer.onRemoveCompleted(null, success); 3332 } catch (RemoteException e) { 3333 Slog.w(TAG, "RemoveException when invoking call back"); 3334 } 3335 } 3336 } 3337 }); 3338 } 3339 3340 @Override 3341 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3342 final IntentSender pi) { 3343 mContext.enforceCallingOrSelfPermission( 3344 android.Manifest.permission.CLEAR_APP_CACHE, null); 3345 // Queue up an async operation since clearing cache may take a little while. 3346 mHandler.post(new Runnable() { 3347 public void run() { 3348 mHandler.removeCallbacks(this); 3349 boolean success = true; 3350 synchronized (mInstallLock) { 3351 try { 3352 mInstaller.freeCache(volumeUuid, freeStorageSize); 3353 } catch (InstallerException e) { 3354 Slog.w(TAG, "Couldn't clear application caches: " + e); 3355 success = false; 3356 } 3357 } 3358 if(pi != null) { 3359 try { 3360 // Callback via pending intent 3361 int code = success ? 1 : 0; 3362 pi.sendIntent(null, code, null, 3363 null, null); 3364 } catch (SendIntentException e1) { 3365 Slog.i(TAG, "Failed to send pending intent"); 3366 } 3367 } 3368 } 3369 }); 3370 } 3371 3372 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3373 synchronized (mInstallLock) { 3374 try { 3375 mInstaller.freeCache(volumeUuid, freeStorageSize); 3376 } catch (InstallerException e) { 3377 throw new IOException("Failed to free enough space", e); 3378 } 3379 } 3380 } 3381 3382 /** 3383 * Update given flags based on encryption status of current user. 3384 */ 3385 private int updateFlags(int flags, int userId) { 3386 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3387 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3388 // Caller expressed an explicit opinion about what encryption 3389 // aware/unaware components they want to see, so fall through and 3390 // give them what they want 3391 } else { 3392 // Caller expressed no opinion, so match based on user state 3393 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3394 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3395 } else { 3396 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3397 } 3398 } 3399 return flags; 3400 } 3401 3402 private UserManagerInternal getUserManagerInternal() { 3403 if (mUserManagerInternal == null) { 3404 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3405 } 3406 return mUserManagerInternal; 3407 } 3408 3409 /** 3410 * Update given flags when being used to request {@link PackageInfo}. 3411 */ 3412 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3413 boolean triaged = true; 3414 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3415 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3416 // Caller is asking for component details, so they'd better be 3417 // asking for specific encryption matching behavior, or be triaged 3418 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3419 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3420 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3421 triaged = false; 3422 } 3423 } 3424 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3425 | PackageManager.MATCH_SYSTEM_ONLY 3426 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3427 triaged = false; 3428 } 3429 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3430 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3431 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3432 } 3433 return updateFlags(flags, userId); 3434 } 3435 3436 /** 3437 * Update given flags when being used to request {@link ApplicationInfo}. 3438 */ 3439 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3440 return updateFlagsForPackage(flags, userId, cookie); 3441 } 3442 3443 /** 3444 * Update given flags when being used to request {@link ComponentInfo}. 3445 */ 3446 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3447 if (cookie instanceof Intent) { 3448 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3449 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3450 } 3451 } 3452 3453 boolean triaged = true; 3454 // Caller is asking for component details, so they'd better be 3455 // asking for specific encryption matching behavior, or be triaged 3456 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3457 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3458 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3459 triaged = false; 3460 } 3461 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3462 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3463 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3464 } 3465 3466 return updateFlags(flags, userId); 3467 } 3468 3469 /** 3470 * Update given flags when being used to request {@link ResolveInfo}. 3471 */ 3472 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3473 // Safe mode means we shouldn't match any third-party components 3474 if (mSafeMode) { 3475 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3476 } 3477 3478 return updateFlagsForComponent(flags, userId, cookie); 3479 } 3480 3481 @Override 3482 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3483 if (!sUserManager.exists(userId)) return null; 3484 flags = updateFlagsForComponent(flags, userId, component); 3485 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3486 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3487 synchronized (mPackages) { 3488 PackageParser.Activity a = mActivities.mActivities.get(component); 3489 3490 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3491 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3492 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3493 if (ps == null) return null; 3494 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3495 userId); 3496 } 3497 if (mResolveComponentName.equals(component)) { 3498 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3499 new PackageUserState(), userId); 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3507 String resolvedType) { 3508 synchronized (mPackages) { 3509 if (component.equals(mResolveComponentName)) { 3510 // The resolver supports EVERYTHING! 3511 return true; 3512 } 3513 PackageParser.Activity a = mActivities.mActivities.get(component); 3514 if (a == null) { 3515 return false; 3516 } 3517 for (int i=0; i<a.intents.size(); i++) { 3518 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3519 intent.getData(), intent.getCategories(), TAG) >= 0) { 3520 return true; 3521 } 3522 } 3523 return false; 3524 } 3525 } 3526 3527 @Override 3528 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3529 if (!sUserManager.exists(userId)) return null; 3530 flags = updateFlagsForComponent(flags, userId, component); 3531 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3532 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3533 synchronized (mPackages) { 3534 PackageParser.Activity a = mReceivers.mActivities.get(component); 3535 if (DEBUG_PACKAGE_INFO) Log.v( 3536 TAG, "getReceiverInfo " + component + ": " + a); 3537 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3538 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3539 if (ps == null) return null; 3540 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3541 userId); 3542 } 3543 } 3544 return null; 3545 } 3546 3547 @Override 3548 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3549 if (!sUserManager.exists(userId)) return null; 3550 flags = updateFlagsForComponent(flags, userId, component); 3551 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3552 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3553 synchronized (mPackages) { 3554 PackageParser.Service s = mServices.mServices.get(component); 3555 if (DEBUG_PACKAGE_INFO) Log.v( 3556 TAG, "getServiceInfo " + component + ": " + s); 3557 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3558 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3559 if (ps == null) return null; 3560 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3561 userId); 3562 } 3563 } 3564 return null; 3565 } 3566 3567 @Override 3568 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3569 if (!sUserManager.exists(userId)) return null; 3570 flags = updateFlagsForComponent(flags, userId, component); 3571 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3572 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3573 synchronized (mPackages) { 3574 PackageParser.Provider p = mProviders.mProviders.get(component); 3575 if (DEBUG_PACKAGE_INFO) Log.v( 3576 TAG, "getProviderInfo " + component + ": " + p); 3577 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3578 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3579 if (ps == null) return null; 3580 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3581 userId); 3582 } 3583 } 3584 return null; 3585 } 3586 3587 @Override 3588 public String[] getSystemSharedLibraryNames() { 3589 Set<String> libSet; 3590 synchronized (mPackages) { 3591 libSet = mSharedLibraries.keySet(); 3592 int size = libSet.size(); 3593 if (size > 0) { 3594 String[] libs = new String[size]; 3595 libSet.toArray(libs); 3596 return libs; 3597 } 3598 } 3599 return null; 3600 } 3601 3602 @Override 3603 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3604 synchronized (mPackages) { 3605 return mServicesSystemSharedLibraryPackageName; 3606 } 3607 } 3608 3609 @Override 3610 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3611 synchronized (mPackages) { 3612 return mSharedSystemSharedLibraryPackageName; 3613 } 3614 } 3615 3616 @Override 3617 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3618 synchronized (mPackages) { 3619 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3620 3621 final FeatureInfo fi = new FeatureInfo(); 3622 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3623 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3624 res.add(fi); 3625 3626 return new ParceledListSlice<>(res); 3627 } 3628 } 3629 3630 @Override 3631 public boolean hasSystemFeature(String name, int version) { 3632 synchronized (mPackages) { 3633 final FeatureInfo feat = mAvailableFeatures.get(name); 3634 if (feat == null) { 3635 return false; 3636 } else { 3637 return feat.version >= version; 3638 } 3639 } 3640 } 3641 3642 @Override 3643 public int checkPermission(String permName, String pkgName, int userId) { 3644 if (!sUserManager.exists(userId)) { 3645 return PackageManager.PERMISSION_DENIED; 3646 } 3647 3648 synchronized (mPackages) { 3649 final PackageParser.Package p = mPackages.get(pkgName); 3650 if (p != null && p.mExtras != null) { 3651 final PackageSetting ps = (PackageSetting) p.mExtras; 3652 final PermissionsState permissionsState = ps.getPermissionsState(); 3653 if (permissionsState.hasPermission(permName, userId)) { 3654 return PackageManager.PERMISSION_GRANTED; 3655 } 3656 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3657 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3658 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3659 return PackageManager.PERMISSION_GRANTED; 3660 } 3661 } 3662 } 3663 3664 return PackageManager.PERMISSION_DENIED; 3665 } 3666 3667 @Override 3668 public int checkUidPermission(String permName, int uid) { 3669 final int userId = UserHandle.getUserId(uid); 3670 3671 if (!sUserManager.exists(userId)) { 3672 return PackageManager.PERMISSION_DENIED; 3673 } 3674 3675 synchronized (mPackages) { 3676 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3677 if (obj != null) { 3678 final SettingBase ps = (SettingBase) obj; 3679 final PermissionsState permissionsState = ps.getPermissionsState(); 3680 if (permissionsState.hasPermission(permName, userId)) { 3681 return PackageManager.PERMISSION_GRANTED; 3682 } 3683 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3684 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3685 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3686 return PackageManager.PERMISSION_GRANTED; 3687 } 3688 } else { 3689 ArraySet<String> perms = mSystemPermissions.get(uid); 3690 if (perms != null) { 3691 if (perms.contains(permName)) { 3692 return PackageManager.PERMISSION_GRANTED; 3693 } 3694 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3695 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3696 return PackageManager.PERMISSION_GRANTED; 3697 } 3698 } 3699 } 3700 } 3701 3702 return PackageManager.PERMISSION_DENIED; 3703 } 3704 3705 @Override 3706 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3707 if (UserHandle.getCallingUserId() != userId) { 3708 mContext.enforceCallingPermission( 3709 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3710 "isPermissionRevokedByPolicy for user " + userId); 3711 } 3712 3713 if (checkPermission(permission, packageName, userId) 3714 == PackageManager.PERMISSION_GRANTED) { 3715 return false; 3716 } 3717 3718 final long identity = Binder.clearCallingIdentity(); 3719 try { 3720 final int flags = getPermissionFlags(permission, packageName, userId); 3721 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3722 } finally { 3723 Binder.restoreCallingIdentity(identity); 3724 } 3725 } 3726 3727 @Override 3728 public String getPermissionControllerPackageName() { 3729 synchronized (mPackages) { 3730 return mRequiredInstallerPackage; 3731 } 3732 } 3733 3734 /** 3735 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3736 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3737 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3738 * @param message the message to log on security exception 3739 */ 3740 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3741 boolean checkShell, String message) { 3742 if (userId < 0) { 3743 throw new IllegalArgumentException("Invalid userId " + userId); 3744 } 3745 if (checkShell) { 3746 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3747 } 3748 if (userId == UserHandle.getUserId(callingUid)) return; 3749 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3750 if (requireFullPermission) { 3751 mContext.enforceCallingOrSelfPermission( 3752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3753 } else { 3754 try { 3755 mContext.enforceCallingOrSelfPermission( 3756 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3757 } catch (SecurityException se) { 3758 mContext.enforceCallingOrSelfPermission( 3759 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3760 } 3761 } 3762 } 3763 } 3764 3765 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3766 if (callingUid == Process.SHELL_UID) { 3767 if (userHandle >= 0 3768 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3769 throw new SecurityException("Shell does not have permission to access user " 3770 + userHandle); 3771 } else if (userHandle < 0) { 3772 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3773 + Debug.getCallers(3)); 3774 } 3775 } 3776 } 3777 3778 private BasePermission findPermissionTreeLP(String permName) { 3779 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3780 if (permName.startsWith(bp.name) && 3781 permName.length() > bp.name.length() && 3782 permName.charAt(bp.name.length()) == '.') { 3783 return bp; 3784 } 3785 } 3786 return null; 3787 } 3788 3789 private BasePermission checkPermissionTreeLP(String permName) { 3790 if (permName != null) { 3791 BasePermission bp = findPermissionTreeLP(permName); 3792 if (bp != null) { 3793 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3794 return bp; 3795 } 3796 throw new SecurityException("Calling uid " 3797 + Binder.getCallingUid() 3798 + " is not allowed to add to permission tree " 3799 + bp.name + " owned by uid " + bp.uid); 3800 } 3801 } 3802 throw new SecurityException("No permission tree found for " + permName); 3803 } 3804 3805 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3806 if (s1 == null) { 3807 return s2 == null; 3808 } 3809 if (s2 == null) { 3810 return false; 3811 } 3812 if (s1.getClass() != s2.getClass()) { 3813 return false; 3814 } 3815 return s1.equals(s2); 3816 } 3817 3818 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3819 if (pi1.icon != pi2.icon) return false; 3820 if (pi1.logo != pi2.logo) return false; 3821 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3822 if (!compareStrings(pi1.name, pi2.name)) return false; 3823 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3824 // We'll take care of setting this one. 3825 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3826 // These are not currently stored in settings. 3827 //if (!compareStrings(pi1.group, pi2.group)) return false; 3828 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3829 //if (pi1.labelRes != pi2.labelRes) return false; 3830 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3831 return true; 3832 } 3833 3834 int permissionInfoFootprint(PermissionInfo info) { 3835 int size = info.name.length(); 3836 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3837 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3838 return size; 3839 } 3840 3841 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3842 int size = 0; 3843 for (BasePermission perm : mSettings.mPermissions.values()) { 3844 if (perm.uid == tree.uid) { 3845 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3846 } 3847 } 3848 return size; 3849 } 3850 3851 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3852 // We calculate the max size of permissions defined by this uid and throw 3853 // if that plus the size of 'info' would exceed our stated maximum. 3854 if (tree.uid != Process.SYSTEM_UID) { 3855 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3856 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3857 throw new SecurityException("Permission tree size cap exceeded"); 3858 } 3859 } 3860 } 3861 3862 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3863 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3864 throw new SecurityException("Label must be specified in permission"); 3865 } 3866 BasePermission tree = checkPermissionTreeLP(info.name); 3867 BasePermission bp = mSettings.mPermissions.get(info.name); 3868 boolean added = bp == null; 3869 boolean changed = true; 3870 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3871 if (added) { 3872 enforcePermissionCapLocked(info, tree); 3873 bp = new BasePermission(info.name, tree.sourcePackage, 3874 BasePermission.TYPE_DYNAMIC); 3875 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3876 throw new SecurityException( 3877 "Not allowed to modify non-dynamic permission " 3878 + info.name); 3879 } else { 3880 if (bp.protectionLevel == fixedLevel 3881 && bp.perm.owner.equals(tree.perm.owner) 3882 && bp.uid == tree.uid 3883 && comparePermissionInfos(bp.perm.info, info)) { 3884 changed = false; 3885 } 3886 } 3887 bp.protectionLevel = fixedLevel; 3888 info = new PermissionInfo(info); 3889 info.protectionLevel = fixedLevel; 3890 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3891 bp.perm.info.packageName = tree.perm.info.packageName; 3892 bp.uid = tree.uid; 3893 if (added) { 3894 mSettings.mPermissions.put(info.name, bp); 3895 } 3896 if (changed) { 3897 if (!async) { 3898 mSettings.writeLPr(); 3899 } else { 3900 scheduleWriteSettingsLocked(); 3901 } 3902 } 3903 return added; 3904 } 3905 3906 @Override 3907 public boolean addPermission(PermissionInfo info) { 3908 synchronized (mPackages) { 3909 return addPermissionLocked(info, false); 3910 } 3911 } 3912 3913 @Override 3914 public boolean addPermissionAsync(PermissionInfo info) { 3915 synchronized (mPackages) { 3916 return addPermissionLocked(info, true); 3917 } 3918 } 3919 3920 @Override 3921 public void removePermission(String name) { 3922 synchronized (mPackages) { 3923 checkPermissionTreeLP(name); 3924 BasePermission bp = mSettings.mPermissions.get(name); 3925 if (bp != null) { 3926 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3927 throw new SecurityException( 3928 "Not allowed to modify non-dynamic permission " 3929 + name); 3930 } 3931 mSettings.mPermissions.remove(name); 3932 mSettings.writeLPr(); 3933 } 3934 } 3935 } 3936 3937 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3938 BasePermission bp) { 3939 int index = pkg.requestedPermissions.indexOf(bp.name); 3940 if (index == -1) { 3941 throw new SecurityException("Package " + pkg.packageName 3942 + " has not requested permission " + bp.name); 3943 } 3944 if (!bp.isRuntime() && !bp.isDevelopment()) { 3945 throw new SecurityException("Permission " + bp.name 3946 + " is not a changeable permission type"); 3947 } 3948 } 3949 3950 @Override 3951 public void grantRuntimePermission(String packageName, String name, final int userId) { 3952 if (!sUserManager.exists(userId)) { 3953 Log.e(TAG, "No such user:" + userId); 3954 return; 3955 } 3956 3957 mContext.enforceCallingOrSelfPermission( 3958 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3959 "grantRuntimePermission"); 3960 3961 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3962 true /* requireFullPermission */, true /* checkShell */, 3963 "grantRuntimePermission"); 3964 3965 final int uid; 3966 final SettingBase sb; 3967 3968 synchronized (mPackages) { 3969 final PackageParser.Package pkg = mPackages.get(packageName); 3970 if (pkg == null) { 3971 throw new IllegalArgumentException("Unknown package: " + packageName); 3972 } 3973 3974 final BasePermission bp = mSettings.mPermissions.get(name); 3975 if (bp == null) { 3976 throw new IllegalArgumentException("Unknown permission: " + name); 3977 } 3978 3979 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3980 3981 // If a permission review is required for legacy apps we represent 3982 // their permissions as always granted runtime ones since we need 3983 // to keep the review required permission flag per user while an 3984 // install permission's state is shared across all users. 3985 if (Build.PERMISSIONS_REVIEW_REQUIRED 3986 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3987 && bp.isRuntime()) { 3988 return; 3989 } 3990 3991 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3992 sb = (SettingBase) pkg.mExtras; 3993 if (sb == null) { 3994 throw new IllegalArgumentException("Unknown package: " + packageName); 3995 } 3996 3997 final PermissionsState permissionsState = sb.getPermissionsState(); 3998 3999 final int flags = permissionsState.getPermissionFlags(name, userId); 4000 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4001 throw new SecurityException("Cannot grant system fixed permission " 4002 + name + " for package " + packageName); 4003 } 4004 4005 if (bp.isDevelopment()) { 4006 // Development permissions must be handled specially, since they are not 4007 // normal runtime permissions. For now they apply to all users. 4008 if (permissionsState.grantInstallPermission(bp) != 4009 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4010 scheduleWriteSettingsLocked(); 4011 } 4012 return; 4013 } 4014 4015 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4016 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4017 return; 4018 } 4019 4020 final int result = permissionsState.grantRuntimePermission(bp, userId); 4021 switch (result) { 4022 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4023 return; 4024 } 4025 4026 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4027 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4028 mHandler.post(new Runnable() { 4029 @Override 4030 public void run() { 4031 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4032 } 4033 }); 4034 } 4035 break; 4036 } 4037 4038 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4039 4040 // Not critical if that is lost - app has to request again. 4041 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4042 } 4043 4044 // Only need to do this if user is initialized. Otherwise it's a new user 4045 // and there are no processes running as the user yet and there's no need 4046 // to make an expensive call to remount processes for the changed permissions. 4047 if (READ_EXTERNAL_STORAGE.equals(name) 4048 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4049 final long token = Binder.clearCallingIdentity(); 4050 try { 4051 if (sUserManager.isInitialized(userId)) { 4052 MountServiceInternal mountServiceInternal = LocalServices.getService( 4053 MountServiceInternal.class); 4054 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4055 } 4056 } finally { 4057 Binder.restoreCallingIdentity(token); 4058 } 4059 } 4060 } 4061 4062 @Override 4063 public void revokeRuntimePermission(String packageName, String name, int userId) { 4064 if (!sUserManager.exists(userId)) { 4065 Log.e(TAG, "No such user:" + userId); 4066 return; 4067 } 4068 4069 mContext.enforceCallingOrSelfPermission( 4070 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4071 "revokeRuntimePermission"); 4072 4073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4074 true /* requireFullPermission */, true /* checkShell */, 4075 "revokeRuntimePermission"); 4076 4077 final int appId; 4078 4079 synchronized (mPackages) { 4080 final PackageParser.Package pkg = mPackages.get(packageName); 4081 if (pkg == null) { 4082 throw new IllegalArgumentException("Unknown package: " + packageName); 4083 } 4084 4085 final BasePermission bp = mSettings.mPermissions.get(name); 4086 if (bp == null) { 4087 throw new IllegalArgumentException("Unknown permission: " + name); 4088 } 4089 4090 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4091 4092 // If a permission review is required for legacy apps we represent 4093 // their permissions as always granted runtime ones since we need 4094 // to keep the review required permission flag per user while an 4095 // install permission's state is shared across all users. 4096 if (Build.PERMISSIONS_REVIEW_REQUIRED 4097 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4098 && bp.isRuntime()) { 4099 return; 4100 } 4101 4102 SettingBase sb = (SettingBase) pkg.mExtras; 4103 if (sb == null) { 4104 throw new IllegalArgumentException("Unknown package: " + packageName); 4105 } 4106 4107 final PermissionsState permissionsState = sb.getPermissionsState(); 4108 4109 final int flags = permissionsState.getPermissionFlags(name, userId); 4110 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4111 throw new SecurityException("Cannot revoke system fixed permission " 4112 + name + " for package " + packageName); 4113 } 4114 4115 if (bp.isDevelopment()) { 4116 // Development permissions must be handled specially, since they are not 4117 // normal runtime permissions. For now they apply to all users. 4118 if (permissionsState.revokeInstallPermission(bp) != 4119 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4120 scheduleWriteSettingsLocked(); 4121 } 4122 return; 4123 } 4124 4125 if (permissionsState.revokeRuntimePermission(bp, userId) == 4126 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4127 return; 4128 } 4129 4130 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4131 4132 // Critical, after this call app should never have the permission. 4133 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4134 4135 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4136 } 4137 4138 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4139 } 4140 4141 @Override 4142 public void resetRuntimePermissions() { 4143 mContext.enforceCallingOrSelfPermission( 4144 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4145 "revokeRuntimePermission"); 4146 4147 int callingUid = Binder.getCallingUid(); 4148 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4149 mContext.enforceCallingOrSelfPermission( 4150 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4151 "resetRuntimePermissions"); 4152 } 4153 4154 synchronized (mPackages) { 4155 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4156 for (int userId : UserManagerService.getInstance().getUserIds()) { 4157 final int packageCount = mPackages.size(); 4158 for (int i = 0; i < packageCount; i++) { 4159 PackageParser.Package pkg = mPackages.valueAt(i); 4160 if (!(pkg.mExtras instanceof PackageSetting)) { 4161 continue; 4162 } 4163 PackageSetting ps = (PackageSetting) pkg.mExtras; 4164 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4165 } 4166 } 4167 } 4168 } 4169 4170 @Override 4171 public int getPermissionFlags(String name, String packageName, int userId) { 4172 if (!sUserManager.exists(userId)) { 4173 return 0; 4174 } 4175 4176 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4177 4178 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4179 true /* requireFullPermission */, false /* checkShell */, 4180 "getPermissionFlags"); 4181 4182 synchronized (mPackages) { 4183 final PackageParser.Package pkg = mPackages.get(packageName); 4184 if (pkg == null) { 4185 return 0; 4186 } 4187 4188 final BasePermission bp = mSettings.mPermissions.get(name); 4189 if (bp == null) { 4190 return 0; 4191 } 4192 4193 SettingBase sb = (SettingBase) pkg.mExtras; 4194 if (sb == null) { 4195 return 0; 4196 } 4197 4198 PermissionsState permissionsState = sb.getPermissionsState(); 4199 return permissionsState.getPermissionFlags(name, userId); 4200 } 4201 } 4202 4203 @Override 4204 public void updatePermissionFlags(String name, String packageName, int flagMask, 4205 int flagValues, int userId) { 4206 if (!sUserManager.exists(userId)) { 4207 return; 4208 } 4209 4210 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4211 4212 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4213 true /* requireFullPermission */, true /* checkShell */, 4214 "updatePermissionFlags"); 4215 4216 // Only the system can change these flags and nothing else. 4217 if (getCallingUid() != Process.SYSTEM_UID) { 4218 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4219 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4220 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4221 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4222 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4223 } 4224 4225 synchronized (mPackages) { 4226 final PackageParser.Package pkg = mPackages.get(packageName); 4227 if (pkg == null) { 4228 throw new IllegalArgumentException("Unknown package: " + packageName); 4229 } 4230 4231 final BasePermission bp = mSettings.mPermissions.get(name); 4232 if (bp == null) { 4233 throw new IllegalArgumentException("Unknown permission: " + name); 4234 } 4235 4236 SettingBase sb = (SettingBase) pkg.mExtras; 4237 if (sb == null) { 4238 throw new IllegalArgumentException("Unknown package: " + packageName); 4239 } 4240 4241 PermissionsState permissionsState = sb.getPermissionsState(); 4242 4243 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4244 4245 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4246 // Install and runtime permissions are stored in different places, 4247 // so figure out what permission changed and persist the change. 4248 if (permissionsState.getInstallPermissionState(name) != null) { 4249 scheduleWriteSettingsLocked(); 4250 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4251 || hadState) { 4252 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4253 } 4254 } 4255 } 4256 } 4257 4258 /** 4259 * Update the permission flags for all packages and runtime permissions of a user in order 4260 * to allow device or profile owner to remove POLICY_FIXED. 4261 */ 4262 @Override 4263 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4264 if (!sUserManager.exists(userId)) { 4265 return; 4266 } 4267 4268 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4269 4270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4271 true /* requireFullPermission */, true /* checkShell */, 4272 "updatePermissionFlagsForAllApps"); 4273 4274 // Only the system can change system fixed flags. 4275 if (getCallingUid() != Process.SYSTEM_UID) { 4276 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4277 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4278 } 4279 4280 synchronized (mPackages) { 4281 boolean changed = false; 4282 final int packageCount = mPackages.size(); 4283 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4284 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4285 SettingBase sb = (SettingBase) pkg.mExtras; 4286 if (sb == null) { 4287 continue; 4288 } 4289 PermissionsState permissionsState = sb.getPermissionsState(); 4290 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4291 userId, flagMask, flagValues); 4292 } 4293 if (changed) { 4294 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4295 } 4296 } 4297 } 4298 4299 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4300 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4301 != PackageManager.PERMISSION_GRANTED 4302 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4303 != PackageManager.PERMISSION_GRANTED) { 4304 throw new SecurityException(message + " requires " 4305 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4306 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4307 } 4308 } 4309 4310 @Override 4311 public boolean shouldShowRequestPermissionRationale(String permissionName, 4312 String packageName, int userId) { 4313 if (UserHandle.getCallingUserId() != userId) { 4314 mContext.enforceCallingPermission( 4315 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4316 "canShowRequestPermissionRationale for user " + userId); 4317 } 4318 4319 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4320 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4321 return false; 4322 } 4323 4324 if (checkPermission(permissionName, packageName, userId) 4325 == PackageManager.PERMISSION_GRANTED) { 4326 return false; 4327 } 4328 4329 final int flags; 4330 4331 final long identity = Binder.clearCallingIdentity(); 4332 try { 4333 flags = getPermissionFlags(permissionName, 4334 packageName, userId); 4335 } finally { 4336 Binder.restoreCallingIdentity(identity); 4337 } 4338 4339 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4340 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4341 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4342 4343 if ((flags & fixedFlags) != 0) { 4344 return false; 4345 } 4346 4347 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4348 } 4349 4350 @Override 4351 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4352 mContext.enforceCallingOrSelfPermission( 4353 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4354 "addOnPermissionsChangeListener"); 4355 4356 synchronized (mPackages) { 4357 mOnPermissionChangeListeners.addListenerLocked(listener); 4358 } 4359 } 4360 4361 @Override 4362 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4363 synchronized (mPackages) { 4364 mOnPermissionChangeListeners.removeListenerLocked(listener); 4365 } 4366 } 4367 4368 @Override 4369 public boolean isProtectedBroadcast(String actionName) { 4370 synchronized (mPackages) { 4371 if (mProtectedBroadcasts.contains(actionName)) { 4372 return true; 4373 } else if (actionName != null) { 4374 // TODO: remove these terrible hacks 4375 if (actionName.startsWith("android.net.netmon.lingerExpired") 4376 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4377 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4378 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4379 return true; 4380 } 4381 } 4382 } 4383 return false; 4384 } 4385 4386 @Override 4387 public int checkSignatures(String pkg1, String pkg2) { 4388 synchronized (mPackages) { 4389 final PackageParser.Package p1 = mPackages.get(pkg1); 4390 final PackageParser.Package p2 = mPackages.get(pkg2); 4391 if (p1 == null || p1.mExtras == null 4392 || p2 == null || p2.mExtras == null) { 4393 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4394 } 4395 return compareSignatures(p1.mSignatures, p2.mSignatures); 4396 } 4397 } 4398 4399 @Override 4400 public int checkUidSignatures(int uid1, int uid2) { 4401 // Map to base uids. 4402 uid1 = UserHandle.getAppId(uid1); 4403 uid2 = UserHandle.getAppId(uid2); 4404 // reader 4405 synchronized (mPackages) { 4406 Signature[] s1; 4407 Signature[] s2; 4408 Object obj = mSettings.getUserIdLPr(uid1); 4409 if (obj != null) { 4410 if (obj instanceof SharedUserSetting) { 4411 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4412 } else if (obj instanceof PackageSetting) { 4413 s1 = ((PackageSetting)obj).signatures.mSignatures; 4414 } else { 4415 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4416 } 4417 } else { 4418 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4419 } 4420 obj = mSettings.getUserIdLPr(uid2); 4421 if (obj != null) { 4422 if (obj instanceof SharedUserSetting) { 4423 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4424 } else if (obj instanceof PackageSetting) { 4425 s2 = ((PackageSetting)obj).signatures.mSignatures; 4426 } else { 4427 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4428 } 4429 } else { 4430 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4431 } 4432 return compareSignatures(s1, s2); 4433 } 4434 } 4435 4436 /** 4437 * This method should typically only be used when granting or revoking 4438 * permissions, since the app may immediately restart after this call. 4439 * <p> 4440 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4441 * guard your work against the app being relaunched. 4442 */ 4443 private void killUid(int appId, int userId, String reason) { 4444 final long identity = Binder.clearCallingIdentity(); 4445 try { 4446 IActivityManager am = ActivityManagerNative.getDefault(); 4447 if (am != null) { 4448 try { 4449 am.killUid(appId, userId, reason); 4450 } catch (RemoteException e) { 4451 /* ignore - same process */ 4452 } 4453 } 4454 } finally { 4455 Binder.restoreCallingIdentity(identity); 4456 } 4457 } 4458 4459 /** 4460 * Compares two sets of signatures. Returns: 4461 * <br /> 4462 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4463 * <br /> 4464 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4465 * <br /> 4466 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4467 * <br /> 4468 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4469 * <br /> 4470 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4471 */ 4472 static int compareSignatures(Signature[] s1, Signature[] s2) { 4473 if (s1 == null) { 4474 return s2 == null 4475 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4476 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4477 } 4478 4479 if (s2 == null) { 4480 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4481 } 4482 4483 if (s1.length != s2.length) { 4484 return PackageManager.SIGNATURE_NO_MATCH; 4485 } 4486 4487 // Since both signature sets are of size 1, we can compare without HashSets. 4488 if (s1.length == 1) { 4489 return s1[0].equals(s2[0]) ? 4490 PackageManager.SIGNATURE_MATCH : 4491 PackageManager.SIGNATURE_NO_MATCH; 4492 } 4493 4494 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4495 for (Signature sig : s1) { 4496 set1.add(sig); 4497 } 4498 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4499 for (Signature sig : s2) { 4500 set2.add(sig); 4501 } 4502 // Make sure s2 contains all signatures in s1. 4503 if (set1.equals(set2)) { 4504 return PackageManager.SIGNATURE_MATCH; 4505 } 4506 return PackageManager.SIGNATURE_NO_MATCH; 4507 } 4508 4509 /** 4510 * If the database version for this type of package (internal storage or 4511 * external storage) is less than the version where package signatures 4512 * were updated, return true. 4513 */ 4514 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4515 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4516 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4517 } 4518 4519 /** 4520 * Used for backward compatibility to make sure any packages with 4521 * certificate chains get upgraded to the new style. {@code existingSigs} 4522 * will be in the old format (since they were stored on disk from before the 4523 * system upgrade) and {@code scannedSigs} will be in the newer format. 4524 */ 4525 private int compareSignaturesCompat(PackageSignatures existingSigs, 4526 PackageParser.Package scannedPkg) { 4527 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4528 return PackageManager.SIGNATURE_NO_MATCH; 4529 } 4530 4531 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4532 for (Signature sig : existingSigs.mSignatures) { 4533 existingSet.add(sig); 4534 } 4535 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4536 for (Signature sig : scannedPkg.mSignatures) { 4537 try { 4538 Signature[] chainSignatures = sig.getChainSignatures(); 4539 for (Signature chainSig : chainSignatures) { 4540 scannedCompatSet.add(chainSig); 4541 } 4542 } catch (CertificateEncodingException e) { 4543 scannedCompatSet.add(sig); 4544 } 4545 } 4546 /* 4547 * Make sure the expanded scanned set contains all signatures in the 4548 * existing one. 4549 */ 4550 if (scannedCompatSet.equals(existingSet)) { 4551 // Migrate the old signatures to the new scheme. 4552 existingSigs.assignSignatures(scannedPkg.mSignatures); 4553 // The new KeySets will be re-added later in the scanning process. 4554 synchronized (mPackages) { 4555 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4556 } 4557 return PackageManager.SIGNATURE_MATCH; 4558 } 4559 return PackageManager.SIGNATURE_NO_MATCH; 4560 } 4561 4562 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4563 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4564 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4565 } 4566 4567 private int compareSignaturesRecover(PackageSignatures existingSigs, 4568 PackageParser.Package scannedPkg) { 4569 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4570 return PackageManager.SIGNATURE_NO_MATCH; 4571 } 4572 4573 String msg = null; 4574 try { 4575 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4576 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4577 + scannedPkg.packageName); 4578 return PackageManager.SIGNATURE_MATCH; 4579 } 4580 } catch (CertificateException e) { 4581 msg = e.getMessage(); 4582 } 4583 4584 logCriticalInfo(Log.INFO, 4585 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4586 return PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 @Override 4590 public List<String> getAllPackages() { 4591 synchronized (mPackages) { 4592 return new ArrayList<String>(mPackages.keySet()); 4593 } 4594 } 4595 4596 @Override 4597 public String[] getPackagesForUid(int uid) { 4598 uid = UserHandle.getAppId(uid); 4599 // reader 4600 synchronized (mPackages) { 4601 Object obj = mSettings.getUserIdLPr(uid); 4602 if (obj instanceof SharedUserSetting) { 4603 final SharedUserSetting sus = (SharedUserSetting) obj; 4604 final int N = sus.packages.size(); 4605 final String[] res = new String[N]; 4606 for (int i = 0; i < N; i++) { 4607 res[i] = sus.packages.valueAt(i).name; 4608 } 4609 return res; 4610 } else if (obj instanceof PackageSetting) { 4611 final PackageSetting ps = (PackageSetting) obj; 4612 return new String[] { ps.name }; 4613 } 4614 } 4615 return null; 4616 } 4617 4618 @Override 4619 public String getNameForUid(int uid) { 4620 // reader 4621 synchronized (mPackages) { 4622 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4623 if (obj instanceof SharedUserSetting) { 4624 final SharedUserSetting sus = (SharedUserSetting) obj; 4625 return sus.name + ":" + sus.userId; 4626 } else if (obj instanceof PackageSetting) { 4627 final PackageSetting ps = (PackageSetting) obj; 4628 return ps.name; 4629 } 4630 } 4631 return null; 4632 } 4633 4634 @Override 4635 public int getUidForSharedUser(String sharedUserName) { 4636 if(sharedUserName == null) { 4637 return -1; 4638 } 4639 // reader 4640 synchronized (mPackages) { 4641 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4642 if (suid == null) { 4643 return -1; 4644 } 4645 return suid.userId; 4646 } 4647 } 4648 4649 @Override 4650 public int getFlagsForUid(int uid) { 4651 synchronized (mPackages) { 4652 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4653 if (obj instanceof SharedUserSetting) { 4654 final SharedUserSetting sus = (SharedUserSetting) obj; 4655 return sus.pkgFlags; 4656 } else if (obj instanceof PackageSetting) { 4657 final PackageSetting ps = (PackageSetting) obj; 4658 return ps.pkgFlags; 4659 } 4660 } 4661 return 0; 4662 } 4663 4664 @Override 4665 public int getPrivateFlagsForUid(int uid) { 4666 synchronized (mPackages) { 4667 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4668 if (obj instanceof SharedUserSetting) { 4669 final SharedUserSetting sus = (SharedUserSetting) obj; 4670 return sus.pkgPrivateFlags; 4671 } else if (obj instanceof PackageSetting) { 4672 final PackageSetting ps = (PackageSetting) obj; 4673 return ps.pkgPrivateFlags; 4674 } 4675 } 4676 return 0; 4677 } 4678 4679 @Override 4680 public boolean isUidPrivileged(int uid) { 4681 uid = UserHandle.getAppId(uid); 4682 // reader 4683 synchronized (mPackages) { 4684 Object obj = mSettings.getUserIdLPr(uid); 4685 if (obj instanceof SharedUserSetting) { 4686 final SharedUserSetting sus = (SharedUserSetting) obj; 4687 final Iterator<PackageSetting> it = sus.packages.iterator(); 4688 while (it.hasNext()) { 4689 if (it.next().isPrivileged()) { 4690 return true; 4691 } 4692 } 4693 } else if (obj instanceof PackageSetting) { 4694 final PackageSetting ps = (PackageSetting) obj; 4695 return ps.isPrivileged(); 4696 } 4697 } 4698 return false; 4699 } 4700 4701 @Override 4702 public String[] getAppOpPermissionPackages(String permissionName) { 4703 synchronized (mPackages) { 4704 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4705 if (pkgs == null) { 4706 return null; 4707 } 4708 return pkgs.toArray(new String[pkgs.size()]); 4709 } 4710 } 4711 4712 @Override 4713 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4714 int flags, int userId) { 4715 try { 4716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4717 4718 if (!sUserManager.exists(userId)) return null; 4719 flags = updateFlagsForResolve(flags, userId, intent); 4720 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4721 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4722 4723 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4724 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4725 flags, userId); 4726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4727 4728 final ResolveInfo bestChoice = 4729 chooseBestActivity(intent, resolvedType, flags, query, userId); 4730 4731 if (isEphemeralAllowed(intent, query, userId)) { 4732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4733 final EphemeralResolveInfo ai = 4734 getEphemeralResolveInfo(intent, resolvedType, userId); 4735 if (ai != null) { 4736 if (DEBUG_EPHEMERAL) { 4737 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4738 } 4739 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4740 bestChoice.ephemeralResolveInfo = ai; 4741 } 4742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4743 } 4744 return bestChoice; 4745 } finally { 4746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4747 } 4748 } 4749 4750 @Override 4751 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4752 IntentFilter filter, int match, ComponentName activity) { 4753 final int userId = UserHandle.getCallingUserId(); 4754 if (DEBUG_PREFERRED) { 4755 Log.v(TAG, "setLastChosenActivity intent=" + intent 4756 + " resolvedType=" + resolvedType 4757 + " flags=" + flags 4758 + " filter=" + filter 4759 + " match=" + match 4760 + " activity=" + activity); 4761 filter.dump(new PrintStreamPrinter(System.out), " "); 4762 } 4763 intent.setComponent(null); 4764 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4765 userId); 4766 // Find any earlier preferred or last chosen entries and nuke them 4767 findPreferredActivity(intent, resolvedType, 4768 flags, query, 0, false, true, false, userId); 4769 // Add the new activity as the last chosen for this filter 4770 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4771 "Setting last chosen"); 4772 } 4773 4774 @Override 4775 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4776 final int userId = UserHandle.getCallingUserId(); 4777 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4778 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4779 userId); 4780 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4781 false, false, false, userId); 4782 } 4783 4784 4785 private boolean isEphemeralAllowed( 4786 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4787 // Short circuit and return early if possible. 4788 if (DISABLE_EPHEMERAL_APPS) { 4789 return false; 4790 } 4791 final int callingUser = UserHandle.getCallingUserId(); 4792 if (callingUser != UserHandle.USER_SYSTEM) { 4793 return false; 4794 } 4795 if (mEphemeralResolverConnection == null) { 4796 return false; 4797 } 4798 if (intent.getComponent() != null) { 4799 return false; 4800 } 4801 if (intent.getPackage() != null) { 4802 return false; 4803 } 4804 final boolean isWebUri = hasWebURI(intent); 4805 if (!isWebUri) { 4806 return false; 4807 } 4808 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4809 synchronized (mPackages) { 4810 final int count = resolvedActivites.size(); 4811 for (int n = 0; n < count; n++) { 4812 ResolveInfo info = resolvedActivites.get(n); 4813 String packageName = info.activityInfo.packageName; 4814 PackageSetting ps = mSettings.mPackages.get(packageName); 4815 if (ps != null) { 4816 // Try to get the status from User settings first 4817 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4818 int status = (int) (packedStatus >> 32); 4819 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4820 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4821 if (DEBUG_EPHEMERAL) { 4822 Slog.v(TAG, "DENY ephemeral apps;" 4823 + " pkg: " + packageName + ", status: " + status); 4824 } 4825 return false; 4826 } 4827 } 4828 } 4829 } 4830 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4831 return true; 4832 } 4833 4834 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4835 int userId) { 4836 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4837 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4838 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 4839 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4840 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4841 ephemeralPrefixCount); 4842 final int[] shaPrefix = digest.getDigestPrefix(); 4843 final byte[][] digestBytes = digest.getDigestBytes(); 4844 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4845 mEphemeralResolverConnection.getEphemeralResolveInfoList( 4846 shaPrefix, ephemeralPrefixMask); 4847 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4848 // No hash prefix match; there are no ephemeral apps for this domain. 4849 return null; 4850 } 4851 4852 // Go in reverse order so we match the narrowest scope first. 4853 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4854 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4855 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4856 continue; 4857 } 4858 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4859 // No filters; this should never happen. 4860 if (filters.isEmpty()) { 4861 continue; 4862 } 4863 // We have a domain match; resolve the filters to see if anything matches. 4864 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4865 for (int j = filters.size() - 1; j >= 0; --j) { 4866 final EphemeralResolveIntentInfo intentInfo = 4867 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4868 ephemeralResolver.addFilter(intentInfo); 4869 } 4870 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4871 intent, resolvedType, false /*defaultOnly*/, userId); 4872 if (!matchedResolveInfoList.isEmpty()) { 4873 return matchedResolveInfoList.get(0); 4874 } 4875 } 4876 } 4877 // Hash or filter mis-match; no ephemeral apps for this domain. 4878 return null; 4879 } 4880 4881 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4882 int flags, List<ResolveInfo> query, int userId) { 4883 if (query != null) { 4884 final int N = query.size(); 4885 if (N == 1) { 4886 return query.get(0); 4887 } else if (N > 1) { 4888 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4889 // If there is more than one activity with the same priority, 4890 // then let the user decide between them. 4891 ResolveInfo r0 = query.get(0); 4892 ResolveInfo r1 = query.get(1); 4893 if (DEBUG_INTENT_MATCHING || debug) { 4894 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4895 + r1.activityInfo.name + "=" + r1.priority); 4896 } 4897 // If the first activity has a higher priority, or a different 4898 // default, then it is always desirable to pick it. 4899 if (r0.priority != r1.priority 4900 || r0.preferredOrder != r1.preferredOrder 4901 || r0.isDefault != r1.isDefault) { 4902 return query.get(0); 4903 } 4904 // If we have saved a preference for a preferred activity for 4905 // this Intent, use that. 4906 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4907 flags, query, r0.priority, true, false, debug, userId); 4908 if (ri != null) { 4909 return ri; 4910 } 4911 ri = new ResolveInfo(mResolveInfo); 4912 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4913 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4914 // If all of the options come from the same package, show the application's 4915 // label and icon instead of the generic resolver's. 4916 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4917 // and then throw away the ResolveInfo itself, meaning that the caller loses 4918 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4919 // a fallback for this case; we only set the target package's resources on 4920 // the ResolveInfo, not the ActivityInfo. 4921 final String intentPackage = intent.getPackage(); 4922 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4923 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4924 ri.resolvePackageName = intentPackage; 4925 if (userNeedsBadging(userId)) { 4926 ri.noResourceId = true; 4927 } else { 4928 ri.icon = appi.icon; 4929 } 4930 ri.iconResourceId = appi.icon; 4931 ri.labelRes = appi.labelRes; 4932 } 4933 ri.activityInfo.applicationInfo = new ApplicationInfo( 4934 ri.activityInfo.applicationInfo); 4935 if (userId != 0) { 4936 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4937 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4938 } 4939 // Make sure that the resolver is displayable in car mode 4940 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4941 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4942 return ri; 4943 } 4944 } 4945 return null; 4946 } 4947 4948 /** 4949 * Return true if the given list is not empty and all of its contents have 4950 * an activityInfo with the given package name. 4951 */ 4952 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4953 if (ArrayUtils.isEmpty(list)) { 4954 return false; 4955 } 4956 for (int i = 0, N = list.size(); i < N; i++) { 4957 final ResolveInfo ri = list.get(i); 4958 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4959 if (ai == null || !packageName.equals(ai.packageName)) { 4960 return false; 4961 } 4962 } 4963 return true; 4964 } 4965 4966 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4967 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4968 final int N = query.size(); 4969 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4970 .get(userId); 4971 // Get the list of persistent preferred activities that handle the intent 4972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4973 List<PersistentPreferredActivity> pprefs = ppir != null 4974 ? ppir.queryIntent(intent, resolvedType, 4975 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4976 : null; 4977 if (pprefs != null && pprefs.size() > 0) { 4978 final int M = pprefs.size(); 4979 for (int i=0; i<M; i++) { 4980 final PersistentPreferredActivity ppa = pprefs.get(i); 4981 if (DEBUG_PREFERRED || debug) { 4982 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4983 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4984 + "\n component=" + ppa.mComponent); 4985 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4986 } 4987 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4988 flags | MATCH_DISABLED_COMPONENTS, userId); 4989 if (DEBUG_PREFERRED || debug) { 4990 Slog.v(TAG, "Found persistent preferred activity:"); 4991 if (ai != null) { 4992 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4993 } else { 4994 Slog.v(TAG, " null"); 4995 } 4996 } 4997 if (ai == null) { 4998 // This previously registered persistent preferred activity 4999 // component is no longer known. Ignore it and do NOT remove it. 5000 continue; 5001 } 5002 for (int j=0; j<N; j++) { 5003 final ResolveInfo ri = query.get(j); 5004 if (!ri.activityInfo.applicationInfo.packageName 5005 .equals(ai.applicationInfo.packageName)) { 5006 continue; 5007 } 5008 if (!ri.activityInfo.name.equals(ai.name)) { 5009 continue; 5010 } 5011 // Found a persistent preference that can handle the intent. 5012 if (DEBUG_PREFERRED || debug) { 5013 Slog.v(TAG, "Returning persistent preferred activity: " + 5014 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5015 } 5016 return ri; 5017 } 5018 } 5019 } 5020 return null; 5021 } 5022 5023 // TODO: handle preferred activities missing while user has amnesia 5024 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5025 List<ResolveInfo> query, int priority, boolean always, 5026 boolean removeMatches, boolean debug, int userId) { 5027 if (!sUserManager.exists(userId)) return null; 5028 flags = updateFlagsForResolve(flags, userId, intent); 5029 // writer 5030 synchronized (mPackages) { 5031 if (intent.getSelector() != null) { 5032 intent = intent.getSelector(); 5033 } 5034 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5035 5036 // Try to find a matching persistent preferred activity. 5037 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5038 debug, userId); 5039 5040 // If a persistent preferred activity matched, use it. 5041 if (pri != null) { 5042 return pri; 5043 } 5044 5045 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5046 // Get the list of preferred activities that handle the intent 5047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5048 List<PreferredActivity> prefs = pir != null 5049 ? pir.queryIntent(intent, resolvedType, 5050 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5051 : null; 5052 if (prefs != null && prefs.size() > 0) { 5053 boolean changed = false; 5054 try { 5055 // First figure out how good the original match set is. 5056 // We will only allow preferred activities that came 5057 // from the same match quality. 5058 int match = 0; 5059 5060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5061 5062 final int N = query.size(); 5063 for (int j=0; j<N; j++) { 5064 final ResolveInfo ri = query.get(j); 5065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5066 + ": 0x" + Integer.toHexString(match)); 5067 if (ri.match > match) { 5068 match = ri.match; 5069 } 5070 } 5071 5072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5073 + Integer.toHexString(match)); 5074 5075 match &= IntentFilter.MATCH_CATEGORY_MASK; 5076 final int M = prefs.size(); 5077 for (int i=0; i<M; i++) { 5078 final PreferredActivity pa = prefs.get(i); 5079 if (DEBUG_PREFERRED || debug) { 5080 Slog.v(TAG, "Checking PreferredActivity ds=" 5081 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5082 + "\n component=" + pa.mPref.mComponent); 5083 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5084 } 5085 if (pa.mPref.mMatch != match) { 5086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5087 + Integer.toHexString(pa.mPref.mMatch)); 5088 continue; 5089 } 5090 // If it's not an "always" type preferred activity and that's what we're 5091 // looking for, skip it. 5092 if (always && !pa.mPref.mAlways) { 5093 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5094 continue; 5095 } 5096 final ActivityInfo ai = getActivityInfo( 5097 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5098 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5099 userId); 5100 if (DEBUG_PREFERRED || debug) { 5101 Slog.v(TAG, "Found preferred activity:"); 5102 if (ai != null) { 5103 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5104 } else { 5105 Slog.v(TAG, " null"); 5106 } 5107 } 5108 if (ai == null) { 5109 // This previously registered preferred activity 5110 // component is no longer known. Most likely an update 5111 // to the app was installed and in the new version this 5112 // component no longer exists. Clean it up by removing 5113 // it from the preferred activities list, and skip it. 5114 Slog.w(TAG, "Removing dangling preferred activity: " 5115 + pa.mPref.mComponent); 5116 pir.removeFilter(pa); 5117 changed = true; 5118 continue; 5119 } 5120 for (int j=0; j<N; j++) { 5121 final ResolveInfo ri = query.get(j); 5122 if (!ri.activityInfo.applicationInfo.packageName 5123 .equals(ai.applicationInfo.packageName)) { 5124 continue; 5125 } 5126 if (!ri.activityInfo.name.equals(ai.name)) { 5127 continue; 5128 } 5129 5130 if (removeMatches) { 5131 pir.removeFilter(pa); 5132 changed = true; 5133 if (DEBUG_PREFERRED) { 5134 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5135 } 5136 break; 5137 } 5138 5139 // Okay we found a previously set preferred or last chosen app. 5140 // If the result set is different from when this 5141 // was created, we need to clear it and re-ask the 5142 // user their preference, if we're looking for an "always" type entry. 5143 if (always && !pa.mPref.sameSet(query)) { 5144 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5145 + intent + " type " + resolvedType); 5146 if (DEBUG_PREFERRED) { 5147 Slog.v(TAG, "Removing preferred activity since set changed " 5148 + pa.mPref.mComponent); 5149 } 5150 pir.removeFilter(pa); 5151 // Re-add the filter as a "last chosen" entry (!always) 5152 PreferredActivity lastChosen = new PreferredActivity( 5153 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5154 pir.addFilter(lastChosen); 5155 changed = true; 5156 return null; 5157 } 5158 5159 // Yay! Either the set matched or we're looking for the last chosen 5160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5161 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5162 return ri; 5163 } 5164 } 5165 } finally { 5166 if (changed) { 5167 if (DEBUG_PREFERRED) { 5168 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5169 } 5170 scheduleWritePackageRestrictionsLocked(userId); 5171 } 5172 } 5173 } 5174 } 5175 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5176 return null; 5177 } 5178 5179 /* 5180 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5181 */ 5182 @Override 5183 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5184 int targetUserId) { 5185 mContext.enforceCallingOrSelfPermission( 5186 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5187 List<CrossProfileIntentFilter> matches = 5188 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5189 if (matches != null) { 5190 int size = matches.size(); 5191 for (int i = 0; i < size; i++) { 5192 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5193 } 5194 } 5195 if (hasWebURI(intent)) { 5196 // cross-profile app linking works only towards the parent. 5197 final UserInfo parent = getProfileParent(sourceUserId); 5198 synchronized(mPackages) { 5199 int flags = updateFlagsForResolve(0, parent.id, intent); 5200 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5201 intent, resolvedType, flags, sourceUserId, parent.id); 5202 return xpDomainInfo != null; 5203 } 5204 } 5205 return false; 5206 } 5207 5208 private UserInfo getProfileParent(int userId) { 5209 final long identity = Binder.clearCallingIdentity(); 5210 try { 5211 return sUserManager.getProfileParent(userId); 5212 } finally { 5213 Binder.restoreCallingIdentity(identity); 5214 } 5215 } 5216 5217 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5218 String resolvedType, int userId) { 5219 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5220 if (resolver != null) { 5221 return resolver.queryIntent(intent, resolvedType, false, userId); 5222 } 5223 return null; 5224 } 5225 5226 @Override 5227 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5228 String resolvedType, int flags, int userId) { 5229 try { 5230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5231 5232 return new ParceledListSlice<>( 5233 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5234 } finally { 5235 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5236 } 5237 } 5238 5239 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5240 String resolvedType, int flags, int userId) { 5241 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5242 flags = updateFlagsForResolve(flags, userId, intent); 5243 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5244 false /* requireFullPermission */, false /* checkShell */, 5245 "query intent activities"); 5246 ComponentName comp = intent.getComponent(); 5247 if (comp == null) { 5248 if (intent.getSelector() != null) { 5249 intent = intent.getSelector(); 5250 comp = intent.getComponent(); 5251 } 5252 } 5253 5254 if (comp != null) { 5255 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5256 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5257 if (ai != null) { 5258 final ResolveInfo ri = new ResolveInfo(); 5259 ri.activityInfo = ai; 5260 list.add(ri); 5261 } 5262 return list; 5263 } 5264 5265 // reader 5266 synchronized (mPackages) { 5267 final String pkgName = intent.getPackage(); 5268 if (pkgName == null) { 5269 List<CrossProfileIntentFilter> matchingFilters = 5270 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5271 // Check for results that need to skip the current profile. 5272 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5273 resolvedType, flags, userId); 5274 if (xpResolveInfo != null) { 5275 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5276 result.add(xpResolveInfo); 5277 return filterIfNotSystemUser(result, userId); 5278 } 5279 5280 // Check for results in the current profile. 5281 List<ResolveInfo> result = mActivities.queryIntent( 5282 intent, resolvedType, flags, userId); 5283 result = filterIfNotSystemUser(result, userId); 5284 5285 // Check for cross profile results. 5286 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5287 xpResolveInfo = queryCrossProfileIntents( 5288 matchingFilters, intent, resolvedType, flags, userId, 5289 hasNonNegativePriorityResult); 5290 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5291 boolean isVisibleToUser = filterIfNotSystemUser( 5292 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5293 if (isVisibleToUser) { 5294 result.add(xpResolveInfo); 5295 Collections.sort(result, mResolvePrioritySorter); 5296 } 5297 } 5298 if (hasWebURI(intent)) { 5299 CrossProfileDomainInfo xpDomainInfo = null; 5300 final UserInfo parent = getProfileParent(userId); 5301 if (parent != null) { 5302 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5303 flags, userId, parent.id); 5304 } 5305 if (xpDomainInfo != null) { 5306 if (xpResolveInfo != null) { 5307 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5308 // in the result. 5309 result.remove(xpResolveInfo); 5310 } 5311 if (result.size() == 0) { 5312 result.add(xpDomainInfo.resolveInfo); 5313 return result; 5314 } 5315 } else if (result.size() <= 1) { 5316 return result; 5317 } 5318 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5319 xpDomainInfo, userId); 5320 Collections.sort(result, mResolvePrioritySorter); 5321 } 5322 return result; 5323 } 5324 final PackageParser.Package pkg = mPackages.get(pkgName); 5325 if (pkg != null) { 5326 return filterIfNotSystemUser( 5327 mActivities.queryIntentForPackage( 5328 intent, resolvedType, flags, pkg.activities, userId), 5329 userId); 5330 } 5331 return new ArrayList<ResolveInfo>(); 5332 } 5333 } 5334 5335 private static class CrossProfileDomainInfo { 5336 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5337 ResolveInfo resolveInfo; 5338 /* Best domain verification status of the activities found in the other profile */ 5339 int bestDomainVerificationStatus; 5340 } 5341 5342 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5343 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5344 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5345 sourceUserId)) { 5346 return null; 5347 } 5348 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5349 resolvedType, flags, parentUserId); 5350 5351 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5352 return null; 5353 } 5354 CrossProfileDomainInfo result = null; 5355 int size = resultTargetUser.size(); 5356 for (int i = 0; i < size; i++) { 5357 ResolveInfo riTargetUser = resultTargetUser.get(i); 5358 // Intent filter verification is only for filters that specify a host. So don't return 5359 // those that handle all web uris. 5360 if (riTargetUser.handleAllWebDataURI) { 5361 continue; 5362 } 5363 String packageName = riTargetUser.activityInfo.packageName; 5364 PackageSetting ps = mSettings.mPackages.get(packageName); 5365 if (ps == null) { 5366 continue; 5367 } 5368 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5369 int status = (int)(verificationState >> 32); 5370 if (result == null) { 5371 result = new CrossProfileDomainInfo(); 5372 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5373 sourceUserId, parentUserId); 5374 result.bestDomainVerificationStatus = status; 5375 } else { 5376 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5377 result.bestDomainVerificationStatus); 5378 } 5379 } 5380 // Don't consider matches with status NEVER across profiles. 5381 if (result != null && result.bestDomainVerificationStatus 5382 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5383 return null; 5384 } 5385 return result; 5386 } 5387 5388 /** 5389 * Verification statuses are ordered from the worse to the best, except for 5390 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5391 */ 5392 private int bestDomainVerificationStatus(int status1, int status2) { 5393 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5394 return status2; 5395 } 5396 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5397 return status1; 5398 } 5399 return (int) MathUtils.max(status1, status2); 5400 } 5401 5402 private boolean isUserEnabled(int userId) { 5403 long callingId = Binder.clearCallingIdentity(); 5404 try { 5405 UserInfo userInfo = sUserManager.getUserInfo(userId); 5406 return userInfo != null && userInfo.isEnabled(); 5407 } finally { 5408 Binder.restoreCallingIdentity(callingId); 5409 } 5410 } 5411 5412 /** 5413 * Filter out activities with systemUserOnly flag set, when current user is not System. 5414 * 5415 * @return filtered list 5416 */ 5417 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5418 if (userId == UserHandle.USER_SYSTEM) { 5419 return resolveInfos; 5420 } 5421 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5422 ResolveInfo info = resolveInfos.get(i); 5423 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5424 resolveInfos.remove(i); 5425 } 5426 } 5427 return resolveInfos; 5428 } 5429 5430 /** 5431 * @param resolveInfos list of resolve infos in descending priority order 5432 * @return if the list contains a resolve info with non-negative priority 5433 */ 5434 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5435 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5436 } 5437 5438 private static boolean hasWebURI(Intent intent) { 5439 if (intent.getData() == null) { 5440 return false; 5441 } 5442 final String scheme = intent.getScheme(); 5443 if (TextUtils.isEmpty(scheme)) { 5444 return false; 5445 } 5446 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5447 } 5448 5449 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5450 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5451 int userId) { 5452 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5453 5454 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5455 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5456 candidates.size()); 5457 } 5458 5459 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5460 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5461 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5462 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5463 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5464 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5465 5466 synchronized (mPackages) { 5467 final int count = candidates.size(); 5468 // First, try to use linked apps. Partition the candidates into four lists: 5469 // one for the final results, one for the "do not use ever", one for "undefined status" 5470 // and finally one for "browser app type". 5471 for (int n=0; n<count; n++) { 5472 ResolveInfo info = candidates.get(n); 5473 String packageName = info.activityInfo.packageName; 5474 PackageSetting ps = mSettings.mPackages.get(packageName); 5475 if (ps != null) { 5476 // Add to the special match all list (Browser use case) 5477 if (info.handleAllWebDataURI) { 5478 matchAllList.add(info); 5479 continue; 5480 } 5481 // Try to get the status from User settings first 5482 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5483 int status = (int)(packedStatus >> 32); 5484 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5485 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5486 if (DEBUG_DOMAIN_VERIFICATION) { 5487 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5488 + " : linkgen=" + linkGeneration); 5489 } 5490 // Use link-enabled generation as preferredOrder, i.e. 5491 // prefer newly-enabled over earlier-enabled. 5492 info.preferredOrder = linkGeneration; 5493 alwaysList.add(info); 5494 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5495 if (DEBUG_DOMAIN_VERIFICATION) { 5496 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5497 } 5498 neverList.add(info); 5499 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5500 if (DEBUG_DOMAIN_VERIFICATION) { 5501 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5502 } 5503 alwaysAskList.add(info); 5504 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5505 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5506 if (DEBUG_DOMAIN_VERIFICATION) { 5507 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5508 } 5509 undefinedList.add(info); 5510 } 5511 } 5512 } 5513 5514 // We'll want to include browser possibilities in a few cases 5515 boolean includeBrowser = false; 5516 5517 // First try to add the "always" resolution(s) for the current user, if any 5518 if (alwaysList.size() > 0) { 5519 result.addAll(alwaysList); 5520 } else { 5521 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5522 result.addAll(undefinedList); 5523 // Maybe add one for the other profile. 5524 if (xpDomainInfo != null && ( 5525 xpDomainInfo.bestDomainVerificationStatus 5526 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5527 result.add(xpDomainInfo.resolveInfo); 5528 } 5529 includeBrowser = true; 5530 } 5531 5532 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5533 // If there were 'always' entries their preferred order has been set, so we also 5534 // back that off to make the alternatives equivalent 5535 if (alwaysAskList.size() > 0) { 5536 for (ResolveInfo i : result) { 5537 i.preferredOrder = 0; 5538 } 5539 result.addAll(alwaysAskList); 5540 includeBrowser = true; 5541 } 5542 5543 if (includeBrowser) { 5544 // Also add browsers (all of them or only the default one) 5545 if (DEBUG_DOMAIN_VERIFICATION) { 5546 Slog.v(TAG, " ...including browsers in candidate set"); 5547 } 5548 if ((matchFlags & MATCH_ALL) != 0) { 5549 result.addAll(matchAllList); 5550 } else { 5551 // Browser/generic handling case. If there's a default browser, go straight 5552 // to that (but only if there is no other higher-priority match). 5553 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5554 int maxMatchPrio = 0; 5555 ResolveInfo defaultBrowserMatch = null; 5556 final int numCandidates = matchAllList.size(); 5557 for (int n = 0; n < numCandidates; n++) { 5558 ResolveInfo info = matchAllList.get(n); 5559 // track the highest overall match priority... 5560 if (info.priority > maxMatchPrio) { 5561 maxMatchPrio = info.priority; 5562 } 5563 // ...and the highest-priority default browser match 5564 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5565 if (defaultBrowserMatch == null 5566 || (defaultBrowserMatch.priority < info.priority)) { 5567 if (debug) { 5568 Slog.v(TAG, "Considering default browser match " + info); 5569 } 5570 defaultBrowserMatch = info; 5571 } 5572 } 5573 } 5574 if (defaultBrowserMatch != null 5575 && defaultBrowserMatch.priority >= maxMatchPrio 5576 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5577 { 5578 if (debug) { 5579 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5580 } 5581 result.add(defaultBrowserMatch); 5582 } else { 5583 result.addAll(matchAllList); 5584 } 5585 } 5586 5587 // If there is nothing selected, add all candidates and remove the ones that the user 5588 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5589 if (result.size() == 0) { 5590 result.addAll(candidates); 5591 result.removeAll(neverList); 5592 } 5593 } 5594 } 5595 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5596 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5597 result.size()); 5598 for (ResolveInfo info : result) { 5599 Slog.v(TAG, " + " + info.activityInfo); 5600 } 5601 } 5602 return result; 5603 } 5604 5605 // Returns a packed value as a long: 5606 // 5607 // high 'int'-sized word: link status: undefined/ask/never/always. 5608 // low 'int'-sized word: relative priority among 'always' results. 5609 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5610 long result = ps.getDomainVerificationStatusForUser(userId); 5611 // if none available, get the master status 5612 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5613 if (ps.getIntentFilterVerificationInfo() != null) { 5614 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5615 } 5616 } 5617 return result; 5618 } 5619 5620 private ResolveInfo querySkipCurrentProfileIntents( 5621 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5622 int flags, int sourceUserId) { 5623 if (matchingFilters != null) { 5624 int size = matchingFilters.size(); 5625 for (int i = 0; i < size; i ++) { 5626 CrossProfileIntentFilter filter = matchingFilters.get(i); 5627 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5628 // Checking if there are activities in the target user that can handle the 5629 // intent. 5630 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5631 resolvedType, flags, sourceUserId); 5632 if (resolveInfo != null) { 5633 return resolveInfo; 5634 } 5635 } 5636 } 5637 } 5638 return null; 5639 } 5640 5641 // Return matching ResolveInfo in target user if any. 5642 private ResolveInfo queryCrossProfileIntents( 5643 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5644 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5645 if (matchingFilters != null) { 5646 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5647 // match the same intent. For performance reasons, it is better not to 5648 // run queryIntent twice for the same userId 5649 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5650 int size = matchingFilters.size(); 5651 for (int i = 0; i < size; i++) { 5652 CrossProfileIntentFilter filter = matchingFilters.get(i); 5653 int targetUserId = filter.getTargetUserId(); 5654 boolean skipCurrentProfile = 5655 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5656 boolean skipCurrentProfileIfNoMatchFound = 5657 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5658 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5659 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5660 // Checking if there are activities in the target user that can handle the 5661 // intent. 5662 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5663 resolvedType, flags, sourceUserId); 5664 if (resolveInfo != null) return resolveInfo; 5665 alreadyTriedUserIds.put(targetUserId, true); 5666 } 5667 } 5668 } 5669 return null; 5670 } 5671 5672 /** 5673 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5674 * will forward the intent to the filter's target user. 5675 * Otherwise, returns null. 5676 */ 5677 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5678 String resolvedType, int flags, int sourceUserId) { 5679 int targetUserId = filter.getTargetUserId(); 5680 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5681 resolvedType, flags, targetUserId); 5682 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5683 // If all the matches in the target profile are suspended, return null. 5684 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5685 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5686 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5687 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5688 targetUserId); 5689 } 5690 } 5691 } 5692 return null; 5693 } 5694 5695 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5696 int sourceUserId, int targetUserId) { 5697 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5698 long ident = Binder.clearCallingIdentity(); 5699 boolean targetIsProfile; 5700 try { 5701 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5702 } finally { 5703 Binder.restoreCallingIdentity(ident); 5704 } 5705 String className; 5706 if (targetIsProfile) { 5707 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5708 } else { 5709 className = FORWARD_INTENT_TO_PARENT; 5710 } 5711 ComponentName forwardingActivityComponentName = new ComponentName( 5712 mAndroidApplication.packageName, className); 5713 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5714 sourceUserId); 5715 if (!targetIsProfile) { 5716 forwardingActivityInfo.showUserIcon = targetUserId; 5717 forwardingResolveInfo.noResourceId = true; 5718 } 5719 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5720 forwardingResolveInfo.priority = 0; 5721 forwardingResolveInfo.preferredOrder = 0; 5722 forwardingResolveInfo.match = 0; 5723 forwardingResolveInfo.isDefault = true; 5724 forwardingResolveInfo.filter = filter; 5725 forwardingResolveInfo.targetUserId = targetUserId; 5726 return forwardingResolveInfo; 5727 } 5728 5729 @Override 5730 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5731 Intent[] specifics, String[] specificTypes, Intent intent, 5732 String resolvedType, int flags, int userId) { 5733 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5734 specificTypes, intent, resolvedType, flags, userId)); 5735 } 5736 5737 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5738 Intent[] specifics, String[] specificTypes, Intent intent, 5739 String resolvedType, int flags, int userId) { 5740 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5741 flags = updateFlagsForResolve(flags, userId, intent); 5742 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5743 false /* requireFullPermission */, false /* checkShell */, 5744 "query intent activity options"); 5745 final String resultsAction = intent.getAction(); 5746 5747 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5748 | PackageManager.GET_RESOLVED_FILTER, userId); 5749 5750 if (DEBUG_INTENT_MATCHING) { 5751 Log.v(TAG, "Query " + intent + ": " + results); 5752 } 5753 5754 int specificsPos = 0; 5755 int N; 5756 5757 // todo: note that the algorithm used here is O(N^2). This 5758 // isn't a problem in our current environment, but if we start running 5759 // into situations where we have more than 5 or 10 matches then this 5760 // should probably be changed to something smarter... 5761 5762 // First we go through and resolve each of the specific items 5763 // that were supplied, taking care of removing any corresponding 5764 // duplicate items in the generic resolve list. 5765 if (specifics != null) { 5766 for (int i=0; i<specifics.length; i++) { 5767 final Intent sintent = specifics[i]; 5768 if (sintent == null) { 5769 continue; 5770 } 5771 5772 if (DEBUG_INTENT_MATCHING) { 5773 Log.v(TAG, "Specific #" + i + ": " + sintent); 5774 } 5775 5776 String action = sintent.getAction(); 5777 if (resultsAction != null && resultsAction.equals(action)) { 5778 // If this action was explicitly requested, then don't 5779 // remove things that have it. 5780 action = null; 5781 } 5782 5783 ResolveInfo ri = null; 5784 ActivityInfo ai = null; 5785 5786 ComponentName comp = sintent.getComponent(); 5787 if (comp == null) { 5788 ri = resolveIntent( 5789 sintent, 5790 specificTypes != null ? specificTypes[i] : null, 5791 flags, userId); 5792 if (ri == null) { 5793 continue; 5794 } 5795 if (ri == mResolveInfo) { 5796 // ACK! Must do something better with this. 5797 } 5798 ai = ri.activityInfo; 5799 comp = new ComponentName(ai.applicationInfo.packageName, 5800 ai.name); 5801 } else { 5802 ai = getActivityInfo(comp, flags, userId); 5803 if (ai == null) { 5804 continue; 5805 } 5806 } 5807 5808 // Look for any generic query activities that are duplicates 5809 // of this specific one, and remove them from the results. 5810 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5811 N = results.size(); 5812 int j; 5813 for (j=specificsPos; j<N; j++) { 5814 ResolveInfo sri = results.get(j); 5815 if ((sri.activityInfo.name.equals(comp.getClassName()) 5816 && sri.activityInfo.applicationInfo.packageName.equals( 5817 comp.getPackageName())) 5818 || (action != null && sri.filter.matchAction(action))) { 5819 results.remove(j); 5820 if (DEBUG_INTENT_MATCHING) Log.v( 5821 TAG, "Removing duplicate item from " + j 5822 + " due to specific " + specificsPos); 5823 if (ri == null) { 5824 ri = sri; 5825 } 5826 j--; 5827 N--; 5828 } 5829 } 5830 5831 // Add this specific item to its proper place. 5832 if (ri == null) { 5833 ri = new ResolveInfo(); 5834 ri.activityInfo = ai; 5835 } 5836 results.add(specificsPos, ri); 5837 ri.specificIndex = i; 5838 specificsPos++; 5839 } 5840 } 5841 5842 // Now we go through the remaining generic results and remove any 5843 // duplicate actions that are found here. 5844 N = results.size(); 5845 for (int i=specificsPos; i<N-1; i++) { 5846 final ResolveInfo rii = results.get(i); 5847 if (rii.filter == null) { 5848 continue; 5849 } 5850 5851 // Iterate over all of the actions of this result's intent 5852 // filter... typically this should be just one. 5853 final Iterator<String> it = rii.filter.actionsIterator(); 5854 if (it == null) { 5855 continue; 5856 } 5857 while (it.hasNext()) { 5858 final String action = it.next(); 5859 if (resultsAction != null && resultsAction.equals(action)) { 5860 // If this action was explicitly requested, then don't 5861 // remove things that have it. 5862 continue; 5863 } 5864 for (int j=i+1; j<N; j++) { 5865 final ResolveInfo rij = results.get(j); 5866 if (rij.filter != null && rij.filter.hasAction(action)) { 5867 results.remove(j); 5868 if (DEBUG_INTENT_MATCHING) Log.v( 5869 TAG, "Removing duplicate item from " + j 5870 + " due to action " + action + " at " + i); 5871 j--; 5872 N--; 5873 } 5874 } 5875 } 5876 5877 // If the caller didn't request filter information, drop it now 5878 // so we don't have to marshall/unmarshall it. 5879 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5880 rii.filter = null; 5881 } 5882 } 5883 5884 // Filter out the caller activity if so requested. 5885 if (caller != null) { 5886 N = results.size(); 5887 for (int i=0; i<N; i++) { 5888 ActivityInfo ainfo = results.get(i).activityInfo; 5889 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5890 && caller.getClassName().equals(ainfo.name)) { 5891 results.remove(i); 5892 break; 5893 } 5894 } 5895 } 5896 5897 // If the caller didn't request filter information, 5898 // drop them now so we don't have to 5899 // marshall/unmarshall it. 5900 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5901 N = results.size(); 5902 for (int i=0; i<N; i++) { 5903 results.get(i).filter = null; 5904 } 5905 } 5906 5907 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5908 return results; 5909 } 5910 5911 @Override 5912 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5913 String resolvedType, int flags, int userId) { 5914 return new ParceledListSlice<>( 5915 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5916 } 5917 5918 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5919 String resolvedType, int flags, int userId) { 5920 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5921 flags = updateFlagsForResolve(flags, userId, intent); 5922 ComponentName comp = intent.getComponent(); 5923 if (comp == null) { 5924 if (intent.getSelector() != null) { 5925 intent = intent.getSelector(); 5926 comp = intent.getComponent(); 5927 } 5928 } 5929 if (comp != null) { 5930 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5931 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5932 if (ai != null) { 5933 ResolveInfo ri = new ResolveInfo(); 5934 ri.activityInfo = ai; 5935 list.add(ri); 5936 } 5937 return list; 5938 } 5939 5940 // reader 5941 synchronized (mPackages) { 5942 String pkgName = intent.getPackage(); 5943 if (pkgName == null) { 5944 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5945 } 5946 final PackageParser.Package pkg = mPackages.get(pkgName); 5947 if (pkg != null) { 5948 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5949 userId); 5950 } 5951 return Collections.emptyList(); 5952 } 5953 } 5954 5955 @Override 5956 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5957 if (!sUserManager.exists(userId)) return null; 5958 flags = updateFlagsForResolve(flags, userId, intent); 5959 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5960 if (query != null) { 5961 if (query.size() >= 1) { 5962 // If there is more than one service with the same priority, 5963 // just arbitrarily pick the first one. 5964 return query.get(0); 5965 } 5966 } 5967 return null; 5968 } 5969 5970 @Override 5971 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5972 String resolvedType, int flags, int userId) { 5973 return new ParceledListSlice<>( 5974 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5975 } 5976 5977 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5978 String resolvedType, int flags, int userId) { 5979 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5980 flags = updateFlagsForResolve(flags, userId, intent); 5981 ComponentName comp = intent.getComponent(); 5982 if (comp == null) { 5983 if (intent.getSelector() != null) { 5984 intent = intent.getSelector(); 5985 comp = intent.getComponent(); 5986 } 5987 } 5988 if (comp != null) { 5989 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5990 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5991 if (si != null) { 5992 final ResolveInfo ri = new ResolveInfo(); 5993 ri.serviceInfo = si; 5994 list.add(ri); 5995 } 5996 return list; 5997 } 5998 5999 // reader 6000 synchronized (mPackages) { 6001 String pkgName = intent.getPackage(); 6002 if (pkgName == null) { 6003 return mServices.queryIntent(intent, resolvedType, flags, userId); 6004 } 6005 final PackageParser.Package pkg = mPackages.get(pkgName); 6006 if (pkg != null) { 6007 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6008 userId); 6009 } 6010 return Collections.emptyList(); 6011 } 6012 } 6013 6014 @Override 6015 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6016 String resolvedType, int flags, int userId) { 6017 return new ParceledListSlice<>( 6018 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6019 } 6020 6021 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6022 Intent intent, String resolvedType, int flags, int userId) { 6023 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6024 flags = updateFlagsForResolve(flags, userId, intent); 6025 ComponentName comp = intent.getComponent(); 6026 if (comp == null) { 6027 if (intent.getSelector() != null) { 6028 intent = intent.getSelector(); 6029 comp = intent.getComponent(); 6030 } 6031 } 6032 if (comp != null) { 6033 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6034 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6035 if (pi != null) { 6036 final ResolveInfo ri = new ResolveInfo(); 6037 ri.providerInfo = pi; 6038 list.add(ri); 6039 } 6040 return list; 6041 } 6042 6043 // reader 6044 synchronized (mPackages) { 6045 String pkgName = intent.getPackage(); 6046 if (pkgName == null) { 6047 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6048 } 6049 final PackageParser.Package pkg = mPackages.get(pkgName); 6050 if (pkg != null) { 6051 return mProviders.queryIntentForPackage( 6052 intent, resolvedType, flags, pkg.providers, userId); 6053 } 6054 return Collections.emptyList(); 6055 } 6056 } 6057 6058 @Override 6059 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6060 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6061 flags = updateFlagsForPackage(flags, userId, null); 6062 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6063 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6064 true /* requireFullPermission */, false /* checkShell */, 6065 "get installed packages"); 6066 6067 // writer 6068 synchronized (mPackages) { 6069 ArrayList<PackageInfo> list; 6070 if (listUninstalled) { 6071 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6072 for (PackageSetting ps : mSettings.mPackages.values()) { 6073 final PackageInfo pi; 6074 if (ps.pkg != null) { 6075 pi = generatePackageInfo(ps, flags, userId); 6076 } else { 6077 pi = generatePackageInfo(ps, flags, userId); 6078 } 6079 if (pi != null) { 6080 list.add(pi); 6081 } 6082 } 6083 } else { 6084 list = new ArrayList<PackageInfo>(mPackages.size()); 6085 for (PackageParser.Package p : mPackages.values()) { 6086 final PackageInfo pi = 6087 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6088 if (pi != null) { 6089 list.add(pi); 6090 } 6091 } 6092 } 6093 6094 return new ParceledListSlice<PackageInfo>(list); 6095 } 6096 } 6097 6098 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6099 String[] permissions, boolean[] tmp, int flags, int userId) { 6100 int numMatch = 0; 6101 final PermissionsState permissionsState = ps.getPermissionsState(); 6102 for (int i=0; i<permissions.length; i++) { 6103 final String permission = permissions[i]; 6104 if (permissionsState.hasPermission(permission, userId)) { 6105 tmp[i] = true; 6106 numMatch++; 6107 } else { 6108 tmp[i] = false; 6109 } 6110 } 6111 if (numMatch == 0) { 6112 return; 6113 } 6114 final PackageInfo pi; 6115 if (ps.pkg != null) { 6116 pi = generatePackageInfo(ps, flags, userId); 6117 } else { 6118 pi = generatePackageInfo(ps, flags, userId); 6119 } 6120 // The above might return null in cases of uninstalled apps or install-state 6121 // skew across users/profiles. 6122 if (pi != null) { 6123 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6124 if (numMatch == permissions.length) { 6125 pi.requestedPermissions = permissions; 6126 } else { 6127 pi.requestedPermissions = new String[numMatch]; 6128 numMatch = 0; 6129 for (int i=0; i<permissions.length; i++) { 6130 if (tmp[i]) { 6131 pi.requestedPermissions[numMatch] = permissions[i]; 6132 numMatch++; 6133 } 6134 } 6135 } 6136 } 6137 list.add(pi); 6138 } 6139 } 6140 6141 @Override 6142 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6143 String[] permissions, int flags, int userId) { 6144 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6145 flags = updateFlagsForPackage(flags, userId, permissions); 6146 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6147 6148 // writer 6149 synchronized (mPackages) { 6150 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6151 boolean[] tmpBools = new boolean[permissions.length]; 6152 if (listUninstalled) { 6153 for (PackageSetting ps : mSettings.mPackages.values()) { 6154 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6155 } 6156 } else { 6157 for (PackageParser.Package pkg : mPackages.values()) { 6158 PackageSetting ps = (PackageSetting)pkg.mExtras; 6159 if (ps != null) { 6160 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6161 userId); 6162 } 6163 } 6164 } 6165 6166 return new ParceledListSlice<PackageInfo>(list); 6167 } 6168 } 6169 6170 @Override 6171 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6172 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6173 flags = updateFlagsForApplication(flags, userId, null); 6174 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6175 6176 // writer 6177 synchronized (mPackages) { 6178 ArrayList<ApplicationInfo> list; 6179 if (listUninstalled) { 6180 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6181 for (PackageSetting ps : mSettings.mPackages.values()) { 6182 ApplicationInfo ai; 6183 if (ps.pkg != null) { 6184 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6185 ps.readUserState(userId), userId); 6186 } else { 6187 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6188 } 6189 if (ai != null) { 6190 list.add(ai); 6191 } 6192 } 6193 } else { 6194 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6195 for (PackageParser.Package p : mPackages.values()) { 6196 if (p.mExtras != null) { 6197 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6198 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6199 if (ai != null) { 6200 list.add(ai); 6201 } 6202 } 6203 } 6204 } 6205 6206 return new ParceledListSlice<ApplicationInfo>(list); 6207 } 6208 } 6209 6210 @Override 6211 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6212 if (DISABLE_EPHEMERAL_APPS) { 6213 return null; 6214 } 6215 6216 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6217 "getEphemeralApplications"); 6218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6219 true /* requireFullPermission */, false /* checkShell */, 6220 "getEphemeralApplications"); 6221 synchronized (mPackages) { 6222 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6223 .getEphemeralApplicationsLPw(userId); 6224 if (ephemeralApps != null) { 6225 return new ParceledListSlice<>(ephemeralApps); 6226 } 6227 } 6228 return null; 6229 } 6230 6231 @Override 6232 public boolean isEphemeralApplication(String packageName, int userId) { 6233 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6234 true /* requireFullPermission */, false /* checkShell */, 6235 "isEphemeral"); 6236 if (DISABLE_EPHEMERAL_APPS) { 6237 return false; 6238 } 6239 6240 if (!isCallerSameApp(packageName)) { 6241 return false; 6242 } 6243 synchronized (mPackages) { 6244 PackageParser.Package pkg = mPackages.get(packageName); 6245 if (pkg != null) { 6246 return pkg.applicationInfo.isEphemeralApp(); 6247 } 6248 } 6249 return false; 6250 } 6251 6252 @Override 6253 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6254 if (DISABLE_EPHEMERAL_APPS) { 6255 return null; 6256 } 6257 6258 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6259 true /* requireFullPermission */, false /* checkShell */, 6260 "getCookie"); 6261 if (!isCallerSameApp(packageName)) { 6262 return null; 6263 } 6264 synchronized (mPackages) { 6265 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6266 packageName, userId); 6267 } 6268 } 6269 6270 @Override 6271 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6272 if (DISABLE_EPHEMERAL_APPS) { 6273 return true; 6274 } 6275 6276 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6277 true /* requireFullPermission */, true /* checkShell */, 6278 "setCookie"); 6279 if (!isCallerSameApp(packageName)) { 6280 return false; 6281 } 6282 synchronized (mPackages) { 6283 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6284 packageName, cookie, userId); 6285 } 6286 } 6287 6288 @Override 6289 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6290 if (DISABLE_EPHEMERAL_APPS) { 6291 return null; 6292 } 6293 6294 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6295 "getEphemeralApplicationIcon"); 6296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6297 true /* requireFullPermission */, false /* checkShell */, 6298 "getEphemeralApplicationIcon"); 6299 synchronized (mPackages) { 6300 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6301 packageName, userId); 6302 } 6303 } 6304 6305 private boolean isCallerSameApp(String packageName) { 6306 PackageParser.Package pkg = mPackages.get(packageName); 6307 return pkg != null 6308 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6309 } 6310 6311 @Override 6312 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6313 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6314 } 6315 6316 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6317 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6318 6319 // reader 6320 synchronized (mPackages) { 6321 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6322 final int userId = UserHandle.getCallingUserId(); 6323 while (i.hasNext()) { 6324 final PackageParser.Package p = i.next(); 6325 if (p.applicationInfo == null) continue; 6326 6327 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6328 && !p.applicationInfo.isDirectBootAware(); 6329 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6330 && p.applicationInfo.isDirectBootAware(); 6331 6332 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6333 && (!mSafeMode || isSystemApp(p)) 6334 && (matchesUnaware || matchesAware)) { 6335 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6336 if (ps != null) { 6337 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6338 ps.readUserState(userId), userId); 6339 if (ai != null) { 6340 finalList.add(ai); 6341 } 6342 } 6343 } 6344 } 6345 } 6346 6347 return finalList; 6348 } 6349 6350 @Override 6351 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6352 if (!sUserManager.exists(userId)) return null; 6353 flags = updateFlagsForComponent(flags, userId, name); 6354 // reader 6355 synchronized (mPackages) { 6356 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6357 PackageSetting ps = provider != null 6358 ? mSettings.mPackages.get(provider.owner.packageName) 6359 : null; 6360 return ps != null 6361 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6362 ? PackageParser.generateProviderInfo(provider, flags, 6363 ps.readUserState(userId), userId) 6364 : null; 6365 } 6366 } 6367 6368 /** 6369 * @deprecated 6370 */ 6371 @Deprecated 6372 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6373 // reader 6374 synchronized (mPackages) { 6375 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6376 .entrySet().iterator(); 6377 final int userId = UserHandle.getCallingUserId(); 6378 while (i.hasNext()) { 6379 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6380 PackageParser.Provider p = entry.getValue(); 6381 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6382 6383 if (ps != null && p.syncable 6384 && (!mSafeMode || (p.info.applicationInfo.flags 6385 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6386 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6387 ps.readUserState(userId), userId); 6388 if (info != null) { 6389 outNames.add(entry.getKey()); 6390 outInfo.add(info); 6391 } 6392 } 6393 } 6394 } 6395 } 6396 6397 @Override 6398 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6399 int uid, int flags) { 6400 final int userId = processName != null ? UserHandle.getUserId(uid) 6401 : UserHandle.getCallingUserId(); 6402 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6403 flags = updateFlagsForComponent(flags, userId, processName); 6404 6405 ArrayList<ProviderInfo> finalList = null; 6406 // reader 6407 synchronized (mPackages) { 6408 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6409 while (i.hasNext()) { 6410 final PackageParser.Provider p = i.next(); 6411 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6412 if (ps != null && p.info.authority != null 6413 && (processName == null 6414 || (p.info.processName.equals(processName) 6415 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6416 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6417 if (finalList == null) { 6418 finalList = new ArrayList<ProviderInfo>(3); 6419 } 6420 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6421 ps.readUserState(userId), userId); 6422 if (info != null) { 6423 finalList.add(info); 6424 } 6425 } 6426 } 6427 } 6428 6429 if (finalList != null) { 6430 Collections.sort(finalList, mProviderInitOrderSorter); 6431 return new ParceledListSlice<ProviderInfo>(finalList); 6432 } 6433 6434 return ParceledListSlice.emptyList(); 6435 } 6436 6437 @Override 6438 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6439 // reader 6440 synchronized (mPackages) { 6441 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6442 return PackageParser.generateInstrumentationInfo(i, flags); 6443 } 6444 } 6445 6446 @Override 6447 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6448 String targetPackage, int flags) { 6449 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6450 } 6451 6452 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6453 int flags) { 6454 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6455 6456 // reader 6457 synchronized (mPackages) { 6458 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6459 while (i.hasNext()) { 6460 final PackageParser.Instrumentation p = i.next(); 6461 if (targetPackage == null 6462 || targetPackage.equals(p.info.targetPackage)) { 6463 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6464 flags); 6465 if (ii != null) { 6466 finalList.add(ii); 6467 } 6468 } 6469 } 6470 } 6471 6472 return finalList; 6473 } 6474 6475 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6476 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6477 if (overlays == null) { 6478 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6479 return; 6480 } 6481 for (PackageParser.Package opkg : overlays.values()) { 6482 // Not much to do if idmap fails: we already logged the error 6483 // and we certainly don't want to abort installation of pkg simply 6484 // because an overlay didn't fit properly. For these reasons, 6485 // ignore the return value of createIdmapForPackagePairLI. 6486 createIdmapForPackagePairLI(pkg, opkg); 6487 } 6488 } 6489 6490 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6491 PackageParser.Package opkg) { 6492 if (!opkg.mTrustedOverlay) { 6493 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6494 opkg.baseCodePath + ": overlay not trusted"); 6495 return false; 6496 } 6497 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6498 if (overlaySet == null) { 6499 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6500 opkg.baseCodePath + " but target package has no known overlays"); 6501 return false; 6502 } 6503 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6504 // TODO: generate idmap for split APKs 6505 try { 6506 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6507 } catch (InstallerException e) { 6508 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6509 + opkg.baseCodePath); 6510 return false; 6511 } 6512 PackageParser.Package[] overlayArray = 6513 overlaySet.values().toArray(new PackageParser.Package[0]); 6514 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6515 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6516 return p1.mOverlayPriority - p2.mOverlayPriority; 6517 } 6518 }; 6519 Arrays.sort(overlayArray, cmp); 6520 6521 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6522 int i = 0; 6523 for (PackageParser.Package p : overlayArray) { 6524 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6525 } 6526 return true; 6527 } 6528 6529 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6531 try { 6532 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6533 } finally { 6534 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6535 } 6536 } 6537 6538 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6539 final File[] files = dir.listFiles(); 6540 if (ArrayUtils.isEmpty(files)) { 6541 Log.d(TAG, "No files in app dir " + dir); 6542 return; 6543 } 6544 6545 if (DEBUG_PACKAGE_SCANNING) { 6546 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6547 + " flags=0x" + Integer.toHexString(parseFlags)); 6548 } 6549 6550 for (File file : files) { 6551 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6552 && !PackageInstallerService.isStageName(file.getName()); 6553 if (!isPackage) { 6554 // Ignore entries which are not packages 6555 continue; 6556 } 6557 try { 6558 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6559 scanFlags, currentTime, null); 6560 } catch (PackageManagerException e) { 6561 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6562 6563 // Delete invalid userdata apps 6564 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6565 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6566 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6567 removeCodePathLI(file); 6568 } 6569 } 6570 } 6571 } 6572 6573 private static File getSettingsProblemFile() { 6574 File dataDir = Environment.getDataDirectory(); 6575 File systemDir = new File(dataDir, "system"); 6576 File fname = new File(systemDir, "uiderrors.txt"); 6577 return fname; 6578 } 6579 6580 static void reportSettingsProblem(int priority, String msg) { 6581 logCriticalInfo(priority, msg); 6582 } 6583 6584 static void logCriticalInfo(int priority, String msg) { 6585 Slog.println(priority, TAG, msg); 6586 EventLogTags.writePmCriticalInfo(msg); 6587 try { 6588 File fname = getSettingsProblemFile(); 6589 FileOutputStream out = new FileOutputStream(fname, true); 6590 PrintWriter pw = new FastPrintWriter(out); 6591 SimpleDateFormat formatter = new SimpleDateFormat(); 6592 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6593 pw.println(dateString + ": " + msg); 6594 pw.close(); 6595 FileUtils.setPermissions( 6596 fname.toString(), 6597 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6598 -1, -1); 6599 } catch (java.io.IOException e) { 6600 } 6601 } 6602 6603 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6604 if (srcFile.isDirectory()) { 6605 final File baseFile = new File(pkg.baseCodePath); 6606 long maxModifiedTime = baseFile.lastModified(); 6607 if (pkg.splitCodePaths != null) { 6608 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6609 final File splitFile = new File(pkg.splitCodePaths[i]); 6610 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6611 } 6612 } 6613 return maxModifiedTime; 6614 } 6615 return srcFile.lastModified(); 6616 } 6617 6618 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6619 final int policyFlags) throws PackageManagerException { 6620 if (ps != null 6621 && ps.codePath.equals(srcFile) 6622 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6623 && !isCompatSignatureUpdateNeeded(pkg) 6624 && !isRecoverSignatureUpdateNeeded(pkg)) { 6625 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6626 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6627 ArraySet<PublicKey> signingKs; 6628 synchronized (mPackages) { 6629 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6630 } 6631 if (ps.signatures.mSignatures != null 6632 && ps.signatures.mSignatures.length != 0 6633 && signingKs != null) { 6634 // Optimization: reuse the existing cached certificates 6635 // if the package appears to be unchanged. 6636 pkg.mSignatures = ps.signatures.mSignatures; 6637 pkg.mSigningKeys = signingKs; 6638 return; 6639 } 6640 6641 Slog.w(TAG, "PackageSetting for " + ps.name 6642 + " is missing signatures. Collecting certs again to recover them."); 6643 } else { 6644 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6645 } 6646 6647 try { 6648 PackageParser.collectCertificates(pkg, policyFlags); 6649 } catch (PackageParserException e) { 6650 throw PackageManagerException.from(e); 6651 } 6652 } 6653 6654 /** 6655 * Traces a package scan. 6656 * @see #scanPackageLI(File, int, int, long, UserHandle) 6657 */ 6658 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6659 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6661 try { 6662 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6663 } finally { 6664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6665 } 6666 } 6667 6668 /** 6669 * Scans a package and returns the newly parsed package. 6670 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6671 */ 6672 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6673 long currentTime, UserHandle user) throws PackageManagerException { 6674 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6675 PackageParser pp = new PackageParser(); 6676 pp.setSeparateProcesses(mSeparateProcesses); 6677 pp.setOnlyCoreApps(mOnlyCore); 6678 pp.setDisplayMetrics(mMetrics); 6679 6680 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6681 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6682 } 6683 6684 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6685 final PackageParser.Package pkg; 6686 try { 6687 pkg = pp.parsePackage(scanFile, parseFlags); 6688 } catch (PackageParserException e) { 6689 throw PackageManagerException.from(e); 6690 } finally { 6691 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6692 } 6693 6694 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6695 } 6696 6697 /** 6698 * Scans a package and returns the newly parsed package. 6699 * @throws PackageManagerException on a parse error. 6700 */ 6701 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6702 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6703 throws PackageManagerException { 6704 // If the package has children and this is the first dive in the function 6705 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6706 // packages (parent and children) would be successfully scanned before the 6707 // actual scan since scanning mutates internal state and we want to atomically 6708 // install the package and its children. 6709 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6710 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6711 scanFlags |= SCAN_CHECK_ONLY; 6712 } 6713 } else { 6714 scanFlags &= ~SCAN_CHECK_ONLY; 6715 } 6716 6717 // Scan the parent 6718 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6719 scanFlags, currentTime, user); 6720 6721 // Scan the children 6722 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6723 for (int i = 0; i < childCount; i++) { 6724 PackageParser.Package childPackage = pkg.childPackages.get(i); 6725 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6726 currentTime, user); 6727 } 6728 6729 6730 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6731 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6732 } 6733 6734 return scannedPkg; 6735 } 6736 6737 /** 6738 * Scans a package and returns the newly parsed package. 6739 * @throws PackageManagerException on a parse error. 6740 */ 6741 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6742 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6743 throws PackageManagerException { 6744 PackageSetting ps = null; 6745 PackageSetting updatedPkg; 6746 // reader 6747 synchronized (mPackages) { 6748 // Look to see if we already know about this package. 6749 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6750 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6751 // This package has been renamed to its original name. Let's 6752 // use that. 6753 ps = mSettings.peekPackageLPr(oldName); 6754 } 6755 // If there was no original package, see one for the real package name. 6756 if (ps == null) { 6757 ps = mSettings.peekPackageLPr(pkg.packageName); 6758 } 6759 // Check to see if this package could be hiding/updating a system 6760 // package. Must look for it either under the original or real 6761 // package name depending on our state. 6762 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6763 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6764 6765 // If this is a package we don't know about on the system partition, we 6766 // may need to remove disabled child packages on the system partition 6767 // or may need to not add child packages if the parent apk is updated 6768 // on the data partition and no longer defines this child package. 6769 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6770 // If this is a parent package for an updated system app and this system 6771 // app got an OTA update which no longer defines some of the child packages 6772 // we have to prune them from the disabled system packages. 6773 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6774 if (disabledPs != null) { 6775 final int scannedChildCount = (pkg.childPackages != null) 6776 ? pkg.childPackages.size() : 0; 6777 final int disabledChildCount = disabledPs.childPackageNames != null 6778 ? disabledPs.childPackageNames.size() : 0; 6779 for (int i = 0; i < disabledChildCount; i++) { 6780 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6781 boolean disabledPackageAvailable = false; 6782 for (int j = 0; j < scannedChildCount; j++) { 6783 PackageParser.Package childPkg = pkg.childPackages.get(j); 6784 if (childPkg.packageName.equals(disabledChildPackageName)) { 6785 disabledPackageAvailable = true; 6786 break; 6787 } 6788 } 6789 if (!disabledPackageAvailable) { 6790 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6791 } 6792 } 6793 } 6794 } 6795 } 6796 6797 boolean updatedPkgBetter = false; 6798 // First check if this is a system package that may involve an update 6799 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6800 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6801 // it needs to drop FLAG_PRIVILEGED. 6802 if (locationIsPrivileged(scanFile)) { 6803 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6804 } else { 6805 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6806 } 6807 6808 if (ps != null && !ps.codePath.equals(scanFile)) { 6809 // The path has changed from what was last scanned... check the 6810 // version of the new path against what we have stored to determine 6811 // what to do. 6812 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6813 if (pkg.mVersionCode <= ps.versionCode) { 6814 // The system package has been updated and the code path does not match 6815 // Ignore entry. Skip it. 6816 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6817 + " ignored: updated version " + ps.versionCode 6818 + " better than this " + pkg.mVersionCode); 6819 if (!updatedPkg.codePath.equals(scanFile)) { 6820 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6821 + ps.name + " changing from " + updatedPkg.codePathString 6822 + " to " + scanFile); 6823 updatedPkg.codePath = scanFile; 6824 updatedPkg.codePathString = scanFile.toString(); 6825 updatedPkg.resourcePath = scanFile; 6826 updatedPkg.resourcePathString = scanFile.toString(); 6827 } 6828 updatedPkg.pkg = pkg; 6829 updatedPkg.versionCode = pkg.mVersionCode; 6830 6831 // Update the disabled system child packages to point to the package too. 6832 final int childCount = updatedPkg.childPackageNames != null 6833 ? updatedPkg.childPackageNames.size() : 0; 6834 for (int i = 0; i < childCount; i++) { 6835 String childPackageName = updatedPkg.childPackageNames.get(i); 6836 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6837 childPackageName); 6838 if (updatedChildPkg != null) { 6839 updatedChildPkg.pkg = pkg; 6840 updatedChildPkg.versionCode = pkg.mVersionCode; 6841 } 6842 } 6843 6844 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6845 + scanFile + " ignored: updated version " + ps.versionCode 6846 + " better than this " + pkg.mVersionCode); 6847 } else { 6848 // The current app on the system partition is better than 6849 // what we have updated to on the data partition; switch 6850 // back to the system partition version. 6851 // At this point, its safely assumed that package installation for 6852 // apps in system partition will go through. If not there won't be a working 6853 // version of the app 6854 // writer 6855 synchronized (mPackages) { 6856 // Just remove the loaded entries from package lists. 6857 mPackages.remove(ps.name); 6858 } 6859 6860 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6861 + " reverting from " + ps.codePathString 6862 + ": new version " + pkg.mVersionCode 6863 + " better than installed " + ps.versionCode); 6864 6865 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6866 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6867 synchronized (mInstallLock) { 6868 args.cleanUpResourcesLI(); 6869 } 6870 synchronized (mPackages) { 6871 mSettings.enableSystemPackageLPw(ps.name); 6872 } 6873 updatedPkgBetter = true; 6874 } 6875 } 6876 } 6877 6878 if (updatedPkg != null) { 6879 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6880 // initially 6881 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6882 6883 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6884 // flag set initially 6885 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6886 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6887 } 6888 } 6889 6890 // Verify certificates against what was last scanned 6891 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6892 6893 /* 6894 * A new system app appeared, but we already had a non-system one of the 6895 * same name installed earlier. 6896 */ 6897 boolean shouldHideSystemApp = false; 6898 if (updatedPkg == null && ps != null 6899 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6900 /* 6901 * Check to make sure the signatures match first. If they don't, 6902 * wipe the installed application and its data. 6903 */ 6904 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6905 != PackageManager.SIGNATURE_MATCH) { 6906 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6907 + " signatures don't match existing userdata copy; removing"); 6908 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6909 "scanPackageInternalLI")) { 6910 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6911 } 6912 ps = null; 6913 } else { 6914 /* 6915 * If the newly-added system app is an older version than the 6916 * already installed version, hide it. It will be scanned later 6917 * and re-added like an update. 6918 */ 6919 if (pkg.mVersionCode <= ps.versionCode) { 6920 shouldHideSystemApp = true; 6921 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6922 + " but new version " + pkg.mVersionCode + " better than installed " 6923 + ps.versionCode + "; hiding system"); 6924 } else { 6925 /* 6926 * The newly found system app is a newer version that the 6927 * one previously installed. Simply remove the 6928 * already-installed application and replace it with our own 6929 * while keeping the application data. 6930 */ 6931 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6932 + " reverting from " + ps.codePathString + ": new version " 6933 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6934 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6935 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6936 synchronized (mInstallLock) { 6937 args.cleanUpResourcesLI(); 6938 } 6939 } 6940 } 6941 } 6942 6943 // The apk is forward locked (not public) if its code and resources 6944 // are kept in different files. (except for app in either system or 6945 // vendor path). 6946 // TODO grab this value from PackageSettings 6947 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6948 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6949 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6950 } 6951 } 6952 6953 // TODO: extend to support forward-locked splits 6954 String resourcePath = null; 6955 String baseResourcePath = null; 6956 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6957 if (ps != null && ps.resourcePathString != null) { 6958 resourcePath = ps.resourcePathString; 6959 baseResourcePath = ps.resourcePathString; 6960 } else { 6961 // Should not happen at all. Just log an error. 6962 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6963 } 6964 } else { 6965 resourcePath = pkg.codePath; 6966 baseResourcePath = pkg.baseCodePath; 6967 } 6968 6969 // Set application objects path explicitly. 6970 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6971 pkg.setApplicationInfoCodePath(pkg.codePath); 6972 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6973 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6974 pkg.setApplicationInfoResourcePath(resourcePath); 6975 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6976 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6977 6978 // Note that we invoke the following method only if we are about to unpack an application 6979 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6980 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6981 6982 /* 6983 * If the system app should be overridden by a previously installed 6984 * data, hide the system app now and let the /data/app scan pick it up 6985 * again. 6986 */ 6987 if (shouldHideSystemApp) { 6988 synchronized (mPackages) { 6989 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6990 } 6991 } 6992 6993 return scannedPkg; 6994 } 6995 6996 private static String fixProcessName(String defProcessName, 6997 String processName, int uid) { 6998 if (processName == null) { 6999 return defProcessName; 7000 } 7001 return processName; 7002 } 7003 7004 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7005 throws PackageManagerException { 7006 if (pkgSetting.signatures.mSignatures != null) { 7007 // Already existing package. Make sure signatures match 7008 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7009 == PackageManager.SIGNATURE_MATCH; 7010 if (!match) { 7011 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7012 == PackageManager.SIGNATURE_MATCH; 7013 } 7014 if (!match) { 7015 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7016 == PackageManager.SIGNATURE_MATCH; 7017 } 7018 if (!match) { 7019 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7020 + pkg.packageName + " signatures do not match the " 7021 + "previously installed version; ignoring!"); 7022 } 7023 } 7024 7025 // Check for shared user signatures 7026 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7027 // Already existing package. Make sure signatures match 7028 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7029 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7030 if (!match) { 7031 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7032 == PackageManager.SIGNATURE_MATCH; 7033 } 7034 if (!match) { 7035 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7036 == PackageManager.SIGNATURE_MATCH; 7037 } 7038 if (!match) { 7039 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7040 "Package " + pkg.packageName 7041 + " has no signatures that match those in shared user " 7042 + pkgSetting.sharedUser.name + "; ignoring!"); 7043 } 7044 } 7045 } 7046 7047 /** 7048 * Enforces that only the system UID or root's UID can call a method exposed 7049 * via Binder. 7050 * 7051 * @param message used as message if SecurityException is thrown 7052 * @throws SecurityException if the caller is not system or root 7053 */ 7054 private static final void enforceSystemOrRoot(String message) { 7055 final int uid = Binder.getCallingUid(); 7056 if (uid != Process.SYSTEM_UID && uid != 0) { 7057 throw new SecurityException(message); 7058 } 7059 } 7060 7061 @Override 7062 public void performFstrimIfNeeded() { 7063 enforceSystemOrRoot("Only the system can request fstrim"); 7064 7065 // Before everything else, see whether we need to fstrim. 7066 try { 7067 IMountService ms = PackageHelper.getMountService(); 7068 if (ms != null) { 7069 boolean doTrim = false; 7070 final long interval = android.provider.Settings.Global.getLong( 7071 mContext.getContentResolver(), 7072 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7073 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7074 if (interval > 0) { 7075 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7076 if (timeSinceLast > interval) { 7077 doTrim = true; 7078 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7079 + "; running immediately"); 7080 } 7081 } 7082 if (doTrim) { 7083 if (!isFirstBoot()) { 7084 try { 7085 ActivityManagerNative.getDefault().showBootMessage( 7086 mContext.getResources().getString( 7087 R.string.android_upgrading_fstrim), true); 7088 } catch (RemoteException e) { 7089 } 7090 } 7091 ms.runMaintenance(); 7092 } 7093 } else { 7094 Slog.e(TAG, "Mount service unavailable!"); 7095 } 7096 } catch (RemoteException e) { 7097 // Can't happen; MountService is local 7098 } 7099 } 7100 7101 @Override 7102 public void updatePackagesIfNeeded() { 7103 enforceSystemOrRoot("Only the system can request package update"); 7104 7105 // We need to re-extract after an OTA. 7106 boolean causeUpgrade = isUpgrade(); 7107 7108 // First boot or factory reset. 7109 // Note: we also handle devices that are upgrading to N right now as if it is their 7110 // first boot, as they do not have profile data. 7111 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7112 7113 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7114 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7115 7116 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7117 return; 7118 } 7119 7120 List<PackageParser.Package> pkgs; 7121 synchronized (mPackages) { 7122 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7123 } 7124 7125 final long startTime = System.nanoTime(); 7126 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7127 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7128 7129 final int elapsedTimeSeconds = 7130 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7131 7132 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7133 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7134 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7135 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7136 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7137 } 7138 7139 /** 7140 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7141 * containing statistics about the invocation. The array consists of three elements, 7142 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7143 * and {@code numberOfPackagesFailed}. 7144 */ 7145 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7146 String compilerFilter) { 7147 7148 int numberOfPackagesVisited = 0; 7149 int numberOfPackagesOptimized = 0; 7150 int numberOfPackagesSkipped = 0; 7151 int numberOfPackagesFailed = 0; 7152 final int numberOfPackagesToDexopt = pkgs.size(); 7153 7154 for (PackageParser.Package pkg : pkgs) { 7155 numberOfPackagesVisited++; 7156 7157 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7158 if (DEBUG_DEXOPT) { 7159 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7160 } 7161 numberOfPackagesSkipped++; 7162 continue; 7163 } 7164 7165 if (DEBUG_DEXOPT) { 7166 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7167 numberOfPackagesToDexopt + ": " + pkg.packageName); 7168 } 7169 7170 if (showDialog) { 7171 try { 7172 ActivityManagerNative.getDefault().showBootMessage( 7173 mContext.getResources().getString(R.string.android_upgrading_apk, 7174 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7175 } catch (RemoteException e) { 7176 } 7177 } 7178 7179 // If the OTA updates a system app which was previously preopted to a non-preopted state 7180 // the app might end up being verified at runtime. That's because by default the apps 7181 // are verify-profile but for preopted apps there's no profile. 7182 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7183 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7184 // filter (by default interpret-only). 7185 // Note that at this stage unused apps are already filtered. 7186 if (isSystemApp(pkg) && 7187 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7188 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7189 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7190 } 7191 7192 // checkProfiles is false to avoid merging profiles during boot which 7193 // might interfere with background compilation (b/28612421). 7194 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7195 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7196 // trade-off worth doing to save boot time work. 7197 int dexOptStatus = performDexOptTraced(pkg.packageName, 7198 false /* checkProfiles */, 7199 compilerFilter, 7200 false /* force */); 7201 switch (dexOptStatus) { 7202 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7203 numberOfPackagesOptimized++; 7204 break; 7205 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7206 numberOfPackagesSkipped++; 7207 break; 7208 case PackageDexOptimizer.DEX_OPT_FAILED: 7209 numberOfPackagesFailed++; 7210 break; 7211 default: 7212 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7213 break; 7214 } 7215 } 7216 7217 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7218 numberOfPackagesFailed }; 7219 } 7220 7221 @Override 7222 public void notifyPackageUse(String packageName, int reason) { 7223 synchronized (mPackages) { 7224 PackageParser.Package p = mPackages.get(packageName); 7225 if (p == null) { 7226 return; 7227 } 7228 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7229 } 7230 } 7231 7232 // TODO: this is not used nor needed. Delete it. 7233 @Override 7234 public boolean performDexOptIfNeeded(String packageName) { 7235 int dexOptStatus = performDexOptTraced(packageName, 7236 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7237 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7238 } 7239 7240 @Override 7241 public boolean performDexOpt(String packageName, 7242 boolean checkProfiles, int compileReason, boolean force) { 7243 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7244 getCompilerFilterForReason(compileReason), force); 7245 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7246 } 7247 7248 @Override 7249 public boolean performDexOptMode(String packageName, 7250 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7251 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7252 targetCompilerFilter, force); 7253 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7254 } 7255 7256 private int performDexOptTraced(String packageName, 7257 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7258 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7259 try { 7260 return performDexOptInternal(packageName, checkProfiles, 7261 targetCompilerFilter, force); 7262 } finally { 7263 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7264 } 7265 } 7266 7267 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7268 // if the package can now be considered up to date for the given filter. 7269 private int performDexOptInternal(String packageName, 7270 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7271 PackageParser.Package p; 7272 synchronized (mPackages) { 7273 p = mPackages.get(packageName); 7274 if (p == null) { 7275 // Package could not be found. Report failure. 7276 return PackageDexOptimizer.DEX_OPT_FAILED; 7277 } 7278 mPackageUsage.maybeWriteAsync(mPackages); 7279 mCompilerStats.maybeWriteAsync(); 7280 } 7281 long callingId = Binder.clearCallingIdentity(); 7282 try { 7283 synchronized (mInstallLock) { 7284 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7285 targetCompilerFilter, force); 7286 } 7287 } finally { 7288 Binder.restoreCallingIdentity(callingId); 7289 } 7290 } 7291 7292 public ArraySet<String> getOptimizablePackages() { 7293 ArraySet<String> pkgs = new ArraySet<String>(); 7294 synchronized (mPackages) { 7295 for (PackageParser.Package p : mPackages.values()) { 7296 if (PackageDexOptimizer.canOptimizePackage(p)) { 7297 pkgs.add(p.packageName); 7298 } 7299 } 7300 } 7301 return pkgs; 7302 } 7303 7304 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7305 boolean checkProfiles, String targetCompilerFilter, 7306 boolean force) { 7307 // Select the dex optimizer based on the force parameter. 7308 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7309 // allocate an object here. 7310 PackageDexOptimizer pdo = force 7311 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7312 : mPackageDexOptimizer; 7313 7314 // Optimize all dependencies first. Note: we ignore the return value and march on 7315 // on errors. 7316 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7317 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7318 if (!deps.isEmpty()) { 7319 for (PackageParser.Package depPackage : deps) { 7320 // TODO: Analyze and investigate if we (should) profile libraries. 7321 // Currently this will do a full compilation of the library by default. 7322 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7323 false /* checkProfiles */, 7324 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7325 getOrCreateCompilerPackageStats(depPackage)); 7326 } 7327 } 7328 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7329 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7330 } 7331 7332 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7333 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7334 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7335 Set<String> collectedNames = new HashSet<>(); 7336 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7337 7338 retValue.remove(p); 7339 7340 return retValue; 7341 } else { 7342 return Collections.emptyList(); 7343 } 7344 } 7345 7346 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7347 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7348 if (!collectedNames.contains(p.packageName)) { 7349 collectedNames.add(p.packageName); 7350 collected.add(p); 7351 7352 if (p.usesLibraries != null) { 7353 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7354 } 7355 if (p.usesOptionalLibraries != null) { 7356 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7357 collectedNames); 7358 } 7359 } 7360 } 7361 7362 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7363 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7364 for (String libName : libs) { 7365 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7366 if (libPkg != null) { 7367 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7368 } 7369 } 7370 } 7371 7372 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7373 synchronized (mPackages) { 7374 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7375 if (lib != null && lib.apk != null) { 7376 return mPackages.get(lib.apk); 7377 } 7378 } 7379 return null; 7380 } 7381 7382 public void shutdown() { 7383 mPackageUsage.writeNow(mPackages); 7384 mCompilerStats.writeNow(); 7385 } 7386 7387 @Override 7388 public void dumpProfiles(String packageName) { 7389 PackageParser.Package pkg; 7390 synchronized (mPackages) { 7391 pkg = mPackages.get(packageName); 7392 if (pkg == null) { 7393 throw new IllegalArgumentException("Unknown package: " + packageName); 7394 } 7395 } 7396 /* Only the shell, root, or the app user should be able to dump profiles. */ 7397 int callingUid = Binder.getCallingUid(); 7398 if (callingUid != Process.SHELL_UID && 7399 callingUid != Process.ROOT_UID && 7400 callingUid != pkg.applicationInfo.uid) { 7401 throw new SecurityException("dumpProfiles"); 7402 } 7403 7404 synchronized (mInstallLock) { 7405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7406 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7407 try { 7408 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7409 String gid = Integer.toString(sharedGid); 7410 String codePaths = TextUtils.join(";", allCodePaths); 7411 mInstaller.dumpProfiles(gid, packageName, codePaths); 7412 } catch (InstallerException e) { 7413 Slog.w(TAG, "Failed to dump profiles", e); 7414 } 7415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7416 } 7417 } 7418 7419 @Override 7420 public void forceDexOpt(String packageName) { 7421 enforceSystemOrRoot("forceDexOpt"); 7422 7423 PackageParser.Package pkg; 7424 synchronized (mPackages) { 7425 pkg = mPackages.get(packageName); 7426 if (pkg == null) { 7427 throw new IllegalArgumentException("Unknown package: " + packageName); 7428 } 7429 } 7430 7431 synchronized (mInstallLock) { 7432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7433 7434 // Whoever is calling forceDexOpt wants a fully compiled package. 7435 // Don't use profiles since that may cause compilation to be skipped. 7436 final int res = performDexOptInternalWithDependenciesLI(pkg, 7437 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7438 true /* force */); 7439 7440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7441 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7442 throw new IllegalStateException("Failed to dexopt: " + res); 7443 } 7444 } 7445 } 7446 7447 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7448 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7449 Slog.w(TAG, "Unable to update from " + oldPkg.name 7450 + " to " + newPkg.packageName 7451 + ": old package not in system partition"); 7452 return false; 7453 } else if (mPackages.get(oldPkg.name) != null) { 7454 Slog.w(TAG, "Unable to update from " + oldPkg.name 7455 + " to " + newPkg.packageName 7456 + ": old package still exists"); 7457 return false; 7458 } 7459 return true; 7460 } 7461 7462 void removeCodePathLI(File codePath) { 7463 if (codePath.isDirectory()) { 7464 try { 7465 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7466 } catch (InstallerException e) { 7467 Slog.w(TAG, "Failed to remove code path", e); 7468 } 7469 } else { 7470 codePath.delete(); 7471 } 7472 } 7473 7474 private int[] resolveUserIds(int userId) { 7475 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7476 } 7477 7478 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7479 if (pkg == null) { 7480 Slog.wtf(TAG, "Package was null!", new Throwable()); 7481 return; 7482 } 7483 clearAppDataLeafLIF(pkg, userId, flags); 7484 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7485 for (int i = 0; i < childCount; i++) { 7486 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7487 } 7488 } 7489 7490 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7491 final PackageSetting ps; 7492 synchronized (mPackages) { 7493 ps = mSettings.mPackages.get(pkg.packageName); 7494 } 7495 for (int realUserId : resolveUserIds(userId)) { 7496 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7497 try { 7498 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7499 ceDataInode); 7500 } catch (InstallerException e) { 7501 Slog.w(TAG, String.valueOf(e)); 7502 } 7503 } 7504 } 7505 7506 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7507 if (pkg == null) { 7508 Slog.wtf(TAG, "Package was null!", new Throwable()); 7509 return; 7510 } 7511 destroyAppDataLeafLIF(pkg, userId, flags); 7512 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7513 for (int i = 0; i < childCount; i++) { 7514 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7515 } 7516 } 7517 7518 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7519 final PackageSetting ps; 7520 synchronized (mPackages) { 7521 ps = mSettings.mPackages.get(pkg.packageName); 7522 } 7523 for (int realUserId : resolveUserIds(userId)) { 7524 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7525 try { 7526 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7527 ceDataInode); 7528 } catch (InstallerException e) { 7529 Slog.w(TAG, String.valueOf(e)); 7530 } 7531 } 7532 } 7533 7534 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7535 if (pkg == null) { 7536 Slog.wtf(TAG, "Package was null!", new Throwable()); 7537 return; 7538 } 7539 destroyAppProfilesLeafLIF(pkg); 7540 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7542 for (int i = 0; i < childCount; i++) { 7543 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7544 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7545 true /* removeBaseMarker */); 7546 } 7547 } 7548 7549 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7550 boolean removeBaseMarker) { 7551 if (pkg.isForwardLocked()) { 7552 return; 7553 } 7554 7555 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7556 try { 7557 path = PackageManagerServiceUtils.realpath(new File(path)); 7558 } catch (IOException e) { 7559 // TODO: Should we return early here ? 7560 Slog.w(TAG, "Failed to get canonical path", e); 7561 continue; 7562 } 7563 7564 final String useMarker = path.replace('/', '@'); 7565 for (int realUserId : resolveUserIds(userId)) { 7566 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7567 if (removeBaseMarker) { 7568 File foreignUseMark = new File(profileDir, useMarker); 7569 if (foreignUseMark.exists()) { 7570 if (!foreignUseMark.delete()) { 7571 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7572 + pkg.packageName); 7573 } 7574 } 7575 } 7576 7577 File[] markers = profileDir.listFiles(); 7578 if (markers != null) { 7579 final String searchString = "@" + pkg.packageName + "@"; 7580 // We also delete all markers that contain the package name we're 7581 // uninstalling. These are associated with secondary dex-files belonging 7582 // to the package. Reconstructing the path of these dex files is messy 7583 // in general. 7584 for (File marker : markers) { 7585 if (marker.getName().indexOf(searchString) > 0) { 7586 if (!marker.delete()) { 7587 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7588 + pkg.packageName); 7589 } 7590 } 7591 } 7592 } 7593 } 7594 } 7595 } 7596 7597 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7598 try { 7599 mInstaller.destroyAppProfiles(pkg.packageName); 7600 } catch (InstallerException e) { 7601 Slog.w(TAG, String.valueOf(e)); 7602 } 7603 } 7604 7605 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7606 if (pkg == null) { 7607 Slog.wtf(TAG, "Package was null!", new Throwable()); 7608 return; 7609 } 7610 clearAppProfilesLeafLIF(pkg); 7611 // We don't remove the base foreign use marker when clearing profiles because 7612 // we will rename it when the app is updated. Unlike the actual profile contents, 7613 // the foreign use marker is good across installs. 7614 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7615 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7616 for (int i = 0; i < childCount; i++) { 7617 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7618 } 7619 } 7620 7621 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7622 try { 7623 mInstaller.clearAppProfiles(pkg.packageName); 7624 } catch (InstallerException e) { 7625 Slog.w(TAG, String.valueOf(e)); 7626 } 7627 } 7628 7629 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7630 long lastUpdateTime) { 7631 // Set parent install/update time 7632 PackageSetting ps = (PackageSetting) pkg.mExtras; 7633 if (ps != null) { 7634 ps.firstInstallTime = firstInstallTime; 7635 ps.lastUpdateTime = lastUpdateTime; 7636 } 7637 // Set children install/update time 7638 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7639 for (int i = 0; i < childCount; i++) { 7640 PackageParser.Package childPkg = pkg.childPackages.get(i); 7641 ps = (PackageSetting) childPkg.mExtras; 7642 if (ps != null) { 7643 ps.firstInstallTime = firstInstallTime; 7644 ps.lastUpdateTime = lastUpdateTime; 7645 } 7646 } 7647 } 7648 7649 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7650 PackageParser.Package changingLib) { 7651 if (file.path != null) { 7652 usesLibraryFiles.add(file.path); 7653 return; 7654 } 7655 PackageParser.Package p = mPackages.get(file.apk); 7656 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7657 // If we are doing this while in the middle of updating a library apk, 7658 // then we need to make sure to use that new apk for determining the 7659 // dependencies here. (We haven't yet finished committing the new apk 7660 // to the package manager state.) 7661 if (p == null || p.packageName.equals(changingLib.packageName)) { 7662 p = changingLib; 7663 } 7664 } 7665 if (p != null) { 7666 usesLibraryFiles.addAll(p.getAllCodePaths()); 7667 } 7668 } 7669 7670 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7671 PackageParser.Package changingLib) throws PackageManagerException { 7672 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7673 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7674 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7675 for (int i=0; i<N; i++) { 7676 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7677 if (file == null) { 7678 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7679 "Package " + pkg.packageName + " requires unavailable shared library " 7680 + pkg.usesLibraries.get(i) + "; failing!"); 7681 } 7682 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7683 } 7684 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7685 for (int i=0; i<N; i++) { 7686 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7687 if (file == null) { 7688 Slog.w(TAG, "Package " + pkg.packageName 7689 + " desires unavailable shared library " 7690 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7691 } else { 7692 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7693 } 7694 } 7695 N = usesLibraryFiles.size(); 7696 if (N > 0) { 7697 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7698 } else { 7699 pkg.usesLibraryFiles = null; 7700 } 7701 } 7702 } 7703 7704 private static boolean hasString(List<String> list, List<String> which) { 7705 if (list == null) { 7706 return false; 7707 } 7708 for (int i=list.size()-1; i>=0; i--) { 7709 for (int j=which.size()-1; j>=0; j--) { 7710 if (which.get(j).equals(list.get(i))) { 7711 return true; 7712 } 7713 } 7714 } 7715 return false; 7716 } 7717 7718 private void updateAllSharedLibrariesLPw() { 7719 for (PackageParser.Package pkg : mPackages.values()) { 7720 try { 7721 updateSharedLibrariesLPw(pkg, null); 7722 } catch (PackageManagerException e) { 7723 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7724 } 7725 } 7726 } 7727 7728 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7729 PackageParser.Package changingPkg) { 7730 ArrayList<PackageParser.Package> res = null; 7731 for (PackageParser.Package pkg : mPackages.values()) { 7732 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7733 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7734 if (res == null) { 7735 res = new ArrayList<PackageParser.Package>(); 7736 } 7737 res.add(pkg); 7738 try { 7739 updateSharedLibrariesLPw(pkg, changingPkg); 7740 } catch (PackageManagerException e) { 7741 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7742 } 7743 } 7744 } 7745 return res; 7746 } 7747 7748 /** 7749 * Derive the value of the {@code cpuAbiOverride} based on the provided 7750 * value and an optional stored value from the package settings. 7751 */ 7752 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7753 String cpuAbiOverride = null; 7754 7755 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7756 cpuAbiOverride = null; 7757 } else if (abiOverride != null) { 7758 cpuAbiOverride = abiOverride; 7759 } else if (settings != null) { 7760 cpuAbiOverride = settings.cpuAbiOverrideString; 7761 } 7762 7763 return cpuAbiOverride; 7764 } 7765 7766 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7767 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7768 throws PackageManagerException { 7769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7770 // If the package has children and this is the first dive in the function 7771 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7772 // whether all packages (parent and children) would be successfully scanned 7773 // before the actual scan since scanning mutates internal state and we want 7774 // to atomically install the package and its children. 7775 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7776 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7777 scanFlags |= SCAN_CHECK_ONLY; 7778 } 7779 } else { 7780 scanFlags &= ~SCAN_CHECK_ONLY; 7781 } 7782 7783 final PackageParser.Package scannedPkg; 7784 try { 7785 // Scan the parent 7786 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7787 // Scan the children 7788 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7789 for (int i = 0; i < childCount; i++) { 7790 PackageParser.Package childPkg = pkg.childPackages.get(i); 7791 scanPackageLI(childPkg, policyFlags, 7792 scanFlags, currentTime, user); 7793 } 7794 } finally { 7795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7796 } 7797 7798 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7799 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7800 } 7801 7802 return scannedPkg; 7803 } 7804 7805 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7806 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7807 boolean success = false; 7808 try { 7809 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7810 currentTime, user); 7811 success = true; 7812 return res; 7813 } finally { 7814 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7815 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7816 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7817 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7818 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7819 } 7820 } 7821 } 7822 7823 /** 7824 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7825 */ 7826 private static boolean apkHasCode(String fileName) { 7827 StrictJarFile jarFile = null; 7828 try { 7829 jarFile = new StrictJarFile(fileName, 7830 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7831 return jarFile.findEntry("classes.dex") != null; 7832 } catch (IOException ignore) { 7833 } finally { 7834 try { 7835 if (jarFile != null) { 7836 jarFile.close(); 7837 } 7838 } catch (IOException ignore) {} 7839 } 7840 return false; 7841 } 7842 7843 /** 7844 * Enforces code policy for the package. This ensures that if an APK has 7845 * declared hasCode="true" in its manifest that the APK actually contains 7846 * code. 7847 * 7848 * @throws PackageManagerException If bytecode could not be found when it should exist 7849 */ 7850 private static void enforceCodePolicy(PackageParser.Package pkg) 7851 throws PackageManagerException { 7852 final boolean shouldHaveCode = 7853 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7854 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7855 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7856 "Package " + pkg.baseCodePath + " code is missing"); 7857 } 7858 7859 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7860 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7861 final boolean splitShouldHaveCode = 7862 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7863 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7864 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7865 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7866 } 7867 } 7868 } 7869 } 7870 7871 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7872 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7873 throws PackageManagerException { 7874 final File scanFile = new File(pkg.codePath); 7875 if (pkg.applicationInfo.getCodePath() == null || 7876 pkg.applicationInfo.getResourcePath() == null) { 7877 // Bail out. The resource and code paths haven't been set. 7878 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7879 "Code and resource paths haven't been set correctly"); 7880 } 7881 7882 // Apply policy 7883 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7884 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7885 if (pkg.applicationInfo.isDirectBootAware()) { 7886 // we're direct boot aware; set for all components 7887 for (PackageParser.Service s : pkg.services) { 7888 s.info.encryptionAware = s.info.directBootAware = true; 7889 } 7890 for (PackageParser.Provider p : pkg.providers) { 7891 p.info.encryptionAware = p.info.directBootAware = true; 7892 } 7893 for (PackageParser.Activity a : pkg.activities) { 7894 a.info.encryptionAware = a.info.directBootAware = true; 7895 } 7896 for (PackageParser.Activity r : pkg.receivers) { 7897 r.info.encryptionAware = r.info.directBootAware = true; 7898 } 7899 } 7900 } else { 7901 // Only allow system apps to be flagged as core apps. 7902 pkg.coreApp = false; 7903 // clear flags not applicable to regular apps 7904 pkg.applicationInfo.privateFlags &= 7905 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7906 pkg.applicationInfo.privateFlags &= 7907 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7908 } 7909 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7910 7911 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7912 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7913 } 7914 7915 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7916 enforceCodePolicy(pkg); 7917 } 7918 7919 if (mCustomResolverComponentName != null && 7920 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7921 setUpCustomResolverActivity(pkg); 7922 } 7923 7924 if (pkg.packageName.equals("android")) { 7925 synchronized (mPackages) { 7926 if (mAndroidApplication != null) { 7927 Slog.w(TAG, "*************************************************"); 7928 Slog.w(TAG, "Core android package being redefined. Skipping."); 7929 Slog.w(TAG, " file=" + scanFile); 7930 Slog.w(TAG, "*************************************************"); 7931 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7932 "Core android package being redefined. Skipping."); 7933 } 7934 7935 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7936 // Set up information for our fall-back user intent resolution activity. 7937 mPlatformPackage = pkg; 7938 pkg.mVersionCode = mSdkVersion; 7939 mAndroidApplication = pkg.applicationInfo; 7940 7941 if (!mResolverReplaced) { 7942 mResolveActivity.applicationInfo = mAndroidApplication; 7943 mResolveActivity.name = ResolverActivity.class.getName(); 7944 mResolveActivity.packageName = mAndroidApplication.packageName; 7945 mResolveActivity.processName = "system:ui"; 7946 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7947 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7948 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7949 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7950 mResolveActivity.exported = true; 7951 mResolveActivity.enabled = true; 7952 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7953 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7954 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7955 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7956 | ActivityInfo.CONFIG_ORIENTATION 7957 | ActivityInfo.CONFIG_KEYBOARD 7958 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7959 mResolveInfo.activityInfo = mResolveActivity; 7960 mResolveInfo.priority = 0; 7961 mResolveInfo.preferredOrder = 0; 7962 mResolveInfo.match = 0; 7963 mResolveComponentName = new ComponentName( 7964 mAndroidApplication.packageName, mResolveActivity.name); 7965 } 7966 } 7967 } 7968 } 7969 7970 if (DEBUG_PACKAGE_SCANNING) { 7971 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7972 Log.d(TAG, "Scanning package " + pkg.packageName); 7973 } 7974 7975 synchronized (mPackages) { 7976 if (mPackages.containsKey(pkg.packageName) 7977 || mSharedLibraries.containsKey(pkg.packageName)) { 7978 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7979 "Application package " + pkg.packageName 7980 + " already installed. Skipping duplicate."); 7981 } 7982 7983 // If we're only installing presumed-existing packages, require that the 7984 // scanned APK is both already known and at the path previously established 7985 // for it. Previously unknown packages we pick up normally, but if we have an 7986 // a priori expectation about this package's install presence, enforce it. 7987 // With a singular exception for new system packages. When an OTA contains 7988 // a new system package, we allow the codepath to change from a system location 7989 // to the user-installed location. If we don't allow this change, any newer, 7990 // user-installed version of the application will be ignored. 7991 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7992 if (mExpectingBetter.containsKey(pkg.packageName)) { 7993 logCriticalInfo(Log.WARN, 7994 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7995 } else { 7996 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7997 if (known != null) { 7998 if (DEBUG_PACKAGE_SCANNING) { 7999 Log.d(TAG, "Examining " + pkg.codePath 8000 + " and requiring known paths " + known.codePathString 8001 + " & " + known.resourcePathString); 8002 } 8003 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8004 || !pkg.applicationInfo.getResourcePath().equals( 8005 known.resourcePathString)) { 8006 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8007 "Application package " + pkg.packageName 8008 + " found at " + pkg.applicationInfo.getCodePath() 8009 + " but expected at " + known.codePathString 8010 + "; ignoring."); 8011 } 8012 } 8013 } 8014 } 8015 } 8016 8017 // Initialize package source and resource directories 8018 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8019 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8020 8021 SharedUserSetting suid = null; 8022 PackageSetting pkgSetting = null; 8023 8024 if (!isSystemApp(pkg)) { 8025 // Only system apps can use these features. 8026 pkg.mOriginalPackages = null; 8027 pkg.mRealPackage = null; 8028 pkg.mAdoptPermissions = null; 8029 } 8030 8031 // Getting the package setting may have a side-effect, so if we 8032 // are only checking if scan would succeed, stash a copy of the 8033 // old setting to restore at the end. 8034 PackageSetting nonMutatedPs = null; 8035 8036 // writer 8037 synchronized (mPackages) { 8038 if (pkg.mSharedUserId != null) { 8039 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8040 if (suid == null) { 8041 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8042 "Creating application package " + pkg.packageName 8043 + " for shared user failed"); 8044 } 8045 if (DEBUG_PACKAGE_SCANNING) { 8046 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8047 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8048 + "): packages=" + suid.packages); 8049 } 8050 } 8051 8052 // Check if we are renaming from an original package name. 8053 PackageSetting origPackage = null; 8054 String realName = null; 8055 if (pkg.mOriginalPackages != null) { 8056 // This package may need to be renamed to a previously 8057 // installed name. Let's check on that... 8058 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8059 if (pkg.mOriginalPackages.contains(renamed)) { 8060 // This package had originally been installed as the 8061 // original name, and we have already taken care of 8062 // transitioning to the new one. Just update the new 8063 // one to continue using the old name. 8064 realName = pkg.mRealPackage; 8065 if (!pkg.packageName.equals(renamed)) { 8066 // Callers into this function may have already taken 8067 // care of renaming the package; only do it here if 8068 // it is not already done. 8069 pkg.setPackageName(renamed); 8070 } 8071 8072 } else { 8073 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8074 if ((origPackage = mSettings.peekPackageLPr( 8075 pkg.mOriginalPackages.get(i))) != null) { 8076 // We do have the package already installed under its 8077 // original name... should we use it? 8078 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8079 // New package is not compatible with original. 8080 origPackage = null; 8081 continue; 8082 } else if (origPackage.sharedUser != null) { 8083 // Make sure uid is compatible between packages. 8084 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8085 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8086 + " to " + pkg.packageName + ": old uid " 8087 + origPackage.sharedUser.name 8088 + " differs from " + pkg.mSharedUserId); 8089 origPackage = null; 8090 continue; 8091 } 8092 // TODO: Add case when shared user id is added [b/28144775] 8093 } else { 8094 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8095 + pkg.packageName + " to old name " + origPackage.name); 8096 } 8097 break; 8098 } 8099 } 8100 } 8101 } 8102 8103 if (mTransferedPackages.contains(pkg.packageName)) { 8104 Slog.w(TAG, "Package " + pkg.packageName 8105 + " was transferred to another, but its .apk remains"); 8106 } 8107 8108 // See comments in nonMutatedPs declaration 8109 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8110 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8111 if (foundPs != null) { 8112 nonMutatedPs = new PackageSetting(foundPs); 8113 } 8114 } 8115 8116 // Just create the setting, don't add it yet. For already existing packages 8117 // the PkgSetting exists already and doesn't have to be created. 8118 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8119 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8120 pkg.applicationInfo.primaryCpuAbi, 8121 pkg.applicationInfo.secondaryCpuAbi, 8122 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8123 user, false); 8124 if (pkgSetting == null) { 8125 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8126 "Creating application package " + pkg.packageName + " failed"); 8127 } 8128 8129 if (pkgSetting.origPackage != null) { 8130 // If we are first transitioning from an original package, 8131 // fix up the new package's name now. We need to do this after 8132 // looking up the package under its new name, so getPackageLP 8133 // can take care of fiddling things correctly. 8134 pkg.setPackageName(origPackage.name); 8135 8136 // File a report about this. 8137 String msg = "New package " + pkgSetting.realName 8138 + " renamed to replace old package " + pkgSetting.name; 8139 reportSettingsProblem(Log.WARN, msg); 8140 8141 // Make a note of it. 8142 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8143 mTransferedPackages.add(origPackage.name); 8144 } 8145 8146 // No longer need to retain this. 8147 pkgSetting.origPackage = null; 8148 } 8149 8150 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8151 // Make a note of it. 8152 mTransferedPackages.add(pkg.packageName); 8153 } 8154 8155 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8156 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8157 } 8158 8159 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8160 // Check all shared libraries and map to their actual file path. 8161 // We only do this here for apps not on a system dir, because those 8162 // are the only ones that can fail an install due to this. We 8163 // will take care of the system apps by updating all of their 8164 // library paths after the scan is done. 8165 updateSharedLibrariesLPw(pkg, null); 8166 } 8167 8168 if (mFoundPolicyFile) { 8169 SELinuxMMAC.assignSeinfoValue(pkg); 8170 } 8171 8172 pkg.applicationInfo.uid = pkgSetting.appId; 8173 pkg.mExtras = pkgSetting; 8174 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8175 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8176 // We just determined the app is signed correctly, so bring 8177 // over the latest parsed certs. 8178 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8179 } else { 8180 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8181 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8182 "Package " + pkg.packageName + " upgrade keys do not match the " 8183 + "previously installed version"); 8184 } else { 8185 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8186 String msg = "System package " + pkg.packageName 8187 + " signature changed; retaining data."; 8188 reportSettingsProblem(Log.WARN, msg); 8189 } 8190 } 8191 } else { 8192 try { 8193 verifySignaturesLP(pkgSetting, pkg); 8194 // We just determined the app is signed correctly, so bring 8195 // over the latest parsed certs. 8196 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8197 } catch (PackageManagerException e) { 8198 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8199 throw e; 8200 } 8201 // The signature has changed, but this package is in the system 8202 // image... let's recover! 8203 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8204 // However... if this package is part of a shared user, but it 8205 // doesn't match the signature of the shared user, let's fail. 8206 // What this means is that you can't change the signatures 8207 // associated with an overall shared user, which doesn't seem all 8208 // that unreasonable. 8209 if (pkgSetting.sharedUser != null) { 8210 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8211 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8212 throw new PackageManagerException( 8213 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8214 "Signature mismatch for shared user: " 8215 + pkgSetting.sharedUser); 8216 } 8217 } 8218 // File a report about this. 8219 String msg = "System package " + pkg.packageName 8220 + " signature changed; retaining data."; 8221 reportSettingsProblem(Log.WARN, msg); 8222 } 8223 } 8224 // Verify that this new package doesn't have any content providers 8225 // that conflict with existing packages. Only do this if the 8226 // package isn't already installed, since we don't want to break 8227 // things that are installed. 8228 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8229 final int N = pkg.providers.size(); 8230 int i; 8231 for (i=0; i<N; i++) { 8232 PackageParser.Provider p = pkg.providers.get(i); 8233 if (p.info.authority != null) { 8234 String names[] = p.info.authority.split(";"); 8235 for (int j = 0; j < names.length; j++) { 8236 if (mProvidersByAuthority.containsKey(names[j])) { 8237 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8238 final String otherPackageName = 8239 ((other != null && other.getComponentName() != null) ? 8240 other.getComponentName().getPackageName() : "?"); 8241 throw new PackageManagerException( 8242 INSTALL_FAILED_CONFLICTING_PROVIDER, 8243 "Can't install because provider name " + names[j] 8244 + " (in package " + pkg.applicationInfo.packageName 8245 + ") is already used by " + otherPackageName); 8246 } 8247 } 8248 } 8249 } 8250 } 8251 8252 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8253 // This package wants to adopt ownership of permissions from 8254 // another package. 8255 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8256 final String origName = pkg.mAdoptPermissions.get(i); 8257 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8258 if (orig != null) { 8259 if (verifyPackageUpdateLPr(orig, pkg)) { 8260 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8261 + pkg.packageName); 8262 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8263 } 8264 } 8265 } 8266 } 8267 } 8268 8269 final String pkgName = pkg.packageName; 8270 8271 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8272 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8273 pkg.applicationInfo.processName = fixProcessName( 8274 pkg.applicationInfo.packageName, 8275 pkg.applicationInfo.processName, 8276 pkg.applicationInfo.uid); 8277 8278 if (pkg != mPlatformPackage) { 8279 // Get all of our default paths setup 8280 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8281 } 8282 8283 final String path = scanFile.getPath(); 8284 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8285 8286 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8287 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8288 8289 // Some system apps still use directory structure for native libraries 8290 // in which case we might end up not detecting abi solely based on apk 8291 // structure. Try to detect abi based on directory structure. 8292 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8293 pkg.applicationInfo.primaryCpuAbi == null) { 8294 setBundledAppAbisAndRoots(pkg, pkgSetting); 8295 setNativeLibraryPaths(pkg); 8296 } 8297 8298 } else { 8299 if ((scanFlags & SCAN_MOVE) != 0) { 8300 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8301 // but we already have this packages package info in the PackageSetting. We just 8302 // use that and derive the native library path based on the new codepath. 8303 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8304 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8305 } 8306 8307 // Set native library paths again. For moves, the path will be updated based on the 8308 // ABIs we've determined above. For non-moves, the path will be updated based on the 8309 // ABIs we determined during compilation, but the path will depend on the final 8310 // package path (after the rename away from the stage path). 8311 setNativeLibraryPaths(pkg); 8312 } 8313 8314 // This is a special case for the "system" package, where the ABI is 8315 // dictated by the zygote configuration (and init.rc). We should keep track 8316 // of this ABI so that we can deal with "normal" applications that run under 8317 // the same UID correctly. 8318 if (mPlatformPackage == pkg) { 8319 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8320 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8321 } 8322 8323 // If there's a mismatch between the abi-override in the package setting 8324 // and the abiOverride specified for the install. Warn about this because we 8325 // would've already compiled the app without taking the package setting into 8326 // account. 8327 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8328 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8329 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8330 " for package " + pkg.packageName); 8331 } 8332 } 8333 8334 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8335 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8336 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8337 8338 // Copy the derived override back to the parsed package, so that we can 8339 // update the package settings accordingly. 8340 pkg.cpuAbiOverride = cpuAbiOverride; 8341 8342 if (DEBUG_ABI_SELECTION) { 8343 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8344 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8345 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8346 } 8347 8348 // Push the derived path down into PackageSettings so we know what to 8349 // clean up at uninstall time. 8350 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8351 8352 if (DEBUG_ABI_SELECTION) { 8353 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8354 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8355 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8356 } 8357 8358 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8359 // We don't do this here during boot because we can do it all 8360 // at once after scanning all existing packages. 8361 // 8362 // We also do this *before* we perform dexopt on this package, so that 8363 // we can avoid redundant dexopts, and also to make sure we've got the 8364 // code and package path correct. 8365 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8366 pkg, true /* boot complete */); 8367 } 8368 8369 if (mFactoryTest && pkg.requestedPermissions.contains( 8370 android.Manifest.permission.FACTORY_TEST)) { 8371 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8372 } 8373 8374 if (isSystemApp(pkg)) { 8375 pkgSetting.isOrphaned = true; 8376 } 8377 8378 ArrayList<PackageParser.Package> clientLibPkgs = null; 8379 8380 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8381 if (nonMutatedPs != null) { 8382 synchronized (mPackages) { 8383 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8384 } 8385 } 8386 return pkg; 8387 } 8388 8389 // Only privileged apps and updated privileged apps can add child packages. 8390 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8391 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8392 throw new PackageManagerException("Only privileged apps and updated " 8393 + "privileged apps can add child packages. Ignoring package " 8394 + pkg.packageName); 8395 } 8396 final int childCount = pkg.childPackages.size(); 8397 for (int i = 0; i < childCount; i++) { 8398 PackageParser.Package childPkg = pkg.childPackages.get(i); 8399 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8400 childPkg.packageName)) { 8401 throw new PackageManagerException("Cannot override a child package of " 8402 + "another disabled system app. Ignoring package " + pkg.packageName); 8403 } 8404 } 8405 } 8406 8407 // writer 8408 synchronized (mPackages) { 8409 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8410 // Only system apps can add new shared libraries. 8411 if (pkg.libraryNames != null) { 8412 for (int i=0; i<pkg.libraryNames.size(); i++) { 8413 String name = pkg.libraryNames.get(i); 8414 boolean allowed = false; 8415 if (pkg.isUpdatedSystemApp()) { 8416 // New library entries can only be added through the 8417 // system image. This is important to get rid of a lot 8418 // of nasty edge cases: for example if we allowed a non- 8419 // system update of the app to add a library, then uninstalling 8420 // the update would make the library go away, and assumptions 8421 // we made such as through app install filtering would now 8422 // have allowed apps on the device which aren't compatible 8423 // with it. Better to just have the restriction here, be 8424 // conservative, and create many fewer cases that can negatively 8425 // impact the user experience. 8426 final PackageSetting sysPs = mSettings 8427 .getDisabledSystemPkgLPr(pkg.packageName); 8428 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8429 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8430 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8431 allowed = true; 8432 break; 8433 } 8434 } 8435 } 8436 } else { 8437 allowed = true; 8438 } 8439 if (allowed) { 8440 if (!mSharedLibraries.containsKey(name)) { 8441 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8442 } else if (!name.equals(pkg.packageName)) { 8443 Slog.w(TAG, "Package " + pkg.packageName + " library " 8444 + name + " already exists; skipping"); 8445 } 8446 } else { 8447 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8448 + name + " that is not declared on system image; skipping"); 8449 } 8450 } 8451 if ((scanFlags & SCAN_BOOTING) == 0) { 8452 // If we are not booting, we need to update any applications 8453 // that are clients of our shared library. If we are booting, 8454 // this will all be done once the scan is complete. 8455 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8456 } 8457 } 8458 } 8459 } 8460 8461 if ((scanFlags & SCAN_BOOTING) != 0) { 8462 // No apps can run during boot scan, so they don't need to be frozen 8463 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8464 // Caller asked to not kill app, so it's probably not frozen 8465 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8466 // Caller asked us to ignore frozen check for some reason; they 8467 // probably didn't know the package name 8468 } else { 8469 // We're doing major surgery on this package, so it better be frozen 8470 // right now to keep it from launching 8471 checkPackageFrozen(pkgName); 8472 } 8473 8474 // Also need to kill any apps that are dependent on the library. 8475 if (clientLibPkgs != null) { 8476 for (int i=0; i<clientLibPkgs.size(); i++) { 8477 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8478 killApplication(clientPkg.applicationInfo.packageName, 8479 clientPkg.applicationInfo.uid, "update lib"); 8480 } 8481 } 8482 8483 // Make sure we're not adding any bogus keyset info 8484 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8485 ksms.assertScannedPackageValid(pkg); 8486 8487 // writer 8488 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8489 8490 boolean createIdmapFailed = false; 8491 synchronized (mPackages) { 8492 // We don't expect installation to fail beyond this point 8493 8494 if (pkgSetting.pkg != null) { 8495 // Note that |user| might be null during the initial boot scan. If a codePath 8496 // for an app has changed during a boot scan, it's due to an app update that's 8497 // part of the system partition and marker changes must be applied to all users. 8498 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8499 (user != null) ? user : UserHandle.ALL); 8500 } 8501 8502 // Add the new setting to mSettings 8503 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8504 // Add the new setting to mPackages 8505 mPackages.put(pkg.applicationInfo.packageName, pkg); 8506 // Make sure we don't accidentally delete its data. 8507 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8508 while (iter.hasNext()) { 8509 PackageCleanItem item = iter.next(); 8510 if (pkgName.equals(item.packageName)) { 8511 iter.remove(); 8512 } 8513 } 8514 8515 // Take care of first install / last update times. 8516 if (currentTime != 0) { 8517 if (pkgSetting.firstInstallTime == 0) { 8518 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8519 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8520 pkgSetting.lastUpdateTime = currentTime; 8521 } 8522 } else if (pkgSetting.firstInstallTime == 0) { 8523 // We need *something*. Take time time stamp of the file. 8524 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8525 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8526 if (scanFileTime != pkgSetting.timeStamp) { 8527 // A package on the system image has changed; consider this 8528 // to be an update. 8529 pkgSetting.lastUpdateTime = scanFileTime; 8530 } 8531 } 8532 8533 // Add the package's KeySets to the global KeySetManagerService 8534 ksms.addScannedPackageLPw(pkg); 8535 8536 int N = pkg.providers.size(); 8537 StringBuilder r = null; 8538 int i; 8539 for (i=0; i<N; i++) { 8540 PackageParser.Provider p = pkg.providers.get(i); 8541 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8542 p.info.processName, pkg.applicationInfo.uid); 8543 mProviders.addProvider(p); 8544 p.syncable = p.info.isSyncable; 8545 if (p.info.authority != null) { 8546 String names[] = p.info.authority.split(";"); 8547 p.info.authority = null; 8548 for (int j = 0; j < names.length; j++) { 8549 if (j == 1 && p.syncable) { 8550 // We only want the first authority for a provider to possibly be 8551 // syncable, so if we already added this provider using a different 8552 // authority clear the syncable flag. We copy the provider before 8553 // changing it because the mProviders object contains a reference 8554 // to a provider that we don't want to change. 8555 // Only do this for the second authority since the resulting provider 8556 // object can be the same for all future authorities for this provider. 8557 p = new PackageParser.Provider(p); 8558 p.syncable = false; 8559 } 8560 if (!mProvidersByAuthority.containsKey(names[j])) { 8561 mProvidersByAuthority.put(names[j], p); 8562 if (p.info.authority == null) { 8563 p.info.authority = names[j]; 8564 } else { 8565 p.info.authority = p.info.authority + ";" + names[j]; 8566 } 8567 if (DEBUG_PACKAGE_SCANNING) { 8568 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8569 Log.d(TAG, "Registered content provider: " + names[j] 8570 + ", className = " + p.info.name + ", isSyncable = " 8571 + p.info.isSyncable); 8572 } 8573 } else { 8574 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8575 Slog.w(TAG, "Skipping provider name " + names[j] + 8576 " (in package " + pkg.applicationInfo.packageName + 8577 "): name already used by " 8578 + ((other != null && other.getComponentName() != null) 8579 ? other.getComponentName().getPackageName() : "?")); 8580 } 8581 } 8582 } 8583 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8584 if (r == null) { 8585 r = new StringBuilder(256); 8586 } else { 8587 r.append(' '); 8588 } 8589 r.append(p.info.name); 8590 } 8591 } 8592 if (r != null) { 8593 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8594 } 8595 8596 N = pkg.services.size(); 8597 r = null; 8598 for (i=0; i<N; i++) { 8599 PackageParser.Service s = pkg.services.get(i); 8600 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8601 s.info.processName, pkg.applicationInfo.uid); 8602 mServices.addService(s); 8603 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8604 if (r == null) { 8605 r = new StringBuilder(256); 8606 } else { 8607 r.append(' '); 8608 } 8609 r.append(s.info.name); 8610 } 8611 } 8612 if (r != null) { 8613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8614 } 8615 8616 N = pkg.receivers.size(); 8617 r = null; 8618 for (i=0; i<N; i++) { 8619 PackageParser.Activity a = pkg.receivers.get(i); 8620 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8621 a.info.processName, pkg.applicationInfo.uid); 8622 mReceivers.addActivity(a, "receiver"); 8623 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8624 if (r == null) { 8625 r = new StringBuilder(256); 8626 } else { 8627 r.append(' '); 8628 } 8629 r.append(a.info.name); 8630 } 8631 } 8632 if (r != null) { 8633 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8634 } 8635 8636 N = pkg.activities.size(); 8637 r = null; 8638 for (i=0; i<N; i++) { 8639 PackageParser.Activity a = pkg.activities.get(i); 8640 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8641 a.info.processName, pkg.applicationInfo.uid); 8642 mActivities.addActivity(a, "activity"); 8643 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8644 if (r == null) { 8645 r = new StringBuilder(256); 8646 } else { 8647 r.append(' '); 8648 } 8649 r.append(a.info.name); 8650 } 8651 } 8652 if (r != null) { 8653 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8654 } 8655 8656 N = pkg.permissionGroups.size(); 8657 r = null; 8658 for (i=0; i<N; i++) { 8659 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8660 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8661 if (cur == null) { 8662 mPermissionGroups.put(pg.info.name, pg); 8663 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8664 if (r == null) { 8665 r = new StringBuilder(256); 8666 } else { 8667 r.append(' '); 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 15855 prepareAppDataAfterInstallLIF(newPkg); 15856 15857 // writer 15858 synchronized (mPackages) { 15859 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15860 15861 // Propagate the permissions state as we do not want to drop on the floor 15862 // runtime permissions. The update permissions method below will take 15863 // care of removing obsolete permissions and grant install permissions. 15864 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15865 updatePermissionsLPw(newPkg.packageName, newPkg, 15866 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15867 15868 if (applyUserRestrictions) { 15869 if (DEBUG_REMOVE) { 15870 Slog.d(TAG, "Propagating install state across reinstall"); 15871 } 15872 for (int userId : allUserHandles) { 15873 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15874 if (DEBUG_REMOVE) { 15875 Slog.d(TAG, " user " + userId + " => " + installed); 15876 } 15877 ps.setInstalled(installed, userId); 15878 15879 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15880 } 15881 // Regardless of writeSettings we need to ensure that this restriction 15882 // state propagation is persisted 15883 mSettings.writeAllUsersPackageRestrictionsLPr(); 15884 } 15885 // can downgrade to reader here 15886 if (writeSettings) { 15887 mSettings.writeLPr(); 15888 } 15889 } 15890 return true; 15891 } 15892 15893 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15894 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15895 PackageRemovedInfo outInfo, boolean writeSettings, 15896 PackageParser.Package replacingPackage) { 15897 synchronized (mPackages) { 15898 if (outInfo != null) { 15899 outInfo.uid = ps.appId; 15900 } 15901 15902 if (outInfo != null && outInfo.removedChildPackages != null) { 15903 final int childCount = (ps.childPackageNames != null) 15904 ? ps.childPackageNames.size() : 0; 15905 for (int i = 0; i < childCount; i++) { 15906 String childPackageName = ps.childPackageNames.get(i); 15907 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15908 if (childPs == null) { 15909 return false; 15910 } 15911 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15912 childPackageName); 15913 if (childInfo != null) { 15914 childInfo.uid = childPs.appId; 15915 } 15916 } 15917 } 15918 } 15919 15920 // Delete package data from internal structures and also remove data if flag is set 15921 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15922 15923 // Delete the child packages data 15924 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15925 for (int i = 0; i < childCount; i++) { 15926 PackageSetting childPs; 15927 synchronized (mPackages) { 15928 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15929 } 15930 if (childPs != null) { 15931 PackageRemovedInfo childOutInfo = (outInfo != null 15932 && outInfo.removedChildPackages != null) 15933 ? outInfo.removedChildPackages.get(childPs.name) : null; 15934 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15935 && (replacingPackage != null 15936 && !replacingPackage.hasChildPackage(childPs.name)) 15937 ? flags & ~DELETE_KEEP_DATA : flags; 15938 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15939 deleteFlags, writeSettings); 15940 } 15941 } 15942 15943 // Delete application code and resources only for parent packages 15944 if (ps.parentPackageName == null) { 15945 if (deleteCodeAndResources && (outInfo != null)) { 15946 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15947 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15948 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15949 } 15950 } 15951 15952 return true; 15953 } 15954 15955 @Override 15956 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15957 int userId) { 15958 mContext.enforceCallingOrSelfPermission( 15959 android.Manifest.permission.DELETE_PACKAGES, null); 15960 synchronized (mPackages) { 15961 PackageSetting ps = mSettings.mPackages.get(packageName); 15962 if (ps == null) { 15963 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15964 return false; 15965 } 15966 if (!ps.getInstalled(userId)) { 15967 // Can't block uninstall for an app that is not installed or enabled. 15968 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15969 return false; 15970 } 15971 ps.setBlockUninstall(blockUninstall, userId); 15972 mSettings.writePackageRestrictionsLPr(userId); 15973 } 15974 return true; 15975 } 15976 15977 @Override 15978 public boolean getBlockUninstallForUser(String packageName, int userId) { 15979 synchronized (mPackages) { 15980 PackageSetting ps = mSettings.mPackages.get(packageName); 15981 if (ps == null) { 15982 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15983 return false; 15984 } 15985 return ps.getBlockUninstall(userId); 15986 } 15987 } 15988 15989 @Override 15990 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15991 int callingUid = Binder.getCallingUid(); 15992 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15993 throw new SecurityException( 15994 "setRequiredForSystemUser can only be run by the system or root"); 15995 } 15996 synchronized (mPackages) { 15997 PackageSetting ps = mSettings.mPackages.get(packageName); 15998 if (ps == null) { 15999 Log.w(TAG, "Package doesn't exist: " + packageName); 16000 return false; 16001 } 16002 if (systemUserApp) { 16003 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16004 } else { 16005 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16006 } 16007 mSettings.writeLPr(); 16008 } 16009 return true; 16010 } 16011 16012 /* 16013 * This method handles package deletion in general 16014 */ 16015 private boolean deletePackageLIF(String packageName, UserHandle user, 16016 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16017 PackageRemovedInfo outInfo, boolean writeSettings, 16018 PackageParser.Package replacingPackage) { 16019 if (packageName == null) { 16020 Slog.w(TAG, "Attempt to delete null packageName."); 16021 return false; 16022 } 16023 16024 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16025 16026 PackageSetting ps; 16027 16028 synchronized (mPackages) { 16029 ps = mSettings.mPackages.get(packageName); 16030 if (ps == null) { 16031 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16032 return false; 16033 } 16034 16035 if (ps.parentPackageName != null && (!isSystemApp(ps) 16036 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16037 if (DEBUG_REMOVE) { 16038 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16039 + ((user == null) ? UserHandle.USER_ALL : user)); 16040 } 16041 final int removedUserId = (user != null) ? user.getIdentifier() 16042 : UserHandle.USER_ALL; 16043 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16044 return false; 16045 } 16046 markPackageUninstalledForUserLPw(ps, user); 16047 scheduleWritePackageRestrictionsLocked(user); 16048 return true; 16049 } 16050 } 16051 16052 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16053 && user.getIdentifier() != UserHandle.USER_ALL)) { 16054 // The caller is asking that the package only be deleted for a single 16055 // user. To do this, we just mark its uninstalled state and delete 16056 // its data. If this is a system app, we only allow this to happen if 16057 // they have set the special DELETE_SYSTEM_APP which requests different 16058 // semantics than normal for uninstalling system apps. 16059 markPackageUninstalledForUserLPw(ps, user); 16060 16061 if (!isSystemApp(ps)) { 16062 // Do not uninstall the APK if an app should be cached 16063 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16064 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16065 // Other user still have this package installed, so all 16066 // we need to do is clear this user's data and save that 16067 // it is uninstalled. 16068 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16069 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16070 return false; 16071 } 16072 scheduleWritePackageRestrictionsLocked(user); 16073 return true; 16074 } else { 16075 // We need to set it back to 'installed' so the uninstall 16076 // broadcasts will be sent correctly. 16077 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16078 ps.setInstalled(true, user.getIdentifier()); 16079 } 16080 } else { 16081 // This is a system app, so we assume that the 16082 // other users still have this package installed, so all 16083 // we need to do is clear this user's data and save that 16084 // it is uninstalled. 16085 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16086 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16087 return false; 16088 } 16089 scheduleWritePackageRestrictionsLocked(user); 16090 return true; 16091 } 16092 } 16093 16094 // If we are deleting a composite package for all users, keep track 16095 // of result for each child. 16096 if (ps.childPackageNames != null && outInfo != null) { 16097 synchronized (mPackages) { 16098 final int childCount = ps.childPackageNames.size(); 16099 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16100 for (int i = 0; i < childCount; i++) { 16101 String childPackageName = ps.childPackageNames.get(i); 16102 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16103 childInfo.removedPackage = childPackageName; 16104 outInfo.removedChildPackages.put(childPackageName, childInfo); 16105 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16106 if (childPs != null) { 16107 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16108 } 16109 } 16110 } 16111 } 16112 16113 boolean ret = false; 16114 if (isSystemApp(ps)) { 16115 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16116 // When an updated system application is deleted we delete the existing resources 16117 // as well and fall back to existing code in system partition 16118 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16119 } else { 16120 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16121 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16122 outInfo, writeSettings, replacingPackage); 16123 } 16124 16125 // Take a note whether we deleted the package for all users 16126 if (outInfo != null) { 16127 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16128 if (outInfo.removedChildPackages != null) { 16129 synchronized (mPackages) { 16130 final int childCount = outInfo.removedChildPackages.size(); 16131 for (int i = 0; i < childCount; i++) { 16132 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16133 if (childInfo != null) { 16134 childInfo.removedForAllUsers = mPackages.get( 16135 childInfo.removedPackage) == null; 16136 } 16137 } 16138 } 16139 } 16140 // If we uninstalled an update to a system app there may be some 16141 // child packages that appeared as they are declared in the system 16142 // app but were not declared in the update. 16143 if (isSystemApp(ps)) { 16144 synchronized (mPackages) { 16145 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16146 final int childCount = (updatedPs.childPackageNames != null) 16147 ? updatedPs.childPackageNames.size() : 0; 16148 for (int i = 0; i < childCount; i++) { 16149 String childPackageName = updatedPs.childPackageNames.get(i); 16150 if (outInfo.removedChildPackages == null 16151 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16152 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16153 if (childPs == null) { 16154 continue; 16155 } 16156 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16157 installRes.name = childPackageName; 16158 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16159 installRes.pkg = mPackages.get(childPackageName); 16160 installRes.uid = childPs.pkg.applicationInfo.uid; 16161 if (outInfo.appearedChildPackages == null) { 16162 outInfo.appearedChildPackages = new ArrayMap<>(); 16163 } 16164 outInfo.appearedChildPackages.put(childPackageName, installRes); 16165 } 16166 } 16167 } 16168 } 16169 } 16170 16171 return ret; 16172 } 16173 16174 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16175 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16176 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16177 for (int nextUserId : userIds) { 16178 if (DEBUG_REMOVE) { 16179 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16180 } 16181 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16182 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16183 false /*hidden*/, false /*suspended*/, null, null, null, 16184 false /*blockUninstall*/, 16185 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16186 } 16187 } 16188 16189 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16190 PackageRemovedInfo outInfo) { 16191 final PackageParser.Package pkg; 16192 synchronized (mPackages) { 16193 pkg = mPackages.get(ps.name); 16194 } 16195 16196 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16197 : new int[] {userId}; 16198 for (int nextUserId : userIds) { 16199 if (DEBUG_REMOVE) { 16200 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16201 + nextUserId); 16202 } 16203 16204 destroyAppDataLIF(pkg, userId, 16205 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16206 destroyAppProfilesLIF(pkg, userId); 16207 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16208 schedulePackageCleaning(ps.name, nextUserId, false); 16209 synchronized (mPackages) { 16210 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16211 scheduleWritePackageRestrictionsLocked(nextUserId); 16212 } 16213 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16214 } 16215 } 16216 16217 if (outInfo != null) { 16218 outInfo.removedPackage = ps.name; 16219 outInfo.removedAppId = ps.appId; 16220 outInfo.removedUsers = userIds; 16221 } 16222 16223 return true; 16224 } 16225 16226 private final class ClearStorageConnection implements ServiceConnection { 16227 IMediaContainerService mContainerService; 16228 16229 @Override 16230 public void onServiceConnected(ComponentName name, IBinder service) { 16231 synchronized (this) { 16232 mContainerService = IMediaContainerService.Stub.asInterface(service); 16233 notifyAll(); 16234 } 16235 } 16236 16237 @Override 16238 public void onServiceDisconnected(ComponentName name) { 16239 } 16240 } 16241 16242 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16243 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16244 16245 final boolean mounted; 16246 if (Environment.isExternalStorageEmulated()) { 16247 mounted = true; 16248 } else { 16249 final String status = Environment.getExternalStorageState(); 16250 16251 mounted = status.equals(Environment.MEDIA_MOUNTED) 16252 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16253 } 16254 16255 if (!mounted) { 16256 return; 16257 } 16258 16259 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16260 int[] users; 16261 if (userId == UserHandle.USER_ALL) { 16262 users = sUserManager.getUserIds(); 16263 } else { 16264 users = new int[] { userId }; 16265 } 16266 final ClearStorageConnection conn = new ClearStorageConnection(); 16267 if (mContext.bindServiceAsUser( 16268 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16269 try { 16270 for (int curUser : users) { 16271 long timeout = SystemClock.uptimeMillis() + 5000; 16272 synchronized (conn) { 16273 long now; 16274 while (conn.mContainerService == null && 16275 (now = SystemClock.uptimeMillis()) < timeout) { 16276 try { 16277 conn.wait(timeout - now); 16278 } catch (InterruptedException e) { 16279 } 16280 } 16281 } 16282 if (conn.mContainerService == null) { 16283 return; 16284 } 16285 16286 final UserEnvironment userEnv = new UserEnvironment(curUser); 16287 clearDirectory(conn.mContainerService, 16288 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16289 if (allData) { 16290 clearDirectory(conn.mContainerService, 16291 userEnv.buildExternalStorageAppDataDirs(packageName)); 16292 clearDirectory(conn.mContainerService, 16293 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16294 } 16295 } 16296 } finally { 16297 mContext.unbindService(conn); 16298 } 16299 } 16300 } 16301 16302 @Override 16303 public void clearApplicationProfileData(String packageName) { 16304 enforceSystemOrRoot("Only the system can clear all profile data"); 16305 16306 final PackageParser.Package pkg; 16307 synchronized (mPackages) { 16308 pkg = mPackages.get(packageName); 16309 } 16310 16311 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16312 synchronized (mInstallLock) { 16313 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16314 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16315 true /* removeBaseMarker */); 16316 } 16317 } 16318 } 16319 16320 @Override 16321 public void clearApplicationUserData(final String packageName, 16322 final IPackageDataObserver observer, final int userId) { 16323 mContext.enforceCallingOrSelfPermission( 16324 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16325 16326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16327 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16328 16329 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16330 throw new SecurityException("Cannot clear data for a protected package: " 16331 + packageName); 16332 } 16333 // Queue up an async operation since the package deletion may take a little while. 16334 mHandler.post(new Runnable() { 16335 public void run() { 16336 mHandler.removeCallbacks(this); 16337 final boolean succeeded; 16338 try (PackageFreezer freezer = freezePackage(packageName, 16339 "clearApplicationUserData")) { 16340 synchronized (mInstallLock) { 16341 succeeded = clearApplicationUserDataLIF(packageName, userId); 16342 } 16343 clearExternalStorageDataSync(packageName, userId, true); 16344 } 16345 if (succeeded) { 16346 // invoke DeviceStorageMonitor's update method to clear any notifications 16347 DeviceStorageMonitorInternal dsm = LocalServices 16348 .getService(DeviceStorageMonitorInternal.class); 16349 if (dsm != null) { 16350 dsm.checkMemory(); 16351 } 16352 } 16353 if(observer != null) { 16354 try { 16355 observer.onRemoveCompleted(packageName, succeeded); 16356 } catch (RemoteException e) { 16357 Log.i(TAG, "Observer no longer exists."); 16358 } 16359 } //end if observer 16360 } //end run 16361 }); 16362 } 16363 16364 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16365 if (packageName == null) { 16366 Slog.w(TAG, "Attempt to delete null packageName."); 16367 return false; 16368 } 16369 16370 // Try finding details about the requested package 16371 PackageParser.Package pkg; 16372 synchronized (mPackages) { 16373 pkg = mPackages.get(packageName); 16374 if (pkg == null) { 16375 final PackageSetting ps = mSettings.mPackages.get(packageName); 16376 if (ps != null) { 16377 pkg = ps.pkg; 16378 } 16379 } 16380 16381 if (pkg == null) { 16382 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16383 return false; 16384 } 16385 16386 PackageSetting ps = (PackageSetting) pkg.mExtras; 16387 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16388 } 16389 16390 clearAppDataLIF(pkg, userId, 16391 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16392 16393 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16394 removeKeystoreDataIfNeeded(userId, appId); 16395 16396 UserManagerInternal umInternal = getUserManagerInternal(); 16397 final int flags; 16398 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16399 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16400 } else if (umInternal.isUserRunning(userId)) { 16401 flags = StorageManager.FLAG_STORAGE_DE; 16402 } else { 16403 flags = 0; 16404 } 16405 prepareAppDataContentsLIF(pkg, userId, flags); 16406 16407 return true; 16408 } 16409 16410 /** 16411 * Reverts user permission state changes (permissions and flags) in 16412 * all packages for a given user. 16413 * 16414 * @param userId The device user for which to do a reset. 16415 */ 16416 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16417 final int packageCount = mPackages.size(); 16418 for (int i = 0; i < packageCount; i++) { 16419 PackageParser.Package pkg = mPackages.valueAt(i); 16420 PackageSetting ps = (PackageSetting) pkg.mExtras; 16421 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16422 } 16423 } 16424 16425 private void resetNetworkPolicies(int userId) { 16426 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16427 } 16428 16429 /** 16430 * Reverts user permission state changes (permissions and flags). 16431 * 16432 * @param ps The package for which to reset. 16433 * @param userId The device user for which to do a reset. 16434 */ 16435 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16436 final PackageSetting ps, final int userId) { 16437 if (ps.pkg == null) { 16438 return; 16439 } 16440 16441 // These are flags that can change base on user actions. 16442 final int userSettableMask = FLAG_PERMISSION_USER_SET 16443 | FLAG_PERMISSION_USER_FIXED 16444 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16445 | FLAG_PERMISSION_REVIEW_REQUIRED; 16446 16447 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16448 | FLAG_PERMISSION_POLICY_FIXED; 16449 16450 boolean writeInstallPermissions = false; 16451 boolean writeRuntimePermissions = false; 16452 16453 final int permissionCount = ps.pkg.requestedPermissions.size(); 16454 for (int i = 0; i < permissionCount; i++) { 16455 String permission = ps.pkg.requestedPermissions.get(i); 16456 16457 BasePermission bp = mSettings.mPermissions.get(permission); 16458 if (bp == null) { 16459 continue; 16460 } 16461 16462 // If shared user we just reset the state to which only this app contributed. 16463 if (ps.sharedUser != null) { 16464 boolean used = false; 16465 final int packageCount = ps.sharedUser.packages.size(); 16466 for (int j = 0; j < packageCount; j++) { 16467 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16468 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16469 && pkg.pkg.requestedPermissions.contains(permission)) { 16470 used = true; 16471 break; 16472 } 16473 } 16474 if (used) { 16475 continue; 16476 } 16477 } 16478 16479 PermissionsState permissionsState = ps.getPermissionsState(); 16480 16481 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16482 16483 // Always clear the user settable flags. 16484 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16485 bp.name) != null; 16486 // If permission review is enabled and this is a legacy app, mark the 16487 // permission as requiring a review as this is the initial state. 16488 int flags = 0; 16489 if (Build.PERMISSIONS_REVIEW_REQUIRED 16490 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16491 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16492 } 16493 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16494 if (hasInstallState) { 16495 writeInstallPermissions = true; 16496 } else { 16497 writeRuntimePermissions = true; 16498 } 16499 } 16500 16501 // Below is only runtime permission handling. 16502 if (!bp.isRuntime()) { 16503 continue; 16504 } 16505 16506 // Never clobber system or policy. 16507 if ((oldFlags & policyOrSystemFlags) != 0) { 16508 continue; 16509 } 16510 16511 // If this permission was granted by default, make sure it is. 16512 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16513 if (permissionsState.grantRuntimePermission(bp, userId) 16514 != PERMISSION_OPERATION_FAILURE) { 16515 writeRuntimePermissions = true; 16516 } 16517 // If permission review is enabled the permissions for a legacy apps 16518 // are represented as constantly granted runtime ones, so don't revoke. 16519 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16520 // Otherwise, reset the permission. 16521 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16522 switch (revokeResult) { 16523 case PERMISSION_OPERATION_SUCCESS: 16524 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16525 writeRuntimePermissions = true; 16526 final int appId = ps.appId; 16527 mHandler.post(new Runnable() { 16528 @Override 16529 public void run() { 16530 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16531 } 16532 }); 16533 } break; 16534 } 16535 } 16536 } 16537 16538 // Synchronously write as we are taking permissions away. 16539 if (writeRuntimePermissions) { 16540 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16541 } 16542 16543 // Synchronously write as we are taking permissions away. 16544 if (writeInstallPermissions) { 16545 mSettings.writeLPr(); 16546 } 16547 } 16548 16549 /** 16550 * Remove entries from the keystore daemon. Will only remove it if the 16551 * {@code appId} is valid. 16552 */ 16553 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16554 if (appId < 0) { 16555 return; 16556 } 16557 16558 final KeyStore keyStore = KeyStore.getInstance(); 16559 if (keyStore != null) { 16560 if (userId == UserHandle.USER_ALL) { 16561 for (final int individual : sUserManager.getUserIds()) { 16562 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16563 } 16564 } else { 16565 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16566 } 16567 } else { 16568 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16569 } 16570 } 16571 16572 @Override 16573 public void deleteApplicationCacheFiles(final String packageName, 16574 final IPackageDataObserver observer) { 16575 final int userId = UserHandle.getCallingUserId(); 16576 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16577 } 16578 16579 @Override 16580 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16581 final IPackageDataObserver observer) { 16582 mContext.enforceCallingOrSelfPermission( 16583 android.Manifest.permission.DELETE_CACHE_FILES, null); 16584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16585 /* requireFullPermission= */ true, /* checkShell= */ false, 16586 "delete application cache files"); 16587 16588 final PackageParser.Package pkg; 16589 synchronized (mPackages) { 16590 pkg = mPackages.get(packageName); 16591 } 16592 16593 // Queue up an async operation since the package deletion may take a little while. 16594 mHandler.post(new Runnable() { 16595 public void run() { 16596 synchronized (mInstallLock) { 16597 final int flags = StorageManager.FLAG_STORAGE_DE 16598 | StorageManager.FLAG_STORAGE_CE; 16599 // We're only clearing cache files, so we don't care if the 16600 // app is unfrozen and still able to run 16601 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16602 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16603 } 16604 clearExternalStorageDataSync(packageName, userId, false); 16605 if (observer != null) { 16606 try { 16607 observer.onRemoveCompleted(packageName, true); 16608 } catch (RemoteException e) { 16609 Log.i(TAG, "Observer no longer exists."); 16610 } 16611 } 16612 } 16613 }); 16614 } 16615 16616 @Override 16617 public void getPackageSizeInfo(final String packageName, int userHandle, 16618 final IPackageStatsObserver observer) { 16619 mContext.enforceCallingOrSelfPermission( 16620 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16621 if (packageName == null) { 16622 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16623 } 16624 16625 PackageStats stats = new PackageStats(packageName, userHandle); 16626 16627 /* 16628 * Queue up an async operation since the package measurement may take a 16629 * little while. 16630 */ 16631 Message msg = mHandler.obtainMessage(INIT_COPY); 16632 msg.obj = new MeasureParams(stats, observer); 16633 mHandler.sendMessage(msg); 16634 } 16635 16636 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16637 final PackageSetting ps; 16638 synchronized (mPackages) { 16639 ps = mSettings.mPackages.get(packageName); 16640 if (ps == null) { 16641 Slog.w(TAG, "Failed to find settings for " + packageName); 16642 return false; 16643 } 16644 } 16645 try { 16646 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16647 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16648 ps.getCeDataInode(userId), ps.codePathString, stats); 16649 } catch (InstallerException e) { 16650 Slog.w(TAG, String.valueOf(e)); 16651 return false; 16652 } 16653 16654 // For now, ignore code size of packages on system partition 16655 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16656 stats.codeSize = 0; 16657 } 16658 16659 return true; 16660 } 16661 16662 private int getUidTargetSdkVersionLockedLPr(int uid) { 16663 Object obj = mSettings.getUserIdLPr(uid); 16664 if (obj instanceof SharedUserSetting) { 16665 final SharedUserSetting sus = (SharedUserSetting) obj; 16666 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16667 final Iterator<PackageSetting> it = sus.packages.iterator(); 16668 while (it.hasNext()) { 16669 final PackageSetting ps = it.next(); 16670 if (ps.pkg != null) { 16671 int v = ps.pkg.applicationInfo.targetSdkVersion; 16672 if (v < vers) vers = v; 16673 } 16674 } 16675 return vers; 16676 } else if (obj instanceof PackageSetting) { 16677 final PackageSetting ps = (PackageSetting) obj; 16678 if (ps.pkg != null) { 16679 return ps.pkg.applicationInfo.targetSdkVersion; 16680 } 16681 } 16682 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16683 } 16684 16685 @Override 16686 public void addPreferredActivity(IntentFilter filter, int match, 16687 ComponentName[] set, ComponentName activity, int userId) { 16688 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16689 "Adding preferred"); 16690 } 16691 16692 private void addPreferredActivityInternal(IntentFilter filter, int match, 16693 ComponentName[] set, ComponentName activity, boolean always, int userId, 16694 String opname) { 16695 // writer 16696 int callingUid = Binder.getCallingUid(); 16697 enforceCrossUserPermission(callingUid, userId, 16698 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16699 if (filter.countActions() == 0) { 16700 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16701 return; 16702 } 16703 synchronized (mPackages) { 16704 if (mContext.checkCallingOrSelfPermission( 16705 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16706 != PackageManager.PERMISSION_GRANTED) { 16707 if (getUidTargetSdkVersionLockedLPr(callingUid) 16708 < Build.VERSION_CODES.FROYO) { 16709 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16710 + callingUid); 16711 return; 16712 } 16713 mContext.enforceCallingOrSelfPermission( 16714 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16715 } 16716 16717 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16718 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16719 + userId + ":"); 16720 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16721 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16722 scheduleWritePackageRestrictionsLocked(userId); 16723 postPreferredActivityChangedBroadcast(userId); 16724 } 16725 } 16726 16727 private void postPreferredActivityChangedBroadcast(int userId) { 16728 mHandler.post(() -> { 16729 final IActivityManager am = ActivityManagerNative.getDefault(); 16730 if (am == null) { 16731 return; 16732 } 16733 16734 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16735 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16736 try { 16737 am.broadcastIntent(null, intent, null, null, 16738 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16739 null, false, false, userId); 16740 } catch (RemoteException e) { 16741 } 16742 }); 16743 } 16744 16745 @Override 16746 public void replacePreferredActivity(IntentFilter filter, int match, 16747 ComponentName[] set, ComponentName activity, int userId) { 16748 if (filter.countActions() != 1) { 16749 throw new IllegalArgumentException( 16750 "replacePreferredActivity expects filter to have only 1 action."); 16751 } 16752 if (filter.countDataAuthorities() != 0 16753 || filter.countDataPaths() != 0 16754 || filter.countDataSchemes() > 1 16755 || filter.countDataTypes() != 0) { 16756 throw new IllegalArgumentException( 16757 "replacePreferredActivity expects filter to have no data authorities, " + 16758 "paths, or types; and at most one scheme."); 16759 } 16760 16761 final int callingUid = Binder.getCallingUid(); 16762 enforceCrossUserPermission(callingUid, userId, 16763 true /* requireFullPermission */, false /* checkShell */, 16764 "replace preferred activity"); 16765 synchronized (mPackages) { 16766 if (mContext.checkCallingOrSelfPermission( 16767 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16768 != PackageManager.PERMISSION_GRANTED) { 16769 if (getUidTargetSdkVersionLockedLPr(callingUid) 16770 < Build.VERSION_CODES.FROYO) { 16771 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16772 + Binder.getCallingUid()); 16773 return; 16774 } 16775 mContext.enforceCallingOrSelfPermission( 16776 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16777 } 16778 16779 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16780 if (pir != null) { 16781 // Get all of the existing entries that exactly match this filter. 16782 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16783 if (existing != null && existing.size() == 1) { 16784 PreferredActivity cur = existing.get(0); 16785 if (DEBUG_PREFERRED) { 16786 Slog.i(TAG, "Checking replace of preferred:"); 16787 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16788 if (!cur.mPref.mAlways) { 16789 Slog.i(TAG, " -- CUR; not mAlways!"); 16790 } else { 16791 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16792 Slog.i(TAG, " -- CUR: mSet=" 16793 + Arrays.toString(cur.mPref.mSetComponents)); 16794 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16795 Slog.i(TAG, " -- NEW: mMatch=" 16796 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16797 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16798 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16799 } 16800 } 16801 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16802 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16803 && cur.mPref.sameSet(set)) { 16804 // Setting the preferred activity to what it happens to be already 16805 if (DEBUG_PREFERRED) { 16806 Slog.i(TAG, "Replacing with same preferred activity " 16807 + cur.mPref.mShortComponent + " for user " 16808 + userId + ":"); 16809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16810 } 16811 return; 16812 } 16813 } 16814 16815 if (existing != null) { 16816 if (DEBUG_PREFERRED) { 16817 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16818 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16819 } 16820 for (int i = 0; i < existing.size(); i++) { 16821 PreferredActivity pa = existing.get(i); 16822 if (DEBUG_PREFERRED) { 16823 Slog.i(TAG, "Removing existing preferred activity " 16824 + pa.mPref.mComponent + ":"); 16825 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16826 } 16827 pir.removeFilter(pa); 16828 } 16829 } 16830 } 16831 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16832 "Replacing preferred"); 16833 } 16834 } 16835 16836 @Override 16837 public void clearPackagePreferredActivities(String packageName) { 16838 final int uid = Binder.getCallingUid(); 16839 // writer 16840 synchronized (mPackages) { 16841 PackageParser.Package pkg = mPackages.get(packageName); 16842 if (pkg == null || pkg.applicationInfo.uid != uid) { 16843 if (mContext.checkCallingOrSelfPermission( 16844 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16845 != PackageManager.PERMISSION_GRANTED) { 16846 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16847 < Build.VERSION_CODES.FROYO) { 16848 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16849 + Binder.getCallingUid()); 16850 return; 16851 } 16852 mContext.enforceCallingOrSelfPermission( 16853 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16854 } 16855 } 16856 16857 int user = UserHandle.getCallingUserId(); 16858 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16859 scheduleWritePackageRestrictionsLocked(user); 16860 } 16861 } 16862 } 16863 16864 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16865 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16866 ArrayList<PreferredActivity> removed = null; 16867 boolean changed = false; 16868 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16869 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16870 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16871 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16872 continue; 16873 } 16874 Iterator<PreferredActivity> it = pir.filterIterator(); 16875 while (it.hasNext()) { 16876 PreferredActivity pa = it.next(); 16877 // Mark entry for removal only if it matches the package name 16878 // and the entry is of type "always". 16879 if (packageName == null || 16880 (pa.mPref.mComponent.getPackageName().equals(packageName) 16881 && pa.mPref.mAlways)) { 16882 if (removed == null) { 16883 removed = new ArrayList<PreferredActivity>(); 16884 } 16885 removed.add(pa); 16886 } 16887 } 16888 if (removed != null) { 16889 for (int j=0; j<removed.size(); j++) { 16890 PreferredActivity pa = removed.get(j); 16891 pir.removeFilter(pa); 16892 } 16893 changed = true; 16894 } 16895 } 16896 if (changed) { 16897 postPreferredActivityChangedBroadcast(userId); 16898 } 16899 return changed; 16900 } 16901 16902 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16903 private void clearIntentFilterVerificationsLPw(int userId) { 16904 final int packageCount = mPackages.size(); 16905 for (int i = 0; i < packageCount; i++) { 16906 PackageParser.Package pkg = mPackages.valueAt(i); 16907 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16908 } 16909 } 16910 16911 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16912 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16913 if (userId == UserHandle.USER_ALL) { 16914 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16915 sUserManager.getUserIds())) { 16916 for (int oneUserId : sUserManager.getUserIds()) { 16917 scheduleWritePackageRestrictionsLocked(oneUserId); 16918 } 16919 } 16920 } else { 16921 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16922 scheduleWritePackageRestrictionsLocked(userId); 16923 } 16924 } 16925 } 16926 16927 void clearDefaultBrowserIfNeeded(String packageName) { 16928 for (int oneUserId : sUserManager.getUserIds()) { 16929 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16930 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16931 if (packageName.equals(defaultBrowserPackageName)) { 16932 setDefaultBrowserPackageName(null, oneUserId); 16933 } 16934 } 16935 } 16936 16937 @Override 16938 public void resetApplicationPreferences(int userId) { 16939 mContext.enforceCallingOrSelfPermission( 16940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16941 final long identity = Binder.clearCallingIdentity(); 16942 // writer 16943 try { 16944 synchronized (mPackages) { 16945 clearPackagePreferredActivitiesLPw(null, userId); 16946 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16947 // TODO: We have to reset the default SMS and Phone. This requires 16948 // significant refactoring to keep all default apps in the package 16949 // manager (cleaner but more work) or have the services provide 16950 // callbacks to the package manager to request a default app reset. 16951 applyFactoryDefaultBrowserLPw(userId); 16952 clearIntentFilterVerificationsLPw(userId); 16953 primeDomainVerificationsLPw(userId); 16954 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16955 scheduleWritePackageRestrictionsLocked(userId); 16956 } 16957 resetNetworkPolicies(userId); 16958 } finally { 16959 Binder.restoreCallingIdentity(identity); 16960 } 16961 } 16962 16963 @Override 16964 public int getPreferredActivities(List<IntentFilter> outFilters, 16965 List<ComponentName> outActivities, String packageName) { 16966 16967 int num = 0; 16968 final int userId = UserHandle.getCallingUserId(); 16969 // reader 16970 synchronized (mPackages) { 16971 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16972 if (pir != null) { 16973 final Iterator<PreferredActivity> it = pir.filterIterator(); 16974 while (it.hasNext()) { 16975 final PreferredActivity pa = it.next(); 16976 if (packageName == null 16977 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16978 && pa.mPref.mAlways)) { 16979 if (outFilters != null) { 16980 outFilters.add(new IntentFilter(pa)); 16981 } 16982 if (outActivities != null) { 16983 outActivities.add(pa.mPref.mComponent); 16984 } 16985 } 16986 } 16987 } 16988 } 16989 16990 return num; 16991 } 16992 16993 @Override 16994 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16995 int userId) { 16996 int callingUid = Binder.getCallingUid(); 16997 if (callingUid != Process.SYSTEM_UID) { 16998 throw new SecurityException( 16999 "addPersistentPreferredActivity can only be run by the system"); 17000 } 17001 if (filter.countActions() == 0) { 17002 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17003 return; 17004 } 17005 synchronized (mPackages) { 17006 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17007 ":"); 17008 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17009 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17010 new PersistentPreferredActivity(filter, activity)); 17011 scheduleWritePackageRestrictionsLocked(userId); 17012 postPreferredActivityChangedBroadcast(userId); 17013 } 17014 } 17015 17016 @Override 17017 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17018 int callingUid = Binder.getCallingUid(); 17019 if (callingUid != Process.SYSTEM_UID) { 17020 throw new SecurityException( 17021 "clearPackagePersistentPreferredActivities can only be run by the system"); 17022 } 17023 ArrayList<PersistentPreferredActivity> removed = null; 17024 boolean changed = false; 17025 synchronized (mPackages) { 17026 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17027 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17028 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17029 .valueAt(i); 17030 if (userId != thisUserId) { 17031 continue; 17032 } 17033 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17034 while (it.hasNext()) { 17035 PersistentPreferredActivity ppa = it.next(); 17036 // Mark entry for removal only if it matches the package name. 17037 if (ppa.mComponent.getPackageName().equals(packageName)) { 17038 if (removed == null) { 17039 removed = new ArrayList<PersistentPreferredActivity>(); 17040 } 17041 removed.add(ppa); 17042 } 17043 } 17044 if (removed != null) { 17045 for (int j=0; j<removed.size(); j++) { 17046 PersistentPreferredActivity ppa = removed.get(j); 17047 ppir.removeFilter(ppa); 17048 } 17049 changed = true; 17050 } 17051 } 17052 17053 if (changed) { 17054 scheduleWritePackageRestrictionsLocked(userId); 17055 postPreferredActivityChangedBroadcast(userId); 17056 } 17057 } 17058 } 17059 17060 /** 17061 * Common machinery for picking apart a restored XML blob and passing 17062 * it to a caller-supplied functor to be applied to the running system. 17063 */ 17064 private void restoreFromXml(XmlPullParser parser, int userId, 17065 String expectedStartTag, BlobXmlRestorer functor) 17066 throws IOException, XmlPullParserException { 17067 int type; 17068 while ((type = parser.next()) != XmlPullParser.START_TAG 17069 && type != XmlPullParser.END_DOCUMENT) { 17070 } 17071 if (type != XmlPullParser.START_TAG) { 17072 // oops didn't find a start tag?! 17073 if (DEBUG_BACKUP) { 17074 Slog.e(TAG, "Didn't find start tag during restore"); 17075 } 17076 return; 17077 } 17078Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17079 // this is supposed to be TAG_PREFERRED_BACKUP 17080 if (!expectedStartTag.equals(parser.getName())) { 17081 if (DEBUG_BACKUP) { 17082 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17083 } 17084 return; 17085 } 17086 17087 // skip interfering stuff, then we're aligned with the backing implementation 17088 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17089Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17090 functor.apply(parser, userId); 17091 } 17092 17093 private interface BlobXmlRestorer { 17094 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17095 } 17096 17097 /** 17098 * Non-Binder method, support for the backup/restore mechanism: write the 17099 * full set of preferred activities in its canonical XML format. Returns the 17100 * XML output as a byte array, or null if there is none. 17101 */ 17102 @Override 17103 public byte[] getPreferredActivityBackup(int userId) { 17104 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17105 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17106 } 17107 17108 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17109 try { 17110 final XmlSerializer serializer = new FastXmlSerializer(); 17111 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17112 serializer.startDocument(null, true); 17113 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17114 17115 synchronized (mPackages) { 17116 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17117 } 17118 17119 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17120 serializer.endDocument(); 17121 serializer.flush(); 17122 } catch (Exception e) { 17123 if (DEBUG_BACKUP) { 17124 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17125 } 17126 return null; 17127 } 17128 17129 return dataStream.toByteArray(); 17130 } 17131 17132 @Override 17133 public void restorePreferredActivities(byte[] backup, int userId) { 17134 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17135 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17136 } 17137 17138 try { 17139 final XmlPullParser parser = Xml.newPullParser(); 17140 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17141 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17142 new BlobXmlRestorer() { 17143 @Override 17144 public void apply(XmlPullParser parser, int userId) 17145 throws XmlPullParserException, IOException { 17146 synchronized (mPackages) { 17147 mSettings.readPreferredActivitiesLPw(parser, userId); 17148 } 17149 } 17150 } ); 17151 } catch (Exception e) { 17152 if (DEBUG_BACKUP) { 17153 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17154 } 17155 } 17156 } 17157 17158 /** 17159 * Non-Binder method, support for the backup/restore mechanism: write the 17160 * default browser (etc) settings in its canonical XML format. Returns the default 17161 * browser XML representation as a byte array, or null if there is none. 17162 */ 17163 @Override 17164 public byte[] getDefaultAppsBackup(int userId) { 17165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17166 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17167 } 17168 17169 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17170 try { 17171 final XmlSerializer serializer = new FastXmlSerializer(); 17172 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17173 serializer.startDocument(null, true); 17174 serializer.startTag(null, TAG_DEFAULT_APPS); 17175 17176 synchronized (mPackages) { 17177 mSettings.writeDefaultAppsLPr(serializer, userId); 17178 } 17179 17180 serializer.endTag(null, TAG_DEFAULT_APPS); 17181 serializer.endDocument(); 17182 serializer.flush(); 17183 } catch (Exception e) { 17184 if (DEBUG_BACKUP) { 17185 Slog.e(TAG, "Unable to write default apps for backup", e); 17186 } 17187 return null; 17188 } 17189 17190 return dataStream.toByteArray(); 17191 } 17192 17193 @Override 17194 public void restoreDefaultApps(byte[] backup, int userId) { 17195 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17196 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17197 } 17198 17199 try { 17200 final XmlPullParser parser = Xml.newPullParser(); 17201 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17202 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17203 new BlobXmlRestorer() { 17204 @Override 17205 public void apply(XmlPullParser parser, int userId) 17206 throws XmlPullParserException, IOException { 17207 synchronized (mPackages) { 17208 mSettings.readDefaultAppsLPw(parser, userId); 17209 } 17210 } 17211 } ); 17212 } catch (Exception e) { 17213 if (DEBUG_BACKUP) { 17214 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17215 } 17216 } 17217 } 17218 17219 @Override 17220 public byte[] getIntentFilterVerificationBackup(int userId) { 17221 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17222 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17223 } 17224 17225 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17226 try { 17227 final XmlSerializer serializer = new FastXmlSerializer(); 17228 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17229 serializer.startDocument(null, true); 17230 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17231 17232 synchronized (mPackages) { 17233 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17234 } 17235 17236 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17237 serializer.endDocument(); 17238 serializer.flush(); 17239 } catch (Exception e) { 17240 if (DEBUG_BACKUP) { 17241 Slog.e(TAG, "Unable to write default apps for backup", e); 17242 } 17243 return null; 17244 } 17245 17246 return dataStream.toByteArray(); 17247 } 17248 17249 @Override 17250 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17251 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17252 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17253 } 17254 17255 try { 17256 final XmlPullParser parser = Xml.newPullParser(); 17257 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17258 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17259 new BlobXmlRestorer() { 17260 @Override 17261 public void apply(XmlPullParser parser, int userId) 17262 throws XmlPullParserException, IOException { 17263 synchronized (mPackages) { 17264 mSettings.readAllDomainVerificationsLPr(parser, userId); 17265 mSettings.writeLPr(); 17266 } 17267 } 17268 } ); 17269 } catch (Exception e) { 17270 if (DEBUG_BACKUP) { 17271 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17272 } 17273 } 17274 } 17275 17276 @Override 17277 public byte[] getPermissionGrantBackup(int userId) { 17278 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17279 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17280 } 17281 17282 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17283 try { 17284 final XmlSerializer serializer = new FastXmlSerializer(); 17285 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17286 serializer.startDocument(null, true); 17287 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17288 17289 synchronized (mPackages) { 17290 serializeRuntimePermissionGrantsLPr(serializer, userId); 17291 } 17292 17293 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17294 serializer.endDocument(); 17295 serializer.flush(); 17296 } catch (Exception e) { 17297 if (DEBUG_BACKUP) { 17298 Slog.e(TAG, "Unable to write default apps for backup", e); 17299 } 17300 return null; 17301 } 17302 17303 return dataStream.toByteArray(); 17304 } 17305 17306 @Override 17307 public void restorePermissionGrants(byte[] backup, int userId) { 17308 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17309 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17310 } 17311 17312 try { 17313 final XmlPullParser parser = Xml.newPullParser(); 17314 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17315 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17316 new BlobXmlRestorer() { 17317 @Override 17318 public void apply(XmlPullParser parser, int userId) 17319 throws XmlPullParserException, IOException { 17320 synchronized (mPackages) { 17321 processRestoredPermissionGrantsLPr(parser, userId); 17322 } 17323 } 17324 } ); 17325 } catch (Exception e) { 17326 if (DEBUG_BACKUP) { 17327 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17328 } 17329 } 17330 } 17331 17332 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17333 throws IOException { 17334 serializer.startTag(null, TAG_ALL_GRANTS); 17335 17336 final int N = mSettings.mPackages.size(); 17337 for (int i = 0; i < N; i++) { 17338 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17339 boolean pkgGrantsKnown = false; 17340 17341 PermissionsState packagePerms = ps.getPermissionsState(); 17342 17343 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17344 final int grantFlags = state.getFlags(); 17345 // only look at grants that are not system/policy fixed 17346 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17347 final boolean isGranted = state.isGranted(); 17348 // And only back up the user-twiddled state bits 17349 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17350 final String packageName = mSettings.mPackages.keyAt(i); 17351 if (!pkgGrantsKnown) { 17352 serializer.startTag(null, TAG_GRANT); 17353 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17354 pkgGrantsKnown = true; 17355 } 17356 17357 final boolean userSet = 17358 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17359 final boolean userFixed = 17360 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17361 final boolean revoke = 17362 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17363 17364 serializer.startTag(null, TAG_PERMISSION); 17365 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17366 if (isGranted) { 17367 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17368 } 17369 if (userSet) { 17370 serializer.attribute(null, ATTR_USER_SET, "true"); 17371 } 17372 if (userFixed) { 17373 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17374 } 17375 if (revoke) { 17376 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17377 } 17378 serializer.endTag(null, TAG_PERMISSION); 17379 } 17380 } 17381 } 17382 17383 if (pkgGrantsKnown) { 17384 serializer.endTag(null, TAG_GRANT); 17385 } 17386 } 17387 17388 serializer.endTag(null, TAG_ALL_GRANTS); 17389 } 17390 17391 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17392 throws XmlPullParserException, IOException { 17393 String pkgName = null; 17394 int outerDepth = parser.getDepth(); 17395 int type; 17396 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17397 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17398 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17399 continue; 17400 } 17401 17402 final String tagName = parser.getName(); 17403 if (tagName.equals(TAG_GRANT)) { 17404 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17405 if (DEBUG_BACKUP) { 17406 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17407 } 17408 } else if (tagName.equals(TAG_PERMISSION)) { 17409 17410 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17411 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17412 17413 int newFlagSet = 0; 17414 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17415 newFlagSet |= FLAG_PERMISSION_USER_SET; 17416 } 17417 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17418 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17419 } 17420 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17421 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17422 } 17423 if (DEBUG_BACKUP) { 17424 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17425 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17426 } 17427 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17428 if (ps != null) { 17429 // Already installed so we apply the grant immediately 17430 if (DEBUG_BACKUP) { 17431 Slog.v(TAG, " + already installed; applying"); 17432 } 17433 PermissionsState perms = ps.getPermissionsState(); 17434 BasePermission bp = mSettings.mPermissions.get(permName); 17435 if (bp != null) { 17436 if (isGranted) { 17437 perms.grantRuntimePermission(bp, userId); 17438 } 17439 if (newFlagSet != 0) { 17440 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17441 } 17442 } 17443 } else { 17444 // Need to wait for post-restore install to apply the grant 17445 if (DEBUG_BACKUP) { 17446 Slog.v(TAG, " - not yet installed; saving for later"); 17447 } 17448 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17449 isGranted, newFlagSet, userId); 17450 } 17451 } else { 17452 PackageManagerService.reportSettingsProblem(Log.WARN, 17453 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17454 XmlUtils.skipCurrentTag(parser); 17455 } 17456 } 17457 17458 scheduleWriteSettingsLocked(); 17459 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17460 } 17461 17462 @Override 17463 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17464 int sourceUserId, int targetUserId, int flags) { 17465 mContext.enforceCallingOrSelfPermission( 17466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17467 int callingUid = Binder.getCallingUid(); 17468 enforceOwnerRights(ownerPackage, callingUid); 17469 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17470 if (intentFilter.countActions() == 0) { 17471 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17472 return; 17473 } 17474 synchronized (mPackages) { 17475 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17476 ownerPackage, targetUserId, flags); 17477 CrossProfileIntentResolver resolver = 17478 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17479 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17480 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17481 if (existing != null) { 17482 int size = existing.size(); 17483 for (int i = 0; i < size; i++) { 17484 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17485 return; 17486 } 17487 } 17488 } 17489 resolver.addFilter(newFilter); 17490 scheduleWritePackageRestrictionsLocked(sourceUserId); 17491 } 17492 } 17493 17494 @Override 17495 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17496 mContext.enforceCallingOrSelfPermission( 17497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17498 int callingUid = Binder.getCallingUid(); 17499 enforceOwnerRights(ownerPackage, callingUid); 17500 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17501 synchronized (mPackages) { 17502 CrossProfileIntentResolver resolver = 17503 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17504 ArraySet<CrossProfileIntentFilter> set = 17505 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17506 for (CrossProfileIntentFilter filter : set) { 17507 if (filter.getOwnerPackage().equals(ownerPackage)) { 17508 resolver.removeFilter(filter); 17509 } 17510 } 17511 scheduleWritePackageRestrictionsLocked(sourceUserId); 17512 } 17513 } 17514 17515 // Enforcing that callingUid is owning pkg on userId 17516 private void enforceOwnerRights(String pkg, int callingUid) { 17517 // The system owns everything. 17518 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17519 return; 17520 } 17521 int callingUserId = UserHandle.getUserId(callingUid); 17522 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17523 if (pi == null) { 17524 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17525 + callingUserId); 17526 } 17527 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17528 throw new SecurityException("Calling uid " + callingUid 17529 + " does not own package " + pkg); 17530 } 17531 } 17532 17533 @Override 17534 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17535 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17536 } 17537 17538 private Intent getHomeIntent() { 17539 Intent intent = new Intent(Intent.ACTION_MAIN); 17540 intent.addCategory(Intent.CATEGORY_HOME); 17541 intent.addCategory(Intent.CATEGORY_DEFAULT); 17542 return intent; 17543 } 17544 17545 private IntentFilter getHomeFilter() { 17546 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17547 filter.addCategory(Intent.CATEGORY_HOME); 17548 filter.addCategory(Intent.CATEGORY_DEFAULT); 17549 return filter; 17550 } 17551 17552 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17553 int userId) { 17554 Intent intent = getHomeIntent(); 17555 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17556 PackageManager.GET_META_DATA, userId); 17557 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17558 true, false, false, userId); 17559 17560 allHomeCandidates.clear(); 17561 if (list != null) { 17562 for (ResolveInfo ri : list) { 17563 allHomeCandidates.add(ri); 17564 } 17565 } 17566 return (preferred == null || preferred.activityInfo == null) 17567 ? null 17568 : new ComponentName(preferred.activityInfo.packageName, 17569 preferred.activityInfo.name); 17570 } 17571 17572 @Override 17573 public void setHomeActivity(ComponentName comp, int userId) { 17574 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17575 getHomeActivitiesAsUser(homeActivities, userId); 17576 17577 boolean found = false; 17578 17579 final int size = homeActivities.size(); 17580 final ComponentName[] set = new ComponentName[size]; 17581 for (int i = 0; i < size; i++) { 17582 final ResolveInfo candidate = homeActivities.get(i); 17583 final ActivityInfo info = candidate.activityInfo; 17584 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17585 set[i] = activityName; 17586 if (!found && activityName.equals(comp)) { 17587 found = true; 17588 } 17589 } 17590 if (!found) { 17591 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17592 + userId); 17593 } 17594 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17595 set, comp, userId); 17596 } 17597 17598 private @Nullable String getSetupWizardPackageName() { 17599 final Intent intent = new Intent(Intent.ACTION_MAIN); 17600 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17601 17602 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17603 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17604 | MATCH_DISABLED_COMPONENTS, 17605 UserHandle.myUserId()); 17606 if (matches.size() == 1) { 17607 return matches.get(0).getComponentInfo().packageName; 17608 } else { 17609 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17610 + ": matches=" + matches); 17611 return null; 17612 } 17613 } 17614 17615 @Override 17616 public void setApplicationEnabledSetting(String appPackageName, 17617 int newState, int flags, int userId, String callingPackage) { 17618 if (!sUserManager.exists(userId)) return; 17619 if (callingPackage == null) { 17620 callingPackage = Integer.toString(Binder.getCallingUid()); 17621 } 17622 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17623 } 17624 17625 @Override 17626 public void setComponentEnabledSetting(ComponentName componentName, 17627 int newState, int flags, int userId) { 17628 if (!sUserManager.exists(userId)) return; 17629 setEnabledSetting(componentName.getPackageName(), 17630 componentName.getClassName(), newState, flags, userId, null); 17631 } 17632 17633 private void setEnabledSetting(final String packageName, String className, int newState, 17634 final int flags, int userId, String callingPackage) { 17635 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17636 || newState == COMPONENT_ENABLED_STATE_ENABLED 17637 || newState == COMPONENT_ENABLED_STATE_DISABLED 17638 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17639 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17640 throw new IllegalArgumentException("Invalid new component state: " 17641 + newState); 17642 } 17643 PackageSetting pkgSetting; 17644 final int uid = Binder.getCallingUid(); 17645 final int permission; 17646 if (uid == Process.SYSTEM_UID) { 17647 permission = PackageManager.PERMISSION_GRANTED; 17648 } else { 17649 permission = mContext.checkCallingOrSelfPermission( 17650 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17651 } 17652 enforceCrossUserPermission(uid, userId, 17653 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17654 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17655 boolean sendNow = false; 17656 boolean isApp = (className == null); 17657 String componentName = isApp ? packageName : className; 17658 int packageUid = -1; 17659 ArrayList<String> components; 17660 17661 // writer 17662 synchronized (mPackages) { 17663 pkgSetting = mSettings.mPackages.get(packageName); 17664 if (pkgSetting == null) { 17665 if (className == null) { 17666 throw new IllegalArgumentException("Unknown package: " + packageName); 17667 } 17668 throw new IllegalArgumentException( 17669 "Unknown component: " + packageName + "/" + className); 17670 } 17671 } 17672 17673 // Limit who can change which apps 17674 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17675 // Don't allow apps that don't have permission to modify other apps 17676 if (!allowedByPermission) { 17677 throw new SecurityException( 17678 "Permission Denial: attempt to change component state from pid=" 17679 + Binder.getCallingPid() 17680 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17681 } 17682 // Don't allow changing protected packages. 17683 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17684 throw new SecurityException("Cannot disable a protected package: " + packageName); 17685 } 17686 } 17687 17688 synchronized (mPackages) { 17689 if (uid == Process.SHELL_UID) { 17690 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17691 int oldState = pkgSetting.getEnabled(userId); 17692 if (className == null 17693 && 17694 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17695 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17696 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17697 && 17698 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17699 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17700 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17701 // ok 17702 } else { 17703 throw new SecurityException( 17704 "Shell cannot change component state for " + packageName + "/" 17705 + className + " to " + newState); 17706 } 17707 } 17708 if (className == null) { 17709 // We're dealing with an application/package level state change 17710 if (pkgSetting.getEnabled(userId) == newState) { 17711 // Nothing to do 17712 return; 17713 } 17714 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17715 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17716 // Don't care about who enables an app. 17717 callingPackage = null; 17718 } 17719 pkgSetting.setEnabled(newState, userId, callingPackage); 17720 // pkgSetting.pkg.mSetEnabled = newState; 17721 } else { 17722 // We're dealing with a component level state change 17723 // First, verify that this is a valid class name. 17724 PackageParser.Package pkg = pkgSetting.pkg; 17725 if (pkg == null || !pkg.hasComponentClassName(className)) { 17726 if (pkg != null && 17727 pkg.applicationInfo.targetSdkVersion >= 17728 Build.VERSION_CODES.JELLY_BEAN) { 17729 throw new IllegalArgumentException("Component class " + className 17730 + " does not exist in " + packageName); 17731 } else { 17732 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17733 + className + " does not exist in " + packageName); 17734 } 17735 } 17736 switch (newState) { 17737 case COMPONENT_ENABLED_STATE_ENABLED: 17738 if (!pkgSetting.enableComponentLPw(className, userId)) { 17739 return; 17740 } 17741 break; 17742 case COMPONENT_ENABLED_STATE_DISABLED: 17743 if (!pkgSetting.disableComponentLPw(className, userId)) { 17744 return; 17745 } 17746 break; 17747 case COMPONENT_ENABLED_STATE_DEFAULT: 17748 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17749 return; 17750 } 17751 break; 17752 default: 17753 Slog.e(TAG, "Invalid new component state: " + newState); 17754 return; 17755 } 17756 } 17757 scheduleWritePackageRestrictionsLocked(userId); 17758 components = mPendingBroadcasts.get(userId, packageName); 17759 final boolean newPackage = components == null; 17760 if (newPackage) { 17761 components = new ArrayList<String>(); 17762 } 17763 if (!components.contains(componentName)) { 17764 components.add(componentName); 17765 } 17766 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17767 sendNow = true; 17768 // Purge entry from pending broadcast list if another one exists already 17769 // since we are sending one right away. 17770 mPendingBroadcasts.remove(userId, packageName); 17771 } else { 17772 if (newPackage) { 17773 mPendingBroadcasts.put(userId, packageName, components); 17774 } 17775 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17776 // Schedule a message 17777 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17778 } 17779 } 17780 } 17781 17782 long callingId = Binder.clearCallingIdentity(); 17783 try { 17784 if (sendNow) { 17785 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17786 sendPackageChangedBroadcast(packageName, 17787 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17788 } 17789 } finally { 17790 Binder.restoreCallingIdentity(callingId); 17791 } 17792 } 17793 17794 @Override 17795 public void flushPackageRestrictionsAsUser(int userId) { 17796 if (!sUserManager.exists(userId)) { 17797 return; 17798 } 17799 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17800 false /* checkShell */, "flushPackageRestrictions"); 17801 synchronized (mPackages) { 17802 mSettings.writePackageRestrictionsLPr(userId); 17803 mDirtyUsers.remove(userId); 17804 if (mDirtyUsers.isEmpty()) { 17805 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17806 } 17807 } 17808 } 17809 17810 private void sendPackageChangedBroadcast(String packageName, 17811 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17812 if (DEBUG_INSTALL) 17813 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17814 + componentNames); 17815 Bundle extras = new Bundle(4); 17816 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17817 String nameList[] = new String[componentNames.size()]; 17818 componentNames.toArray(nameList); 17819 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17820 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17821 extras.putInt(Intent.EXTRA_UID, packageUid); 17822 // If this is not reporting a change of the overall package, then only send it 17823 // to registered receivers. We don't want to launch a swath of apps for every 17824 // little component state change. 17825 final int flags = !componentNames.contains(packageName) 17826 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17827 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17828 new int[] {UserHandle.getUserId(packageUid)}); 17829 } 17830 17831 @Override 17832 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17833 if (!sUserManager.exists(userId)) return; 17834 final int uid = Binder.getCallingUid(); 17835 final int permission = mContext.checkCallingOrSelfPermission( 17836 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17837 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17838 enforceCrossUserPermission(uid, userId, 17839 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17840 // writer 17841 synchronized (mPackages) { 17842 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17843 allowedByPermission, uid, userId)) { 17844 scheduleWritePackageRestrictionsLocked(userId); 17845 } 17846 } 17847 } 17848 17849 @Override 17850 public String getInstallerPackageName(String packageName) { 17851 // reader 17852 synchronized (mPackages) { 17853 return mSettings.getInstallerPackageNameLPr(packageName); 17854 } 17855 } 17856 17857 public boolean isOrphaned(String packageName) { 17858 // reader 17859 synchronized (mPackages) { 17860 return mSettings.isOrphaned(packageName); 17861 } 17862 } 17863 17864 @Override 17865 public int getApplicationEnabledSetting(String packageName, int userId) { 17866 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17867 int uid = Binder.getCallingUid(); 17868 enforceCrossUserPermission(uid, userId, 17869 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17870 // reader 17871 synchronized (mPackages) { 17872 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17873 } 17874 } 17875 17876 @Override 17877 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17878 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17879 int uid = Binder.getCallingUid(); 17880 enforceCrossUserPermission(uid, userId, 17881 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17882 // reader 17883 synchronized (mPackages) { 17884 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17885 } 17886 } 17887 17888 @Override 17889 public void enterSafeMode() { 17890 enforceSystemOrRoot("Only the system can request entering safe mode"); 17891 17892 if (!mSystemReady) { 17893 mSafeMode = true; 17894 } 17895 } 17896 17897 @Override 17898 public void systemReady() { 17899 mSystemReady = true; 17900 17901 // Read the compatibilty setting when the system is ready. 17902 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17903 mContext.getContentResolver(), 17904 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17905 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17906 if (DEBUG_SETTINGS) { 17907 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17908 } 17909 17910 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17911 17912 synchronized (mPackages) { 17913 // Verify that all of the preferred activity components actually 17914 // exist. It is possible for applications to be updated and at 17915 // that point remove a previously declared activity component that 17916 // had been set as a preferred activity. We try to clean this up 17917 // the next time we encounter that preferred activity, but it is 17918 // possible for the user flow to never be able to return to that 17919 // situation so here we do a sanity check to make sure we haven't 17920 // left any junk around. 17921 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17922 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17923 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17924 removed.clear(); 17925 for (PreferredActivity pa : pir.filterSet()) { 17926 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17927 removed.add(pa); 17928 } 17929 } 17930 if (removed.size() > 0) { 17931 for (int r=0; r<removed.size(); r++) { 17932 PreferredActivity pa = removed.get(r); 17933 Slog.w(TAG, "Removing dangling preferred activity: " 17934 + pa.mPref.mComponent); 17935 pir.removeFilter(pa); 17936 } 17937 mSettings.writePackageRestrictionsLPr( 17938 mSettings.mPreferredActivities.keyAt(i)); 17939 } 17940 } 17941 17942 for (int userId : UserManagerService.getInstance().getUserIds()) { 17943 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17944 grantPermissionsUserIds = ArrayUtils.appendInt( 17945 grantPermissionsUserIds, userId); 17946 } 17947 } 17948 } 17949 sUserManager.systemReady(); 17950 17951 // If we upgraded grant all default permissions before kicking off. 17952 for (int userId : grantPermissionsUserIds) { 17953 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17954 } 17955 17956 // Kick off any messages waiting for system ready 17957 if (mPostSystemReadyMessages != null) { 17958 for (Message msg : mPostSystemReadyMessages) { 17959 msg.sendToTarget(); 17960 } 17961 mPostSystemReadyMessages = null; 17962 } 17963 17964 // Watch for external volumes that come and go over time 17965 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17966 storage.registerListener(mStorageListener); 17967 17968 mInstallerService.systemReady(); 17969 mPackageDexOptimizer.systemReady(); 17970 17971 MountServiceInternal mountServiceInternal = LocalServices.getService( 17972 MountServiceInternal.class); 17973 mountServiceInternal.addExternalStoragePolicy( 17974 new MountServiceInternal.ExternalStorageMountPolicy() { 17975 @Override 17976 public int getMountMode(int uid, String packageName) { 17977 if (Process.isIsolated(uid)) { 17978 return Zygote.MOUNT_EXTERNAL_NONE; 17979 } 17980 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17981 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17982 } 17983 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17984 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17985 } 17986 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17987 return Zygote.MOUNT_EXTERNAL_READ; 17988 } 17989 return Zygote.MOUNT_EXTERNAL_WRITE; 17990 } 17991 17992 @Override 17993 public boolean hasExternalStorage(int uid, String packageName) { 17994 return true; 17995 } 17996 }); 17997 17998 // Now that we're mostly running, clean up stale users and apps 17999 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18000 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18001 } 18002 18003 @Override 18004 public boolean isSafeMode() { 18005 return mSafeMode; 18006 } 18007 18008 @Override 18009 public boolean hasSystemUidErrors() { 18010 return mHasSystemUidErrors; 18011 } 18012 18013 static String arrayToString(int[] array) { 18014 StringBuffer buf = new StringBuffer(128); 18015 buf.append('['); 18016 if (array != null) { 18017 for (int i=0; i<array.length; i++) { 18018 if (i > 0) buf.append(", "); 18019 buf.append(array[i]); 18020 } 18021 } 18022 buf.append(']'); 18023 return buf.toString(); 18024 } 18025 18026 static class DumpState { 18027 public static final int DUMP_LIBS = 1 << 0; 18028 public static final int DUMP_FEATURES = 1 << 1; 18029 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18030 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18031 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18032 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18033 public static final int DUMP_PERMISSIONS = 1 << 6; 18034 public static final int DUMP_PACKAGES = 1 << 7; 18035 public static final int DUMP_SHARED_USERS = 1 << 8; 18036 public static final int DUMP_MESSAGES = 1 << 9; 18037 public static final int DUMP_PROVIDERS = 1 << 10; 18038 public static final int DUMP_VERIFIERS = 1 << 11; 18039 public static final int DUMP_PREFERRED = 1 << 12; 18040 public static final int DUMP_PREFERRED_XML = 1 << 13; 18041 public static final int DUMP_KEYSETS = 1 << 14; 18042 public static final int DUMP_VERSION = 1 << 15; 18043 public static final int DUMP_INSTALLS = 1 << 16; 18044 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18045 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18046 public static final int DUMP_FROZEN = 1 << 19; 18047 public static final int DUMP_DEXOPT = 1 << 20; 18048 public static final int DUMP_COMPILER_STATS = 1 << 21; 18049 18050 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18051 18052 private int mTypes; 18053 18054 private int mOptions; 18055 18056 private boolean mTitlePrinted; 18057 18058 private SharedUserSetting mSharedUser; 18059 18060 public boolean isDumping(int type) { 18061 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18062 return true; 18063 } 18064 18065 return (mTypes & type) != 0; 18066 } 18067 18068 public void setDump(int type) { 18069 mTypes |= type; 18070 } 18071 18072 public boolean isOptionEnabled(int option) { 18073 return (mOptions & option) != 0; 18074 } 18075 18076 public void setOptionEnabled(int option) { 18077 mOptions |= option; 18078 } 18079 18080 public boolean onTitlePrinted() { 18081 final boolean printed = mTitlePrinted; 18082 mTitlePrinted = true; 18083 return printed; 18084 } 18085 18086 public boolean getTitlePrinted() { 18087 return mTitlePrinted; 18088 } 18089 18090 public void setTitlePrinted(boolean enabled) { 18091 mTitlePrinted = enabled; 18092 } 18093 18094 public SharedUserSetting getSharedUser() { 18095 return mSharedUser; 18096 } 18097 18098 public void setSharedUser(SharedUserSetting user) { 18099 mSharedUser = user; 18100 } 18101 } 18102 18103 @Override 18104 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18105 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18106 (new PackageManagerShellCommand(this)).exec( 18107 this, in, out, err, args, resultReceiver); 18108 } 18109 18110 @Override 18111 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18112 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18113 != PackageManager.PERMISSION_GRANTED) { 18114 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18115 + Binder.getCallingPid() 18116 + ", uid=" + Binder.getCallingUid() 18117 + " without permission " 18118 + android.Manifest.permission.DUMP); 18119 return; 18120 } 18121 18122 DumpState dumpState = new DumpState(); 18123 boolean fullPreferred = false; 18124 boolean checkin = false; 18125 18126 String packageName = null; 18127 ArraySet<String> permissionNames = null; 18128 18129 int opti = 0; 18130 while (opti < args.length) { 18131 String opt = args[opti]; 18132 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18133 break; 18134 } 18135 opti++; 18136 18137 if ("-a".equals(opt)) { 18138 // Right now we only know how to print all. 18139 } else if ("-h".equals(opt)) { 18140 pw.println("Package manager dump options:"); 18141 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18142 pw.println(" --checkin: dump for a checkin"); 18143 pw.println(" -f: print details of intent filters"); 18144 pw.println(" -h: print this help"); 18145 pw.println(" cmd may be one of:"); 18146 pw.println(" l[ibraries]: list known shared libraries"); 18147 pw.println(" f[eatures]: list device features"); 18148 pw.println(" k[eysets]: print known keysets"); 18149 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18150 pw.println(" perm[issions]: dump permissions"); 18151 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18152 pw.println(" pref[erred]: print preferred package settings"); 18153 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18154 pw.println(" prov[iders]: dump content providers"); 18155 pw.println(" p[ackages]: dump installed packages"); 18156 pw.println(" s[hared-users]: dump shared user IDs"); 18157 pw.println(" m[essages]: print collected runtime messages"); 18158 pw.println(" v[erifiers]: print package verifier info"); 18159 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18160 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18161 pw.println(" version: print database version info"); 18162 pw.println(" write: write current settings now"); 18163 pw.println(" installs: details about install sessions"); 18164 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18165 pw.println(" dexopt: dump dexopt state"); 18166 pw.println(" compiler-stats: dump compiler statistics"); 18167 pw.println(" <package.name>: info about given package"); 18168 return; 18169 } else if ("--checkin".equals(opt)) { 18170 checkin = true; 18171 } else if ("-f".equals(opt)) { 18172 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18173 } else { 18174 pw.println("Unknown argument: " + opt + "; use -h for help"); 18175 } 18176 } 18177 18178 // Is the caller requesting to dump a particular piece of data? 18179 if (opti < args.length) { 18180 String cmd = args[opti]; 18181 opti++; 18182 // Is this a package name? 18183 if ("android".equals(cmd) || cmd.contains(".")) { 18184 packageName = cmd; 18185 // When dumping a single package, we always dump all of its 18186 // filter information since the amount of data will be reasonable. 18187 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18188 } else if ("check-permission".equals(cmd)) { 18189 if (opti >= args.length) { 18190 pw.println("Error: check-permission missing permission argument"); 18191 return; 18192 } 18193 String perm = args[opti]; 18194 opti++; 18195 if (opti >= args.length) { 18196 pw.println("Error: check-permission missing package argument"); 18197 return; 18198 } 18199 String pkg = args[opti]; 18200 opti++; 18201 int user = UserHandle.getUserId(Binder.getCallingUid()); 18202 if (opti < args.length) { 18203 try { 18204 user = Integer.parseInt(args[opti]); 18205 } catch (NumberFormatException e) { 18206 pw.println("Error: check-permission user argument is not a number: " 18207 + args[opti]); 18208 return; 18209 } 18210 } 18211 pw.println(checkPermission(perm, pkg, user)); 18212 return; 18213 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18214 dumpState.setDump(DumpState.DUMP_LIBS); 18215 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18216 dumpState.setDump(DumpState.DUMP_FEATURES); 18217 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18218 if (opti >= args.length) { 18219 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18220 | DumpState.DUMP_SERVICE_RESOLVERS 18221 | DumpState.DUMP_RECEIVER_RESOLVERS 18222 | DumpState.DUMP_CONTENT_RESOLVERS); 18223 } else { 18224 while (opti < args.length) { 18225 String name = args[opti]; 18226 if ("a".equals(name) || "activity".equals(name)) { 18227 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18228 } else if ("s".equals(name) || "service".equals(name)) { 18229 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18230 } else if ("r".equals(name) || "receiver".equals(name)) { 18231 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18232 } else if ("c".equals(name) || "content".equals(name)) { 18233 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18234 } else { 18235 pw.println("Error: unknown resolver table type: " + name); 18236 return; 18237 } 18238 opti++; 18239 } 18240 } 18241 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18242 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18243 } else if ("permission".equals(cmd)) { 18244 if (opti >= args.length) { 18245 pw.println("Error: permission requires permission name"); 18246 return; 18247 } 18248 permissionNames = new ArraySet<>(); 18249 while (opti < args.length) { 18250 permissionNames.add(args[opti]); 18251 opti++; 18252 } 18253 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18254 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18255 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18256 dumpState.setDump(DumpState.DUMP_PREFERRED); 18257 } else if ("preferred-xml".equals(cmd)) { 18258 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18259 if (opti < args.length && "--full".equals(args[opti])) { 18260 fullPreferred = true; 18261 opti++; 18262 } 18263 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18264 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18265 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18266 dumpState.setDump(DumpState.DUMP_PACKAGES); 18267 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18268 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18269 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18270 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18271 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18272 dumpState.setDump(DumpState.DUMP_MESSAGES); 18273 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18274 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18275 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18276 || "intent-filter-verifiers".equals(cmd)) { 18277 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18278 } else if ("version".equals(cmd)) { 18279 dumpState.setDump(DumpState.DUMP_VERSION); 18280 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18281 dumpState.setDump(DumpState.DUMP_KEYSETS); 18282 } else if ("installs".equals(cmd)) { 18283 dumpState.setDump(DumpState.DUMP_INSTALLS); 18284 } else if ("frozen".equals(cmd)) { 18285 dumpState.setDump(DumpState.DUMP_FROZEN); 18286 } else if ("dexopt".equals(cmd)) { 18287 dumpState.setDump(DumpState.DUMP_DEXOPT); 18288 } else if ("compiler-stats".equals(cmd)) { 18289 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18290 } else if ("write".equals(cmd)) { 18291 synchronized (mPackages) { 18292 mSettings.writeLPr(); 18293 pw.println("Settings written."); 18294 return; 18295 } 18296 } 18297 } 18298 18299 if (checkin) { 18300 pw.println("vers,1"); 18301 } 18302 18303 // reader 18304 synchronized (mPackages) { 18305 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18306 if (!checkin) { 18307 if (dumpState.onTitlePrinted()) 18308 pw.println(); 18309 pw.println("Database versions:"); 18310 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18311 } 18312 } 18313 18314 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18315 if (!checkin) { 18316 if (dumpState.onTitlePrinted()) 18317 pw.println(); 18318 pw.println("Verifiers:"); 18319 pw.print(" Required: "); 18320 pw.print(mRequiredVerifierPackage); 18321 pw.print(" (uid="); 18322 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18323 UserHandle.USER_SYSTEM)); 18324 pw.println(")"); 18325 } else if (mRequiredVerifierPackage != null) { 18326 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18327 pw.print(","); 18328 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18329 UserHandle.USER_SYSTEM)); 18330 } 18331 } 18332 18333 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18334 packageName == null) { 18335 if (mIntentFilterVerifierComponent != null) { 18336 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18337 if (!checkin) { 18338 if (dumpState.onTitlePrinted()) 18339 pw.println(); 18340 pw.println("Intent Filter Verifier:"); 18341 pw.print(" Using: "); 18342 pw.print(verifierPackageName); 18343 pw.print(" (uid="); 18344 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18345 UserHandle.USER_SYSTEM)); 18346 pw.println(")"); 18347 } else if (verifierPackageName != null) { 18348 pw.print("ifv,"); pw.print(verifierPackageName); 18349 pw.print(","); 18350 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18351 UserHandle.USER_SYSTEM)); 18352 } 18353 } else { 18354 pw.println(); 18355 pw.println("No Intent Filter Verifier available!"); 18356 } 18357 } 18358 18359 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18360 boolean printedHeader = false; 18361 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18362 while (it.hasNext()) { 18363 String name = it.next(); 18364 SharedLibraryEntry ent = mSharedLibraries.get(name); 18365 if (!checkin) { 18366 if (!printedHeader) { 18367 if (dumpState.onTitlePrinted()) 18368 pw.println(); 18369 pw.println("Libraries:"); 18370 printedHeader = true; 18371 } 18372 pw.print(" "); 18373 } else { 18374 pw.print("lib,"); 18375 } 18376 pw.print(name); 18377 if (!checkin) { 18378 pw.print(" -> "); 18379 } 18380 if (ent.path != null) { 18381 if (!checkin) { 18382 pw.print("(jar) "); 18383 pw.print(ent.path); 18384 } else { 18385 pw.print(",jar,"); 18386 pw.print(ent.path); 18387 } 18388 } else { 18389 if (!checkin) { 18390 pw.print("(apk) "); 18391 pw.print(ent.apk); 18392 } else { 18393 pw.print(",apk,"); 18394 pw.print(ent.apk); 18395 } 18396 } 18397 pw.println(); 18398 } 18399 } 18400 18401 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18402 if (dumpState.onTitlePrinted()) 18403 pw.println(); 18404 if (!checkin) { 18405 pw.println("Features:"); 18406 } 18407 18408 for (FeatureInfo feat : mAvailableFeatures.values()) { 18409 if (checkin) { 18410 pw.print("feat,"); 18411 pw.print(feat.name); 18412 pw.print(","); 18413 pw.println(feat.version); 18414 } else { 18415 pw.print(" "); 18416 pw.print(feat.name); 18417 if (feat.version > 0) { 18418 pw.print(" version="); 18419 pw.print(feat.version); 18420 } 18421 pw.println(); 18422 } 18423 } 18424 } 18425 18426 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18427 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18428 : "Activity Resolver Table:", " ", packageName, 18429 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18430 dumpState.setTitlePrinted(true); 18431 } 18432 } 18433 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18434 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18435 : "Receiver Resolver Table:", " ", packageName, 18436 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18437 dumpState.setTitlePrinted(true); 18438 } 18439 } 18440 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18441 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18442 : "Service Resolver Table:", " ", packageName, 18443 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18444 dumpState.setTitlePrinted(true); 18445 } 18446 } 18447 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18448 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18449 : "Provider Resolver Table:", " ", packageName, 18450 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18451 dumpState.setTitlePrinted(true); 18452 } 18453 } 18454 18455 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18456 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18457 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18458 int user = mSettings.mPreferredActivities.keyAt(i); 18459 if (pir.dump(pw, 18460 dumpState.getTitlePrinted() 18461 ? "\nPreferred Activities User " + user + ":" 18462 : "Preferred Activities User " + user + ":", " ", 18463 packageName, true, false)) { 18464 dumpState.setTitlePrinted(true); 18465 } 18466 } 18467 } 18468 18469 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18470 pw.flush(); 18471 FileOutputStream fout = new FileOutputStream(fd); 18472 BufferedOutputStream str = new BufferedOutputStream(fout); 18473 XmlSerializer serializer = new FastXmlSerializer(); 18474 try { 18475 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18476 serializer.startDocument(null, true); 18477 serializer.setFeature( 18478 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18479 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18480 serializer.endDocument(); 18481 serializer.flush(); 18482 } catch (IllegalArgumentException e) { 18483 pw.println("Failed writing: " + e); 18484 } catch (IllegalStateException e) { 18485 pw.println("Failed writing: " + e); 18486 } catch (IOException e) { 18487 pw.println("Failed writing: " + e); 18488 } 18489 } 18490 18491 if (!checkin 18492 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18493 && packageName == null) { 18494 pw.println(); 18495 int count = mSettings.mPackages.size(); 18496 if (count == 0) { 18497 pw.println("No applications!"); 18498 pw.println(); 18499 } else { 18500 final String prefix = " "; 18501 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18502 if (allPackageSettings.size() == 0) { 18503 pw.println("No domain preferred apps!"); 18504 pw.println(); 18505 } else { 18506 pw.println("App verification status:"); 18507 pw.println(); 18508 count = 0; 18509 for (PackageSetting ps : allPackageSettings) { 18510 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18511 if (ivi == null || ivi.getPackageName() == null) continue; 18512 pw.println(prefix + "Package: " + ivi.getPackageName()); 18513 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18514 pw.println(prefix + "Status: " + ivi.getStatusString()); 18515 pw.println(); 18516 count++; 18517 } 18518 if (count == 0) { 18519 pw.println(prefix + "No app verification established."); 18520 pw.println(); 18521 } 18522 for (int userId : sUserManager.getUserIds()) { 18523 pw.println("App linkages for user " + userId + ":"); 18524 pw.println(); 18525 count = 0; 18526 for (PackageSetting ps : allPackageSettings) { 18527 final long status = ps.getDomainVerificationStatusForUser(userId); 18528 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18529 continue; 18530 } 18531 pw.println(prefix + "Package: " + ps.name); 18532 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18533 String statusStr = IntentFilterVerificationInfo. 18534 getStatusStringFromValue(status); 18535 pw.println(prefix + "Status: " + statusStr); 18536 pw.println(); 18537 count++; 18538 } 18539 if (count == 0) { 18540 pw.println(prefix + "No configured app linkages."); 18541 pw.println(); 18542 } 18543 } 18544 } 18545 } 18546 } 18547 18548 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18549 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18550 if (packageName == null && permissionNames == null) { 18551 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18552 if (iperm == 0) { 18553 if (dumpState.onTitlePrinted()) 18554 pw.println(); 18555 pw.println("AppOp Permissions:"); 18556 } 18557 pw.print(" AppOp Permission "); 18558 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18559 pw.println(":"); 18560 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18561 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18562 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18563 } 18564 } 18565 } 18566 } 18567 18568 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18569 boolean printedSomething = false; 18570 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18571 if (packageName != null && !packageName.equals(p.info.packageName)) { 18572 continue; 18573 } 18574 if (!printedSomething) { 18575 if (dumpState.onTitlePrinted()) 18576 pw.println(); 18577 pw.println("Registered ContentProviders:"); 18578 printedSomething = true; 18579 } 18580 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18581 pw.print(" "); pw.println(p.toString()); 18582 } 18583 printedSomething = false; 18584 for (Map.Entry<String, PackageParser.Provider> entry : 18585 mProvidersByAuthority.entrySet()) { 18586 PackageParser.Provider p = entry.getValue(); 18587 if (packageName != null && !packageName.equals(p.info.packageName)) { 18588 continue; 18589 } 18590 if (!printedSomething) { 18591 if (dumpState.onTitlePrinted()) 18592 pw.println(); 18593 pw.println("ContentProvider Authorities:"); 18594 printedSomething = true; 18595 } 18596 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18597 pw.print(" "); pw.println(p.toString()); 18598 if (p.info != null && p.info.applicationInfo != null) { 18599 final String appInfo = p.info.applicationInfo.toString(); 18600 pw.print(" applicationInfo="); pw.println(appInfo); 18601 } 18602 } 18603 } 18604 18605 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18606 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18607 } 18608 18609 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18610 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18611 } 18612 18613 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18614 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18615 } 18616 18617 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18618 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18619 } 18620 18621 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18622 // XXX should handle packageName != null by dumping only install data that 18623 // the given package is involved with. 18624 if (dumpState.onTitlePrinted()) pw.println(); 18625 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18626 } 18627 18628 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18629 // XXX should handle packageName != null by dumping only install data that 18630 // the given package is involved with. 18631 if (dumpState.onTitlePrinted()) pw.println(); 18632 18633 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18634 ipw.println(); 18635 ipw.println("Frozen packages:"); 18636 ipw.increaseIndent(); 18637 if (mFrozenPackages.size() == 0) { 18638 ipw.println("(none)"); 18639 } else { 18640 for (int i = 0; i < mFrozenPackages.size(); i++) { 18641 ipw.println(mFrozenPackages.valueAt(i)); 18642 } 18643 } 18644 ipw.decreaseIndent(); 18645 } 18646 18647 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18648 if (dumpState.onTitlePrinted()) pw.println(); 18649 dumpDexoptStateLPr(pw, packageName); 18650 } 18651 18652 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18653 if (dumpState.onTitlePrinted()) pw.println(); 18654 dumpCompilerStatsLPr(pw, packageName); 18655 } 18656 18657 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18658 if (dumpState.onTitlePrinted()) pw.println(); 18659 mSettings.dumpReadMessagesLPr(pw, dumpState); 18660 18661 pw.println(); 18662 pw.println("Package warning messages:"); 18663 BufferedReader in = null; 18664 String line = null; 18665 try { 18666 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18667 while ((line = in.readLine()) != null) { 18668 if (line.contains("ignored: updated version")) continue; 18669 pw.println(line); 18670 } 18671 } catch (IOException ignored) { 18672 } finally { 18673 IoUtils.closeQuietly(in); 18674 } 18675 } 18676 18677 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18678 BufferedReader in = null; 18679 String line = null; 18680 try { 18681 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18682 while ((line = in.readLine()) != null) { 18683 if (line.contains("ignored: updated version")) continue; 18684 pw.print("msg,"); 18685 pw.println(line); 18686 } 18687 } catch (IOException ignored) { 18688 } finally { 18689 IoUtils.closeQuietly(in); 18690 } 18691 } 18692 } 18693 } 18694 18695 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18696 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18697 ipw.println(); 18698 ipw.println("Dexopt state:"); 18699 ipw.increaseIndent(); 18700 Collection<PackageParser.Package> packages = null; 18701 if (packageName != null) { 18702 PackageParser.Package targetPackage = mPackages.get(packageName); 18703 if (targetPackage != null) { 18704 packages = Collections.singletonList(targetPackage); 18705 } else { 18706 ipw.println("Unable to find package: " + packageName); 18707 return; 18708 } 18709 } else { 18710 packages = mPackages.values(); 18711 } 18712 18713 for (PackageParser.Package pkg : packages) { 18714 ipw.println("[" + pkg.packageName + "]"); 18715 ipw.increaseIndent(); 18716 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18717 ipw.decreaseIndent(); 18718 } 18719 } 18720 18721 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18722 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18723 ipw.println(); 18724 ipw.println("Compiler stats:"); 18725 ipw.increaseIndent(); 18726 Collection<PackageParser.Package> packages = null; 18727 if (packageName != null) { 18728 PackageParser.Package targetPackage = mPackages.get(packageName); 18729 if (targetPackage != null) { 18730 packages = Collections.singletonList(targetPackage); 18731 } else { 18732 ipw.println("Unable to find package: " + packageName); 18733 return; 18734 } 18735 } else { 18736 packages = mPackages.values(); 18737 } 18738 18739 for (PackageParser.Package pkg : packages) { 18740 ipw.println("[" + pkg.packageName + "]"); 18741 ipw.increaseIndent(); 18742 18743 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18744 if (stats == null) { 18745 ipw.println("(No recorded stats)"); 18746 } else { 18747 stats.dump(ipw); 18748 } 18749 ipw.decreaseIndent(); 18750 } 18751 } 18752 18753 private String dumpDomainString(String packageName) { 18754 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18755 .getList(); 18756 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18757 18758 ArraySet<String> result = new ArraySet<>(); 18759 if (iviList.size() > 0) { 18760 for (IntentFilterVerificationInfo ivi : iviList) { 18761 for (String host : ivi.getDomains()) { 18762 result.add(host); 18763 } 18764 } 18765 } 18766 if (filters != null && filters.size() > 0) { 18767 for (IntentFilter filter : filters) { 18768 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18769 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18770 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18771 result.addAll(filter.getHostsList()); 18772 } 18773 } 18774 } 18775 18776 StringBuilder sb = new StringBuilder(result.size() * 16); 18777 for (String domain : result) { 18778 if (sb.length() > 0) sb.append(" "); 18779 sb.append(domain); 18780 } 18781 return sb.toString(); 18782 } 18783 18784 // ------- apps on sdcard specific code ------- 18785 static final boolean DEBUG_SD_INSTALL = false; 18786 18787 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18788 18789 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18790 18791 private boolean mMediaMounted = false; 18792 18793 static String getEncryptKey() { 18794 try { 18795 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18796 SD_ENCRYPTION_KEYSTORE_NAME); 18797 if (sdEncKey == null) { 18798 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18799 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18800 if (sdEncKey == null) { 18801 Slog.e(TAG, "Failed to create encryption keys"); 18802 return null; 18803 } 18804 } 18805 return sdEncKey; 18806 } catch (NoSuchAlgorithmException nsae) { 18807 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18808 return null; 18809 } catch (IOException ioe) { 18810 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18811 return null; 18812 } 18813 } 18814 18815 /* 18816 * Update media status on PackageManager. 18817 */ 18818 @Override 18819 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18820 int callingUid = Binder.getCallingUid(); 18821 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18822 throw new SecurityException("Media status can only be updated by the system"); 18823 } 18824 // reader; this apparently protects mMediaMounted, but should probably 18825 // be a different lock in that case. 18826 synchronized (mPackages) { 18827 Log.i(TAG, "Updating external media status from " 18828 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18829 + (mediaStatus ? "mounted" : "unmounted")); 18830 if (DEBUG_SD_INSTALL) 18831 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18832 + ", mMediaMounted=" + mMediaMounted); 18833 if (mediaStatus == mMediaMounted) { 18834 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18835 : 0, -1); 18836 mHandler.sendMessage(msg); 18837 return; 18838 } 18839 mMediaMounted = mediaStatus; 18840 } 18841 // Queue up an async operation since the package installation may take a 18842 // little while. 18843 mHandler.post(new Runnable() { 18844 public void run() { 18845 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18846 } 18847 }); 18848 } 18849 18850 /** 18851 * Called by MountService when the initial ASECs to scan are available. 18852 * Should block until all the ASEC containers are finished being scanned. 18853 */ 18854 public void scanAvailableAsecs() { 18855 updateExternalMediaStatusInner(true, false, false); 18856 } 18857 18858 /* 18859 * Collect information of applications on external media, map them against 18860 * existing containers and update information based on current mount status. 18861 * Please note that we always have to report status if reportStatus has been 18862 * set to true especially when unloading packages. 18863 */ 18864 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18865 boolean externalStorage) { 18866 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18867 int[] uidArr = EmptyArray.INT; 18868 18869 final String[] list = PackageHelper.getSecureContainerList(); 18870 if (ArrayUtils.isEmpty(list)) { 18871 Log.i(TAG, "No secure containers found"); 18872 } else { 18873 // Process list of secure containers and categorize them 18874 // as active or stale based on their package internal state. 18875 18876 // reader 18877 synchronized (mPackages) { 18878 for (String cid : list) { 18879 // Leave stages untouched for now; installer service owns them 18880 if (PackageInstallerService.isStageName(cid)) continue; 18881 18882 if (DEBUG_SD_INSTALL) 18883 Log.i(TAG, "Processing container " + cid); 18884 String pkgName = getAsecPackageName(cid); 18885 if (pkgName == null) { 18886 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18887 continue; 18888 } 18889 if (DEBUG_SD_INSTALL) 18890 Log.i(TAG, "Looking for pkg : " + pkgName); 18891 18892 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18893 if (ps == null) { 18894 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18895 continue; 18896 } 18897 18898 /* 18899 * Skip packages that are not external if we're unmounting 18900 * external storage. 18901 */ 18902 if (externalStorage && !isMounted && !isExternal(ps)) { 18903 continue; 18904 } 18905 18906 final AsecInstallArgs args = new AsecInstallArgs(cid, 18907 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18908 // The package status is changed only if the code path 18909 // matches between settings and the container id. 18910 if (ps.codePathString != null 18911 && ps.codePathString.startsWith(args.getCodePath())) { 18912 if (DEBUG_SD_INSTALL) { 18913 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18914 + " at code path: " + ps.codePathString); 18915 } 18916 18917 // We do have a valid package installed on sdcard 18918 processCids.put(args, ps.codePathString); 18919 final int uid = ps.appId; 18920 if (uid != -1) { 18921 uidArr = ArrayUtils.appendInt(uidArr, uid); 18922 } 18923 } else { 18924 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18925 + ps.codePathString); 18926 } 18927 } 18928 } 18929 18930 Arrays.sort(uidArr); 18931 } 18932 18933 // Process packages with valid entries. 18934 if (isMounted) { 18935 if (DEBUG_SD_INSTALL) 18936 Log.i(TAG, "Loading packages"); 18937 loadMediaPackages(processCids, uidArr, externalStorage); 18938 startCleaningPackages(); 18939 mInstallerService.onSecureContainersAvailable(); 18940 } else { 18941 if (DEBUG_SD_INSTALL) 18942 Log.i(TAG, "Unloading packages"); 18943 unloadMediaPackages(processCids, uidArr, reportStatus); 18944 } 18945 } 18946 18947 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18948 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18949 final int size = infos.size(); 18950 final String[] packageNames = new String[size]; 18951 final int[] packageUids = new int[size]; 18952 for (int i = 0; i < size; i++) { 18953 final ApplicationInfo info = infos.get(i); 18954 packageNames[i] = info.packageName; 18955 packageUids[i] = info.uid; 18956 } 18957 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18958 finishedReceiver); 18959 } 18960 18961 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18962 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18963 sendResourcesChangedBroadcast(mediaStatus, replacing, 18964 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18965 } 18966 18967 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18968 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18969 int size = pkgList.length; 18970 if (size > 0) { 18971 // Send broadcasts here 18972 Bundle extras = new Bundle(); 18973 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18974 if (uidArr != null) { 18975 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18976 } 18977 if (replacing) { 18978 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18979 } 18980 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18981 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18982 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18983 } 18984 } 18985 18986 /* 18987 * Look at potentially valid container ids from processCids If package 18988 * information doesn't match the one on record or package scanning fails, 18989 * the cid is added to list of removeCids. We currently don't delete stale 18990 * containers. 18991 */ 18992 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18993 boolean externalStorage) { 18994 ArrayList<String> pkgList = new ArrayList<String>(); 18995 Set<AsecInstallArgs> keys = processCids.keySet(); 18996 18997 for (AsecInstallArgs args : keys) { 18998 String codePath = processCids.get(args); 18999 if (DEBUG_SD_INSTALL) 19000 Log.i(TAG, "Loading container : " + args.cid); 19001 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19002 try { 19003 // Make sure there are no container errors first. 19004 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19005 Slog.e(TAG, "Failed to mount cid : " + args.cid 19006 + " when installing from sdcard"); 19007 continue; 19008 } 19009 // Check code path here. 19010 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19011 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19012 + " does not match one in settings " + codePath); 19013 continue; 19014 } 19015 // Parse package 19016 int parseFlags = mDefParseFlags; 19017 if (args.isExternalAsec()) { 19018 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19019 } 19020 if (args.isFwdLocked()) { 19021 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19022 } 19023 19024 synchronized (mInstallLock) { 19025 PackageParser.Package pkg = null; 19026 try { 19027 // Sadly we don't know the package name yet to freeze it 19028 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19029 SCAN_IGNORE_FROZEN, 0, null); 19030 } catch (PackageManagerException e) { 19031 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19032 } 19033 // Scan the package 19034 if (pkg != null) { 19035 /* 19036 * TODO why is the lock being held? doPostInstall is 19037 * called in other places without the lock. This needs 19038 * to be straightened out. 19039 */ 19040 // writer 19041 synchronized (mPackages) { 19042 retCode = PackageManager.INSTALL_SUCCEEDED; 19043 pkgList.add(pkg.packageName); 19044 // Post process args 19045 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19046 pkg.applicationInfo.uid); 19047 } 19048 } else { 19049 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19050 } 19051 } 19052 19053 } finally { 19054 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19055 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19056 } 19057 } 19058 } 19059 // writer 19060 synchronized (mPackages) { 19061 // If the platform SDK has changed since the last time we booted, 19062 // we need to re-grant app permission to catch any new ones that 19063 // appear. This is really a hack, and means that apps can in some 19064 // cases get permissions that the user didn't initially explicitly 19065 // allow... it would be nice to have some better way to handle 19066 // this situation. 19067 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19068 : mSettings.getInternalVersion(); 19069 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19070 : StorageManager.UUID_PRIVATE_INTERNAL; 19071 19072 int updateFlags = UPDATE_PERMISSIONS_ALL; 19073 if (ver.sdkVersion != mSdkVersion) { 19074 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19075 + mSdkVersion + "; regranting permissions for external"); 19076 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19077 } 19078 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19079 19080 // Yay, everything is now upgraded 19081 ver.forceCurrent(); 19082 19083 // can downgrade to reader 19084 // Persist settings 19085 mSettings.writeLPr(); 19086 } 19087 // Send a broadcast to let everyone know we are done processing 19088 if (pkgList.size() > 0) { 19089 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19090 } 19091 } 19092 19093 /* 19094 * Utility method to unload a list of specified containers 19095 */ 19096 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19097 // Just unmount all valid containers. 19098 for (AsecInstallArgs arg : cidArgs) { 19099 synchronized (mInstallLock) { 19100 arg.doPostDeleteLI(false); 19101 } 19102 } 19103 } 19104 19105 /* 19106 * Unload packages mounted on external media. This involves deleting package 19107 * data from internal structures, sending broadcasts about disabled packages, 19108 * gc'ing to free up references, unmounting all secure containers 19109 * corresponding to packages on external media, and posting a 19110 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19111 * that we always have to post this message if status has been requested no 19112 * matter what. 19113 */ 19114 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19115 final boolean reportStatus) { 19116 if (DEBUG_SD_INSTALL) 19117 Log.i(TAG, "unloading media packages"); 19118 ArrayList<String> pkgList = new ArrayList<String>(); 19119 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19120 final Set<AsecInstallArgs> keys = processCids.keySet(); 19121 for (AsecInstallArgs args : keys) { 19122 String pkgName = args.getPackageName(); 19123 if (DEBUG_SD_INSTALL) 19124 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19125 // Delete package internally 19126 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19127 synchronized (mInstallLock) { 19128 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19129 final boolean res; 19130 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19131 "unloadMediaPackages")) { 19132 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19133 null); 19134 } 19135 if (res) { 19136 pkgList.add(pkgName); 19137 } else { 19138 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19139 failedList.add(args); 19140 } 19141 } 19142 } 19143 19144 // reader 19145 synchronized (mPackages) { 19146 // We didn't update the settings after removing each package; 19147 // write them now for all packages. 19148 mSettings.writeLPr(); 19149 } 19150 19151 // We have to absolutely send UPDATED_MEDIA_STATUS only 19152 // after confirming that all the receivers processed the ordered 19153 // broadcast when packages get disabled, force a gc to clean things up. 19154 // and unload all the containers. 19155 if (pkgList.size() > 0) { 19156 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19157 new IIntentReceiver.Stub() { 19158 public void performReceive(Intent intent, int resultCode, String data, 19159 Bundle extras, boolean ordered, boolean sticky, 19160 int sendingUser) throws RemoteException { 19161 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19162 reportStatus ? 1 : 0, 1, keys); 19163 mHandler.sendMessage(msg); 19164 } 19165 }); 19166 } else { 19167 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19168 keys); 19169 mHandler.sendMessage(msg); 19170 } 19171 } 19172 19173 private void loadPrivatePackages(final VolumeInfo vol) { 19174 mHandler.post(new Runnable() { 19175 @Override 19176 public void run() { 19177 loadPrivatePackagesInner(vol); 19178 } 19179 }); 19180 } 19181 19182 private void loadPrivatePackagesInner(VolumeInfo vol) { 19183 final String volumeUuid = vol.fsUuid; 19184 if (TextUtils.isEmpty(volumeUuid)) { 19185 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19186 return; 19187 } 19188 19189 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19190 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19191 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19192 19193 final VersionInfo ver; 19194 final List<PackageSetting> packages; 19195 synchronized (mPackages) { 19196 ver = mSettings.findOrCreateVersion(volumeUuid); 19197 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19198 } 19199 19200 for (PackageSetting ps : packages) { 19201 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19202 synchronized (mInstallLock) { 19203 final PackageParser.Package pkg; 19204 try { 19205 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19206 loaded.add(pkg.applicationInfo); 19207 19208 } catch (PackageManagerException e) { 19209 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19210 } 19211 19212 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19213 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19214 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19215 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19216 } 19217 } 19218 } 19219 19220 // Reconcile app data for all started/unlocked users 19221 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19222 final UserManager um = mContext.getSystemService(UserManager.class); 19223 UserManagerInternal umInternal = getUserManagerInternal(); 19224 for (UserInfo user : um.getUsers()) { 19225 final int flags; 19226 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19227 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19228 } else if (umInternal.isUserRunning(user.id)) { 19229 flags = StorageManager.FLAG_STORAGE_DE; 19230 } else { 19231 continue; 19232 } 19233 19234 try { 19235 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19236 synchronized (mInstallLock) { 19237 reconcileAppsDataLI(volumeUuid, user.id, flags); 19238 } 19239 } catch (IllegalStateException e) { 19240 // Device was probably ejected, and we'll process that event momentarily 19241 Slog.w(TAG, "Failed to prepare storage: " + e); 19242 } 19243 } 19244 19245 synchronized (mPackages) { 19246 int updateFlags = UPDATE_PERMISSIONS_ALL; 19247 if (ver.sdkVersion != mSdkVersion) { 19248 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19249 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19250 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19251 } 19252 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19253 19254 // Yay, everything is now upgraded 19255 ver.forceCurrent(); 19256 19257 mSettings.writeLPr(); 19258 } 19259 19260 for (PackageFreezer freezer : freezers) { 19261 freezer.close(); 19262 } 19263 19264 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19265 sendResourcesChangedBroadcast(true, false, loaded, null); 19266 } 19267 19268 private void unloadPrivatePackages(final VolumeInfo vol) { 19269 mHandler.post(new Runnable() { 19270 @Override 19271 public void run() { 19272 unloadPrivatePackagesInner(vol); 19273 } 19274 }); 19275 } 19276 19277 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19278 final String volumeUuid = vol.fsUuid; 19279 if (TextUtils.isEmpty(volumeUuid)) { 19280 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19281 return; 19282 } 19283 19284 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19285 synchronized (mInstallLock) { 19286 synchronized (mPackages) { 19287 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19288 for (PackageSetting ps : packages) { 19289 if (ps.pkg == null) continue; 19290 19291 final ApplicationInfo info = ps.pkg.applicationInfo; 19292 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19293 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19294 19295 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19296 "unloadPrivatePackagesInner")) { 19297 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19298 false, null)) { 19299 unloaded.add(info); 19300 } else { 19301 Slog.w(TAG, "Failed to unload " + ps.codePath); 19302 } 19303 } 19304 19305 // Try very hard to release any references to this package 19306 // so we don't risk the system server being killed due to 19307 // open FDs 19308 AttributeCache.instance().removePackage(ps.name); 19309 } 19310 19311 mSettings.writeLPr(); 19312 } 19313 } 19314 19315 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19316 sendResourcesChangedBroadcast(false, false, unloaded, null); 19317 19318 // Try very hard to release any references to this path so we don't risk 19319 // the system server being killed due to open FDs 19320 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19321 19322 for (int i = 0; i < 3; i++) { 19323 System.gc(); 19324 System.runFinalization(); 19325 } 19326 } 19327 19328 /** 19329 * Prepare storage areas for given user on all mounted devices. 19330 */ 19331 void prepareUserData(int userId, int userSerial, int flags) { 19332 synchronized (mInstallLock) { 19333 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19334 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19335 final String volumeUuid = vol.getFsUuid(); 19336 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19337 } 19338 } 19339 } 19340 19341 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19342 boolean allowRecover) { 19343 // Prepare storage and verify that serial numbers are consistent; if 19344 // there's a mismatch we need to destroy to avoid leaking data 19345 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19346 try { 19347 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19348 19349 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19350 UserManagerService.enforceSerialNumber( 19351 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19352 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19353 UserManagerService.enforceSerialNumber( 19354 Environment.getDataSystemDeDirectory(userId), userSerial); 19355 } 19356 } 19357 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19358 UserManagerService.enforceSerialNumber( 19359 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19360 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19361 UserManagerService.enforceSerialNumber( 19362 Environment.getDataSystemCeDirectory(userId), userSerial); 19363 } 19364 } 19365 19366 synchronized (mInstallLock) { 19367 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19368 } 19369 } catch (Exception e) { 19370 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19371 + " because we failed to prepare: " + e); 19372 destroyUserDataLI(volumeUuid, userId, 19373 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19374 19375 if (allowRecover) { 19376 // Try one last time; if we fail again we're really in trouble 19377 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19378 } 19379 } 19380 } 19381 19382 /** 19383 * Destroy storage areas for given user on all mounted devices. 19384 */ 19385 void destroyUserData(int userId, int flags) { 19386 synchronized (mInstallLock) { 19387 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19388 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19389 final String volumeUuid = vol.getFsUuid(); 19390 destroyUserDataLI(volumeUuid, userId, flags); 19391 } 19392 } 19393 } 19394 19395 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19396 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19397 try { 19398 // Clean up app data, profile data, and media data 19399 mInstaller.destroyUserData(volumeUuid, userId, flags); 19400 19401 // Clean up system data 19402 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19403 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19404 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19405 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19406 } 19407 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19408 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19409 } 19410 } 19411 19412 // Data with special labels is now gone, so finish the job 19413 storage.destroyUserStorage(volumeUuid, userId, flags); 19414 19415 } catch (Exception e) { 19416 logCriticalInfo(Log.WARN, 19417 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19418 } 19419 } 19420 19421 /** 19422 * Examine all users present on given mounted volume, and destroy data 19423 * belonging to users that are no longer valid, or whose user ID has been 19424 * recycled. 19425 */ 19426 private void reconcileUsers(String volumeUuid) { 19427 final List<File> files = new ArrayList<>(); 19428 Collections.addAll(files, FileUtils 19429 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19430 Collections.addAll(files, FileUtils 19431 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19432 Collections.addAll(files, FileUtils 19433 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19434 Collections.addAll(files, FileUtils 19435 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19436 for (File file : files) { 19437 if (!file.isDirectory()) continue; 19438 19439 final int userId; 19440 final UserInfo info; 19441 try { 19442 userId = Integer.parseInt(file.getName()); 19443 info = sUserManager.getUserInfo(userId); 19444 } catch (NumberFormatException e) { 19445 Slog.w(TAG, "Invalid user directory " + file); 19446 continue; 19447 } 19448 19449 boolean destroyUser = false; 19450 if (info == null) { 19451 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19452 + " because no matching user was found"); 19453 destroyUser = true; 19454 } else if (!mOnlyCore) { 19455 try { 19456 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19457 } catch (IOException e) { 19458 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19459 + " because we failed to enforce serial number: " + e); 19460 destroyUser = true; 19461 } 19462 } 19463 19464 if (destroyUser) { 19465 synchronized (mInstallLock) { 19466 destroyUserDataLI(volumeUuid, userId, 19467 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19468 } 19469 } 19470 } 19471 } 19472 19473 private void assertPackageKnown(String volumeUuid, String packageName) 19474 throws PackageManagerException { 19475 synchronized (mPackages) { 19476 final PackageSetting ps = mSettings.mPackages.get(packageName); 19477 if (ps == null) { 19478 throw new PackageManagerException("Package " + packageName + " is unknown"); 19479 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19480 throw new PackageManagerException( 19481 "Package " + packageName + " found on unknown volume " + volumeUuid 19482 + "; expected volume " + ps.volumeUuid); 19483 } 19484 } 19485 } 19486 19487 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19488 throws PackageManagerException { 19489 synchronized (mPackages) { 19490 final PackageSetting ps = mSettings.mPackages.get(packageName); 19491 if (ps == null) { 19492 throw new PackageManagerException("Package " + packageName + " is unknown"); 19493 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19494 throw new PackageManagerException( 19495 "Package " + packageName + " found on unknown volume " + volumeUuid 19496 + "; expected volume " + ps.volumeUuid); 19497 } else if (!ps.getInstalled(userId)) { 19498 throw new PackageManagerException( 19499 "Package " + packageName + " not installed for user " + userId); 19500 } 19501 } 19502 } 19503 19504 /** 19505 * Examine all apps present on given mounted volume, and destroy apps that 19506 * aren't expected, either due to uninstallation or reinstallation on 19507 * another volume. 19508 */ 19509 private void reconcileApps(String volumeUuid) { 19510 final File[] files = FileUtils 19511 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19512 for (File file : files) { 19513 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19514 && !PackageInstallerService.isStageName(file.getName()); 19515 if (!isPackage) { 19516 // Ignore entries which are not packages 19517 continue; 19518 } 19519 19520 try { 19521 final PackageLite pkg = PackageParser.parsePackageLite(file, 19522 PackageParser.PARSE_MUST_BE_APK); 19523 assertPackageKnown(volumeUuid, pkg.packageName); 19524 19525 } catch (PackageParserException | PackageManagerException e) { 19526 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19527 synchronized (mInstallLock) { 19528 removeCodePathLI(file); 19529 } 19530 } 19531 } 19532 } 19533 19534 /** 19535 * Reconcile all app data for the given user. 19536 * <p> 19537 * Verifies that directories exist and that ownership and labeling is 19538 * correct for all installed apps on all mounted volumes. 19539 */ 19540 void reconcileAppsData(int userId, int flags) { 19541 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19542 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19543 final String volumeUuid = vol.getFsUuid(); 19544 synchronized (mInstallLock) { 19545 reconcileAppsDataLI(volumeUuid, userId, flags); 19546 } 19547 } 19548 } 19549 19550 /** 19551 * Reconcile all app data on given mounted volume. 19552 * <p> 19553 * Destroys app data that isn't expected, either due to uninstallation or 19554 * reinstallation on another volume. 19555 * <p> 19556 * Verifies that directories exist and that ownership and labeling is 19557 * correct for all installed apps. 19558 */ 19559 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19560 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19561 + Integer.toHexString(flags)); 19562 19563 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19564 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19565 19566 boolean restoreconNeeded = false; 19567 19568 // First look for stale data that doesn't belong, and check if things 19569 // have changed since we did our last restorecon 19570 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19571 if (StorageManager.isFileEncryptedNativeOrEmulated() 19572 && !StorageManager.isUserKeyUnlocked(userId)) { 19573 throw new RuntimeException( 19574 "Yikes, someone asked us to reconcile CE storage while " + userId 19575 + " was still locked; this would have caused massive data loss!"); 19576 } 19577 19578 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19579 19580 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19581 for (File file : files) { 19582 final String packageName = file.getName(); 19583 try { 19584 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19585 } catch (PackageManagerException e) { 19586 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19587 try { 19588 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19589 StorageManager.FLAG_STORAGE_CE, 0); 19590 } catch (InstallerException e2) { 19591 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19592 } 19593 } 19594 } 19595 } 19596 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19597 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19598 19599 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19600 for (File file : files) { 19601 final String packageName = file.getName(); 19602 try { 19603 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19604 } catch (PackageManagerException e) { 19605 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19606 try { 19607 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19608 StorageManager.FLAG_STORAGE_DE, 0); 19609 } catch (InstallerException e2) { 19610 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19611 } 19612 } 19613 } 19614 } 19615 19616 // Ensure that data directories are ready to roll for all packages 19617 // installed for this volume and user 19618 final List<PackageSetting> packages; 19619 synchronized (mPackages) { 19620 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19621 } 19622 int preparedCount = 0; 19623 for (PackageSetting ps : packages) { 19624 final String packageName = ps.name; 19625 if (ps.pkg == null) { 19626 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19627 // TODO: might be due to legacy ASEC apps; we should circle back 19628 // and reconcile again once they're scanned 19629 continue; 19630 } 19631 19632 if (ps.getInstalled(userId)) { 19633 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19634 19635 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19636 // We may have just shuffled around app data directories, so 19637 // prepare them one more time 19638 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19639 } 19640 19641 preparedCount++; 19642 } 19643 } 19644 19645 if (restoreconNeeded) { 19646 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19647 SELinuxMMAC.setRestoreconDone(ceDir); 19648 } 19649 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19650 SELinuxMMAC.setRestoreconDone(deDir); 19651 } 19652 } 19653 19654 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19655 + " packages; restoreconNeeded was " + restoreconNeeded); 19656 } 19657 19658 /** 19659 * Prepare app data for the given app just after it was installed or 19660 * upgraded. This method carefully only touches users that it's installed 19661 * for, and it forces a restorecon to handle any seinfo changes. 19662 * <p> 19663 * Verifies that directories exist and that ownership and labeling is 19664 * correct for all installed apps. If there is an ownership mismatch, it 19665 * will try recovering system apps by wiping data; third-party app data is 19666 * left intact. 19667 * <p> 19668 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19669 */ 19670 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19671 final PackageSetting ps; 19672 synchronized (mPackages) { 19673 ps = mSettings.mPackages.get(pkg.packageName); 19674 mSettings.writeKernelMappingLPr(ps); 19675 } 19676 19677 final UserManager um = mContext.getSystemService(UserManager.class); 19678 UserManagerInternal umInternal = getUserManagerInternal(); 19679 for (UserInfo user : um.getUsers()) { 19680 final int flags; 19681 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19682 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19683 } else if (umInternal.isUserRunning(user.id)) { 19684 flags = StorageManager.FLAG_STORAGE_DE; 19685 } else { 19686 continue; 19687 } 19688 19689 if (ps.getInstalled(user.id)) { 19690 // Whenever an app changes, force a restorecon of its data 19691 // TODO: when user data is locked, mark that we're still dirty 19692 prepareAppDataLIF(pkg, user.id, flags, true); 19693 } 19694 } 19695 } 19696 19697 /** 19698 * Prepare app data for the given app. 19699 * <p> 19700 * Verifies that directories exist and that ownership and labeling is 19701 * correct for all installed apps. If there is an ownership mismatch, this 19702 * will try recovering system apps by wiping data; third-party app data is 19703 * left intact. 19704 */ 19705 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19706 boolean restoreconNeeded) { 19707 if (pkg == null) { 19708 Slog.wtf(TAG, "Package was null!", new Throwable()); 19709 return; 19710 } 19711 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19712 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19713 for (int i = 0; i < childCount; i++) { 19714 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19715 } 19716 } 19717 19718 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19719 boolean restoreconNeeded) { 19720 if (DEBUG_APP_DATA) { 19721 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19722 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19723 } 19724 19725 final String volumeUuid = pkg.volumeUuid; 19726 final String packageName = pkg.packageName; 19727 final ApplicationInfo app = pkg.applicationInfo; 19728 final int appId = UserHandle.getAppId(app.uid); 19729 19730 Preconditions.checkNotNull(app.seinfo); 19731 19732 try { 19733 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19734 appId, app.seinfo, app.targetSdkVersion); 19735 } catch (InstallerException e) { 19736 if (app.isSystemApp()) { 19737 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19738 + ", but trying to recover: " + e); 19739 destroyAppDataLeafLIF(pkg, userId, flags); 19740 try { 19741 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19742 appId, app.seinfo, app.targetSdkVersion); 19743 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19744 } catch (InstallerException e2) { 19745 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19746 } 19747 } else { 19748 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19749 } 19750 } 19751 19752 if (restoreconNeeded) { 19753 try { 19754 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19755 app.seinfo); 19756 } catch (InstallerException e) { 19757 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19758 } 19759 } 19760 19761 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19762 try { 19763 // CE storage is unlocked right now, so read out the inode and 19764 // remember for use later when it's locked 19765 // TODO: mark this structure as dirty so we persist it! 19766 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19767 StorageManager.FLAG_STORAGE_CE); 19768 synchronized (mPackages) { 19769 final PackageSetting ps = mSettings.mPackages.get(packageName); 19770 if (ps != null) { 19771 ps.setCeDataInode(ceDataInode, userId); 19772 } 19773 } 19774 } catch (InstallerException e) { 19775 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19776 } 19777 } 19778 19779 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19780 } 19781 19782 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19783 if (pkg == null) { 19784 Slog.wtf(TAG, "Package was null!", new Throwable()); 19785 return; 19786 } 19787 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19788 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19789 for (int i = 0; i < childCount; i++) { 19790 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19791 } 19792 } 19793 19794 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19795 final String volumeUuid = pkg.volumeUuid; 19796 final String packageName = pkg.packageName; 19797 final ApplicationInfo app = pkg.applicationInfo; 19798 19799 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19800 // Create a native library symlink only if we have native libraries 19801 // and if the native libraries are 32 bit libraries. We do not provide 19802 // this symlink for 64 bit libraries. 19803 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19804 final String nativeLibPath = app.nativeLibraryDir; 19805 try { 19806 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19807 nativeLibPath, userId); 19808 } catch (InstallerException e) { 19809 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19810 } 19811 } 19812 } 19813 } 19814 19815 /** 19816 * For system apps on non-FBE devices, this method migrates any existing 19817 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19818 * requested by the app. 19819 */ 19820 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19821 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19822 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19823 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19824 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19825 try { 19826 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19827 storageTarget); 19828 } catch (InstallerException e) { 19829 logCriticalInfo(Log.WARN, 19830 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19831 } 19832 return true; 19833 } else { 19834 return false; 19835 } 19836 } 19837 19838 public PackageFreezer freezePackage(String packageName, String killReason) { 19839 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19840 } 19841 19842 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19843 return new PackageFreezer(packageName, userId, killReason); 19844 } 19845 19846 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19847 String killReason) { 19848 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19849 } 19850 19851 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19852 String killReason) { 19853 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19854 return new PackageFreezer(); 19855 } else { 19856 return freezePackage(packageName, userId, killReason); 19857 } 19858 } 19859 19860 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19861 String killReason) { 19862 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19863 } 19864 19865 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19866 String killReason) { 19867 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19868 return new PackageFreezer(); 19869 } else { 19870 return freezePackage(packageName, userId, killReason); 19871 } 19872 } 19873 19874 /** 19875 * Class that freezes and kills the given package upon creation, and 19876 * unfreezes it upon closing. This is typically used when doing surgery on 19877 * app code/data to prevent the app from running while you're working. 19878 */ 19879 private class PackageFreezer implements AutoCloseable { 19880 private final String mPackageName; 19881 private final PackageFreezer[] mChildren; 19882 19883 private final boolean mWeFroze; 19884 19885 private final AtomicBoolean mClosed = new AtomicBoolean(); 19886 private final CloseGuard mCloseGuard = CloseGuard.get(); 19887 19888 /** 19889 * Create and return a stub freezer that doesn't actually do anything, 19890 * typically used when someone requested 19891 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19892 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19893 */ 19894 public PackageFreezer() { 19895 mPackageName = null; 19896 mChildren = null; 19897 mWeFroze = false; 19898 mCloseGuard.open("close"); 19899 } 19900 19901 public PackageFreezer(String packageName, int userId, String killReason) { 19902 synchronized (mPackages) { 19903 mPackageName = packageName; 19904 mWeFroze = mFrozenPackages.add(mPackageName); 19905 19906 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19907 if (ps != null) { 19908 killApplication(ps.name, ps.appId, userId, killReason); 19909 } 19910 19911 final PackageParser.Package p = mPackages.get(packageName); 19912 if (p != null && p.childPackages != null) { 19913 final int N = p.childPackages.size(); 19914 mChildren = new PackageFreezer[N]; 19915 for (int i = 0; i < N; i++) { 19916 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19917 userId, killReason); 19918 } 19919 } else { 19920 mChildren = null; 19921 } 19922 } 19923 mCloseGuard.open("close"); 19924 } 19925 19926 @Override 19927 protected void finalize() throws Throwable { 19928 try { 19929 mCloseGuard.warnIfOpen(); 19930 close(); 19931 } finally { 19932 super.finalize(); 19933 } 19934 } 19935 19936 @Override 19937 public void close() { 19938 mCloseGuard.close(); 19939 if (mClosed.compareAndSet(false, true)) { 19940 synchronized (mPackages) { 19941 if (mWeFroze) { 19942 mFrozenPackages.remove(mPackageName); 19943 } 19944 19945 if (mChildren != null) { 19946 for (PackageFreezer freezer : mChildren) { 19947 freezer.close(); 19948 } 19949 } 19950 } 19951 } 19952 } 19953 } 19954 19955 /** 19956 * Verify that given package is currently frozen. 19957 */ 19958 private void checkPackageFrozen(String packageName) { 19959 synchronized (mPackages) { 19960 if (!mFrozenPackages.contains(packageName)) { 19961 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19962 } 19963 } 19964 } 19965 19966 @Override 19967 public int movePackage(final String packageName, final String volumeUuid) { 19968 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19969 19970 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19971 final int moveId = mNextMoveId.getAndIncrement(); 19972 mHandler.post(new Runnable() { 19973 @Override 19974 public void run() { 19975 try { 19976 movePackageInternal(packageName, volumeUuid, moveId, user); 19977 } catch (PackageManagerException e) { 19978 Slog.w(TAG, "Failed to move " + packageName, e); 19979 mMoveCallbacks.notifyStatusChanged(moveId, 19980 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19981 } 19982 } 19983 }); 19984 return moveId; 19985 } 19986 19987 private void movePackageInternal(final String packageName, final String volumeUuid, 19988 final int moveId, UserHandle user) throws PackageManagerException { 19989 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19990 final PackageManager pm = mContext.getPackageManager(); 19991 19992 final boolean currentAsec; 19993 final String currentVolumeUuid; 19994 final File codeFile; 19995 final String installerPackageName; 19996 final String packageAbiOverride; 19997 final int appId; 19998 final String seinfo; 19999 final String label; 20000 final int targetSdkVersion; 20001 final PackageFreezer freezer; 20002 final int[] installedUserIds; 20003 20004 // reader 20005 synchronized (mPackages) { 20006 final PackageParser.Package pkg = mPackages.get(packageName); 20007 final PackageSetting ps = mSettings.mPackages.get(packageName); 20008 if (pkg == null || ps == null) { 20009 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20010 } 20011 20012 if (pkg.applicationInfo.isSystemApp()) { 20013 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20014 "Cannot move system application"); 20015 } 20016 20017 if (pkg.applicationInfo.isExternalAsec()) { 20018 currentAsec = true; 20019 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20020 } else if (pkg.applicationInfo.isForwardLocked()) { 20021 currentAsec = true; 20022 currentVolumeUuid = "forward_locked"; 20023 } else { 20024 currentAsec = false; 20025 currentVolumeUuid = ps.volumeUuid; 20026 20027 final File probe = new File(pkg.codePath); 20028 final File probeOat = new File(probe, "oat"); 20029 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20030 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20031 "Move only supported for modern cluster style installs"); 20032 } 20033 } 20034 20035 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20036 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20037 "Package already moved to " + volumeUuid); 20038 } 20039 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20040 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20041 "Device admin cannot be moved"); 20042 } 20043 20044 if (mFrozenPackages.contains(packageName)) { 20045 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20046 "Failed to move already frozen package"); 20047 } 20048 20049 codeFile = new File(pkg.codePath); 20050 installerPackageName = ps.installerPackageName; 20051 packageAbiOverride = ps.cpuAbiOverrideString; 20052 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20053 seinfo = pkg.applicationInfo.seinfo; 20054 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20055 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20056 freezer = freezePackage(packageName, "movePackageInternal"); 20057 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20058 } 20059 20060 final Bundle extras = new Bundle(); 20061 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20062 extras.putString(Intent.EXTRA_TITLE, label); 20063 mMoveCallbacks.notifyCreated(moveId, extras); 20064 20065 int installFlags; 20066 final boolean moveCompleteApp; 20067 final File measurePath; 20068 20069 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20070 installFlags = INSTALL_INTERNAL; 20071 moveCompleteApp = !currentAsec; 20072 measurePath = Environment.getDataAppDirectory(volumeUuid); 20073 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20074 installFlags = INSTALL_EXTERNAL; 20075 moveCompleteApp = false; 20076 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20077 } else { 20078 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20079 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20080 || !volume.isMountedWritable()) { 20081 freezer.close(); 20082 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20083 "Move location not mounted private volume"); 20084 } 20085 20086 Preconditions.checkState(!currentAsec); 20087 20088 installFlags = INSTALL_INTERNAL; 20089 moveCompleteApp = true; 20090 measurePath = Environment.getDataAppDirectory(volumeUuid); 20091 } 20092 20093 final PackageStats stats = new PackageStats(null, -1); 20094 synchronized (mInstaller) { 20095 for (int userId : installedUserIds) { 20096 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20097 freezer.close(); 20098 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20099 "Failed to measure package size"); 20100 } 20101 } 20102 } 20103 20104 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20105 + stats.dataSize); 20106 20107 final long startFreeBytes = measurePath.getFreeSpace(); 20108 final long sizeBytes; 20109 if (moveCompleteApp) { 20110 sizeBytes = stats.codeSize + stats.dataSize; 20111 } else { 20112 sizeBytes = stats.codeSize; 20113 } 20114 20115 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20116 freezer.close(); 20117 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20118 "Not enough free space to move"); 20119 } 20120 20121 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20122 20123 final CountDownLatch installedLatch = new CountDownLatch(1); 20124 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20125 @Override 20126 public void onUserActionRequired(Intent intent) throws RemoteException { 20127 throw new IllegalStateException(); 20128 } 20129 20130 @Override 20131 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20132 Bundle extras) throws RemoteException { 20133 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20134 + PackageManager.installStatusToString(returnCode, msg)); 20135 20136 installedLatch.countDown(); 20137 freezer.close(); 20138 20139 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20140 switch (status) { 20141 case PackageInstaller.STATUS_SUCCESS: 20142 mMoveCallbacks.notifyStatusChanged(moveId, 20143 PackageManager.MOVE_SUCCEEDED); 20144 break; 20145 case PackageInstaller.STATUS_FAILURE_STORAGE: 20146 mMoveCallbacks.notifyStatusChanged(moveId, 20147 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20148 break; 20149 default: 20150 mMoveCallbacks.notifyStatusChanged(moveId, 20151 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20152 break; 20153 } 20154 } 20155 }; 20156 20157 final MoveInfo move; 20158 if (moveCompleteApp) { 20159 // Kick off a thread to report progress estimates 20160 new Thread() { 20161 @Override 20162 public void run() { 20163 while (true) { 20164 try { 20165 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20166 break; 20167 } 20168 } catch (InterruptedException ignored) { 20169 } 20170 20171 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20172 final int progress = 10 + (int) MathUtils.constrain( 20173 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20174 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20175 } 20176 } 20177 }.start(); 20178 20179 final String dataAppName = codeFile.getName(); 20180 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20181 dataAppName, appId, seinfo, targetSdkVersion); 20182 } else { 20183 move = null; 20184 } 20185 20186 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20187 20188 final Message msg = mHandler.obtainMessage(INIT_COPY); 20189 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20190 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20191 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20192 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20193 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20194 msg.obj = params; 20195 20196 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20197 System.identityHashCode(msg.obj)); 20198 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20199 System.identityHashCode(msg.obj)); 20200 20201 mHandler.sendMessage(msg); 20202 } 20203 20204 @Override 20205 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20207 20208 final int realMoveId = mNextMoveId.getAndIncrement(); 20209 final Bundle extras = new Bundle(); 20210 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20211 mMoveCallbacks.notifyCreated(realMoveId, extras); 20212 20213 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20214 @Override 20215 public void onCreated(int moveId, Bundle extras) { 20216 // Ignored 20217 } 20218 20219 @Override 20220 public void onStatusChanged(int moveId, int status, long estMillis) { 20221 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20222 } 20223 }; 20224 20225 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20226 storage.setPrimaryStorageUuid(volumeUuid, callback); 20227 return realMoveId; 20228 } 20229 20230 @Override 20231 public int getMoveStatus(int moveId) { 20232 mContext.enforceCallingOrSelfPermission( 20233 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20234 return mMoveCallbacks.mLastStatus.get(moveId); 20235 } 20236 20237 @Override 20238 public void registerMoveCallback(IPackageMoveObserver callback) { 20239 mContext.enforceCallingOrSelfPermission( 20240 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20241 mMoveCallbacks.register(callback); 20242 } 20243 20244 @Override 20245 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20246 mContext.enforceCallingOrSelfPermission( 20247 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20248 mMoveCallbacks.unregister(callback); 20249 } 20250 20251 @Override 20252 public boolean setInstallLocation(int loc) { 20253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20254 null); 20255 if (getInstallLocation() == loc) { 20256 return true; 20257 } 20258 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20259 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20260 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20261 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20262 return true; 20263 } 20264 return false; 20265 } 20266 20267 @Override 20268 public int getInstallLocation() { 20269 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20270 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20271 PackageHelper.APP_INSTALL_AUTO); 20272 } 20273 20274 /** Called by UserManagerService */ 20275 void cleanUpUser(UserManagerService userManager, int userHandle) { 20276 synchronized (mPackages) { 20277 mDirtyUsers.remove(userHandle); 20278 mUserNeedsBadging.delete(userHandle); 20279 mSettings.removeUserLPw(userHandle); 20280 mPendingBroadcasts.remove(userHandle); 20281 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20282 removeUnusedPackagesLPw(userManager, userHandle); 20283 } 20284 } 20285 20286 /** 20287 * We're removing userHandle and would like to remove any downloaded packages 20288 * that are no longer in use by any other user. 20289 * @param userHandle the user being removed 20290 */ 20291 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20292 final boolean DEBUG_CLEAN_APKS = false; 20293 int [] users = userManager.getUserIds(); 20294 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20295 while (psit.hasNext()) { 20296 PackageSetting ps = psit.next(); 20297 if (ps.pkg == null) { 20298 continue; 20299 } 20300 final String packageName = ps.pkg.packageName; 20301 // Skip over if system app 20302 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20303 continue; 20304 } 20305 if (DEBUG_CLEAN_APKS) { 20306 Slog.i(TAG, "Checking package " + packageName); 20307 } 20308 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20309 if (keep) { 20310 if (DEBUG_CLEAN_APKS) { 20311 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20312 } 20313 } else { 20314 for (int i = 0; i < users.length; i++) { 20315 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20316 keep = true; 20317 if (DEBUG_CLEAN_APKS) { 20318 Slog.i(TAG, " Keeping package " + packageName + " for user " 20319 + users[i]); 20320 } 20321 break; 20322 } 20323 } 20324 } 20325 if (!keep) { 20326 if (DEBUG_CLEAN_APKS) { 20327 Slog.i(TAG, " Removing package " + packageName); 20328 } 20329 mHandler.post(new Runnable() { 20330 public void run() { 20331 deletePackageX(packageName, userHandle, 0); 20332 } //end run 20333 }); 20334 } 20335 } 20336 } 20337 20338 /** Called by UserManagerService */ 20339 void createNewUser(int userId) { 20340 synchronized (mInstallLock) { 20341 mSettings.createNewUserLI(this, mInstaller, userId); 20342 } 20343 synchronized (mPackages) { 20344 scheduleWritePackageRestrictionsLocked(userId); 20345 scheduleWritePackageListLocked(userId); 20346 applyFactoryDefaultBrowserLPw(userId); 20347 primeDomainVerificationsLPw(userId); 20348 } 20349 } 20350 20351 void onNewUserCreated(final int userId) { 20352 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20353 // If permission review for legacy apps is required, we represent 20354 // dagerous permissions for such apps as always granted runtime 20355 // permissions to keep per user flag state whether review is needed. 20356 // Hence, if a new user is added we have to propagate dangerous 20357 // permission grants for these legacy apps. 20358 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20359 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20360 | UPDATE_PERMISSIONS_REPLACE_ALL); 20361 } 20362 } 20363 20364 @Override 20365 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20366 mContext.enforceCallingOrSelfPermission( 20367 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20368 "Only package verification agents can read the verifier device identity"); 20369 20370 synchronized (mPackages) { 20371 return mSettings.getVerifierDeviceIdentityLPw(); 20372 } 20373 } 20374 20375 @Override 20376 public void setPermissionEnforced(String permission, boolean enforced) { 20377 // TODO: Now that we no longer change GID for storage, this should to away. 20378 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20379 "setPermissionEnforced"); 20380 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20381 synchronized (mPackages) { 20382 if (mSettings.mReadExternalStorageEnforced == null 20383 || mSettings.mReadExternalStorageEnforced != enforced) { 20384 mSettings.mReadExternalStorageEnforced = enforced; 20385 mSettings.writeLPr(); 20386 } 20387 } 20388 // kill any non-foreground processes so we restart them and 20389 // grant/revoke the GID. 20390 final IActivityManager am = ActivityManagerNative.getDefault(); 20391 if (am != null) { 20392 final long token = Binder.clearCallingIdentity(); 20393 try { 20394 am.killProcessesBelowForeground("setPermissionEnforcement"); 20395 } catch (RemoteException e) { 20396 } finally { 20397 Binder.restoreCallingIdentity(token); 20398 } 20399 } 20400 } else { 20401 throw new IllegalArgumentException("No selective enforcement for " + permission); 20402 } 20403 } 20404 20405 @Override 20406 @Deprecated 20407 public boolean isPermissionEnforced(String permission) { 20408 return true; 20409 } 20410 20411 @Override 20412 public boolean isStorageLow() { 20413 final long token = Binder.clearCallingIdentity(); 20414 try { 20415 final DeviceStorageMonitorInternal 20416 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20417 if (dsm != null) { 20418 return dsm.isMemoryLow(); 20419 } else { 20420 return false; 20421 } 20422 } finally { 20423 Binder.restoreCallingIdentity(token); 20424 } 20425 } 20426 20427 @Override 20428 public IPackageInstaller getPackageInstaller() { 20429 return mInstallerService; 20430 } 20431 20432 private boolean userNeedsBadging(int userId) { 20433 int index = mUserNeedsBadging.indexOfKey(userId); 20434 if (index < 0) { 20435 final UserInfo userInfo; 20436 final long token = Binder.clearCallingIdentity(); 20437 try { 20438 userInfo = sUserManager.getUserInfo(userId); 20439 } finally { 20440 Binder.restoreCallingIdentity(token); 20441 } 20442 final boolean b; 20443 if (userInfo != null && userInfo.isManagedProfile()) { 20444 b = true; 20445 } else { 20446 b = false; 20447 } 20448 mUserNeedsBadging.put(userId, b); 20449 return b; 20450 } 20451 return mUserNeedsBadging.valueAt(index); 20452 } 20453 20454 @Override 20455 public KeySet getKeySetByAlias(String packageName, String alias) { 20456 if (packageName == null || alias == null) { 20457 return null; 20458 } 20459 synchronized(mPackages) { 20460 final PackageParser.Package pkg = mPackages.get(packageName); 20461 if (pkg == null) { 20462 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20463 throw new IllegalArgumentException("Unknown package: " + packageName); 20464 } 20465 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20466 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20467 } 20468 } 20469 20470 @Override 20471 public KeySet getSigningKeySet(String packageName) { 20472 if (packageName == null) { 20473 return null; 20474 } 20475 synchronized(mPackages) { 20476 final PackageParser.Package pkg = mPackages.get(packageName); 20477 if (pkg == null) { 20478 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20479 throw new IllegalArgumentException("Unknown package: " + packageName); 20480 } 20481 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20482 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20483 throw new SecurityException("May not access signing KeySet of other apps."); 20484 } 20485 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20486 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20487 } 20488 } 20489 20490 @Override 20491 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20492 if (packageName == null || ks == null) { 20493 return false; 20494 } 20495 synchronized(mPackages) { 20496 final PackageParser.Package pkg = mPackages.get(packageName); 20497 if (pkg == null) { 20498 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20499 throw new IllegalArgumentException("Unknown package: " + packageName); 20500 } 20501 IBinder ksh = ks.getToken(); 20502 if (ksh instanceof KeySetHandle) { 20503 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20504 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20505 } 20506 return false; 20507 } 20508 } 20509 20510 @Override 20511 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20512 if (packageName == null || ks == null) { 20513 return false; 20514 } 20515 synchronized(mPackages) { 20516 final PackageParser.Package pkg = mPackages.get(packageName); 20517 if (pkg == null) { 20518 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20519 throw new IllegalArgumentException("Unknown package: " + packageName); 20520 } 20521 IBinder ksh = ks.getToken(); 20522 if (ksh instanceof KeySetHandle) { 20523 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20524 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20525 } 20526 return false; 20527 } 20528 } 20529 20530 private void deletePackageIfUnusedLPr(final String packageName) { 20531 PackageSetting ps = mSettings.mPackages.get(packageName); 20532 if (ps == null) { 20533 return; 20534 } 20535 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20536 // TODO Implement atomic delete if package is unused 20537 // It is currently possible that the package will be deleted even if it is installed 20538 // after this method returns. 20539 mHandler.post(new Runnable() { 20540 public void run() { 20541 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20542 } 20543 }); 20544 } 20545 } 20546 20547 /** 20548 * Check and throw if the given before/after packages would be considered a 20549 * downgrade. 20550 */ 20551 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20552 throws PackageManagerException { 20553 if (after.versionCode < before.mVersionCode) { 20554 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20555 "Update version code " + after.versionCode + " is older than current " 20556 + before.mVersionCode); 20557 } else if (after.versionCode == before.mVersionCode) { 20558 if (after.baseRevisionCode < before.baseRevisionCode) { 20559 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20560 "Update base revision code " + after.baseRevisionCode 20561 + " is older than current " + before.baseRevisionCode); 20562 } 20563 20564 if (!ArrayUtils.isEmpty(after.splitNames)) { 20565 for (int i = 0; i < after.splitNames.length; i++) { 20566 final String splitName = after.splitNames[i]; 20567 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20568 if (j != -1) { 20569 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20570 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20571 "Update split " + splitName + " revision code " 20572 + after.splitRevisionCodes[i] + " is older than current " 20573 + before.splitRevisionCodes[j]); 20574 } 20575 } 20576 } 20577 } 20578 } 20579 } 20580 20581 private static class MoveCallbacks extends Handler { 20582 private static final int MSG_CREATED = 1; 20583 private static final int MSG_STATUS_CHANGED = 2; 20584 20585 private final RemoteCallbackList<IPackageMoveObserver> 20586 mCallbacks = new RemoteCallbackList<>(); 20587 20588 private final SparseIntArray mLastStatus = new SparseIntArray(); 20589 20590 public MoveCallbacks(Looper looper) { 20591 super(looper); 20592 } 20593 20594 public void register(IPackageMoveObserver callback) { 20595 mCallbacks.register(callback); 20596 } 20597 20598 public void unregister(IPackageMoveObserver callback) { 20599 mCallbacks.unregister(callback); 20600 } 20601 20602 @Override 20603 public void handleMessage(Message msg) { 20604 final SomeArgs args = (SomeArgs) msg.obj; 20605 final int n = mCallbacks.beginBroadcast(); 20606 for (int i = 0; i < n; i++) { 20607 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20608 try { 20609 invokeCallback(callback, msg.what, args); 20610 } catch (RemoteException ignored) { 20611 } 20612 } 20613 mCallbacks.finishBroadcast(); 20614 args.recycle(); 20615 } 20616 20617 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20618 throws RemoteException { 20619 switch (what) { 20620 case MSG_CREATED: { 20621 callback.onCreated(args.argi1, (Bundle) args.arg2); 20622 break; 20623 } 20624 case MSG_STATUS_CHANGED: { 20625 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20626 break; 20627 } 20628 } 20629 } 20630 20631 private void notifyCreated(int moveId, Bundle extras) { 20632 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20633 20634 final SomeArgs args = SomeArgs.obtain(); 20635 args.argi1 = moveId; 20636 args.arg2 = extras; 20637 obtainMessage(MSG_CREATED, args).sendToTarget(); 20638 } 20639 20640 private void notifyStatusChanged(int moveId, int status) { 20641 notifyStatusChanged(moveId, status, -1); 20642 } 20643 20644 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20645 Slog.v(TAG, "Move " + moveId + " status " + status); 20646 20647 final SomeArgs args = SomeArgs.obtain(); 20648 args.argi1 = moveId; 20649 args.argi2 = status; 20650 args.arg3 = estMillis; 20651 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20652 20653 synchronized (mLastStatus) { 20654 mLastStatus.put(moveId, status); 20655 } 20656 } 20657 } 20658 20659 private final static class OnPermissionChangeListeners extends Handler { 20660 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20661 20662 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20663 new RemoteCallbackList<>(); 20664 20665 public OnPermissionChangeListeners(Looper looper) { 20666 super(looper); 20667 } 20668 20669 @Override 20670 public void handleMessage(Message msg) { 20671 switch (msg.what) { 20672 case MSG_ON_PERMISSIONS_CHANGED: { 20673 final int uid = msg.arg1; 20674 handleOnPermissionsChanged(uid); 20675 } break; 20676 } 20677 } 20678 20679 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20680 mPermissionListeners.register(listener); 20681 20682 } 20683 20684 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20685 mPermissionListeners.unregister(listener); 20686 } 20687 20688 public void onPermissionsChanged(int uid) { 20689 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20690 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20691 } 20692 } 20693 20694 private void handleOnPermissionsChanged(int uid) { 20695 final int count = mPermissionListeners.beginBroadcast(); 20696 try { 20697 for (int i = 0; i < count; i++) { 20698 IOnPermissionsChangeListener callback = mPermissionListeners 20699 .getBroadcastItem(i); 20700 try { 20701 callback.onPermissionsChanged(uid); 20702 } catch (RemoteException e) { 20703 Log.e(TAG, "Permission listener is dead", e); 20704 } 20705 } 20706 } finally { 20707 mPermissionListeners.finishBroadcast(); 20708 } 20709 } 20710 } 20711 20712 private class PackageManagerInternalImpl extends PackageManagerInternal { 20713 @Override 20714 public void setLocationPackagesProvider(PackagesProvider provider) { 20715 synchronized (mPackages) { 20716 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20717 } 20718 } 20719 20720 @Override 20721 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20722 synchronized (mPackages) { 20723 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20724 } 20725 } 20726 20727 @Override 20728 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20729 synchronized (mPackages) { 20730 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20731 } 20732 } 20733 20734 @Override 20735 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20736 synchronized (mPackages) { 20737 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20738 } 20739 } 20740 20741 @Override 20742 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20743 synchronized (mPackages) { 20744 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20745 } 20746 } 20747 20748 @Override 20749 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20750 synchronized (mPackages) { 20751 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20752 } 20753 } 20754 20755 @Override 20756 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20757 synchronized (mPackages) { 20758 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20759 packageName, userId); 20760 } 20761 } 20762 20763 @Override 20764 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20765 synchronized (mPackages) { 20766 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20767 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20768 packageName, userId); 20769 } 20770 } 20771 20772 @Override 20773 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20774 synchronized (mPackages) { 20775 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20776 packageName, userId); 20777 } 20778 } 20779 20780 @Override 20781 public void setKeepUninstalledPackages(final List<String> packageList) { 20782 Preconditions.checkNotNull(packageList); 20783 List<String> removedFromList = null; 20784 synchronized (mPackages) { 20785 if (mKeepUninstalledPackages != null) { 20786 final int packagesCount = mKeepUninstalledPackages.size(); 20787 for (int i = 0; i < packagesCount; i++) { 20788 String oldPackage = mKeepUninstalledPackages.get(i); 20789 if (packageList != null && packageList.contains(oldPackage)) { 20790 continue; 20791 } 20792 if (removedFromList == null) { 20793 removedFromList = new ArrayList<>(); 20794 } 20795 removedFromList.add(oldPackage); 20796 } 20797 } 20798 mKeepUninstalledPackages = new ArrayList<>(packageList); 20799 if (removedFromList != null) { 20800 final int removedCount = removedFromList.size(); 20801 for (int i = 0; i < removedCount; i++) { 20802 deletePackageIfUnusedLPr(removedFromList.get(i)); 20803 } 20804 } 20805 } 20806 } 20807 20808 @Override 20809 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20810 synchronized (mPackages) { 20811 // If we do not support permission review, done. 20812 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20813 return false; 20814 } 20815 20816 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20817 if (packageSetting == null) { 20818 return false; 20819 } 20820 20821 // Permission review applies only to apps not supporting the new permission model. 20822 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20823 return false; 20824 } 20825 20826 // Legacy apps have the permission and get user consent on launch. 20827 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20828 return permissionsState.isPermissionReviewRequired(userId); 20829 } 20830 } 20831 20832 @Override 20833 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20834 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20835 } 20836 20837 @Override 20838 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20839 int userId) { 20840 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20841 } 20842 20843 @Override 20844 public void setDeviceAndProfileOwnerPackages( 20845 int deviceOwnerUserId, String deviceOwnerPackage, 20846 SparseArray<String> profileOwnerPackages) { 20847 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20848 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20849 } 20850 20851 @Override 20852 public boolean isPackageDataProtected(int userId, String packageName) { 20853 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20854 } 20855 } 20856 20857 @Override 20858 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20859 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20860 synchronized (mPackages) { 20861 final long identity = Binder.clearCallingIdentity(); 20862 try { 20863 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20864 packageNames, userId); 20865 } finally { 20866 Binder.restoreCallingIdentity(identity); 20867 } 20868 } 20869 } 20870 20871 private static void enforceSystemOrPhoneCaller(String tag) { 20872 int callingUid = Binder.getCallingUid(); 20873 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20874 throw new SecurityException( 20875 "Cannot call " + tag + " from UID " + callingUid); 20876 } 20877 } 20878 20879 boolean isHistoricalPackageUsageAvailable() { 20880 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20881 } 20882 20883 /** 20884 * Return a <b>copy</b> of the collection of packages known to the package manager. 20885 * @return A copy of the values of mPackages. 20886 */ 20887 Collection<PackageParser.Package> getPackages() { 20888 synchronized (mPackages) { 20889 return new ArrayList<>(mPackages.values()); 20890 } 20891 } 20892 20893 /** 20894 * Logs process start information (including base APK hash) to the security log. 20895 * @hide 20896 */ 20897 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20898 String apkFile, int pid) { 20899 if (!SecurityLog.isLoggingEnabled()) { 20900 return; 20901 } 20902 Bundle data = new Bundle(); 20903 data.putLong("startTimestamp", System.currentTimeMillis()); 20904 data.putString("processName", processName); 20905 data.putInt("uid", uid); 20906 data.putString("seinfo", seinfo); 20907 data.putString("apkFile", apkFile); 20908 data.putInt("pid", pid); 20909 Message msg = mProcessLoggingHandler.obtainMessage( 20910 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20911 msg.setData(data); 20912 mProcessLoggingHandler.sendMessage(msg); 20913 } 20914 20915 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20916 return mCompilerStats.getPackageStats(pkgName); 20917 } 20918 20919 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20920 return getOrCreateCompilerPackageStats(pkg.packageName); 20921 } 20922 20923 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20924 return mCompilerStats.getOrCreatePackageStats(pkgName); 20925 } 20926 20927 public void deleteCompilerPackageStats(String pkgName) { 20928 mCompilerStats.deletePackageStats(pkgName); 20929 } 20930} 20931