PackageManagerService.java revision cf70a17a7100e06d873d15edcfa4497685476327
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.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 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.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 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.BufferedInputStream; 268import java.io.BufferedOutputStream; 269import java.io.BufferedReader; 270import java.io.ByteArrayInputStream; 271import java.io.ByteArrayOutputStream; 272import java.io.File; 273import java.io.FileDescriptor; 274import java.io.FileInputStream; 275import java.io.FileNotFoundException; 276import java.io.FileOutputStream; 277import java.io.FileReader; 278import java.io.FilenameFilter; 279import java.io.IOException; 280import java.io.InputStream; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307import java.util.concurrent.atomic.AtomicLong; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = false; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 370 371 private static final boolean DISABLE_EPHEMERAL_APPS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 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 boolean mRestoredSettings; 626 627 // System configuration read by SystemConfig. 628 final int[] mGlobalGids; 629 final SparseArray<ArraySet<String>> mSystemPermissions; 630 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 631 632 // If mac_permissions.xml was found for seinfo labeling. 633 boolean mFoundPolicyFile; 634 635 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 636 637 public static final class SharedLibraryEntry { 638 public final String path; 639 public final String apk; 640 641 SharedLibraryEntry(String _path, String _apk) { 642 path = _path; 643 apk = _apk; 644 } 645 } 646 647 // Currently known shared libraries. 648 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 649 new ArrayMap<String, SharedLibraryEntry>(); 650 651 // All available activities, for your resolving pleasure. 652 final ActivityIntentResolver mActivities = 653 new ActivityIntentResolver(); 654 655 // All available receivers, for your resolving pleasure. 656 final ActivityIntentResolver mReceivers = 657 new ActivityIntentResolver(); 658 659 // All available services, for your resolving pleasure. 660 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 661 662 // All available providers, for your resolving pleasure. 663 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 664 665 // Mapping from provider base names (first directory in content URI codePath) 666 // to the provider information. 667 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 668 new ArrayMap<String, PackageParser.Provider>(); 669 670 // Mapping from instrumentation class names to info about them. 671 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 672 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 673 674 // Mapping from permission names to info about them. 675 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 676 new ArrayMap<String, PackageParser.PermissionGroup>(); 677 678 // Packages whose data we have transfered into another package, thus 679 // should no longer exist. 680 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 681 682 // Broadcast actions that are only available to the system. 683 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 684 685 /** List of packages waiting for verification. */ 686 final SparseArray<PackageVerificationState> mPendingVerification 687 = new SparseArray<PackageVerificationState>(); 688 689 /** Set of packages associated with each app op permission. */ 690 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 691 692 final PackageInstallerService mInstallerService; 693 694 private final PackageDexOptimizer mPackageDexOptimizer; 695 696 private AtomicInteger mNextMoveId = new AtomicInteger(); 697 private final MoveCallbacks mMoveCallbacks; 698 699 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 700 701 // Cache of users who need badging. 702 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 703 704 /** Token for keys in mPendingVerification. */ 705 private int mPendingVerificationToken = 0; 706 707 volatile boolean mSystemReady; 708 volatile boolean mSafeMode; 709 volatile boolean mHasSystemUidErrors; 710 711 ApplicationInfo mAndroidApplication; 712 final ActivityInfo mResolveActivity = new ActivityInfo(); 713 final ResolveInfo mResolveInfo = new ResolveInfo(); 714 ComponentName mResolveComponentName; 715 PackageParser.Package mPlatformPackage; 716 ComponentName mCustomResolverComponentName; 717 718 boolean mResolverReplaced = false; 719 720 private final @Nullable ComponentName mIntentFilterVerifierComponent; 721 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 722 723 private int mIntentFilterVerificationToken = 0; 724 725 /** Component that knows whether or not an ephemeral application exists */ 726 final ComponentName mEphemeralResolverComponent; 727 /** The service connection to the ephemeral resolver */ 728 final EphemeralResolverConnection mEphemeralResolverConnection; 729 730 /** Component used to install ephemeral applications */ 731 final ComponentName mEphemeralInstallerComponent; 732 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 733 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 734 735 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 736 = new SparseArray<IntentFilterVerificationState>(); 737 738 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 739 new DefaultPermissionGrantPolicy(this); 740 741 // List of packages names to keep cached, even if they are uninstalled for all users 742 private List<String> mKeepUninstalledPackages; 743 744 private UserManagerInternal mUserManagerInternal; 745 746 private static class IFVerificationParams { 747 PackageParser.Package pkg; 748 boolean replacing; 749 int userId; 750 int verifierUid; 751 752 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 753 int _userId, int _verifierUid) { 754 pkg = _pkg; 755 replacing = _replacing; 756 userId = _userId; 757 replacing = _replacing; 758 verifierUid = _verifierUid; 759 } 760 } 761 762 private interface IntentFilterVerifier<T extends IntentFilter> { 763 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 764 T filter, String packageName); 765 void startVerifications(int userId); 766 void receiveVerificationResponse(int verificationId); 767 } 768 769 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 770 private Context mContext; 771 private ComponentName mIntentFilterVerifierComponent; 772 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 773 774 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 775 mContext = context; 776 mIntentFilterVerifierComponent = verifierComponent; 777 } 778 779 private String getDefaultScheme() { 780 return IntentFilter.SCHEME_HTTPS; 781 } 782 783 @Override 784 public void startVerifications(int userId) { 785 // Launch verifications requests 786 int count = mCurrentIntentFilterVerifications.size(); 787 for (int n=0; n<count; n++) { 788 int verificationId = mCurrentIntentFilterVerifications.get(n); 789 final IntentFilterVerificationState ivs = 790 mIntentFilterVerificationStates.get(verificationId); 791 792 String packageName = ivs.getPackageName(); 793 794 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 795 final int filterCount = filters.size(); 796 ArraySet<String> domainsSet = new ArraySet<>(); 797 for (int m=0; m<filterCount; m++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(m); 799 domainsSet.addAll(filter.getHostsList()); 800 } 801 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 802 synchronized (mPackages) { 803 if (mSettings.createIntentFilterVerificationIfNeededLPw( 804 packageName, domainsList) != null) { 805 scheduleWriteSettingsLocked(); 806 } 807 } 808 sendVerificationRequest(userId, verificationId, ivs); 809 } 810 mCurrentIntentFilterVerifications.clear(); 811 } 812 813 private void sendVerificationRequest(int userId, int verificationId, 814 IntentFilterVerificationState ivs) { 815 816 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 819 verificationId); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 822 getDefaultScheme()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 825 ivs.getHostsString()); 826 verificationIntent.putExtra( 827 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 828 ivs.getPackageName()); 829 verificationIntent.setComponent(mIntentFilterVerifierComponent); 830 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 831 832 UserHandle user = new UserHandle(userId); 833 mContext.sendBroadcastAsUser(verificationIntent, user); 834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 835 "Sending IntentFilter verification broadcast"); 836 } 837 838 public void receiveVerificationResponse(int verificationId) { 839 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 840 841 final boolean verified = ivs.isVerified(); 842 843 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 844 final int count = filters.size(); 845 if (DEBUG_DOMAIN_VERIFICATION) { 846 Slog.i(TAG, "Received verification response " + verificationId 847 + " for " + count + " filters, verified=" + verified); 848 } 849 for (int n=0; n<count; n++) { 850 PackageParser.ActivityIntentInfo filter = filters.get(n); 851 filter.setVerified(verified); 852 853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 854 + " verified with result:" + verified + " and hosts:" 855 + ivs.getHostsString()); 856 } 857 858 mIntentFilterVerificationStates.remove(verificationId); 859 860 final String packageName = ivs.getPackageName(); 861 IntentFilterVerificationInfo ivi = null; 862 863 synchronized (mPackages) { 864 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 865 } 866 if (ivi == null) { 867 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 868 + verificationId + " packageName:" + packageName); 869 return; 870 } 871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 872 "Updating IntentFilterVerificationInfo for package " + packageName 873 +" verificationId:" + verificationId); 874 875 synchronized (mPackages) { 876 if (verified) { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 878 } else { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 880 } 881 scheduleWriteSettingsLocked(); 882 883 final int userId = ivs.getUserId(); 884 if (userId != UserHandle.USER_ALL) { 885 final int userStatus = 886 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 887 888 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 889 boolean needUpdate = false; 890 891 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 892 // already been set by the User thru the Disambiguation dialog 893 switch (userStatus) { 894 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 895 if (verified) { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 897 } else { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 899 } 900 needUpdate = true; 901 break; 902 903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 904 if (verified) { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 906 needUpdate = true; 907 } 908 break; 909 910 default: 911 // Nothing to do 912 } 913 914 if (needUpdate) { 915 mSettings.updateIntentFilterVerificationStatusLPw( 916 packageName, updatedStatus, userId); 917 scheduleWritePackageRestrictionsLocked(userId); 918 } 919 } 920 } 921 } 922 923 @Override 924 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 925 ActivityIntentInfo filter, String packageName) { 926 if (!hasValidDomains(filter)) { 927 return false; 928 } 929 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 930 if (ivs == null) { 931 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 932 packageName); 933 } 934 if (DEBUG_DOMAIN_VERIFICATION) { 935 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 936 } 937 ivs.addFilter(filter); 938 return true; 939 } 940 941 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 942 int userId, int verificationId, String packageName) { 943 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 944 verifierUid, userId, packageName); 945 ivs.setPendingState(); 946 synchronized (mPackages) { 947 mIntentFilterVerificationStates.append(verificationId, ivs); 948 mCurrentIntentFilterVerifications.add(verificationId); 949 } 950 return ivs; 951 } 952 } 953 954 private static boolean hasValidDomains(ActivityIntentInfo filter) { 955 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 956 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 957 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 958 } 959 960 // Set of pending broadcasts for aggregating enable/disable of components. 961 static class PendingPackageBroadcasts { 962 // for each user id, a map of <package name -> components within that package> 963 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 964 965 public PendingPackageBroadcasts() { 966 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 967 } 968 969 public ArrayList<String> get(int userId, String packageName) { 970 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 971 return packages.get(packageName); 972 } 973 974 public void put(int userId, String packageName, ArrayList<String> components) { 975 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 976 packages.put(packageName, components); 977 } 978 979 public void remove(int userId, String packageName) { 980 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 981 if (packages != null) { 982 packages.remove(packageName); 983 } 984 } 985 986 public void remove(int userId) { 987 mUidMap.remove(userId); 988 } 989 990 public int userIdCount() { 991 return mUidMap.size(); 992 } 993 994 public int userIdAt(int n) { 995 return mUidMap.keyAt(n); 996 } 997 998 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 999 return mUidMap.get(userId); 1000 } 1001 1002 public int size() { 1003 // total number of pending broadcast entries across all userIds 1004 int num = 0; 1005 for (int i = 0; i< mUidMap.size(); i++) { 1006 num += mUidMap.valueAt(i).size(); 1007 } 1008 return num; 1009 } 1010 1011 public void clear() { 1012 mUidMap.clear(); 1013 } 1014 1015 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1016 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1017 if (map == null) { 1018 map = new ArrayMap<String, ArrayList<String>>(); 1019 mUidMap.put(userId, map); 1020 } 1021 return map; 1022 } 1023 } 1024 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1025 1026 // Service Connection to remote media container service to copy 1027 // package uri's from external media onto secure containers 1028 // or internal storage. 1029 private IMediaContainerService mContainerService = null; 1030 1031 static final int SEND_PENDING_BROADCAST = 1; 1032 static final int MCS_BOUND = 3; 1033 static final int END_COPY = 4; 1034 static final int INIT_COPY = 5; 1035 static final int MCS_UNBIND = 6; 1036 static final int START_CLEANING_PACKAGE = 7; 1037 static final int FIND_INSTALL_LOC = 8; 1038 static final int POST_INSTALL = 9; 1039 static final int MCS_RECONNECT = 10; 1040 static final int MCS_GIVE_UP = 11; 1041 static final int UPDATED_MEDIA_STATUS = 12; 1042 static final int WRITE_SETTINGS = 13; 1043 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1044 static final int PACKAGE_VERIFIED = 15; 1045 static final int CHECK_PENDING_VERIFICATION = 16; 1046 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1047 static final int INTENT_FILTER_VERIFIED = 18; 1048 static final int WRITE_PACKAGE_LIST = 19; 1049 1050 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1051 1052 // Delay time in millisecs 1053 static final int BROADCAST_DELAY = 10 * 1000; 1054 1055 static UserManagerService sUserManager; 1056 1057 // Stores a list of users whose package restrictions file needs to be updated 1058 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1059 1060 final private DefaultContainerConnection mDefContainerConn = 1061 new DefaultContainerConnection(); 1062 class DefaultContainerConnection implements ServiceConnection { 1063 public void onServiceConnected(ComponentName name, IBinder service) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1065 IMediaContainerService imcs = 1066 IMediaContainerService.Stub.asInterface(service); 1067 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1068 } 1069 1070 public void onServiceDisconnected(ComponentName name) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1072 } 1073 } 1074 1075 // Recordkeeping of restore-after-install operations that are currently in flight 1076 // between the Package Manager and the Backup Manager 1077 static class PostInstallData { 1078 public InstallArgs args; 1079 public PackageInstalledInfo res; 1080 1081 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1082 args = _a; 1083 res = _r; 1084 } 1085 } 1086 1087 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1088 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1089 1090 // XML tags for backup/restore of various bits of state 1091 private static final String TAG_PREFERRED_BACKUP = "pa"; 1092 private static final String TAG_DEFAULT_APPS = "da"; 1093 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1094 1095 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1096 private static final String TAG_ALL_GRANTS = "rt-grants"; 1097 private static final String TAG_GRANT = "grant"; 1098 private static final String ATTR_PACKAGE_NAME = "pkg"; 1099 1100 private static final String TAG_PERMISSION = "perm"; 1101 private static final String ATTR_PERMISSION_NAME = "name"; 1102 private static final String ATTR_IS_GRANTED = "g"; 1103 private static final String ATTR_USER_SET = "set"; 1104 private static final String ATTR_USER_FIXED = "fixed"; 1105 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1106 1107 // System/policy permission grants are not backed up 1108 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1109 FLAG_PERMISSION_POLICY_FIXED 1110 | FLAG_PERMISSION_SYSTEM_FIXED 1111 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1112 1113 // And we back up these user-adjusted states 1114 private static final int USER_RUNTIME_GRANT_MASK = 1115 FLAG_PERMISSION_USER_SET 1116 | FLAG_PERMISSION_USER_FIXED 1117 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1118 1119 final @Nullable String mRequiredVerifierPackage; 1120 final @NonNull String mRequiredInstallerPackage; 1121 final @Nullable String mSetupWizardPackage; 1122 final @NonNull String mServicesSystemSharedLibraryPackageName; 1123 final @NonNull String mSharedSystemSharedLibraryPackageName; 1124 1125 private final PackageUsage mPackageUsage = new PackageUsage(); 1126 1127 private class PackageUsage { 1128 private static final int WRITE_INTERVAL 1129 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1130 1131 private final Object mFileLock = new Object(); 1132 private final AtomicLong mLastWritten = new AtomicLong(0); 1133 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1134 1135 private boolean mIsHistoricalPackageUsageAvailable = true; 1136 1137 boolean isHistoricalPackageUsageAvailable() { 1138 return mIsHistoricalPackageUsageAvailable; 1139 } 1140 1141 void write(boolean force) { 1142 if (force) { 1143 writeInternal(); 1144 return; 1145 } 1146 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1147 && !DEBUG_DEXOPT) { 1148 return; 1149 } 1150 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1151 new Thread("PackageUsage_DiskWriter") { 1152 @Override 1153 public void run() { 1154 try { 1155 writeInternal(); 1156 } finally { 1157 mBackgroundWriteRunning.set(false); 1158 } 1159 } 1160 }.start(); 1161 } 1162 } 1163 1164 private void writeInternal() { 1165 synchronized (mPackages) { 1166 synchronized (mFileLock) { 1167 AtomicFile file = getFile(); 1168 FileOutputStream f = null; 1169 try { 1170 f = file.startWrite(); 1171 BufferedOutputStream out = new BufferedOutputStream(f); 1172 FileUtils.setPermissions(file.getBaseFile().getPath(), 1173 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1174 StringBuilder sb = new StringBuilder(); 1175 1176 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1177 sb.append('\n'); 1178 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1179 1180 for (PackageParser.Package pkg : mPackages.values()) { 1181 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1182 continue; 1183 } 1184 sb.setLength(0); 1185 sb.append(pkg.packageName); 1186 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1187 sb.append(' '); 1188 sb.append(usageTimeInMillis); 1189 } 1190 sb.append('\n'); 1191 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1192 } 1193 out.flush(); 1194 file.finishWrite(f); 1195 } catch (IOException e) { 1196 if (f != null) { 1197 file.failWrite(f); 1198 } 1199 Log.e(TAG, "Failed to write package usage times", e); 1200 } 1201 } 1202 } 1203 mLastWritten.set(SystemClock.elapsedRealtime()); 1204 } 1205 1206 void readLP() { 1207 synchronized (mFileLock) { 1208 AtomicFile file = getFile(); 1209 BufferedInputStream in = null; 1210 try { 1211 in = new BufferedInputStream(file.openRead()); 1212 StringBuffer sb = new StringBuffer(); 1213 1214 String firstLine = readLine(in, sb); 1215 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1216 readVersion1LP(in, sb); 1217 } else { 1218 readVersion0LP(in, sb, firstLine); 1219 } 1220 } catch (FileNotFoundException expected) { 1221 mIsHistoricalPackageUsageAvailable = false; 1222 } catch (IOException e) { 1223 Log.w(TAG, "Failed to read package usage times", e); 1224 } finally { 1225 IoUtils.closeQuietly(in); 1226 } 1227 } 1228 mLastWritten.set(SystemClock.elapsedRealtime()); 1229 } 1230 1231 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1232 throws IOException { 1233 // Initial version of the file had no version number and stored one 1234 // package-timestamp pair per line. 1235 // Note that the first line has already been read from the InputStream. 1236 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1237 String[] tokens = line.split(" "); 1238 if (tokens.length != 2) { 1239 throw new IOException("Failed to parse " + line + 1240 " as package-timestamp pair."); 1241 } 1242 1243 String packageName = tokens[0]; 1244 PackageParser.Package pkg = mPackages.get(packageName); 1245 if (pkg == null) { 1246 continue; 1247 } 1248 1249 long timestamp = parseAsLong(tokens[1]); 1250 for (int reason = 0; 1251 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1252 reason++) { 1253 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1254 } 1255 } 1256 } 1257 1258 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1259 // Version 1 of the file started with the corresponding version 1260 // number and then stored a package name and eight timestamps per line. 1261 String line; 1262 while ((line = readLine(in, sb)) != null) { 1263 String[] tokens = line.split(" "); 1264 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1265 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1266 } 1267 1268 String packageName = tokens[0]; 1269 PackageParser.Package pkg = mPackages.get(packageName); 1270 if (pkg == null) { 1271 continue; 1272 } 1273 1274 for (int reason = 0; 1275 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1276 reason++) { 1277 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1278 } 1279 } 1280 } 1281 1282 private long parseAsLong(String token) throws IOException { 1283 try { 1284 return Long.parseLong(token); 1285 } catch (NumberFormatException e) { 1286 throw new IOException("Failed to parse " + token + " as a long.", e); 1287 } 1288 } 1289 1290 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1291 return readToken(in, sb, '\n'); 1292 } 1293 1294 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1295 throws IOException { 1296 sb.setLength(0); 1297 while (true) { 1298 int ch = in.read(); 1299 if (ch == -1) { 1300 if (sb.length() == 0) { 1301 return null; 1302 } 1303 throw new IOException("Unexpected EOF"); 1304 } 1305 if (ch == endOfToken) { 1306 return sb.toString(); 1307 } 1308 sb.append((char)ch); 1309 } 1310 } 1311 1312 private AtomicFile getFile() { 1313 File dataDir = Environment.getDataDirectory(); 1314 File systemDir = new File(dataDir, "system"); 1315 File fname = new File(systemDir, "package-usage.list"); 1316 return new AtomicFile(fname); 1317 } 1318 1319 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1320 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1321 } 1322 1323 class PackageHandler extends Handler { 1324 private boolean mBound = false; 1325 final ArrayList<HandlerParams> mPendingInstalls = 1326 new ArrayList<HandlerParams>(); 1327 1328 private boolean connectToService() { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1330 " DefaultContainerService"); 1331 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1333 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1334 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 mBound = true; 1337 return true; 1338 } 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 return false; 1341 } 1342 1343 private void disconnectService() { 1344 mContainerService = null; 1345 mBound = false; 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1347 mContext.unbindService(mDefContainerConn); 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 } 1350 1351 PackageHandler(Looper looper) { 1352 super(looper); 1353 } 1354 1355 public void handleMessage(Message msg) { 1356 try { 1357 doHandleMessage(msg); 1358 } finally { 1359 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1360 } 1361 } 1362 1363 void doHandleMessage(Message msg) { 1364 switch (msg.what) { 1365 case INIT_COPY: { 1366 HandlerParams params = (HandlerParams) msg.obj; 1367 int idx = mPendingInstalls.size(); 1368 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1369 // If a bind was already initiated we dont really 1370 // need to do anything. The pending install 1371 // will be processed later on. 1372 if (!mBound) { 1373 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1374 System.identityHashCode(mHandler)); 1375 // If this is the only one pending we might 1376 // have to bind to the service again. 1377 if (!connectToService()) { 1378 Slog.e(TAG, "Failed to bind to media container service"); 1379 params.serviceError(); 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1381 System.identityHashCode(mHandler)); 1382 if (params.traceMethod != null) { 1383 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1384 params.traceCookie); 1385 } 1386 return; 1387 } else { 1388 // Once we bind to the service, the first 1389 // pending request will be processed. 1390 mPendingInstalls.add(idx, params); 1391 } 1392 } else { 1393 mPendingInstalls.add(idx, params); 1394 // Already bound to the service. Just make 1395 // sure we trigger off processing the first request. 1396 if (idx == 0) { 1397 mHandler.sendEmptyMessage(MCS_BOUND); 1398 } 1399 } 1400 break; 1401 } 1402 case MCS_BOUND: { 1403 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1404 if (msg.obj != null) { 1405 mContainerService = (IMediaContainerService) msg.obj; 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1407 System.identityHashCode(mHandler)); 1408 } 1409 if (mContainerService == null) { 1410 if (!mBound) { 1411 // Something seriously wrong since we are not bound and we are not 1412 // waiting for connection. Bail out. 1413 Slog.e(TAG, "Cannot bind to media container service"); 1414 for (HandlerParams params : mPendingInstalls) { 1415 // Indicate service bind error 1416 params.serviceError(); 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1418 System.identityHashCode(params)); 1419 if (params.traceMethod != null) { 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1421 params.traceMethod, params.traceCookie); 1422 } 1423 return; 1424 } 1425 mPendingInstalls.clear(); 1426 } else { 1427 Slog.w(TAG, "Waiting to connect to media container service"); 1428 } 1429 } else if (mPendingInstalls.size() > 0) { 1430 HandlerParams params = mPendingInstalls.get(0); 1431 if (params != null) { 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1433 System.identityHashCode(params)); 1434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1435 if (params.startCopy()) { 1436 // We are done... look for more work or to 1437 // go idle. 1438 if (DEBUG_SD_INSTALL) Log.i(TAG, 1439 "Checking for more work or unbind..."); 1440 // Delete pending install 1441 if (mPendingInstalls.size() > 0) { 1442 mPendingInstalls.remove(0); 1443 } 1444 if (mPendingInstalls.size() == 0) { 1445 if (mBound) { 1446 if (DEBUG_SD_INSTALL) Log.i(TAG, 1447 "Posting delayed MCS_UNBIND"); 1448 removeMessages(MCS_UNBIND); 1449 Message ubmsg = obtainMessage(MCS_UNBIND); 1450 // Unbind after a little delay, to avoid 1451 // continual thrashing. 1452 sendMessageDelayed(ubmsg, 10000); 1453 } 1454 } else { 1455 // There are more pending requests in queue. 1456 // Just post MCS_BOUND message to trigger processing 1457 // of next pending install. 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, 1459 "Posting MCS_BOUND for next work"); 1460 mHandler.sendEmptyMessage(MCS_BOUND); 1461 } 1462 } 1463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1464 } 1465 } else { 1466 // Should never happen ideally. 1467 Slog.w(TAG, "Empty queue"); 1468 } 1469 break; 1470 } 1471 case MCS_RECONNECT: { 1472 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1473 if (mPendingInstalls.size() > 0) { 1474 if (mBound) { 1475 disconnectService(); 1476 } 1477 if (!connectToService()) { 1478 Slog.e(TAG, "Failed to bind to media container service"); 1479 for (HandlerParams params : mPendingInstalls) { 1480 // Indicate service bind error 1481 params.serviceError(); 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1483 System.identityHashCode(params)); 1484 } 1485 mPendingInstalls.clear(); 1486 } 1487 } 1488 break; 1489 } 1490 case MCS_UNBIND: { 1491 // If there is no actual work left, then time to unbind. 1492 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1493 1494 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1495 if (mBound) { 1496 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1497 1498 disconnectService(); 1499 } 1500 } else if (mPendingInstalls.size() > 0) { 1501 // There are more pending requests in queue. 1502 // Just post MCS_BOUND message to trigger processing 1503 // of next pending install. 1504 mHandler.sendEmptyMessage(MCS_BOUND); 1505 } 1506 1507 break; 1508 } 1509 case MCS_GIVE_UP: { 1510 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1511 HandlerParams params = mPendingInstalls.remove(0); 1512 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1513 System.identityHashCode(params)); 1514 break; 1515 } 1516 case SEND_PENDING_BROADCAST: { 1517 String packages[]; 1518 ArrayList<String> components[]; 1519 int size = 0; 1520 int uids[]; 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1522 synchronized (mPackages) { 1523 if (mPendingBroadcasts == null) { 1524 return; 1525 } 1526 size = mPendingBroadcasts.size(); 1527 if (size <= 0) { 1528 // Nothing to be done. Just return 1529 return; 1530 } 1531 packages = new String[size]; 1532 components = new ArrayList[size]; 1533 uids = new int[size]; 1534 int i = 0; // filling out the above arrays 1535 1536 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1537 int packageUserId = mPendingBroadcasts.userIdAt(n); 1538 Iterator<Map.Entry<String, ArrayList<String>>> it 1539 = mPendingBroadcasts.packagesForUserId(packageUserId) 1540 .entrySet().iterator(); 1541 while (it.hasNext() && i < size) { 1542 Map.Entry<String, ArrayList<String>> ent = it.next(); 1543 packages[i] = ent.getKey(); 1544 components[i] = ent.getValue(); 1545 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1546 uids[i] = (ps != null) 1547 ? UserHandle.getUid(packageUserId, ps.appId) 1548 : -1; 1549 i++; 1550 } 1551 } 1552 size = i; 1553 mPendingBroadcasts.clear(); 1554 } 1555 // Send broadcasts 1556 for (int i = 0; i < size; i++) { 1557 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 break; 1561 } 1562 case START_CLEANING_PACKAGE: { 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1564 final String packageName = (String)msg.obj; 1565 final int userId = msg.arg1; 1566 final boolean andCode = msg.arg2 != 0; 1567 synchronized (mPackages) { 1568 if (userId == UserHandle.USER_ALL) { 1569 int[] users = sUserManager.getUserIds(); 1570 for (int user : users) { 1571 mSettings.addPackageToCleanLPw( 1572 new PackageCleanItem(user, packageName, andCode)); 1573 } 1574 } else { 1575 mSettings.addPackageToCleanLPw( 1576 new PackageCleanItem(userId, packageName, andCode)); 1577 } 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 startCleaningPackages(); 1581 } break; 1582 case POST_INSTALL: { 1583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1584 1585 PostInstallData data = mRunningInstalls.get(msg.arg1); 1586 final boolean didRestore = (msg.arg2 != 0); 1587 mRunningInstalls.delete(msg.arg1); 1588 1589 if (data != null) { 1590 InstallArgs args = data.args; 1591 PackageInstalledInfo parentRes = data.res; 1592 1593 final boolean grantPermissions = (args.installFlags 1594 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1595 final boolean killApp = (args.installFlags 1596 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1597 final String[] grantedPermissions = args.installGrantPermissions; 1598 1599 // Handle the parent package 1600 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1601 grantedPermissions, didRestore, args.installerPackageName, 1602 args.observer); 1603 1604 // Handle the child packages 1605 final int childCount = (parentRes.addedChildPackages != null) 1606 ? parentRes.addedChildPackages.size() : 0; 1607 for (int i = 0; i < childCount; i++) { 1608 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1609 handlePackagePostInstall(childRes, grantPermissions, killApp, 1610 grantedPermissions, false, args.installerPackageName, 1611 args.observer); 1612 } 1613 1614 // Log tracing if needed 1615 if (args.traceMethod != null) { 1616 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1617 args.traceCookie); 1618 } 1619 } else { 1620 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1621 } 1622 1623 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1624 } break; 1625 case UPDATED_MEDIA_STATUS: { 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1627 boolean reportStatus = msg.arg1 == 1; 1628 boolean doGc = msg.arg2 == 1; 1629 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1630 if (doGc) { 1631 // Force a gc to clear up stale containers. 1632 Runtime.getRuntime().gc(); 1633 } 1634 if (msg.obj != null) { 1635 @SuppressWarnings("unchecked") 1636 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1638 // Unload containers 1639 unloadAllContainers(args); 1640 } 1641 if (reportStatus) { 1642 try { 1643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1644 PackageHelper.getMountService().finishMediaUpdate(); 1645 } catch (RemoteException e) { 1646 Log.e(TAG, "MountService not running?"); 1647 } 1648 } 1649 } break; 1650 case WRITE_SETTINGS: { 1651 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1652 synchronized (mPackages) { 1653 removeMessages(WRITE_SETTINGS); 1654 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1655 mSettings.writeLPr(); 1656 mDirtyUsers.clear(); 1657 } 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1659 } break; 1660 case WRITE_PACKAGE_RESTRICTIONS: { 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1662 synchronized (mPackages) { 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 for (int userId : mDirtyUsers) { 1665 mSettings.writePackageRestrictionsLPr(userId); 1666 } 1667 mDirtyUsers.clear(); 1668 } 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1670 } break; 1671 case WRITE_PACKAGE_LIST: { 1672 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1673 synchronized (mPackages) { 1674 removeMessages(WRITE_PACKAGE_LIST); 1675 mSettings.writePackageListLPr(msg.arg1); 1676 } 1677 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1678 } break; 1679 case CHECK_PENDING_VERIFICATION: { 1680 final int verificationId = msg.arg1; 1681 final PackageVerificationState state = mPendingVerification.get(verificationId); 1682 1683 if ((state != null) && !state.timeoutExtended()) { 1684 final InstallArgs args = state.getInstallArgs(); 1685 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1686 1687 Slog.i(TAG, "Verification timed out for " + originUri); 1688 mPendingVerification.remove(verificationId); 1689 1690 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1691 1692 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1693 Slog.i(TAG, "Continuing with installation of " + originUri); 1694 state.setVerifierResponse(Binder.getCallingUid(), 1695 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1696 broadcastPackageVerified(verificationId, originUri, 1697 PackageManager.VERIFICATION_ALLOW, 1698 state.getInstallArgs().getUser()); 1699 try { 1700 ret = args.copyApk(mContainerService, true); 1701 } catch (RemoteException e) { 1702 Slog.e(TAG, "Could not contact the ContainerService"); 1703 } 1704 } else { 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_REJECT, 1707 state.getInstallArgs().getUser()); 1708 } 1709 1710 Trace.asyncTraceEnd( 1711 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1712 1713 processPendingInstall(args, ret); 1714 mHandler.sendEmptyMessage(MCS_UNBIND); 1715 } 1716 break; 1717 } 1718 case PACKAGE_VERIFIED: { 1719 final int verificationId = msg.arg1; 1720 1721 final PackageVerificationState state = mPendingVerification.get(verificationId); 1722 if (state == null) { 1723 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1724 break; 1725 } 1726 1727 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1728 1729 state.setVerifierResponse(response.callerUid, response.code); 1730 1731 if (state.isVerificationComplete()) { 1732 mPendingVerification.remove(verificationId); 1733 1734 final InstallArgs args = state.getInstallArgs(); 1735 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1736 1737 int ret; 1738 if (state.isInstallAllowed()) { 1739 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1740 broadcastPackageVerified(verificationId, originUri, 1741 response.code, state.getInstallArgs().getUser()); 1742 try { 1743 ret = args.copyApk(mContainerService, true); 1744 } catch (RemoteException e) { 1745 Slog.e(TAG, "Could not contact the ContainerService"); 1746 } 1747 } else { 1748 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1749 } 1750 1751 Trace.asyncTraceEnd( 1752 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1753 1754 processPendingInstall(args, ret); 1755 mHandler.sendEmptyMessage(MCS_UNBIND); 1756 } 1757 1758 break; 1759 } 1760 case START_INTENT_FILTER_VERIFICATIONS: { 1761 IFVerificationParams params = (IFVerificationParams) msg.obj; 1762 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1763 params.replacing, params.pkg); 1764 break; 1765 } 1766 case INTENT_FILTER_VERIFIED: { 1767 final int verificationId = msg.arg1; 1768 1769 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1770 verificationId); 1771 if (state == null) { 1772 Slog.w(TAG, "Invalid IntentFilter verification token " 1773 + verificationId + " received"); 1774 break; 1775 } 1776 1777 final int userId = state.getUserId(); 1778 1779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1780 "Processing IntentFilter verification with token:" 1781 + verificationId + " and userId:" + userId); 1782 1783 final IntentFilterVerificationResponse response = 1784 (IntentFilterVerificationResponse) msg.obj; 1785 1786 state.setVerifierResponse(response.callerUid, response.code); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "IntentFilter verification with token:" + verificationId 1790 + " and userId:" + userId 1791 + " is settings verifier response with response code:" 1792 + response.code); 1793 1794 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1795 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1796 + response.getFailedDomainsString()); 1797 } 1798 1799 if (state.isVerificationComplete()) { 1800 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1801 } else { 1802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1803 "IntentFilter verification with token:" + verificationId 1804 + " was not said to be complete"); 1805 } 1806 1807 break; 1808 } 1809 } 1810 } 1811 } 1812 1813 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1814 boolean killApp, String[] grantedPermissions, 1815 boolean launchedForRestore, String installerPackage, 1816 IPackageInstallObserver2 installObserver) { 1817 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1818 // Send the removed broadcasts 1819 if (res.removedInfo != null) { 1820 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1821 } 1822 1823 // Now that we successfully installed the package, grant runtime 1824 // permissions if requested before broadcasting the install. 1825 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1826 >= Build.VERSION_CODES.M) { 1827 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1828 } 1829 1830 final boolean update = res.removedInfo != null 1831 && res.removedInfo.removedPackage != null; 1832 1833 // If this is the first time we have child packages for a disabled privileged 1834 // app that had no children, we grant requested runtime permissions to the new 1835 // children if the parent on the system image had them already granted. 1836 if (res.pkg.parentPackage != null) { 1837 synchronized (mPackages) { 1838 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1839 } 1840 } 1841 1842 synchronized (mPackages) { 1843 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1844 } 1845 1846 final String packageName = res.pkg.applicationInfo.packageName; 1847 Bundle extras = new Bundle(1); 1848 extras.putInt(Intent.EXTRA_UID, res.uid); 1849 1850 // Determine the set of users who are adding this package for 1851 // the first time vs. those who are seeing an update. 1852 int[] firstUsers = EMPTY_INT_ARRAY; 1853 int[] updateUsers = EMPTY_INT_ARRAY; 1854 if (res.origUsers == null || res.origUsers.length == 0) { 1855 firstUsers = res.newUsers; 1856 } else { 1857 for (int newUser : res.newUsers) { 1858 boolean isNew = true; 1859 for (int origUser : res.origUsers) { 1860 if (origUser == newUser) { 1861 isNew = false; 1862 break; 1863 } 1864 } 1865 if (isNew) { 1866 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1867 } else { 1868 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1869 } 1870 } 1871 } 1872 1873 // Send installed broadcasts if the install/update is not ephemeral 1874 if (!isEphemeral(res.pkg)) { 1875 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1876 1877 // Send added for users that see the package for the first time 1878 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1879 extras, 0 /*flags*/, null /*targetPackage*/, 1880 null /*finishedReceiver*/, firstUsers); 1881 1882 // Send added for users that don't see the package for the first time 1883 if (update) { 1884 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1885 } 1886 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1887 extras, 0 /*flags*/, null /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 1890 // Send replaced for users that don't see the package for the first time 1891 if (update) { 1892 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1893 packageName, extras, 0 /*flags*/, 1894 null /*targetPackage*/, null /*finishedReceiver*/, 1895 updateUsers); 1896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1897 null /*package*/, null /*extras*/, 0 /*flags*/, 1898 packageName /*targetPackage*/, 1899 null /*finishedReceiver*/, updateUsers); 1900 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1901 // First-install and we did a restore, so we're responsible for the 1902 // first-launch broadcast. 1903 if (DEBUG_BACKUP) { 1904 Slog.i(TAG, "Post-restore of " + packageName 1905 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1906 } 1907 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1908 } 1909 1910 // Send broadcast package appeared if forward locked/external for all users 1911 // treat asec-hosted packages like removable media on upgrade 1912 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1913 if (DEBUG_INSTALL) { 1914 Slog.i(TAG, "upgrading pkg " + res.pkg 1915 + " is ASEC-hosted -> AVAILABLE"); 1916 } 1917 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1918 ArrayList<String> pkgList = new ArrayList<>(1); 1919 pkgList.add(packageName); 1920 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1921 } 1922 } 1923 1924 // Work that needs to happen on first install within each user 1925 if (firstUsers != null && firstUsers.length > 0) { 1926 synchronized (mPackages) { 1927 for (int userId : firstUsers) { 1928 // If this app is a browser and it's newly-installed for some 1929 // users, clear any default-browser state in those users. The 1930 // app's nature doesn't depend on the user, so we can just check 1931 // its browser nature in any user and generalize. 1932 if (packageIsBrowser(packageName, userId)) { 1933 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1934 } 1935 1936 // We may also need to apply pending (restored) runtime 1937 // permission grants within these users. 1938 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1939 } 1940 } 1941 } 1942 1943 // Log current value of "unknown sources" setting 1944 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1945 getUnknownSourcesSettings()); 1946 1947 // Force a gc to clear up things 1948 Runtime.getRuntime().gc(); 1949 1950 // Remove the replaced package's older resources safely now 1951 // We delete after a gc for applications on sdcard. 1952 if (res.removedInfo != null && res.removedInfo.args != null) { 1953 synchronized (mInstallLock) { 1954 res.removedInfo.args.doPostDeleteLI(true); 1955 } 1956 } 1957 } 1958 1959 // If someone is watching installs - notify them 1960 if (installObserver != null) { 1961 try { 1962 Bundle extras = extrasForInstallResult(res); 1963 installObserver.onPackageInstalled(res.name, res.returnCode, 1964 res.returnMsg, extras); 1965 } catch (RemoteException e) { 1966 Slog.i(TAG, "Observer no longer exists."); 1967 } 1968 } 1969 } 1970 1971 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1972 PackageParser.Package pkg) { 1973 if (pkg.parentPackage == null) { 1974 return; 1975 } 1976 if (pkg.requestedPermissions == null) { 1977 return; 1978 } 1979 final PackageSetting disabledSysParentPs = mSettings 1980 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1981 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1982 || !disabledSysParentPs.isPrivileged() 1983 || (disabledSysParentPs.childPackageNames != null 1984 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1985 return; 1986 } 1987 final int[] allUserIds = sUserManager.getUserIds(); 1988 final int permCount = pkg.requestedPermissions.size(); 1989 for (int i = 0; i < permCount; i++) { 1990 String permission = pkg.requestedPermissions.get(i); 1991 BasePermission bp = mSettings.mPermissions.get(permission); 1992 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1993 continue; 1994 } 1995 for (int userId : allUserIds) { 1996 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1997 permission, userId)) { 1998 grantRuntimePermission(pkg.packageName, permission, userId); 1999 } 2000 } 2001 } 2002 } 2003 2004 private StorageEventListener mStorageListener = new StorageEventListener() { 2005 @Override 2006 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2007 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2008 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2009 final String volumeUuid = vol.getFsUuid(); 2010 2011 // Clean up any users or apps that were removed or recreated 2012 // while this volume was missing 2013 reconcileUsers(volumeUuid); 2014 reconcileApps(volumeUuid); 2015 2016 // Clean up any install sessions that expired or were 2017 // cancelled while this volume was missing 2018 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2019 2020 loadPrivatePackages(vol); 2021 2022 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2023 unloadPrivatePackages(vol); 2024 } 2025 } 2026 2027 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2028 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2029 updateExternalMediaStatus(true, false); 2030 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2031 updateExternalMediaStatus(false, false); 2032 } 2033 } 2034 } 2035 2036 @Override 2037 public void onVolumeForgotten(String fsUuid) { 2038 if (TextUtils.isEmpty(fsUuid)) { 2039 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2040 return; 2041 } 2042 2043 // Remove any apps installed on the forgotten volume 2044 synchronized (mPackages) { 2045 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2046 for (PackageSetting ps : packages) { 2047 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2048 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2049 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2050 } 2051 2052 mSettings.onVolumeForgotten(fsUuid); 2053 mSettings.writeLPr(); 2054 } 2055 } 2056 }; 2057 2058 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2059 String[] grantedPermissions) { 2060 for (int userId : userIds) { 2061 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2062 } 2063 2064 // We could have touched GID membership, so flush out packages.list 2065 synchronized (mPackages) { 2066 mSettings.writePackageListLPr(); 2067 } 2068 } 2069 2070 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2071 String[] grantedPermissions) { 2072 SettingBase sb = (SettingBase) pkg.mExtras; 2073 if (sb == null) { 2074 return; 2075 } 2076 2077 PermissionsState permissionsState = sb.getPermissionsState(); 2078 2079 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2080 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2081 2082 for (String permission : pkg.requestedPermissions) { 2083 final BasePermission bp; 2084 synchronized (mPackages) { 2085 bp = mSettings.mPermissions.get(permission); 2086 } 2087 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2088 && (grantedPermissions == null 2089 || ArrayUtils.contains(grantedPermissions, permission))) { 2090 final int flags = permissionsState.getPermissionFlags(permission, userId); 2091 // Installer cannot change immutable permissions. 2092 if ((flags & immutableFlags) == 0) { 2093 grantRuntimePermission(pkg.packageName, permission, userId); 2094 } 2095 } 2096 } 2097 } 2098 2099 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2100 Bundle extras = null; 2101 switch (res.returnCode) { 2102 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2103 extras = new Bundle(); 2104 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2105 res.origPermission); 2106 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2107 res.origPackage); 2108 break; 2109 } 2110 case PackageManager.INSTALL_SUCCEEDED: { 2111 extras = new Bundle(); 2112 extras.putBoolean(Intent.EXTRA_REPLACING, 2113 res.removedInfo != null && res.removedInfo.removedPackage != null); 2114 break; 2115 } 2116 } 2117 return extras; 2118 } 2119 2120 void scheduleWriteSettingsLocked() { 2121 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2122 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2123 } 2124 } 2125 2126 void scheduleWritePackageListLocked(int userId) { 2127 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2128 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2129 msg.arg1 = userId; 2130 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2131 } 2132 } 2133 2134 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2135 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2136 scheduleWritePackageRestrictionsLocked(userId); 2137 } 2138 2139 void scheduleWritePackageRestrictionsLocked(int userId) { 2140 final int[] userIds = (userId == UserHandle.USER_ALL) 2141 ? sUserManager.getUserIds() : new int[]{userId}; 2142 for (int nextUserId : userIds) { 2143 if (!sUserManager.exists(nextUserId)) return; 2144 mDirtyUsers.add(nextUserId); 2145 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2146 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2147 } 2148 } 2149 } 2150 2151 public static PackageManagerService main(Context context, Installer installer, 2152 boolean factoryTest, boolean onlyCore) { 2153 // Self-check for initial settings. 2154 PackageManagerServiceCompilerMapping.checkProperties(); 2155 2156 PackageManagerService m = new PackageManagerService(context, installer, 2157 factoryTest, onlyCore); 2158 m.enableSystemUserPackages(); 2159 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2160 // disabled after already being started. 2161 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2162 UserHandle.USER_SYSTEM); 2163 ServiceManager.addService("package", m); 2164 return m; 2165 } 2166 2167 private void enableSystemUserPackages() { 2168 if (!UserManager.isSplitSystemUser()) { 2169 return; 2170 } 2171 // For system user, enable apps based on the following conditions: 2172 // - app is whitelisted or belong to one of these groups: 2173 // -- system app which has no launcher icons 2174 // -- system app which has INTERACT_ACROSS_USERS permission 2175 // -- system IME app 2176 // - app is not in the blacklist 2177 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2178 Set<String> enableApps = new ArraySet<>(); 2179 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2180 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2181 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2182 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2183 enableApps.addAll(wlApps); 2184 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2185 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2186 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2187 enableApps.removeAll(blApps); 2188 Log.i(TAG, "Applications installed for system user: " + enableApps); 2189 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2190 UserHandle.SYSTEM); 2191 final int allAppsSize = allAps.size(); 2192 synchronized (mPackages) { 2193 for (int i = 0; i < allAppsSize; i++) { 2194 String pName = allAps.get(i); 2195 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2196 // Should not happen, but we shouldn't be failing if it does 2197 if (pkgSetting == null) { 2198 continue; 2199 } 2200 boolean install = enableApps.contains(pName); 2201 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2202 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2203 + " for system user"); 2204 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2205 } 2206 } 2207 } 2208 } 2209 2210 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2211 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2212 Context.DISPLAY_SERVICE); 2213 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2214 } 2215 2216 public PackageManagerService(Context context, Installer installer, 2217 boolean factoryTest, boolean onlyCore) { 2218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2219 SystemClock.uptimeMillis()); 2220 2221 if (mSdkVersion <= 0) { 2222 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2223 } 2224 2225 mContext = context; 2226 mFactoryTest = factoryTest; 2227 mOnlyCore = onlyCore; 2228 mMetrics = new DisplayMetrics(); 2229 mSettings = new Settings(mPackages); 2230 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2231 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2232 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 2243 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2244 if (separateProcesses != null && separateProcesses.length() > 0) { 2245 if ("*".equals(separateProcesses)) { 2246 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2247 mSeparateProcesses = null; 2248 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2249 } else { 2250 mDefParseFlags = 0; 2251 mSeparateProcesses = separateProcesses.split(","); 2252 Slog.w(TAG, "Running with debug.separate_processes: " 2253 + separateProcesses); 2254 } 2255 } else { 2256 mDefParseFlags = 0; 2257 mSeparateProcesses = null; 2258 } 2259 2260 mInstaller = installer; 2261 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2262 "*dexopt*"); 2263 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2264 2265 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2266 FgThread.get().getLooper()); 2267 2268 getDefaultDisplayMetrics(context, mMetrics); 2269 2270 SystemConfig systemConfig = SystemConfig.getInstance(); 2271 mGlobalGids = systemConfig.getGlobalGids(); 2272 mSystemPermissions = systemConfig.getSystemPermissions(); 2273 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2274 2275 synchronized (mInstallLock) { 2276 // writer 2277 synchronized (mPackages) { 2278 mHandlerThread = new ServiceThread(TAG, 2279 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2280 mHandlerThread.start(); 2281 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2282 mProcessLoggingHandler = new ProcessLoggingHandler(); 2283 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2284 2285 File dataDir = Environment.getDataDirectory(); 2286 mAppInstallDir = new File(dataDir, "app"); 2287 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2288 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2289 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2290 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2291 2292 sUserManager = new UserManagerService(context, this, mPackages); 2293 2294 // Propagate permission configuration in to package manager. 2295 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2296 = systemConfig.getPermissions(); 2297 for (int i=0; i<permConfig.size(); i++) { 2298 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2299 BasePermission bp = mSettings.mPermissions.get(perm.name); 2300 if (bp == null) { 2301 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2302 mSettings.mPermissions.put(perm.name, bp); 2303 } 2304 if (perm.gids != null) { 2305 bp.setGids(perm.gids, perm.perUser); 2306 } 2307 } 2308 2309 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2310 for (int i=0; i<libConfig.size(); i++) { 2311 mSharedLibraries.put(libConfig.keyAt(i), 2312 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2313 } 2314 2315 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2316 2317 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2318 2319 String customResolverActivity = Resources.getSystem().getString( 2320 R.string.config_customResolverActivity); 2321 if (TextUtils.isEmpty(customResolverActivity)) { 2322 customResolverActivity = null; 2323 } else { 2324 mCustomResolverComponentName = ComponentName.unflattenFromString( 2325 customResolverActivity); 2326 } 2327 2328 long startTime = SystemClock.uptimeMillis(); 2329 2330 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2331 startTime); 2332 2333 // Set flag to monitor and not change apk file paths when 2334 // scanning install directories. 2335 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2336 2337 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2338 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2339 2340 if (bootClassPath == null) { 2341 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2342 } 2343 2344 if (systemServerClassPath == null) { 2345 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2346 } 2347 2348 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2349 final String[] dexCodeInstructionSets = 2350 getDexCodeInstructionSets( 2351 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2352 2353 /** 2354 * Ensure all external libraries have had dexopt run on them. 2355 */ 2356 if (mSharedLibraries.size() > 0) { 2357 // NOTE: For now, we're compiling these system "shared libraries" 2358 // (and framework jars) into all available architectures. It's possible 2359 // to compile them only when we come across an app that uses them (there's 2360 // already logic for that in scanPackageLI) but that adds some complexity. 2361 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2362 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2363 final String lib = libEntry.path; 2364 if (lib == null) { 2365 continue; 2366 } 2367 2368 try { 2369 // Shared libraries do not have profiles so we perform a full 2370 // AOT compilation (if needed). 2371 int dexoptNeeded = DexFile.getDexOptNeeded( 2372 lib, dexCodeInstructionSet, 2373 getCompilerFilterForReason(REASON_SHARED_APK), 2374 false /* newProfile */); 2375 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2376 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2377 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2378 getCompilerFilterForReason(REASON_SHARED_APK), 2379 StorageManager.UUID_PRIVATE_INTERNAL, 2380 SKIP_SHARED_LIBRARY_CHECK); 2381 } 2382 } catch (FileNotFoundException e) { 2383 Slog.w(TAG, "Library not found: " + lib); 2384 } catch (IOException | InstallerException e) { 2385 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2386 + e.getMessage()); 2387 } 2388 } 2389 } 2390 } 2391 2392 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2393 2394 final VersionInfo ver = mSettings.getInternalVersion(); 2395 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2396 2397 // when upgrading from pre-M, promote system app permissions from install to runtime 2398 mPromoteSystemApps = 2399 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2400 2401 // When upgrading from pre-N, we need to handle package extraction like first boot, 2402 // as there is no profiling data available. 2403 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2404 2405 // save off the names of pre-existing system packages prior to scanning; we don't 2406 // want to automatically grant runtime permissions for new system apps 2407 if (mPromoteSystemApps) { 2408 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2409 while (pkgSettingIter.hasNext()) { 2410 PackageSetting ps = pkgSettingIter.next(); 2411 if (isSystemApp(ps)) { 2412 mExistingSystemPackages.add(ps.name); 2413 } 2414 } 2415 } 2416 2417 // Collect vendor overlay packages. 2418 // (Do this before scanning any apps.) 2419 // For security and version matching reason, only consider 2420 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2421 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2422 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR 2425 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2426 2427 // Find base frameworks (resource packages without code). 2428 scanDirTracedLI(frameworkDir, mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_IS_PRIVILEGED, 2432 scanFlags | SCAN_NO_DEX, 0); 2433 2434 // Collected privileged system packages. 2435 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2436 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2440 2441 // Collect ordinary system packages. 2442 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2443 scanDirTracedLI(systemAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2446 2447 // Collect all vendor packages. 2448 File vendorAppDir = new File("/vendor/app"); 2449 try { 2450 vendorAppDir = vendorAppDir.getCanonicalFile(); 2451 } catch (IOException e) { 2452 // failed to look up canonical path, continue with original one 2453 } 2454 scanDirTracedLI(vendorAppDir, mDefParseFlags 2455 | PackageParser.PARSE_IS_SYSTEM 2456 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2457 2458 // Collect all OEM packages. 2459 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2460 scanDirTracedLI(oemAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Prune any system packages that no longer exist. 2465 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2466 if (!mOnlyCore) { 2467 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2468 while (psit.hasNext()) { 2469 PackageSetting ps = psit.next(); 2470 2471 /* 2472 * If this is not a system app, it can't be a 2473 * disable system app. 2474 */ 2475 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2476 continue; 2477 } 2478 2479 /* 2480 * If the package is scanned, it's not erased. 2481 */ 2482 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2483 if (scannedPkg != null) { 2484 /* 2485 * If the system app is both scanned and in the 2486 * disabled packages list, then it must have been 2487 * added via OTA. Remove it from the currently 2488 * scanned package so the previously user-installed 2489 * application can be scanned. 2490 */ 2491 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2492 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2493 + ps.name + "; removing system app. Last known codePath=" 2494 + ps.codePathString + ", installStatus=" + ps.installStatus 2495 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2496 + scannedPkg.mVersionCode); 2497 removePackageLI(scannedPkg, true); 2498 mExpectingBetter.put(ps.name, ps.codePath); 2499 } 2500 2501 continue; 2502 } 2503 2504 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2505 psit.remove(); 2506 logCriticalInfo(Log.WARN, "System package " + ps.name 2507 + " no longer exists; it's data will be wiped"); 2508 // Actual deletion of code and data will be handled by later 2509 // reconciliation step 2510 } else { 2511 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2512 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2513 possiblyDeletedUpdatedSystemApps.add(ps.name); 2514 } 2515 } 2516 } 2517 } 2518 2519 //look for any incomplete package installations 2520 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2521 for (int i = 0; i < deletePkgsList.size(); i++) { 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 final String packageName = deletePkgsList.get(i).name; 2525 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2526 synchronized (mPackages) { 2527 mSettings.removePackageLPw(packageName); 2528 } 2529 } 2530 2531 //delete tmp files 2532 deleteTempPackageFiles(); 2533 2534 // Remove any shared userIDs that have no associated packages 2535 mSettings.pruneSharedUsersLPw(); 2536 2537 if (!mOnlyCore) { 2538 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2539 SystemClock.uptimeMillis()); 2540 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2541 2542 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2543 | PackageParser.PARSE_FORWARD_LOCK, 2544 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2545 2546 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2547 | PackageParser.PARSE_IS_EPHEMERAL, 2548 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 /** 2551 * Remove disable package settings for any updated system 2552 * apps that were removed via an OTA. If they're not a 2553 * previously-updated app, remove them completely. 2554 * Otherwise, just revoke their system-level permissions. 2555 */ 2556 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2557 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2558 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2559 2560 String msg; 2561 if (deletedPkg == null) { 2562 msg = "Updated system package " + deletedAppName 2563 + " no longer exists; it's data will be wiped"; 2564 // Actual deletion of code and data will be handled by later 2565 // reconciliation step 2566 } else { 2567 msg = "Updated system app + " + deletedAppName 2568 + " no longer present; removing system privileges for " 2569 + deletedAppName; 2570 2571 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2572 2573 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2574 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2575 } 2576 logCriticalInfo(Log.WARN, msg); 2577 } 2578 2579 /** 2580 * Make sure all system apps that we expected to appear on 2581 * the userdata partition actually showed up. If they never 2582 * appeared, crawl back and revive the system version. 2583 */ 2584 for (int i = 0; i < mExpectingBetter.size(); i++) { 2585 final String packageName = mExpectingBetter.keyAt(i); 2586 if (!mPackages.containsKey(packageName)) { 2587 final File scanFile = mExpectingBetter.valueAt(i); 2588 2589 logCriticalInfo(Log.WARN, "Expected better " + packageName 2590 + " but never showed up; reverting to system"); 2591 2592 int reparseFlags = mDefParseFlags; 2593 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2594 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2595 | PackageParser.PARSE_IS_SYSTEM_DIR 2596 | PackageParser.PARSE_IS_PRIVILEGED; 2597 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2598 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR; 2600 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR; 2603 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR; 2606 } else { 2607 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2608 continue; 2609 } 2610 2611 mSettings.enableSystemPackageLPw(packageName); 2612 2613 try { 2614 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2615 } catch (PackageManagerException e) { 2616 Slog.e(TAG, "Failed to parse original system package: " 2617 + e.getMessage()); 2618 } 2619 } 2620 } 2621 } 2622 mExpectingBetter.clear(); 2623 2624 // Resolve protected action filters. Only the setup wizard is allowed to 2625 // have a high priority filter for these actions. 2626 mSetupWizardPackage = getSetupWizardPackageName(); 2627 if (mProtectedFilters.size() > 0) { 2628 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2629 Slog.i(TAG, "No setup wizard;" 2630 + " All protected intents capped to priority 0"); 2631 } 2632 for (ActivityIntentInfo filter : mProtectedFilters) { 2633 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2634 if (DEBUG_FILTERS) { 2635 Slog.i(TAG, "Found setup wizard;" 2636 + " allow priority " + filter.getPriority() + ";" 2637 + " package: " + filter.activity.info.packageName 2638 + " activity: " + filter.activity.className 2639 + " priority: " + filter.getPriority()); 2640 } 2641 // skip setup wizard; allow it to keep the high priority filter 2642 continue; 2643 } 2644 Slog.w(TAG, "Protected action; cap priority to 0;" 2645 + " package: " + filter.activity.info.packageName 2646 + " activity: " + filter.activity.className 2647 + " origPrio: " + filter.getPriority()); 2648 filter.setPriority(0); 2649 } 2650 } 2651 mDeferProtectedFilters = false; 2652 mProtectedFilters.clear(); 2653 2654 // Now that we know all of the shared libraries, update all clients to have 2655 // the correct library paths. 2656 updateAllSharedLibrariesLPw(); 2657 2658 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2659 // NOTE: We ignore potential failures here during a system scan (like 2660 // the rest of the commands above) because there's precious little we 2661 // can do about it. A settings error is reported, though. 2662 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2663 false /* boot complete */); 2664 } 2665 2666 // Now that we know all the packages we are keeping, 2667 // read and update their last usage times. 2668 mPackageUsage.readLP(); 2669 2670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2671 SystemClock.uptimeMillis()); 2672 Slog.i(TAG, "Time to scan packages: " 2673 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2674 + " seconds"); 2675 2676 // If the platform SDK has changed since the last time we booted, 2677 // we need to re-grant app permission to catch any new ones that 2678 // appear. This is really a hack, and means that apps can in some 2679 // cases get permissions that the user didn't initially explicitly 2680 // allow... it would be nice to have some better way to handle 2681 // this situation. 2682 int updateFlags = UPDATE_PERMISSIONS_ALL; 2683 if (ver.sdkVersion != mSdkVersion) { 2684 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2685 + mSdkVersion + "; regranting permissions for internal storage"); 2686 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2687 } 2688 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2689 ver.sdkVersion = mSdkVersion; 2690 2691 // If this is the first boot or an update from pre-M, and it is a normal 2692 // boot, then we need to initialize the default preferred apps across 2693 // all defined users. 2694 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2695 for (UserInfo user : sUserManager.getUsers(true)) { 2696 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2697 applyFactoryDefaultBrowserLPw(user.id); 2698 primeDomainVerificationsLPw(user.id); 2699 } 2700 } 2701 2702 // Prepare storage for system user really early during boot, 2703 // since core system apps like SettingsProvider and SystemUI 2704 // can't wait for user to start 2705 final int storageFlags; 2706 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE; 2708 } else { 2709 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2710 } 2711 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2712 storageFlags); 2713 2714 // If this is first boot after an OTA, and a normal boot, then 2715 // we need to clear code cache directories. 2716 // Note that we do *not* clear the application profiles. These remain valid 2717 // across OTAs and are used to drive profile verification (post OTA) and 2718 // profile compilation (without waiting to collect a fresh set of profiles). 2719 if (mIsUpgrade && !onlyCore) { 2720 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2721 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2722 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2723 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2724 // No apps are running this early, so no need to freeze 2725 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2726 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2727 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2728 } 2729 } 2730 ver.fingerprint = Build.FINGERPRINT; 2731 } 2732 2733 checkDefaultBrowser(); 2734 2735 // clear only after permissions and other defaults have been updated 2736 mExistingSystemPackages.clear(); 2737 mPromoteSystemApps = false; 2738 2739 // All the changes are done during package scanning. 2740 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2741 2742 // can downgrade to reader 2743 mSettings.writeLPr(); 2744 2745 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2746 // early on (before the package manager declares itself as early) because other 2747 // components in the system server might ask for package contexts for these apps. 2748 // 2749 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2750 // (i.e, that the data partition is unavailable). 2751 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2752 long start = System.nanoTime(); 2753 List<PackageParser.Package> coreApps = new ArrayList<>(); 2754 for (PackageParser.Package pkg : mPackages.values()) { 2755 if (pkg.coreApp) { 2756 coreApps.add(pkg); 2757 } 2758 } 2759 2760 int[] stats = performDexOpt(coreApps, false, 2761 getCompilerFilterForReason(REASON_CORE_APP)); 2762 2763 final int elapsedTimeSeconds = 2764 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2765 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2766 2767 if (DEBUG_DEXOPT) { 2768 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2769 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2770 } 2771 2772 2773 // TODO: Should we log these stats to tron too ? 2774 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2775 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2776 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2777 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2778 } 2779 2780 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2781 SystemClock.uptimeMillis()); 2782 2783 if (!mOnlyCore) { 2784 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2785 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2786 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2787 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2788 mIntentFilterVerifierComponent); 2789 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2790 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2791 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2792 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2793 } else { 2794 mRequiredVerifierPackage = null; 2795 mRequiredInstallerPackage = null; 2796 mIntentFilterVerifierComponent = null; 2797 mIntentFilterVerifier = null; 2798 mServicesSystemSharedLibraryPackageName = null; 2799 mSharedSystemSharedLibraryPackageName = null; 2800 } 2801 2802 mInstallerService = new PackageInstallerService(context, this); 2803 2804 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2805 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2806 // both the installer and resolver must be present to enable ephemeral 2807 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2808 if (DEBUG_EPHEMERAL) { 2809 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2810 + " installer:" + ephemeralInstallerComponent); 2811 } 2812 mEphemeralResolverComponent = ephemeralResolverComponent; 2813 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2814 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2815 mEphemeralResolverConnection = 2816 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2817 } else { 2818 if (DEBUG_EPHEMERAL) { 2819 final String missingComponent = 2820 (ephemeralResolverComponent == null) 2821 ? (ephemeralInstallerComponent == null) 2822 ? "resolver and installer" 2823 : "resolver" 2824 : "installer"; 2825 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2826 } 2827 mEphemeralResolverComponent = null; 2828 mEphemeralInstallerComponent = null; 2829 mEphemeralResolverConnection = null; 2830 } 2831 2832 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2833 } // synchronized (mPackages) 2834 } // synchronized (mInstallLock) 2835 2836 // Now after opening every single application zip, make sure they 2837 // are all flushed. Not really needed, but keeps things nice and 2838 // tidy. 2839 Runtime.getRuntime().gc(); 2840 2841 // The initial scanning above does many calls into installd while 2842 // holding the mPackages lock, but we're mostly interested in yelling 2843 // once we have a booted system. 2844 mInstaller.setWarnIfHeld(mPackages); 2845 2846 // Expose private service for system components to use. 2847 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2848 } 2849 2850 @Override 2851 public boolean isFirstBoot() { 2852 return !mRestoredSettings; 2853 } 2854 2855 @Override 2856 public boolean isOnlyCoreApps() { 2857 return mOnlyCore; 2858 } 2859 2860 @Override 2861 public boolean isUpgrade() { 2862 return mIsUpgrade; 2863 } 2864 2865 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2866 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2867 2868 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2869 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2870 UserHandle.USER_SYSTEM); 2871 if (matches.size() == 1) { 2872 return matches.get(0).getComponentInfo().packageName; 2873 } else { 2874 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2875 return null; 2876 } 2877 } 2878 2879 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2880 synchronized (mPackages) { 2881 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2882 if (libraryEntry == null) { 2883 throw new IllegalStateException("Missing required shared library:" + libraryName); 2884 } 2885 return libraryEntry.apk; 2886 } 2887 } 2888 2889 private @NonNull String getRequiredInstallerLPr() { 2890 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2891 intent.addCategory(Intent.CATEGORY_DEFAULT); 2892 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2893 2894 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2895 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2896 UserHandle.USER_SYSTEM); 2897 if (matches.size() == 1) { 2898 ResolveInfo resolveInfo = matches.get(0); 2899 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2900 throw new RuntimeException("The installer must be a privileged app"); 2901 } 2902 return matches.get(0).getComponentInfo().packageName; 2903 } else { 2904 throw new RuntimeException("There must be exactly one installer; found " + matches); 2905 } 2906 } 2907 2908 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2910 2911 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 ResolveInfo best = null; 2915 final int N = matches.size(); 2916 for (int i = 0; i < N; i++) { 2917 final ResolveInfo cur = matches.get(i); 2918 final String packageName = cur.getComponentInfo().packageName; 2919 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2920 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2921 continue; 2922 } 2923 2924 if (best == null || cur.priority > best.priority) { 2925 best = cur; 2926 } 2927 } 2928 2929 if (best != null) { 2930 return best.getComponentInfo().getComponentName(); 2931 } else { 2932 throw new RuntimeException("There must be at least one intent filter verifier"); 2933 } 2934 } 2935 2936 private @Nullable ComponentName getEphemeralResolverLPr() { 2937 final String[] packageArray = 2938 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2939 if (packageArray.length == 0) { 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2942 } 2943 return null; 2944 } 2945 2946 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2947 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2948 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2949 UserHandle.USER_SYSTEM); 2950 2951 final int N = resolvers.size(); 2952 if (N == 0) { 2953 if (DEBUG_EPHEMERAL) { 2954 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2955 } 2956 return null; 2957 } 2958 2959 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2960 for (int i = 0; i < N; i++) { 2961 final ResolveInfo info = resolvers.get(i); 2962 2963 if (info.serviceInfo == null) { 2964 continue; 2965 } 2966 2967 final String packageName = info.serviceInfo.packageName; 2968 if (!possiblePackages.contains(packageName)) { 2969 if (DEBUG_EPHEMERAL) { 2970 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2971 + " pkg: " + packageName + ", info:" + info); 2972 } 2973 continue; 2974 } 2975 2976 if (DEBUG_EPHEMERAL) { 2977 Slog.v(TAG, "Ephemeral resolver found;" 2978 + " pkg: " + packageName + ", info:" + info); 2979 } 2980 return new ComponentName(packageName, info.serviceInfo.name); 2981 } 2982 if (DEBUG_EPHEMERAL) { 2983 Slog.v(TAG, "Ephemeral resolver NOT found"); 2984 } 2985 return null; 2986 } 2987 2988 private @Nullable ComponentName getEphemeralInstallerLPr() { 2989 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2990 intent.addCategory(Intent.CATEGORY_DEFAULT); 2991 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2992 2993 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2994 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2995 UserHandle.USER_SYSTEM); 2996 if (matches.size() == 0) { 2997 return null; 2998 } else if (matches.size() == 1) { 2999 return matches.get(0).getComponentInfo().getComponentName(); 3000 } else { 3001 throw new RuntimeException( 3002 "There must be at most one ephemeral installer; found " + matches); 3003 } 3004 } 3005 3006 private void primeDomainVerificationsLPw(int userId) { 3007 if (DEBUG_DOMAIN_VERIFICATION) { 3008 Slog.d(TAG, "Priming domain verifications in user " + userId); 3009 } 3010 3011 SystemConfig systemConfig = SystemConfig.getInstance(); 3012 ArraySet<String> packages = systemConfig.getLinkedApps(); 3013 ArraySet<String> domains = new ArraySet<String>(); 3014 3015 for (String packageName : packages) { 3016 PackageParser.Package pkg = mPackages.get(packageName); 3017 if (pkg != null) { 3018 if (!pkg.isSystemApp()) { 3019 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3020 continue; 3021 } 3022 3023 domains.clear(); 3024 for (PackageParser.Activity a : pkg.activities) { 3025 for (ActivityIntentInfo filter : a.intents) { 3026 if (hasValidDomains(filter)) { 3027 domains.addAll(filter.getHostsList()); 3028 } 3029 } 3030 } 3031 3032 if (domains.size() > 0) { 3033 if (DEBUG_DOMAIN_VERIFICATION) { 3034 Slog.v(TAG, " + " + packageName); 3035 } 3036 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3037 // state w.r.t. the formal app-linkage "no verification attempted" state; 3038 // and then 'always' in the per-user state actually used for intent resolution. 3039 final IntentFilterVerificationInfo ivi; 3040 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3041 new ArrayList<String>(domains)); 3042 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3043 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3044 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3045 } else { 3046 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3047 + "' does not handle web links"); 3048 } 3049 } else { 3050 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3051 } 3052 } 3053 3054 scheduleWritePackageRestrictionsLocked(userId); 3055 scheduleWriteSettingsLocked(); 3056 } 3057 3058 private void applyFactoryDefaultBrowserLPw(int userId) { 3059 // The default browser app's package name is stored in a string resource, 3060 // with a product-specific overlay used for vendor customization. 3061 String browserPkg = mContext.getResources().getString( 3062 com.android.internal.R.string.default_browser); 3063 if (!TextUtils.isEmpty(browserPkg)) { 3064 // non-empty string => required to be a known package 3065 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3066 if (ps == null) { 3067 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3068 browserPkg = null; 3069 } else { 3070 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3071 } 3072 } 3073 3074 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3075 // default. If there's more than one, just leave everything alone. 3076 if (browserPkg == null) { 3077 calculateDefaultBrowserLPw(userId); 3078 } 3079 } 3080 3081 private void calculateDefaultBrowserLPw(int userId) { 3082 List<String> allBrowsers = resolveAllBrowserApps(userId); 3083 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3084 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3085 } 3086 3087 private List<String> resolveAllBrowserApps(int userId) { 3088 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3089 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3090 PackageManager.MATCH_ALL, userId); 3091 3092 final int count = list.size(); 3093 List<String> result = new ArrayList<String>(count); 3094 for (int i=0; i<count; i++) { 3095 ResolveInfo info = list.get(i); 3096 if (info.activityInfo == null 3097 || !info.handleAllWebDataURI 3098 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3099 || result.contains(info.activityInfo.packageName)) { 3100 continue; 3101 } 3102 result.add(info.activityInfo.packageName); 3103 } 3104 3105 return result; 3106 } 3107 3108 private boolean packageIsBrowser(String packageName, int userId) { 3109 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3110 PackageManager.MATCH_ALL, userId); 3111 final int N = list.size(); 3112 for (int i = 0; i < N; i++) { 3113 ResolveInfo info = list.get(i); 3114 if (packageName.equals(info.activityInfo.packageName)) { 3115 return true; 3116 } 3117 } 3118 return false; 3119 } 3120 3121 private void checkDefaultBrowser() { 3122 final int myUserId = UserHandle.myUserId(); 3123 final String packageName = getDefaultBrowserPackageName(myUserId); 3124 if (packageName != null) { 3125 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3126 if (info == null) { 3127 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3128 synchronized (mPackages) { 3129 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3130 } 3131 } 3132 } 3133 } 3134 3135 @Override 3136 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3137 throws RemoteException { 3138 try { 3139 return super.onTransact(code, data, reply, flags); 3140 } catch (RuntimeException e) { 3141 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3142 Slog.wtf(TAG, "Package Manager Crash", e); 3143 } 3144 throw e; 3145 } 3146 } 3147 3148 static int[] appendInts(int[] cur, int[] add) { 3149 if (add == null) return cur; 3150 if (cur == null) return add; 3151 final int N = add.length; 3152 for (int i=0; i<N; i++) { 3153 cur = appendInt(cur, add[i]); 3154 } 3155 return cur; 3156 } 3157 3158 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 if (ps == null) { 3161 return null; 3162 } 3163 final PackageParser.Package p = ps.pkg; 3164 if (p == null) { 3165 return null; 3166 } 3167 3168 final PermissionsState permissionsState = ps.getPermissionsState(); 3169 3170 final int[] gids = permissionsState.computeGids(userId); 3171 final Set<String> permissions = permissionsState.getPermissions(userId); 3172 final PackageUserState state = ps.readUserState(userId); 3173 3174 return PackageParser.generatePackageInfo(p, gids, flags, 3175 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3176 } 3177 3178 @Override 3179 public void checkPackageStartable(String packageName, int userId) { 3180 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3181 3182 synchronized (mPackages) { 3183 final PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps == null) { 3185 throw new SecurityException("Package " + packageName + " was not found!"); 3186 } 3187 3188 if (!ps.getInstalled(userId)) { 3189 throw new SecurityException( 3190 "Package " + packageName + " was not installed for user " + userId + "!"); 3191 } 3192 3193 if (mSafeMode && !ps.isSystem()) { 3194 throw new SecurityException("Package " + packageName + " not a system app!"); 3195 } 3196 3197 if (mFrozenPackages.contains(packageName)) { 3198 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3199 } 3200 3201 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3202 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3203 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3204 } 3205 } 3206 } 3207 3208 @Override 3209 public boolean isPackageAvailable(String packageName, int userId) { 3210 if (!sUserManager.exists(userId)) return false; 3211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3212 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3213 synchronized (mPackages) { 3214 PackageParser.Package p = mPackages.get(packageName); 3215 if (p != null) { 3216 final PackageSetting ps = (PackageSetting) p.mExtras; 3217 if (ps != null) { 3218 final PackageUserState state = ps.readUserState(userId); 3219 if (state != null) { 3220 return PackageParser.isAvailable(state); 3221 } 3222 } 3223 } 3224 } 3225 return false; 3226 } 3227 3228 @Override 3229 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return null; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3234 // reader 3235 synchronized (mPackages) { 3236 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3237 PackageParser.Package p = null; 3238 if (matchFactoryOnly) { 3239 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3240 if (ps != null) { 3241 return generatePackageInfo(ps, flags, userId); 3242 } 3243 } 3244 if (p == null) { 3245 p = mPackages.get(packageName); 3246 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3247 return null; 3248 } 3249 } 3250 if (DEBUG_PACKAGE_INFO) 3251 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3252 if (p != null) { 3253 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3254 } 3255 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3256 final PackageSetting ps = mSettings.mPackages.get(packageName); 3257 return generatePackageInfo(ps, flags, userId); 3258 } 3259 } 3260 return null; 3261 } 3262 3263 @Override 3264 public String[] currentToCanonicalPackageNames(String[] names) { 3265 String[] out = new String[names.length]; 3266 // reader 3267 synchronized (mPackages) { 3268 for (int i=names.length-1; i>=0; i--) { 3269 PackageSetting ps = mSettings.mPackages.get(names[i]); 3270 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3271 } 3272 } 3273 return out; 3274 } 3275 3276 @Override 3277 public String[] canonicalToCurrentPackageNames(String[] names) { 3278 String[] out = new String[names.length]; 3279 // reader 3280 synchronized (mPackages) { 3281 for (int i=names.length-1; i>=0; i--) { 3282 String cur = mSettings.mRenamedPackages.get(names[i]); 3283 out[i] = cur != null ? cur : names[i]; 3284 } 3285 } 3286 return out; 3287 } 3288 3289 @Override 3290 public int getPackageUid(String packageName, int flags, int userId) { 3291 if (!sUserManager.exists(userId)) return -1; 3292 flags = updateFlagsForPackage(flags, userId, packageName); 3293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3294 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3295 3296 // reader 3297 synchronized (mPackages) { 3298 final PackageParser.Package p = mPackages.get(packageName); 3299 if (p != null && p.isMatch(flags)) { 3300 return UserHandle.getUid(userId, p.applicationInfo.uid); 3301 } 3302 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3303 final PackageSetting ps = mSettings.mPackages.get(packageName); 3304 if (ps != null && ps.isMatch(flags)) { 3305 return UserHandle.getUid(userId, ps.appId); 3306 } 3307 } 3308 } 3309 3310 return -1; 3311 } 3312 3313 @Override 3314 public int[] getPackageGids(String packageName, int flags, int userId) { 3315 if (!sUserManager.exists(userId)) return null; 3316 flags = updateFlagsForPackage(flags, userId, packageName); 3317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3318 false /* requireFullPermission */, false /* checkShell */, 3319 "getPackageGids"); 3320 3321 // reader 3322 synchronized (mPackages) { 3323 final PackageParser.Package p = mPackages.get(packageName); 3324 if (p != null && p.isMatch(flags)) { 3325 PackageSetting ps = (PackageSetting) p.mExtras; 3326 return ps.getPermissionsState().computeGids(userId); 3327 } 3328 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3329 final PackageSetting ps = mSettings.mPackages.get(packageName); 3330 if (ps != null && ps.isMatch(flags)) { 3331 return ps.getPermissionsState().computeGids(userId); 3332 } 3333 } 3334 } 3335 3336 return null; 3337 } 3338 3339 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3340 if (bp.perm != null) { 3341 return PackageParser.generatePermissionInfo(bp.perm, flags); 3342 } 3343 PermissionInfo pi = new PermissionInfo(); 3344 pi.name = bp.name; 3345 pi.packageName = bp.sourcePackage; 3346 pi.nonLocalizedLabel = bp.name; 3347 pi.protectionLevel = bp.protectionLevel; 3348 return pi; 3349 } 3350 3351 @Override 3352 public PermissionInfo getPermissionInfo(String name, int flags) { 3353 // reader 3354 synchronized (mPackages) { 3355 final BasePermission p = mSettings.mPermissions.get(name); 3356 if (p != null) { 3357 return generatePermissionInfo(p, flags); 3358 } 3359 return null; 3360 } 3361 } 3362 3363 @Override 3364 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3365 int flags) { 3366 // reader 3367 synchronized (mPackages) { 3368 if (group != null && !mPermissionGroups.containsKey(group)) { 3369 // This is thrown as NameNotFoundException 3370 return null; 3371 } 3372 3373 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3374 for (BasePermission p : mSettings.mPermissions.values()) { 3375 if (group == null) { 3376 if (p.perm == null || p.perm.info.group == null) { 3377 out.add(generatePermissionInfo(p, flags)); 3378 } 3379 } else { 3380 if (p.perm != null && group.equals(p.perm.info.group)) { 3381 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3382 } 3383 } 3384 } 3385 return new ParceledListSlice<>(out); 3386 } 3387 } 3388 3389 @Override 3390 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3391 // reader 3392 synchronized (mPackages) { 3393 return PackageParser.generatePermissionGroupInfo( 3394 mPermissionGroups.get(name), flags); 3395 } 3396 } 3397 3398 @Override 3399 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3400 // reader 3401 synchronized (mPackages) { 3402 final int N = mPermissionGroups.size(); 3403 ArrayList<PermissionGroupInfo> out 3404 = new ArrayList<PermissionGroupInfo>(N); 3405 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3406 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3407 } 3408 return new ParceledListSlice<>(out); 3409 } 3410 } 3411 3412 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3413 int userId) { 3414 if (!sUserManager.exists(userId)) return null; 3415 PackageSetting ps = mSettings.mPackages.get(packageName); 3416 if (ps != null) { 3417 if (ps.pkg == null) { 3418 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3419 if (pInfo != null) { 3420 return pInfo.applicationInfo; 3421 } 3422 return null; 3423 } 3424 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3425 ps.readUserState(userId), userId); 3426 } 3427 return null; 3428 } 3429 3430 @Override 3431 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3432 if (!sUserManager.exists(userId)) return null; 3433 flags = updateFlagsForApplication(flags, userId, packageName); 3434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3435 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3436 // writer 3437 synchronized (mPackages) { 3438 PackageParser.Package p = mPackages.get(packageName); 3439 if (DEBUG_PACKAGE_INFO) Log.v( 3440 TAG, "getApplicationInfo " + packageName 3441 + ": " + p); 3442 if (p != null) { 3443 PackageSetting ps = mSettings.mPackages.get(packageName); 3444 if (ps == null) return null; 3445 // Note: isEnabledLP() does not apply here - always return info 3446 return PackageParser.generateApplicationInfo( 3447 p, flags, ps.readUserState(userId), userId); 3448 } 3449 if ("android".equals(packageName)||"system".equals(packageName)) { 3450 return mAndroidApplication; 3451 } 3452 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3453 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3461 final IPackageDataObserver observer) { 3462 mContext.enforceCallingOrSelfPermission( 3463 android.Manifest.permission.CLEAR_APP_CACHE, null); 3464 // Queue up an async operation since clearing cache may take a little while. 3465 mHandler.post(new Runnable() { 3466 public void run() { 3467 mHandler.removeCallbacks(this); 3468 boolean success = true; 3469 synchronized (mInstallLock) { 3470 try { 3471 mInstaller.freeCache(volumeUuid, freeStorageSize); 3472 } catch (InstallerException e) { 3473 Slog.w(TAG, "Couldn't clear application caches: " + e); 3474 success = false; 3475 } 3476 } 3477 if (observer != null) { 3478 try { 3479 observer.onRemoveCompleted(null, success); 3480 } catch (RemoteException e) { 3481 Slog.w(TAG, "RemoveException when invoking call back"); 3482 } 3483 } 3484 } 3485 }); 3486 } 3487 3488 @Override 3489 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3490 final IntentSender pi) { 3491 mContext.enforceCallingOrSelfPermission( 3492 android.Manifest.permission.CLEAR_APP_CACHE, null); 3493 // Queue up an async operation since clearing cache may take a little while. 3494 mHandler.post(new Runnable() { 3495 public void run() { 3496 mHandler.removeCallbacks(this); 3497 boolean success = true; 3498 synchronized (mInstallLock) { 3499 try { 3500 mInstaller.freeCache(volumeUuid, freeStorageSize); 3501 } catch (InstallerException e) { 3502 Slog.w(TAG, "Couldn't clear application caches: " + e); 3503 success = false; 3504 } 3505 } 3506 if(pi != null) { 3507 try { 3508 // Callback via pending intent 3509 int code = success ? 1 : 0; 3510 pi.sendIntent(null, code, null, 3511 null, null); 3512 } catch (SendIntentException e1) { 3513 Slog.i(TAG, "Failed to send pending intent"); 3514 } 3515 } 3516 } 3517 }); 3518 } 3519 3520 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3521 synchronized (mInstallLock) { 3522 try { 3523 mInstaller.freeCache(volumeUuid, freeStorageSize); 3524 } catch (InstallerException e) { 3525 throw new IOException("Failed to free enough space", e); 3526 } 3527 } 3528 } 3529 3530 /** 3531 * Update given flags based on encryption status of current user. 3532 */ 3533 private int updateFlags(int flags, int userId) { 3534 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3535 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3536 // Caller expressed an explicit opinion about what encryption 3537 // aware/unaware components they want to see, so fall through and 3538 // give them what they want 3539 } else { 3540 // Caller expressed no opinion, so match based on user state 3541 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3542 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3543 } else { 3544 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3545 } 3546 } 3547 return flags; 3548 } 3549 3550 private UserManagerInternal getUserManagerInternal() { 3551 if (mUserManagerInternal == null) { 3552 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3553 } 3554 return mUserManagerInternal; 3555 } 3556 3557 /** 3558 * Update given flags when being used to request {@link PackageInfo}. 3559 */ 3560 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3561 boolean triaged = true; 3562 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3563 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3564 // Caller is asking for component details, so they'd better be 3565 // asking for specific encryption matching behavior, or be triaged 3566 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3567 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3568 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3569 triaged = false; 3570 } 3571 } 3572 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3573 | PackageManager.MATCH_SYSTEM_ONLY 3574 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3575 triaged = false; 3576 } 3577 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3578 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3579 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3580 } 3581 return updateFlags(flags, userId); 3582 } 3583 3584 /** 3585 * Update given flags when being used to request {@link ApplicationInfo}. 3586 */ 3587 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3588 return updateFlagsForPackage(flags, userId, cookie); 3589 } 3590 3591 /** 3592 * Update given flags when being used to request {@link ComponentInfo}. 3593 */ 3594 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3595 if (cookie instanceof Intent) { 3596 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3597 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3598 } 3599 } 3600 3601 boolean triaged = true; 3602 // Caller is asking for component details, so they'd better be 3603 // asking for specific encryption matching behavior, or be triaged 3604 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3605 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3606 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3607 triaged = false; 3608 } 3609 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3610 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3611 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3612 } 3613 3614 return updateFlags(flags, userId); 3615 } 3616 3617 /** 3618 * Update given flags when being used to request {@link ResolveInfo}. 3619 */ 3620 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3621 // Safe mode means we shouldn't match any third-party components 3622 if (mSafeMode) { 3623 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3624 } 3625 3626 return updateFlagsForComponent(flags, userId, cookie); 3627 } 3628 3629 @Override 3630 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3631 if (!sUserManager.exists(userId)) return null; 3632 flags = updateFlagsForComponent(flags, userId, component); 3633 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3634 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3635 synchronized (mPackages) { 3636 PackageParser.Activity a = mActivities.mActivities.get(component); 3637 3638 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3639 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3640 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3641 if (ps == null) return null; 3642 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3643 userId); 3644 } 3645 if (mResolveComponentName.equals(component)) { 3646 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3647 new PackageUserState(), userId); 3648 } 3649 } 3650 return null; 3651 } 3652 3653 @Override 3654 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3655 String resolvedType) { 3656 synchronized (mPackages) { 3657 if (component.equals(mResolveComponentName)) { 3658 // The resolver supports EVERYTHING! 3659 return true; 3660 } 3661 PackageParser.Activity a = mActivities.mActivities.get(component); 3662 if (a == null) { 3663 return false; 3664 } 3665 for (int i=0; i<a.intents.size(); i++) { 3666 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3667 intent.getData(), intent.getCategories(), TAG) >= 0) { 3668 return true; 3669 } 3670 } 3671 return false; 3672 } 3673 } 3674 3675 @Override 3676 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3677 if (!sUserManager.exists(userId)) return null; 3678 flags = updateFlagsForComponent(flags, userId, component); 3679 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3680 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3681 synchronized (mPackages) { 3682 PackageParser.Activity a = mReceivers.mActivities.get(component); 3683 if (DEBUG_PACKAGE_INFO) Log.v( 3684 TAG, "getReceiverInfo " + component + ": " + a); 3685 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3686 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3687 if (ps == null) return null; 3688 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3689 userId); 3690 } 3691 } 3692 return null; 3693 } 3694 3695 @Override 3696 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3697 if (!sUserManager.exists(userId)) return null; 3698 flags = updateFlagsForComponent(flags, userId, component); 3699 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3700 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3701 synchronized (mPackages) { 3702 PackageParser.Service s = mServices.mServices.get(component); 3703 if (DEBUG_PACKAGE_INFO) Log.v( 3704 TAG, "getServiceInfo " + component + ": " + s); 3705 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3706 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3707 if (ps == null) return null; 3708 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3709 userId); 3710 } 3711 } 3712 return null; 3713 } 3714 3715 @Override 3716 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return null; 3718 flags = updateFlagsForComponent(flags, userId, component); 3719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3720 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3721 synchronized (mPackages) { 3722 PackageParser.Provider p = mProviders.mProviders.get(component); 3723 if (DEBUG_PACKAGE_INFO) Log.v( 3724 TAG, "getProviderInfo " + component + ": " + p); 3725 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3726 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3727 if (ps == null) return null; 3728 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3729 userId); 3730 } 3731 } 3732 return null; 3733 } 3734 3735 @Override 3736 public String[] getSystemSharedLibraryNames() { 3737 Set<String> libSet; 3738 synchronized (mPackages) { 3739 libSet = mSharedLibraries.keySet(); 3740 int size = libSet.size(); 3741 if (size > 0) { 3742 String[] libs = new String[size]; 3743 libSet.toArray(libs); 3744 return libs; 3745 } 3746 } 3747 return null; 3748 } 3749 3750 @Override 3751 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3752 synchronized (mPackages) { 3753 return mServicesSystemSharedLibraryPackageName; 3754 } 3755 } 3756 3757 @Override 3758 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3759 synchronized (mPackages) { 3760 return mSharedSystemSharedLibraryPackageName; 3761 } 3762 } 3763 3764 @Override 3765 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3766 synchronized (mPackages) { 3767 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3768 3769 final FeatureInfo fi = new FeatureInfo(); 3770 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3771 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3772 res.add(fi); 3773 3774 return new ParceledListSlice<>(res); 3775 } 3776 } 3777 3778 @Override 3779 public boolean hasSystemFeature(String name, int version) { 3780 synchronized (mPackages) { 3781 final FeatureInfo feat = mAvailableFeatures.get(name); 3782 if (feat == null) { 3783 return false; 3784 } else { 3785 return feat.version >= version; 3786 } 3787 } 3788 } 3789 3790 @Override 3791 public int checkPermission(String permName, String pkgName, int userId) { 3792 if (!sUserManager.exists(userId)) { 3793 return PackageManager.PERMISSION_DENIED; 3794 } 3795 3796 synchronized (mPackages) { 3797 final PackageParser.Package p = mPackages.get(pkgName); 3798 if (p != null && p.mExtras != null) { 3799 final PackageSetting ps = (PackageSetting) p.mExtras; 3800 final PermissionsState permissionsState = ps.getPermissionsState(); 3801 if (permissionsState.hasPermission(permName, userId)) { 3802 return PackageManager.PERMISSION_GRANTED; 3803 } 3804 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3805 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3806 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3807 return PackageManager.PERMISSION_GRANTED; 3808 } 3809 } 3810 } 3811 3812 return PackageManager.PERMISSION_DENIED; 3813 } 3814 3815 @Override 3816 public int checkUidPermission(String permName, int uid) { 3817 final int userId = UserHandle.getUserId(uid); 3818 3819 if (!sUserManager.exists(userId)) { 3820 return PackageManager.PERMISSION_DENIED; 3821 } 3822 3823 synchronized (mPackages) { 3824 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3825 if (obj != null) { 3826 final SettingBase ps = (SettingBase) obj; 3827 final PermissionsState permissionsState = ps.getPermissionsState(); 3828 if (permissionsState.hasPermission(permName, userId)) { 3829 return PackageManager.PERMISSION_GRANTED; 3830 } 3831 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3832 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3833 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3834 return PackageManager.PERMISSION_GRANTED; 3835 } 3836 } else { 3837 ArraySet<String> perms = mSystemPermissions.get(uid); 3838 if (perms != null) { 3839 if (perms.contains(permName)) { 3840 return PackageManager.PERMISSION_GRANTED; 3841 } 3842 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3843 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3844 return PackageManager.PERMISSION_GRANTED; 3845 } 3846 } 3847 } 3848 } 3849 3850 return PackageManager.PERMISSION_DENIED; 3851 } 3852 3853 @Override 3854 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3855 if (UserHandle.getCallingUserId() != userId) { 3856 mContext.enforceCallingPermission( 3857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3858 "isPermissionRevokedByPolicy for user " + userId); 3859 } 3860 3861 if (checkPermission(permission, packageName, userId) 3862 == PackageManager.PERMISSION_GRANTED) { 3863 return false; 3864 } 3865 3866 final long identity = Binder.clearCallingIdentity(); 3867 try { 3868 final int flags = getPermissionFlags(permission, packageName, userId); 3869 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3870 } finally { 3871 Binder.restoreCallingIdentity(identity); 3872 } 3873 } 3874 3875 @Override 3876 public String getPermissionControllerPackageName() { 3877 synchronized (mPackages) { 3878 return mRequiredInstallerPackage; 3879 } 3880 } 3881 3882 /** 3883 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3884 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3885 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3886 * @param message the message to log on security exception 3887 */ 3888 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3889 boolean checkShell, String message) { 3890 if (userId < 0) { 3891 throw new IllegalArgumentException("Invalid userId " + userId); 3892 } 3893 if (checkShell) { 3894 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3895 } 3896 if (userId == UserHandle.getUserId(callingUid)) return; 3897 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3898 if (requireFullPermission) { 3899 mContext.enforceCallingOrSelfPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3901 } else { 3902 try { 3903 mContext.enforceCallingOrSelfPermission( 3904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3905 } catch (SecurityException se) { 3906 mContext.enforceCallingOrSelfPermission( 3907 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3908 } 3909 } 3910 } 3911 } 3912 3913 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3914 if (callingUid == Process.SHELL_UID) { 3915 if (userHandle >= 0 3916 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3917 throw new SecurityException("Shell does not have permission to access user " 3918 + userHandle); 3919 } else if (userHandle < 0) { 3920 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3921 + Debug.getCallers(3)); 3922 } 3923 } 3924 } 3925 3926 private BasePermission findPermissionTreeLP(String permName) { 3927 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3928 if (permName.startsWith(bp.name) && 3929 permName.length() > bp.name.length() && 3930 permName.charAt(bp.name.length()) == '.') { 3931 return bp; 3932 } 3933 } 3934 return null; 3935 } 3936 3937 private BasePermission checkPermissionTreeLP(String permName) { 3938 if (permName != null) { 3939 BasePermission bp = findPermissionTreeLP(permName); 3940 if (bp != null) { 3941 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3942 return bp; 3943 } 3944 throw new SecurityException("Calling uid " 3945 + Binder.getCallingUid() 3946 + " is not allowed to add to permission tree " 3947 + bp.name + " owned by uid " + bp.uid); 3948 } 3949 } 3950 throw new SecurityException("No permission tree found for " + permName); 3951 } 3952 3953 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3954 if (s1 == null) { 3955 return s2 == null; 3956 } 3957 if (s2 == null) { 3958 return false; 3959 } 3960 if (s1.getClass() != s2.getClass()) { 3961 return false; 3962 } 3963 return s1.equals(s2); 3964 } 3965 3966 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3967 if (pi1.icon != pi2.icon) return false; 3968 if (pi1.logo != pi2.logo) return false; 3969 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3970 if (!compareStrings(pi1.name, pi2.name)) return false; 3971 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3972 // We'll take care of setting this one. 3973 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3974 // These are not currently stored in settings. 3975 //if (!compareStrings(pi1.group, pi2.group)) return false; 3976 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3977 //if (pi1.labelRes != pi2.labelRes) return false; 3978 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3979 return true; 3980 } 3981 3982 int permissionInfoFootprint(PermissionInfo info) { 3983 int size = info.name.length(); 3984 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3985 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3986 return size; 3987 } 3988 3989 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3990 int size = 0; 3991 for (BasePermission perm : mSettings.mPermissions.values()) { 3992 if (perm.uid == tree.uid) { 3993 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3994 } 3995 } 3996 return size; 3997 } 3998 3999 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4000 // We calculate the max size of permissions defined by this uid and throw 4001 // if that plus the size of 'info' would exceed our stated maximum. 4002 if (tree.uid != Process.SYSTEM_UID) { 4003 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4004 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4005 throw new SecurityException("Permission tree size cap exceeded"); 4006 } 4007 } 4008 } 4009 4010 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4011 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4012 throw new SecurityException("Label must be specified in permission"); 4013 } 4014 BasePermission tree = checkPermissionTreeLP(info.name); 4015 BasePermission bp = mSettings.mPermissions.get(info.name); 4016 boolean added = bp == null; 4017 boolean changed = true; 4018 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4019 if (added) { 4020 enforcePermissionCapLocked(info, tree); 4021 bp = new BasePermission(info.name, tree.sourcePackage, 4022 BasePermission.TYPE_DYNAMIC); 4023 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4024 throw new SecurityException( 4025 "Not allowed to modify non-dynamic permission " 4026 + info.name); 4027 } else { 4028 if (bp.protectionLevel == fixedLevel 4029 && bp.perm.owner.equals(tree.perm.owner) 4030 && bp.uid == tree.uid 4031 && comparePermissionInfos(bp.perm.info, info)) { 4032 changed = false; 4033 } 4034 } 4035 bp.protectionLevel = fixedLevel; 4036 info = new PermissionInfo(info); 4037 info.protectionLevel = fixedLevel; 4038 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4039 bp.perm.info.packageName = tree.perm.info.packageName; 4040 bp.uid = tree.uid; 4041 if (added) { 4042 mSettings.mPermissions.put(info.name, bp); 4043 } 4044 if (changed) { 4045 if (!async) { 4046 mSettings.writeLPr(); 4047 } else { 4048 scheduleWriteSettingsLocked(); 4049 } 4050 } 4051 return added; 4052 } 4053 4054 @Override 4055 public boolean addPermission(PermissionInfo info) { 4056 synchronized (mPackages) { 4057 return addPermissionLocked(info, false); 4058 } 4059 } 4060 4061 @Override 4062 public boolean addPermissionAsync(PermissionInfo info) { 4063 synchronized (mPackages) { 4064 return addPermissionLocked(info, true); 4065 } 4066 } 4067 4068 @Override 4069 public void removePermission(String name) { 4070 synchronized (mPackages) { 4071 checkPermissionTreeLP(name); 4072 BasePermission bp = mSettings.mPermissions.get(name); 4073 if (bp != null) { 4074 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4075 throw new SecurityException( 4076 "Not allowed to modify non-dynamic permission " 4077 + name); 4078 } 4079 mSettings.mPermissions.remove(name); 4080 mSettings.writeLPr(); 4081 } 4082 } 4083 } 4084 4085 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4086 BasePermission bp) { 4087 int index = pkg.requestedPermissions.indexOf(bp.name); 4088 if (index == -1) { 4089 throw new SecurityException("Package " + pkg.packageName 4090 + " has not requested permission " + bp.name); 4091 } 4092 if (!bp.isRuntime() && !bp.isDevelopment()) { 4093 throw new SecurityException("Permission " + bp.name 4094 + " is not a changeable permission type"); 4095 } 4096 } 4097 4098 @Override 4099 public void grantRuntimePermission(String packageName, String name, final int userId) { 4100 if (!sUserManager.exists(userId)) { 4101 Log.e(TAG, "No such user:" + userId); 4102 return; 4103 } 4104 4105 mContext.enforceCallingOrSelfPermission( 4106 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4107 "grantRuntimePermission"); 4108 4109 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4110 true /* requireFullPermission */, true /* checkShell */, 4111 "grantRuntimePermission"); 4112 4113 final int uid; 4114 final SettingBase sb; 4115 4116 synchronized (mPackages) { 4117 final PackageParser.Package pkg = mPackages.get(packageName); 4118 if (pkg == null) { 4119 throw new IllegalArgumentException("Unknown package: " + packageName); 4120 } 4121 4122 final BasePermission bp = mSettings.mPermissions.get(name); 4123 if (bp == null) { 4124 throw new IllegalArgumentException("Unknown permission: " + name); 4125 } 4126 4127 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4128 4129 // If a permission review is required for legacy apps we represent 4130 // their permissions as always granted runtime ones since we need 4131 // to keep the review required permission flag per user while an 4132 // install permission's state is shared across all users. 4133 if (Build.PERMISSIONS_REVIEW_REQUIRED 4134 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4135 && bp.isRuntime()) { 4136 return; 4137 } 4138 4139 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4140 sb = (SettingBase) pkg.mExtras; 4141 if (sb == null) { 4142 throw new IllegalArgumentException("Unknown package: " + packageName); 4143 } 4144 4145 final PermissionsState permissionsState = sb.getPermissionsState(); 4146 4147 final int flags = permissionsState.getPermissionFlags(name, userId); 4148 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4149 throw new SecurityException("Cannot grant system fixed permission " 4150 + name + " for package " + packageName); 4151 } 4152 4153 if (bp.isDevelopment()) { 4154 // Development permissions must be handled specially, since they are not 4155 // normal runtime permissions. For now they apply to all users. 4156 if (permissionsState.grantInstallPermission(bp) != 4157 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4158 scheduleWriteSettingsLocked(); 4159 } 4160 return; 4161 } 4162 4163 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4164 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4165 return; 4166 } 4167 4168 final int result = permissionsState.grantRuntimePermission(bp, userId); 4169 switch (result) { 4170 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4171 return; 4172 } 4173 4174 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4175 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4176 mHandler.post(new Runnable() { 4177 @Override 4178 public void run() { 4179 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4180 } 4181 }); 4182 } 4183 break; 4184 } 4185 4186 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4187 4188 // Not critical if that is lost - app has to request again. 4189 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4190 } 4191 4192 // Only need to do this if user is initialized. Otherwise it's a new user 4193 // and there are no processes running as the user yet and there's no need 4194 // to make an expensive call to remount processes for the changed permissions. 4195 if (READ_EXTERNAL_STORAGE.equals(name) 4196 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4197 final long token = Binder.clearCallingIdentity(); 4198 try { 4199 if (sUserManager.isInitialized(userId)) { 4200 MountServiceInternal mountServiceInternal = LocalServices.getService( 4201 MountServiceInternal.class); 4202 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4203 } 4204 } finally { 4205 Binder.restoreCallingIdentity(token); 4206 } 4207 } 4208 } 4209 4210 @Override 4211 public void revokeRuntimePermission(String packageName, String name, int userId) { 4212 if (!sUserManager.exists(userId)) { 4213 Log.e(TAG, "No such user:" + userId); 4214 return; 4215 } 4216 4217 mContext.enforceCallingOrSelfPermission( 4218 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4219 "revokeRuntimePermission"); 4220 4221 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4222 true /* requireFullPermission */, true /* checkShell */, 4223 "revokeRuntimePermission"); 4224 4225 final int appId; 4226 4227 synchronized (mPackages) { 4228 final PackageParser.Package pkg = mPackages.get(packageName); 4229 if (pkg == null) { 4230 throw new IllegalArgumentException("Unknown package: " + packageName); 4231 } 4232 4233 final BasePermission bp = mSettings.mPermissions.get(name); 4234 if (bp == null) { 4235 throw new IllegalArgumentException("Unknown permission: " + name); 4236 } 4237 4238 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4239 4240 // If a permission review is required for legacy apps we represent 4241 // their permissions as always granted runtime ones since we need 4242 // to keep the review required permission flag per user while an 4243 // install permission's state is shared across all users. 4244 if (Build.PERMISSIONS_REVIEW_REQUIRED 4245 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4246 && bp.isRuntime()) { 4247 return; 4248 } 4249 4250 SettingBase sb = (SettingBase) pkg.mExtras; 4251 if (sb == null) { 4252 throw new IllegalArgumentException("Unknown package: " + packageName); 4253 } 4254 4255 final PermissionsState permissionsState = sb.getPermissionsState(); 4256 4257 final int flags = permissionsState.getPermissionFlags(name, userId); 4258 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4259 throw new SecurityException("Cannot revoke system fixed permission " 4260 + name + " for package " + packageName); 4261 } 4262 4263 if (bp.isDevelopment()) { 4264 // Development permissions must be handled specially, since they are not 4265 // normal runtime permissions. For now they apply to all users. 4266 if (permissionsState.revokeInstallPermission(bp) != 4267 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4268 scheduleWriteSettingsLocked(); 4269 } 4270 return; 4271 } 4272 4273 if (permissionsState.revokeRuntimePermission(bp, userId) == 4274 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4275 return; 4276 } 4277 4278 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4279 4280 // Critical, after this call app should never have the permission. 4281 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4282 4283 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4284 } 4285 4286 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4287 } 4288 4289 @Override 4290 public void resetRuntimePermissions() { 4291 mContext.enforceCallingOrSelfPermission( 4292 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4293 "revokeRuntimePermission"); 4294 4295 int callingUid = Binder.getCallingUid(); 4296 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4297 mContext.enforceCallingOrSelfPermission( 4298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4299 "resetRuntimePermissions"); 4300 } 4301 4302 synchronized (mPackages) { 4303 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4304 for (int userId : UserManagerService.getInstance().getUserIds()) { 4305 final int packageCount = mPackages.size(); 4306 for (int i = 0; i < packageCount; i++) { 4307 PackageParser.Package pkg = mPackages.valueAt(i); 4308 if (!(pkg.mExtras instanceof PackageSetting)) { 4309 continue; 4310 } 4311 PackageSetting ps = (PackageSetting) pkg.mExtras; 4312 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4313 } 4314 } 4315 } 4316 } 4317 4318 @Override 4319 public int getPermissionFlags(String name, String packageName, int userId) { 4320 if (!sUserManager.exists(userId)) { 4321 return 0; 4322 } 4323 4324 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4325 4326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4327 true /* requireFullPermission */, false /* checkShell */, 4328 "getPermissionFlags"); 4329 4330 synchronized (mPackages) { 4331 final PackageParser.Package pkg = mPackages.get(packageName); 4332 if (pkg == null) { 4333 return 0; 4334 } 4335 4336 final BasePermission bp = mSettings.mPermissions.get(name); 4337 if (bp == null) { 4338 return 0; 4339 } 4340 4341 SettingBase sb = (SettingBase) pkg.mExtras; 4342 if (sb == null) { 4343 return 0; 4344 } 4345 4346 PermissionsState permissionsState = sb.getPermissionsState(); 4347 return permissionsState.getPermissionFlags(name, userId); 4348 } 4349 } 4350 4351 @Override 4352 public void updatePermissionFlags(String name, String packageName, int flagMask, 4353 int flagValues, int userId) { 4354 if (!sUserManager.exists(userId)) { 4355 return; 4356 } 4357 4358 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4359 4360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4361 true /* requireFullPermission */, true /* checkShell */, 4362 "updatePermissionFlags"); 4363 4364 // Only the system can change these flags and nothing else. 4365 if (getCallingUid() != Process.SYSTEM_UID) { 4366 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4367 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4368 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4369 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4370 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4371 } 4372 4373 synchronized (mPackages) { 4374 final PackageParser.Package pkg = mPackages.get(packageName); 4375 if (pkg == null) { 4376 throw new IllegalArgumentException("Unknown package: " + packageName); 4377 } 4378 4379 final BasePermission bp = mSettings.mPermissions.get(name); 4380 if (bp == null) { 4381 throw new IllegalArgumentException("Unknown permission: " + name); 4382 } 4383 4384 SettingBase sb = (SettingBase) pkg.mExtras; 4385 if (sb == null) { 4386 throw new IllegalArgumentException("Unknown package: " + packageName); 4387 } 4388 4389 PermissionsState permissionsState = sb.getPermissionsState(); 4390 4391 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4392 4393 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4394 // Install and runtime permissions are stored in different places, 4395 // so figure out what permission changed and persist the change. 4396 if (permissionsState.getInstallPermissionState(name) != null) { 4397 scheduleWriteSettingsLocked(); 4398 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4399 || hadState) { 4400 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4401 } 4402 } 4403 } 4404 } 4405 4406 /** 4407 * Update the permission flags for all packages and runtime permissions of a user in order 4408 * to allow device or profile owner to remove POLICY_FIXED. 4409 */ 4410 @Override 4411 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4412 if (!sUserManager.exists(userId)) { 4413 return; 4414 } 4415 4416 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4417 4418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4419 true /* requireFullPermission */, true /* checkShell */, 4420 "updatePermissionFlagsForAllApps"); 4421 4422 // Only the system can change system fixed flags. 4423 if (getCallingUid() != Process.SYSTEM_UID) { 4424 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4425 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4426 } 4427 4428 synchronized (mPackages) { 4429 boolean changed = false; 4430 final int packageCount = mPackages.size(); 4431 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4432 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4433 SettingBase sb = (SettingBase) pkg.mExtras; 4434 if (sb == null) { 4435 continue; 4436 } 4437 PermissionsState permissionsState = sb.getPermissionsState(); 4438 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4439 userId, flagMask, flagValues); 4440 } 4441 if (changed) { 4442 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4443 } 4444 } 4445 } 4446 4447 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4448 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4449 != PackageManager.PERMISSION_GRANTED 4450 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4451 != PackageManager.PERMISSION_GRANTED) { 4452 throw new SecurityException(message + " requires " 4453 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4454 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4455 } 4456 } 4457 4458 @Override 4459 public boolean shouldShowRequestPermissionRationale(String permissionName, 4460 String packageName, int userId) { 4461 if (UserHandle.getCallingUserId() != userId) { 4462 mContext.enforceCallingPermission( 4463 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4464 "canShowRequestPermissionRationale for user " + userId); 4465 } 4466 4467 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4468 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4469 return false; 4470 } 4471 4472 if (checkPermission(permissionName, packageName, userId) 4473 == PackageManager.PERMISSION_GRANTED) { 4474 return false; 4475 } 4476 4477 final int flags; 4478 4479 final long identity = Binder.clearCallingIdentity(); 4480 try { 4481 flags = getPermissionFlags(permissionName, 4482 packageName, userId); 4483 } finally { 4484 Binder.restoreCallingIdentity(identity); 4485 } 4486 4487 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4488 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4489 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4490 4491 if ((flags & fixedFlags) != 0) { 4492 return false; 4493 } 4494 4495 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4496 } 4497 4498 @Override 4499 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4500 mContext.enforceCallingOrSelfPermission( 4501 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4502 "addOnPermissionsChangeListener"); 4503 4504 synchronized (mPackages) { 4505 mOnPermissionChangeListeners.addListenerLocked(listener); 4506 } 4507 } 4508 4509 @Override 4510 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4511 synchronized (mPackages) { 4512 mOnPermissionChangeListeners.removeListenerLocked(listener); 4513 } 4514 } 4515 4516 @Override 4517 public boolean isProtectedBroadcast(String actionName) { 4518 synchronized (mPackages) { 4519 if (mProtectedBroadcasts.contains(actionName)) { 4520 return true; 4521 } else if (actionName != null) { 4522 // TODO: remove these terrible hacks 4523 if (actionName.startsWith("android.net.netmon.lingerExpired") 4524 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4525 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4526 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4527 return true; 4528 } 4529 } 4530 } 4531 return false; 4532 } 4533 4534 @Override 4535 public int checkSignatures(String pkg1, String pkg2) { 4536 synchronized (mPackages) { 4537 final PackageParser.Package p1 = mPackages.get(pkg1); 4538 final PackageParser.Package p2 = mPackages.get(pkg2); 4539 if (p1 == null || p1.mExtras == null 4540 || p2 == null || p2.mExtras == null) { 4541 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4542 } 4543 return compareSignatures(p1.mSignatures, p2.mSignatures); 4544 } 4545 } 4546 4547 @Override 4548 public int checkUidSignatures(int uid1, int uid2) { 4549 // Map to base uids. 4550 uid1 = UserHandle.getAppId(uid1); 4551 uid2 = UserHandle.getAppId(uid2); 4552 // reader 4553 synchronized (mPackages) { 4554 Signature[] s1; 4555 Signature[] s2; 4556 Object obj = mSettings.getUserIdLPr(uid1); 4557 if (obj != null) { 4558 if (obj instanceof SharedUserSetting) { 4559 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4560 } else if (obj instanceof PackageSetting) { 4561 s1 = ((PackageSetting)obj).signatures.mSignatures; 4562 } else { 4563 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4564 } 4565 } else { 4566 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4567 } 4568 obj = mSettings.getUserIdLPr(uid2); 4569 if (obj != null) { 4570 if (obj instanceof SharedUserSetting) { 4571 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4572 } else if (obj instanceof PackageSetting) { 4573 s2 = ((PackageSetting)obj).signatures.mSignatures; 4574 } else { 4575 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4576 } 4577 } else { 4578 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4579 } 4580 return compareSignatures(s1, s2); 4581 } 4582 } 4583 4584 /** 4585 * This method should typically only be used when granting or revoking 4586 * permissions, since the app may immediately restart after this call. 4587 * <p> 4588 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4589 * guard your work against the app being relaunched. 4590 */ 4591 private void killUid(int appId, int userId, String reason) { 4592 final long identity = Binder.clearCallingIdentity(); 4593 try { 4594 IActivityManager am = ActivityManagerNative.getDefault(); 4595 if (am != null) { 4596 try { 4597 am.killUid(appId, userId, reason); 4598 } catch (RemoteException e) { 4599 /* ignore - same process */ 4600 } 4601 } 4602 } finally { 4603 Binder.restoreCallingIdentity(identity); 4604 } 4605 } 4606 4607 /** 4608 * Compares two sets of signatures. Returns: 4609 * <br /> 4610 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4611 * <br /> 4612 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4613 * <br /> 4614 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4615 * <br /> 4616 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4617 * <br /> 4618 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4619 */ 4620 static int compareSignatures(Signature[] s1, Signature[] s2) { 4621 if (s1 == null) { 4622 return s2 == null 4623 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4624 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4625 } 4626 4627 if (s2 == null) { 4628 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4629 } 4630 4631 if (s1.length != s2.length) { 4632 return PackageManager.SIGNATURE_NO_MATCH; 4633 } 4634 4635 // Since both signature sets are of size 1, we can compare without HashSets. 4636 if (s1.length == 1) { 4637 return s1[0].equals(s2[0]) ? 4638 PackageManager.SIGNATURE_MATCH : 4639 PackageManager.SIGNATURE_NO_MATCH; 4640 } 4641 4642 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4643 for (Signature sig : s1) { 4644 set1.add(sig); 4645 } 4646 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4647 for (Signature sig : s2) { 4648 set2.add(sig); 4649 } 4650 // Make sure s2 contains all signatures in s1. 4651 if (set1.equals(set2)) { 4652 return PackageManager.SIGNATURE_MATCH; 4653 } 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 /** 4658 * If the database version for this type of package (internal storage or 4659 * external storage) is less than the version where package signatures 4660 * were updated, return true. 4661 */ 4662 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4663 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4664 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4665 } 4666 4667 /** 4668 * Used for backward compatibility to make sure any packages with 4669 * certificate chains get upgraded to the new style. {@code existingSigs} 4670 * will be in the old format (since they were stored on disk from before the 4671 * system upgrade) and {@code scannedSigs} will be in the newer format. 4672 */ 4673 private int compareSignaturesCompat(PackageSignatures existingSigs, 4674 PackageParser.Package scannedPkg) { 4675 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4676 return PackageManager.SIGNATURE_NO_MATCH; 4677 } 4678 4679 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4680 for (Signature sig : existingSigs.mSignatures) { 4681 existingSet.add(sig); 4682 } 4683 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4684 for (Signature sig : scannedPkg.mSignatures) { 4685 try { 4686 Signature[] chainSignatures = sig.getChainSignatures(); 4687 for (Signature chainSig : chainSignatures) { 4688 scannedCompatSet.add(chainSig); 4689 } 4690 } catch (CertificateEncodingException e) { 4691 scannedCompatSet.add(sig); 4692 } 4693 } 4694 /* 4695 * Make sure the expanded scanned set contains all signatures in the 4696 * existing one. 4697 */ 4698 if (scannedCompatSet.equals(existingSet)) { 4699 // Migrate the old signatures to the new scheme. 4700 existingSigs.assignSignatures(scannedPkg.mSignatures); 4701 // The new KeySets will be re-added later in the scanning process. 4702 synchronized (mPackages) { 4703 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4704 } 4705 return PackageManager.SIGNATURE_MATCH; 4706 } 4707 return PackageManager.SIGNATURE_NO_MATCH; 4708 } 4709 4710 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4711 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4712 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4713 } 4714 4715 private int compareSignaturesRecover(PackageSignatures existingSigs, 4716 PackageParser.Package scannedPkg) { 4717 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4718 return PackageManager.SIGNATURE_NO_MATCH; 4719 } 4720 4721 String msg = null; 4722 try { 4723 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4724 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4725 + scannedPkg.packageName); 4726 return PackageManager.SIGNATURE_MATCH; 4727 } 4728 } catch (CertificateException e) { 4729 msg = e.getMessage(); 4730 } 4731 4732 logCriticalInfo(Log.INFO, 4733 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4734 return PackageManager.SIGNATURE_NO_MATCH; 4735 } 4736 4737 @Override 4738 public List<String> getAllPackages() { 4739 synchronized (mPackages) { 4740 return new ArrayList<String>(mPackages.keySet()); 4741 } 4742 } 4743 4744 @Override 4745 public String[] getPackagesForUid(int uid) { 4746 uid = UserHandle.getAppId(uid); 4747 // reader 4748 synchronized (mPackages) { 4749 Object obj = mSettings.getUserIdLPr(uid); 4750 if (obj instanceof SharedUserSetting) { 4751 final SharedUserSetting sus = (SharedUserSetting) obj; 4752 final int N = sus.packages.size(); 4753 final String[] res = new String[N]; 4754 final Iterator<PackageSetting> it = sus.packages.iterator(); 4755 int i = 0; 4756 while (it.hasNext()) { 4757 res[i++] = it.next().name; 4758 } 4759 return res; 4760 } else if (obj instanceof PackageSetting) { 4761 final PackageSetting ps = (PackageSetting) obj; 4762 return new String[] { ps.name }; 4763 } 4764 } 4765 return null; 4766 } 4767 4768 @Override 4769 public String getNameForUid(int uid) { 4770 // reader 4771 synchronized (mPackages) { 4772 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4773 if (obj instanceof SharedUserSetting) { 4774 final SharedUserSetting sus = (SharedUserSetting) obj; 4775 return sus.name + ":" + sus.userId; 4776 } else if (obj instanceof PackageSetting) { 4777 final PackageSetting ps = (PackageSetting) obj; 4778 return ps.name; 4779 } 4780 } 4781 return null; 4782 } 4783 4784 @Override 4785 public int getUidForSharedUser(String sharedUserName) { 4786 if(sharedUserName == null) { 4787 return -1; 4788 } 4789 // reader 4790 synchronized (mPackages) { 4791 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4792 if (suid == null) { 4793 return -1; 4794 } 4795 return suid.userId; 4796 } 4797 } 4798 4799 @Override 4800 public int getFlagsForUid(int uid) { 4801 synchronized (mPackages) { 4802 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4803 if (obj instanceof SharedUserSetting) { 4804 final SharedUserSetting sus = (SharedUserSetting) obj; 4805 return sus.pkgFlags; 4806 } else if (obj instanceof PackageSetting) { 4807 final PackageSetting ps = (PackageSetting) obj; 4808 return ps.pkgFlags; 4809 } 4810 } 4811 return 0; 4812 } 4813 4814 @Override 4815 public int getPrivateFlagsForUid(int uid) { 4816 synchronized (mPackages) { 4817 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4818 if (obj instanceof SharedUserSetting) { 4819 final SharedUserSetting sus = (SharedUserSetting) obj; 4820 return sus.pkgPrivateFlags; 4821 } else if (obj instanceof PackageSetting) { 4822 final PackageSetting ps = (PackageSetting) obj; 4823 return ps.pkgPrivateFlags; 4824 } 4825 } 4826 return 0; 4827 } 4828 4829 @Override 4830 public boolean isUidPrivileged(int uid) { 4831 uid = UserHandle.getAppId(uid); 4832 // reader 4833 synchronized (mPackages) { 4834 Object obj = mSettings.getUserIdLPr(uid); 4835 if (obj instanceof SharedUserSetting) { 4836 final SharedUserSetting sus = (SharedUserSetting) obj; 4837 final Iterator<PackageSetting> it = sus.packages.iterator(); 4838 while (it.hasNext()) { 4839 if (it.next().isPrivileged()) { 4840 return true; 4841 } 4842 } 4843 } else if (obj instanceof PackageSetting) { 4844 final PackageSetting ps = (PackageSetting) obj; 4845 return ps.isPrivileged(); 4846 } 4847 } 4848 return false; 4849 } 4850 4851 @Override 4852 public String[] getAppOpPermissionPackages(String permissionName) { 4853 synchronized (mPackages) { 4854 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4855 if (pkgs == null) { 4856 return null; 4857 } 4858 return pkgs.toArray(new String[pkgs.size()]); 4859 } 4860 } 4861 4862 @Override 4863 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4864 int flags, int userId) { 4865 try { 4866 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4867 4868 if (!sUserManager.exists(userId)) return null; 4869 flags = updateFlagsForResolve(flags, userId, intent); 4870 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4871 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4872 4873 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4874 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4875 flags, userId); 4876 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4877 4878 final ResolveInfo bestChoice = 4879 chooseBestActivity(intent, resolvedType, flags, query, userId); 4880 4881 if (isEphemeralAllowed(intent, query, userId)) { 4882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4883 final EphemeralResolveInfo ai = 4884 getEphemeralResolveInfo(intent, resolvedType, userId); 4885 if (ai != null) { 4886 if (DEBUG_EPHEMERAL) { 4887 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4888 } 4889 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4890 bestChoice.ephemeralResolveInfo = ai; 4891 } 4892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4893 } 4894 return bestChoice; 4895 } finally { 4896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4897 } 4898 } 4899 4900 @Override 4901 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4902 IntentFilter filter, int match, ComponentName activity) { 4903 final int userId = UserHandle.getCallingUserId(); 4904 if (DEBUG_PREFERRED) { 4905 Log.v(TAG, "setLastChosenActivity intent=" + intent 4906 + " resolvedType=" + resolvedType 4907 + " flags=" + flags 4908 + " filter=" + filter 4909 + " match=" + match 4910 + " activity=" + activity); 4911 filter.dump(new PrintStreamPrinter(System.out), " "); 4912 } 4913 intent.setComponent(null); 4914 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4915 userId); 4916 // Find any earlier preferred or last chosen entries and nuke them 4917 findPreferredActivity(intent, resolvedType, 4918 flags, query, 0, false, true, false, userId); 4919 // Add the new activity as the last chosen for this filter 4920 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4921 "Setting last chosen"); 4922 } 4923 4924 @Override 4925 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4926 final int userId = UserHandle.getCallingUserId(); 4927 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4928 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4929 userId); 4930 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4931 false, false, false, userId); 4932 } 4933 4934 4935 private boolean isEphemeralAllowed( 4936 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4937 // Short circuit and return early if possible. 4938 if (DISABLE_EPHEMERAL_APPS) { 4939 return false; 4940 } 4941 final int callingUser = UserHandle.getCallingUserId(); 4942 if (callingUser != UserHandle.USER_SYSTEM) { 4943 return false; 4944 } 4945 if (mEphemeralResolverConnection == null) { 4946 return false; 4947 } 4948 if (intent.getComponent() != null) { 4949 return false; 4950 } 4951 if (intent.getPackage() != null) { 4952 return false; 4953 } 4954 final boolean isWebUri = hasWebURI(intent); 4955 if (!isWebUri) { 4956 return false; 4957 } 4958 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4959 synchronized (mPackages) { 4960 final int count = resolvedActivites.size(); 4961 for (int n = 0; n < count; n++) { 4962 ResolveInfo info = resolvedActivites.get(n); 4963 String packageName = info.activityInfo.packageName; 4964 PackageSetting ps = mSettings.mPackages.get(packageName); 4965 if (ps != null) { 4966 // Try to get the status from User settings first 4967 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4968 int status = (int) (packedStatus >> 32); 4969 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4970 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4971 if (DEBUG_EPHEMERAL) { 4972 Slog.v(TAG, "DENY ephemeral apps;" 4973 + " pkg: " + packageName + ", status: " + status); 4974 } 4975 return false; 4976 } 4977 } 4978 } 4979 } 4980 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4981 return true; 4982 } 4983 4984 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4985 int userId) { 4986 MessageDigest digest = null; 4987 try { 4988 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4989 } catch (NoSuchAlgorithmException e) { 4990 // If we can't create a digest, ignore ephemeral apps. 4991 return null; 4992 } 4993 4994 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4995 final byte[] digestBytes = digest.digest(hostBytes); 4996 int shaPrefix = 4997 digestBytes[0] << 24 4998 | digestBytes[1] << 16 4999 | digestBytes[2] << 8 5000 | digestBytes[3] << 0; 5001 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5002 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 5003 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5004 // No hash prefix match; there are no ephemeral apps for this domain. 5005 return null; 5006 } 5007 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 5008 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 5009 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 5010 continue; 5011 } 5012 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5013 // No filters; this should never happen. 5014 if (filters.isEmpty()) { 5015 continue; 5016 } 5017 // We have a domain match; resolve the filters to see if anything matches. 5018 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5019 for (int j = filters.size() - 1; j >= 0; --j) { 5020 final EphemeralResolveIntentInfo intentInfo = 5021 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5022 ephemeralResolver.addFilter(intentInfo); 5023 } 5024 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5025 intent, resolvedType, false /*defaultOnly*/, userId); 5026 if (!matchedResolveInfoList.isEmpty()) { 5027 return matchedResolveInfoList.get(0); 5028 } 5029 } 5030 // Hash or filter mis-match; no ephemeral apps for this domain. 5031 return null; 5032 } 5033 5034 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5035 int flags, List<ResolveInfo> query, int userId) { 5036 if (query != null) { 5037 final int N = query.size(); 5038 if (N == 1) { 5039 return query.get(0); 5040 } else if (N > 1) { 5041 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5042 // If there is more than one activity with the same priority, 5043 // then let the user decide between them. 5044 ResolveInfo r0 = query.get(0); 5045 ResolveInfo r1 = query.get(1); 5046 if (DEBUG_INTENT_MATCHING || debug) { 5047 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5048 + r1.activityInfo.name + "=" + r1.priority); 5049 } 5050 // If the first activity has a higher priority, or a different 5051 // default, then it is always desirable to pick it. 5052 if (r0.priority != r1.priority 5053 || r0.preferredOrder != r1.preferredOrder 5054 || r0.isDefault != r1.isDefault) { 5055 return query.get(0); 5056 } 5057 // If we have saved a preference for a preferred activity for 5058 // this Intent, use that. 5059 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5060 flags, query, r0.priority, true, false, debug, userId); 5061 if (ri != null) { 5062 return ri; 5063 } 5064 ri = new ResolveInfo(mResolveInfo); 5065 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5066 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5067 // If all of the options come from the same package, show the application's 5068 // label and icon instead of the generic resolver's. 5069 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5070 // and then throw away the ResolveInfo itself, meaning that the caller loses 5071 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5072 // a fallback for this case; we only set the target package's resources on 5073 // the ResolveInfo, not the ActivityInfo. 5074 final String intentPackage = intent.getPackage(); 5075 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5076 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5077 ri.resolvePackageName = intentPackage; 5078 if (userNeedsBadging(userId)) { 5079 ri.noResourceId = true; 5080 } else { 5081 ri.icon = appi.icon; 5082 } 5083 ri.iconResourceId = appi.icon; 5084 ri.labelRes = appi.labelRes; 5085 } 5086 ri.activityInfo.applicationInfo = new ApplicationInfo( 5087 ri.activityInfo.applicationInfo); 5088 if (userId != 0) { 5089 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5090 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5091 } 5092 // Make sure that the resolver is displayable in car mode 5093 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5094 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5095 return ri; 5096 } 5097 } 5098 return null; 5099 } 5100 5101 /** 5102 * Return true if the given list is not empty and all of its contents have 5103 * an activityInfo with the given package name. 5104 */ 5105 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5106 if (ArrayUtils.isEmpty(list)) { 5107 return false; 5108 } 5109 for (int i = 0, N = list.size(); i < N; i++) { 5110 final ResolveInfo ri = list.get(i); 5111 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5112 if (ai == null || !packageName.equals(ai.packageName)) { 5113 return false; 5114 } 5115 } 5116 return true; 5117 } 5118 5119 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5120 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5121 final int N = query.size(); 5122 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5123 .get(userId); 5124 // Get the list of persistent preferred activities that handle the intent 5125 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5126 List<PersistentPreferredActivity> pprefs = ppir != null 5127 ? ppir.queryIntent(intent, resolvedType, 5128 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5129 : null; 5130 if (pprefs != null && pprefs.size() > 0) { 5131 final int M = pprefs.size(); 5132 for (int i=0; i<M; i++) { 5133 final PersistentPreferredActivity ppa = pprefs.get(i); 5134 if (DEBUG_PREFERRED || debug) { 5135 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5136 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5137 + "\n component=" + ppa.mComponent); 5138 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5139 } 5140 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5141 flags | MATCH_DISABLED_COMPONENTS, userId); 5142 if (DEBUG_PREFERRED || debug) { 5143 Slog.v(TAG, "Found persistent preferred activity:"); 5144 if (ai != null) { 5145 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } else { 5147 Slog.v(TAG, " null"); 5148 } 5149 } 5150 if (ai == null) { 5151 // This previously registered persistent preferred activity 5152 // component is no longer known. Ignore it and do NOT remove it. 5153 continue; 5154 } 5155 for (int j=0; j<N; j++) { 5156 final ResolveInfo ri = query.get(j); 5157 if (!ri.activityInfo.applicationInfo.packageName 5158 .equals(ai.applicationInfo.packageName)) { 5159 continue; 5160 } 5161 if (!ri.activityInfo.name.equals(ai.name)) { 5162 continue; 5163 } 5164 // Found a persistent preference that can handle the intent. 5165 if (DEBUG_PREFERRED || debug) { 5166 Slog.v(TAG, "Returning persistent preferred activity: " + 5167 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5168 } 5169 return ri; 5170 } 5171 } 5172 } 5173 return null; 5174 } 5175 5176 // TODO: handle preferred activities missing while user has amnesia 5177 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5178 List<ResolveInfo> query, int priority, boolean always, 5179 boolean removeMatches, boolean debug, int userId) { 5180 if (!sUserManager.exists(userId)) return null; 5181 flags = updateFlagsForResolve(flags, userId, intent); 5182 // writer 5183 synchronized (mPackages) { 5184 if (intent.getSelector() != null) { 5185 intent = intent.getSelector(); 5186 } 5187 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5188 5189 // Try to find a matching persistent preferred activity. 5190 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5191 debug, userId); 5192 5193 // If a persistent preferred activity matched, use it. 5194 if (pri != null) { 5195 return pri; 5196 } 5197 5198 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5199 // Get the list of preferred activities that handle the intent 5200 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5201 List<PreferredActivity> prefs = pir != null 5202 ? pir.queryIntent(intent, resolvedType, 5203 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5204 : null; 5205 if (prefs != null && prefs.size() > 0) { 5206 boolean changed = false; 5207 try { 5208 // First figure out how good the original match set is. 5209 // We will only allow preferred activities that came 5210 // from the same match quality. 5211 int match = 0; 5212 5213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5214 5215 final int N = query.size(); 5216 for (int j=0; j<N; j++) { 5217 final ResolveInfo ri = query.get(j); 5218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5219 + ": 0x" + Integer.toHexString(match)); 5220 if (ri.match > match) { 5221 match = ri.match; 5222 } 5223 } 5224 5225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5226 + Integer.toHexString(match)); 5227 5228 match &= IntentFilter.MATCH_CATEGORY_MASK; 5229 final int M = prefs.size(); 5230 for (int i=0; i<M; i++) { 5231 final PreferredActivity pa = prefs.get(i); 5232 if (DEBUG_PREFERRED || debug) { 5233 Slog.v(TAG, "Checking PreferredActivity ds=" 5234 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5235 + "\n component=" + pa.mPref.mComponent); 5236 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5237 } 5238 if (pa.mPref.mMatch != match) { 5239 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5240 + Integer.toHexString(pa.mPref.mMatch)); 5241 continue; 5242 } 5243 // If it's not an "always" type preferred activity and that's what we're 5244 // looking for, skip it. 5245 if (always && !pa.mPref.mAlways) { 5246 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5247 continue; 5248 } 5249 final ActivityInfo ai = getActivityInfo( 5250 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5251 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5252 userId); 5253 if (DEBUG_PREFERRED || debug) { 5254 Slog.v(TAG, "Found preferred activity:"); 5255 if (ai != null) { 5256 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5257 } else { 5258 Slog.v(TAG, " null"); 5259 } 5260 } 5261 if (ai == null) { 5262 // This previously registered preferred activity 5263 // component is no longer known. Most likely an update 5264 // to the app was installed and in the new version this 5265 // component no longer exists. Clean it up by removing 5266 // it from the preferred activities list, and skip it. 5267 Slog.w(TAG, "Removing dangling preferred activity: " 5268 + pa.mPref.mComponent); 5269 pir.removeFilter(pa); 5270 changed = true; 5271 continue; 5272 } 5273 for (int j=0; j<N; j++) { 5274 final ResolveInfo ri = query.get(j); 5275 if (!ri.activityInfo.applicationInfo.packageName 5276 .equals(ai.applicationInfo.packageName)) { 5277 continue; 5278 } 5279 if (!ri.activityInfo.name.equals(ai.name)) { 5280 continue; 5281 } 5282 5283 if (removeMatches) { 5284 pir.removeFilter(pa); 5285 changed = true; 5286 if (DEBUG_PREFERRED) { 5287 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5288 } 5289 break; 5290 } 5291 5292 // Okay we found a previously set preferred or last chosen app. 5293 // If the result set is different from when this 5294 // was created, we need to clear it and re-ask the 5295 // user their preference, if we're looking for an "always" type entry. 5296 if (always && !pa.mPref.sameSet(query)) { 5297 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5298 + intent + " type " + resolvedType); 5299 if (DEBUG_PREFERRED) { 5300 Slog.v(TAG, "Removing preferred activity since set changed " 5301 + pa.mPref.mComponent); 5302 } 5303 pir.removeFilter(pa); 5304 // Re-add the filter as a "last chosen" entry (!always) 5305 PreferredActivity lastChosen = new PreferredActivity( 5306 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5307 pir.addFilter(lastChosen); 5308 changed = true; 5309 return null; 5310 } 5311 5312 // Yay! Either the set matched or we're looking for the last chosen 5313 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5314 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5315 return ri; 5316 } 5317 } 5318 } finally { 5319 if (changed) { 5320 if (DEBUG_PREFERRED) { 5321 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5322 } 5323 scheduleWritePackageRestrictionsLocked(userId); 5324 } 5325 } 5326 } 5327 } 5328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5329 return null; 5330 } 5331 5332 /* 5333 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5334 */ 5335 @Override 5336 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5337 int targetUserId) { 5338 mContext.enforceCallingOrSelfPermission( 5339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5340 List<CrossProfileIntentFilter> matches = 5341 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5342 if (matches != null) { 5343 int size = matches.size(); 5344 for (int i = 0; i < size; i++) { 5345 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5346 } 5347 } 5348 if (hasWebURI(intent)) { 5349 // cross-profile app linking works only towards the parent. 5350 final UserInfo parent = getProfileParent(sourceUserId); 5351 synchronized(mPackages) { 5352 int flags = updateFlagsForResolve(0, parent.id, intent); 5353 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5354 intent, resolvedType, flags, sourceUserId, parent.id); 5355 return xpDomainInfo != null; 5356 } 5357 } 5358 return false; 5359 } 5360 5361 private UserInfo getProfileParent(int userId) { 5362 final long identity = Binder.clearCallingIdentity(); 5363 try { 5364 return sUserManager.getProfileParent(userId); 5365 } finally { 5366 Binder.restoreCallingIdentity(identity); 5367 } 5368 } 5369 5370 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5371 String resolvedType, int userId) { 5372 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5373 if (resolver != null) { 5374 return resolver.queryIntent(intent, resolvedType, false, userId); 5375 } 5376 return null; 5377 } 5378 5379 @Override 5380 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5381 String resolvedType, int flags, int userId) { 5382 try { 5383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5384 5385 return new ParceledListSlice<>( 5386 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5387 } finally { 5388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5389 } 5390 } 5391 5392 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5393 String resolvedType, int flags, int userId) { 5394 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5395 flags = updateFlagsForResolve(flags, userId, intent); 5396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5397 false /* requireFullPermission */, false /* checkShell */, 5398 "query intent activities"); 5399 ComponentName comp = intent.getComponent(); 5400 if (comp == null) { 5401 if (intent.getSelector() != null) { 5402 intent = intent.getSelector(); 5403 comp = intent.getComponent(); 5404 } 5405 } 5406 5407 if (comp != null) { 5408 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5409 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5410 if (ai != null) { 5411 final ResolveInfo ri = new ResolveInfo(); 5412 ri.activityInfo = ai; 5413 list.add(ri); 5414 } 5415 return list; 5416 } 5417 5418 // reader 5419 synchronized (mPackages) { 5420 final String pkgName = intent.getPackage(); 5421 if (pkgName == null) { 5422 List<CrossProfileIntentFilter> matchingFilters = 5423 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5424 // Check for results that need to skip the current profile. 5425 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5426 resolvedType, flags, userId); 5427 if (xpResolveInfo != null) { 5428 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5429 result.add(xpResolveInfo); 5430 return filterIfNotSystemUser(result, userId); 5431 } 5432 5433 // Check for results in the current profile. 5434 List<ResolveInfo> result = mActivities.queryIntent( 5435 intent, resolvedType, flags, userId); 5436 result = filterIfNotSystemUser(result, userId); 5437 5438 // Check for cross profile results. 5439 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5440 xpResolveInfo = queryCrossProfileIntents( 5441 matchingFilters, intent, resolvedType, flags, userId, 5442 hasNonNegativePriorityResult); 5443 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5444 boolean isVisibleToUser = filterIfNotSystemUser( 5445 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5446 if (isVisibleToUser) { 5447 result.add(xpResolveInfo); 5448 Collections.sort(result, mResolvePrioritySorter); 5449 } 5450 } 5451 if (hasWebURI(intent)) { 5452 CrossProfileDomainInfo xpDomainInfo = null; 5453 final UserInfo parent = getProfileParent(userId); 5454 if (parent != null) { 5455 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5456 flags, userId, parent.id); 5457 } 5458 if (xpDomainInfo != null) { 5459 if (xpResolveInfo != null) { 5460 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5461 // in the result. 5462 result.remove(xpResolveInfo); 5463 } 5464 if (result.size() == 0) { 5465 result.add(xpDomainInfo.resolveInfo); 5466 return result; 5467 } 5468 } else if (result.size() <= 1) { 5469 return result; 5470 } 5471 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5472 xpDomainInfo, userId); 5473 Collections.sort(result, mResolvePrioritySorter); 5474 } 5475 return result; 5476 } 5477 final PackageParser.Package pkg = mPackages.get(pkgName); 5478 if (pkg != null) { 5479 return filterIfNotSystemUser( 5480 mActivities.queryIntentForPackage( 5481 intent, resolvedType, flags, pkg.activities, userId), 5482 userId); 5483 } 5484 return new ArrayList<ResolveInfo>(); 5485 } 5486 } 5487 5488 private static class CrossProfileDomainInfo { 5489 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5490 ResolveInfo resolveInfo; 5491 /* Best domain verification status of the activities found in the other profile */ 5492 int bestDomainVerificationStatus; 5493 } 5494 5495 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5496 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5497 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5498 sourceUserId)) { 5499 return null; 5500 } 5501 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5502 resolvedType, flags, parentUserId); 5503 5504 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5505 return null; 5506 } 5507 CrossProfileDomainInfo result = null; 5508 int size = resultTargetUser.size(); 5509 for (int i = 0; i < size; i++) { 5510 ResolveInfo riTargetUser = resultTargetUser.get(i); 5511 // Intent filter verification is only for filters that specify a host. So don't return 5512 // those that handle all web uris. 5513 if (riTargetUser.handleAllWebDataURI) { 5514 continue; 5515 } 5516 String packageName = riTargetUser.activityInfo.packageName; 5517 PackageSetting ps = mSettings.mPackages.get(packageName); 5518 if (ps == null) { 5519 continue; 5520 } 5521 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5522 int status = (int)(verificationState >> 32); 5523 if (result == null) { 5524 result = new CrossProfileDomainInfo(); 5525 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5526 sourceUserId, parentUserId); 5527 result.bestDomainVerificationStatus = status; 5528 } else { 5529 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5530 result.bestDomainVerificationStatus); 5531 } 5532 } 5533 // Don't consider matches with status NEVER across profiles. 5534 if (result != null && result.bestDomainVerificationStatus 5535 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5536 return null; 5537 } 5538 return result; 5539 } 5540 5541 /** 5542 * Verification statuses are ordered from the worse to the best, except for 5543 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5544 */ 5545 private int bestDomainVerificationStatus(int status1, int status2) { 5546 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5547 return status2; 5548 } 5549 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5550 return status1; 5551 } 5552 return (int) MathUtils.max(status1, status2); 5553 } 5554 5555 private boolean isUserEnabled(int userId) { 5556 long callingId = Binder.clearCallingIdentity(); 5557 try { 5558 UserInfo userInfo = sUserManager.getUserInfo(userId); 5559 return userInfo != null && userInfo.isEnabled(); 5560 } finally { 5561 Binder.restoreCallingIdentity(callingId); 5562 } 5563 } 5564 5565 /** 5566 * Filter out activities with systemUserOnly flag set, when current user is not System. 5567 * 5568 * @return filtered list 5569 */ 5570 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5571 if (userId == UserHandle.USER_SYSTEM) { 5572 return resolveInfos; 5573 } 5574 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5575 ResolveInfo info = resolveInfos.get(i); 5576 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5577 resolveInfos.remove(i); 5578 } 5579 } 5580 return resolveInfos; 5581 } 5582 5583 /** 5584 * @param resolveInfos list of resolve infos in descending priority order 5585 * @return if the list contains a resolve info with non-negative priority 5586 */ 5587 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5588 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5589 } 5590 5591 private static boolean hasWebURI(Intent intent) { 5592 if (intent.getData() == null) { 5593 return false; 5594 } 5595 final String scheme = intent.getScheme(); 5596 if (TextUtils.isEmpty(scheme)) { 5597 return false; 5598 } 5599 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5600 } 5601 5602 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5603 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5604 int userId) { 5605 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5606 5607 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5608 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5609 candidates.size()); 5610 } 5611 5612 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5613 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5614 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5615 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5616 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5617 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5618 5619 synchronized (mPackages) { 5620 final int count = candidates.size(); 5621 // First, try to use linked apps. Partition the candidates into four lists: 5622 // one for the final results, one for the "do not use ever", one for "undefined status" 5623 // and finally one for "browser app type". 5624 for (int n=0; n<count; n++) { 5625 ResolveInfo info = candidates.get(n); 5626 String packageName = info.activityInfo.packageName; 5627 PackageSetting ps = mSettings.mPackages.get(packageName); 5628 if (ps != null) { 5629 // Add to the special match all list (Browser use case) 5630 if (info.handleAllWebDataURI) { 5631 matchAllList.add(info); 5632 continue; 5633 } 5634 // Try to get the status from User settings first 5635 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5636 int status = (int)(packedStatus >> 32); 5637 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5638 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5639 if (DEBUG_DOMAIN_VERIFICATION) { 5640 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5641 + " : linkgen=" + linkGeneration); 5642 } 5643 // Use link-enabled generation as preferredOrder, i.e. 5644 // prefer newly-enabled over earlier-enabled. 5645 info.preferredOrder = linkGeneration; 5646 alwaysList.add(info); 5647 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5648 if (DEBUG_DOMAIN_VERIFICATION) { 5649 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5650 } 5651 neverList.add(info); 5652 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5653 if (DEBUG_DOMAIN_VERIFICATION) { 5654 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5655 } 5656 alwaysAskList.add(info); 5657 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5658 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5659 if (DEBUG_DOMAIN_VERIFICATION) { 5660 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5661 } 5662 undefinedList.add(info); 5663 } 5664 } 5665 } 5666 5667 // We'll want to include browser possibilities in a few cases 5668 boolean includeBrowser = false; 5669 5670 // First try to add the "always" resolution(s) for the current user, if any 5671 if (alwaysList.size() > 0) { 5672 result.addAll(alwaysList); 5673 } else { 5674 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5675 result.addAll(undefinedList); 5676 // Maybe add one for the other profile. 5677 if (xpDomainInfo != null && ( 5678 xpDomainInfo.bestDomainVerificationStatus 5679 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5680 result.add(xpDomainInfo.resolveInfo); 5681 } 5682 includeBrowser = true; 5683 } 5684 5685 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5686 // If there were 'always' entries their preferred order has been set, so we also 5687 // back that off to make the alternatives equivalent 5688 if (alwaysAskList.size() > 0) { 5689 for (ResolveInfo i : result) { 5690 i.preferredOrder = 0; 5691 } 5692 result.addAll(alwaysAskList); 5693 includeBrowser = true; 5694 } 5695 5696 if (includeBrowser) { 5697 // Also add browsers (all of them or only the default one) 5698 if (DEBUG_DOMAIN_VERIFICATION) { 5699 Slog.v(TAG, " ...including browsers in candidate set"); 5700 } 5701 if ((matchFlags & MATCH_ALL) != 0) { 5702 result.addAll(matchAllList); 5703 } else { 5704 // Browser/generic handling case. If there's a default browser, go straight 5705 // to that (but only if there is no other higher-priority match). 5706 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5707 int maxMatchPrio = 0; 5708 ResolveInfo defaultBrowserMatch = null; 5709 final int numCandidates = matchAllList.size(); 5710 for (int n = 0; n < numCandidates; n++) { 5711 ResolveInfo info = matchAllList.get(n); 5712 // track the highest overall match priority... 5713 if (info.priority > maxMatchPrio) { 5714 maxMatchPrio = info.priority; 5715 } 5716 // ...and the highest-priority default browser match 5717 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5718 if (defaultBrowserMatch == null 5719 || (defaultBrowserMatch.priority < info.priority)) { 5720 if (debug) { 5721 Slog.v(TAG, "Considering default browser match " + info); 5722 } 5723 defaultBrowserMatch = info; 5724 } 5725 } 5726 } 5727 if (defaultBrowserMatch != null 5728 && defaultBrowserMatch.priority >= maxMatchPrio 5729 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5730 { 5731 if (debug) { 5732 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5733 } 5734 result.add(defaultBrowserMatch); 5735 } else { 5736 result.addAll(matchAllList); 5737 } 5738 } 5739 5740 // If there is nothing selected, add all candidates and remove the ones that the user 5741 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5742 if (result.size() == 0) { 5743 result.addAll(candidates); 5744 result.removeAll(neverList); 5745 } 5746 } 5747 } 5748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5749 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5750 result.size()); 5751 for (ResolveInfo info : result) { 5752 Slog.v(TAG, " + " + info.activityInfo); 5753 } 5754 } 5755 return result; 5756 } 5757 5758 // Returns a packed value as a long: 5759 // 5760 // high 'int'-sized word: link status: undefined/ask/never/always. 5761 // low 'int'-sized word: relative priority among 'always' results. 5762 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5763 long result = ps.getDomainVerificationStatusForUser(userId); 5764 // if none available, get the master status 5765 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5766 if (ps.getIntentFilterVerificationInfo() != null) { 5767 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5768 } 5769 } 5770 return result; 5771 } 5772 5773 private ResolveInfo querySkipCurrentProfileIntents( 5774 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5775 int flags, int sourceUserId) { 5776 if (matchingFilters != null) { 5777 int size = matchingFilters.size(); 5778 for (int i = 0; i < size; i ++) { 5779 CrossProfileIntentFilter filter = matchingFilters.get(i); 5780 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5781 // Checking if there are activities in the target user that can handle the 5782 // intent. 5783 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5784 resolvedType, flags, sourceUserId); 5785 if (resolveInfo != null) { 5786 return resolveInfo; 5787 } 5788 } 5789 } 5790 } 5791 return null; 5792 } 5793 5794 // Return matching ResolveInfo in target user if any. 5795 private ResolveInfo queryCrossProfileIntents( 5796 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5797 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5798 if (matchingFilters != null) { 5799 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5800 // match the same intent. For performance reasons, it is better not to 5801 // run queryIntent twice for the same userId 5802 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5803 int size = matchingFilters.size(); 5804 for (int i = 0; i < size; i++) { 5805 CrossProfileIntentFilter filter = matchingFilters.get(i); 5806 int targetUserId = filter.getTargetUserId(); 5807 boolean skipCurrentProfile = 5808 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5809 boolean skipCurrentProfileIfNoMatchFound = 5810 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5811 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5812 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5813 // Checking if there are activities in the target user that can handle the 5814 // intent. 5815 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5816 resolvedType, flags, sourceUserId); 5817 if (resolveInfo != null) return resolveInfo; 5818 alreadyTriedUserIds.put(targetUserId, true); 5819 } 5820 } 5821 } 5822 return null; 5823 } 5824 5825 /** 5826 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5827 * will forward the intent to the filter's target user. 5828 * Otherwise, returns null. 5829 */ 5830 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5831 String resolvedType, int flags, int sourceUserId) { 5832 int targetUserId = filter.getTargetUserId(); 5833 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5834 resolvedType, flags, targetUserId); 5835 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5836 // If all the matches in the target profile are suspended, return null. 5837 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5838 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5839 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5840 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5841 targetUserId); 5842 } 5843 } 5844 } 5845 return null; 5846 } 5847 5848 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5849 int sourceUserId, int targetUserId) { 5850 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5851 long ident = Binder.clearCallingIdentity(); 5852 boolean targetIsProfile; 5853 try { 5854 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5855 } finally { 5856 Binder.restoreCallingIdentity(ident); 5857 } 5858 String className; 5859 if (targetIsProfile) { 5860 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5861 } else { 5862 className = FORWARD_INTENT_TO_PARENT; 5863 } 5864 ComponentName forwardingActivityComponentName = new ComponentName( 5865 mAndroidApplication.packageName, className); 5866 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5867 sourceUserId); 5868 if (!targetIsProfile) { 5869 forwardingActivityInfo.showUserIcon = targetUserId; 5870 forwardingResolveInfo.noResourceId = true; 5871 } 5872 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5873 forwardingResolveInfo.priority = 0; 5874 forwardingResolveInfo.preferredOrder = 0; 5875 forwardingResolveInfo.match = 0; 5876 forwardingResolveInfo.isDefault = true; 5877 forwardingResolveInfo.filter = filter; 5878 forwardingResolveInfo.targetUserId = targetUserId; 5879 return forwardingResolveInfo; 5880 } 5881 5882 @Override 5883 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5884 Intent[] specifics, String[] specificTypes, Intent intent, 5885 String resolvedType, int flags, int userId) { 5886 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5887 specificTypes, intent, resolvedType, flags, userId)); 5888 } 5889 5890 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5891 Intent[] specifics, String[] specificTypes, Intent intent, 5892 String resolvedType, int flags, int userId) { 5893 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5894 flags = updateFlagsForResolve(flags, userId, intent); 5895 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5896 false /* requireFullPermission */, false /* checkShell */, 5897 "query intent activity options"); 5898 final String resultsAction = intent.getAction(); 5899 5900 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5901 | PackageManager.GET_RESOLVED_FILTER, userId); 5902 5903 if (DEBUG_INTENT_MATCHING) { 5904 Log.v(TAG, "Query " + intent + ": " + results); 5905 } 5906 5907 int specificsPos = 0; 5908 int N; 5909 5910 // todo: note that the algorithm used here is O(N^2). This 5911 // isn't a problem in our current environment, but if we start running 5912 // into situations where we have more than 5 or 10 matches then this 5913 // should probably be changed to something smarter... 5914 5915 // First we go through and resolve each of the specific items 5916 // that were supplied, taking care of removing any corresponding 5917 // duplicate items in the generic resolve list. 5918 if (specifics != null) { 5919 for (int i=0; i<specifics.length; i++) { 5920 final Intent sintent = specifics[i]; 5921 if (sintent == null) { 5922 continue; 5923 } 5924 5925 if (DEBUG_INTENT_MATCHING) { 5926 Log.v(TAG, "Specific #" + i + ": " + sintent); 5927 } 5928 5929 String action = sintent.getAction(); 5930 if (resultsAction != null && resultsAction.equals(action)) { 5931 // If this action was explicitly requested, then don't 5932 // remove things that have it. 5933 action = null; 5934 } 5935 5936 ResolveInfo ri = null; 5937 ActivityInfo ai = null; 5938 5939 ComponentName comp = sintent.getComponent(); 5940 if (comp == null) { 5941 ri = resolveIntent( 5942 sintent, 5943 specificTypes != null ? specificTypes[i] : null, 5944 flags, userId); 5945 if (ri == null) { 5946 continue; 5947 } 5948 if (ri == mResolveInfo) { 5949 // ACK! Must do something better with this. 5950 } 5951 ai = ri.activityInfo; 5952 comp = new ComponentName(ai.applicationInfo.packageName, 5953 ai.name); 5954 } else { 5955 ai = getActivityInfo(comp, flags, userId); 5956 if (ai == null) { 5957 continue; 5958 } 5959 } 5960 5961 // Look for any generic query activities that are duplicates 5962 // of this specific one, and remove them from the results. 5963 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5964 N = results.size(); 5965 int j; 5966 for (j=specificsPos; j<N; j++) { 5967 ResolveInfo sri = results.get(j); 5968 if ((sri.activityInfo.name.equals(comp.getClassName()) 5969 && sri.activityInfo.applicationInfo.packageName.equals( 5970 comp.getPackageName())) 5971 || (action != null && sri.filter.matchAction(action))) { 5972 results.remove(j); 5973 if (DEBUG_INTENT_MATCHING) Log.v( 5974 TAG, "Removing duplicate item from " + j 5975 + " due to specific " + specificsPos); 5976 if (ri == null) { 5977 ri = sri; 5978 } 5979 j--; 5980 N--; 5981 } 5982 } 5983 5984 // Add this specific item to its proper place. 5985 if (ri == null) { 5986 ri = new ResolveInfo(); 5987 ri.activityInfo = ai; 5988 } 5989 results.add(specificsPos, ri); 5990 ri.specificIndex = i; 5991 specificsPos++; 5992 } 5993 } 5994 5995 // Now we go through the remaining generic results and remove any 5996 // duplicate actions that are found here. 5997 N = results.size(); 5998 for (int i=specificsPos; i<N-1; i++) { 5999 final ResolveInfo rii = results.get(i); 6000 if (rii.filter == null) { 6001 continue; 6002 } 6003 6004 // Iterate over all of the actions of this result's intent 6005 // filter... typically this should be just one. 6006 final Iterator<String> it = rii.filter.actionsIterator(); 6007 if (it == null) { 6008 continue; 6009 } 6010 while (it.hasNext()) { 6011 final String action = it.next(); 6012 if (resultsAction != null && resultsAction.equals(action)) { 6013 // If this action was explicitly requested, then don't 6014 // remove things that have it. 6015 continue; 6016 } 6017 for (int j=i+1; j<N; j++) { 6018 final ResolveInfo rij = results.get(j); 6019 if (rij.filter != null && rij.filter.hasAction(action)) { 6020 results.remove(j); 6021 if (DEBUG_INTENT_MATCHING) Log.v( 6022 TAG, "Removing duplicate item from " + j 6023 + " due to action " + action + " at " + i); 6024 j--; 6025 N--; 6026 } 6027 } 6028 } 6029 6030 // If the caller didn't request filter information, drop it now 6031 // so we don't have to marshall/unmarshall it. 6032 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6033 rii.filter = null; 6034 } 6035 } 6036 6037 // Filter out the caller activity if so requested. 6038 if (caller != null) { 6039 N = results.size(); 6040 for (int i=0; i<N; i++) { 6041 ActivityInfo ainfo = results.get(i).activityInfo; 6042 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6043 && caller.getClassName().equals(ainfo.name)) { 6044 results.remove(i); 6045 break; 6046 } 6047 } 6048 } 6049 6050 // If the caller didn't request filter information, 6051 // drop them now so we don't have to 6052 // marshall/unmarshall it. 6053 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6054 N = results.size(); 6055 for (int i=0; i<N; i++) { 6056 results.get(i).filter = null; 6057 } 6058 } 6059 6060 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6061 return results; 6062 } 6063 6064 @Override 6065 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6066 String resolvedType, int flags, int userId) { 6067 return new ParceledListSlice<>( 6068 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6069 } 6070 6071 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6072 String resolvedType, int flags, int userId) { 6073 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6074 flags = updateFlagsForResolve(flags, userId, intent); 6075 ComponentName comp = intent.getComponent(); 6076 if (comp == null) { 6077 if (intent.getSelector() != null) { 6078 intent = intent.getSelector(); 6079 comp = intent.getComponent(); 6080 } 6081 } 6082 if (comp != null) { 6083 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6084 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6085 if (ai != null) { 6086 ResolveInfo ri = new ResolveInfo(); 6087 ri.activityInfo = ai; 6088 list.add(ri); 6089 } 6090 return list; 6091 } 6092 6093 // reader 6094 synchronized (mPackages) { 6095 String pkgName = intent.getPackage(); 6096 if (pkgName == null) { 6097 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6098 } 6099 final PackageParser.Package pkg = mPackages.get(pkgName); 6100 if (pkg != null) { 6101 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6102 userId); 6103 } 6104 return Collections.emptyList(); 6105 } 6106 } 6107 6108 @Override 6109 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6110 if (!sUserManager.exists(userId)) return null; 6111 flags = updateFlagsForResolve(flags, userId, intent); 6112 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6113 if (query != null) { 6114 if (query.size() >= 1) { 6115 // If there is more than one service with the same priority, 6116 // just arbitrarily pick the first one. 6117 return query.get(0); 6118 } 6119 } 6120 return null; 6121 } 6122 6123 @Override 6124 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6125 String resolvedType, int flags, int userId) { 6126 return new ParceledListSlice<>( 6127 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6128 } 6129 6130 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6131 String resolvedType, int flags, int userId) { 6132 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6133 flags = updateFlagsForResolve(flags, userId, intent); 6134 ComponentName comp = intent.getComponent(); 6135 if (comp == null) { 6136 if (intent.getSelector() != null) { 6137 intent = intent.getSelector(); 6138 comp = intent.getComponent(); 6139 } 6140 } 6141 if (comp != null) { 6142 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6143 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6144 if (si != null) { 6145 final ResolveInfo ri = new ResolveInfo(); 6146 ri.serviceInfo = si; 6147 list.add(ri); 6148 } 6149 return list; 6150 } 6151 6152 // reader 6153 synchronized (mPackages) { 6154 String pkgName = intent.getPackage(); 6155 if (pkgName == null) { 6156 return mServices.queryIntent(intent, resolvedType, flags, userId); 6157 } 6158 final PackageParser.Package pkg = mPackages.get(pkgName); 6159 if (pkg != null) { 6160 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6161 userId); 6162 } 6163 return Collections.emptyList(); 6164 } 6165 } 6166 6167 @Override 6168 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6169 String resolvedType, int flags, int userId) { 6170 return new ParceledListSlice<>( 6171 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6172 } 6173 6174 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6175 Intent intent, String resolvedType, int flags, int userId) { 6176 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6177 flags = updateFlagsForResolve(flags, userId, intent); 6178 ComponentName comp = intent.getComponent(); 6179 if (comp == null) { 6180 if (intent.getSelector() != null) { 6181 intent = intent.getSelector(); 6182 comp = intent.getComponent(); 6183 } 6184 } 6185 if (comp != null) { 6186 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6187 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6188 if (pi != null) { 6189 final ResolveInfo ri = new ResolveInfo(); 6190 ri.providerInfo = pi; 6191 list.add(ri); 6192 } 6193 return list; 6194 } 6195 6196 // reader 6197 synchronized (mPackages) { 6198 String pkgName = intent.getPackage(); 6199 if (pkgName == null) { 6200 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6201 } 6202 final PackageParser.Package pkg = mPackages.get(pkgName); 6203 if (pkg != null) { 6204 return mProviders.queryIntentForPackage( 6205 intent, resolvedType, flags, pkg.providers, userId); 6206 } 6207 return Collections.emptyList(); 6208 } 6209 } 6210 6211 @Override 6212 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6213 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6214 flags = updateFlagsForPackage(flags, userId, null); 6215 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6217 true /* requireFullPermission */, false /* checkShell */, 6218 "get installed packages"); 6219 6220 // writer 6221 synchronized (mPackages) { 6222 ArrayList<PackageInfo> list; 6223 if (listUninstalled) { 6224 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6225 for (PackageSetting ps : mSettings.mPackages.values()) { 6226 final PackageInfo pi; 6227 if (ps.pkg != null) { 6228 pi = generatePackageInfo(ps, flags, userId); 6229 } else { 6230 pi = generatePackageInfo(ps, flags, userId); 6231 } 6232 if (pi != null) { 6233 list.add(pi); 6234 } 6235 } 6236 } else { 6237 list = new ArrayList<PackageInfo>(mPackages.size()); 6238 for (PackageParser.Package p : mPackages.values()) { 6239 final PackageInfo pi = 6240 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6241 if (pi != null) { 6242 list.add(pi); 6243 } 6244 } 6245 } 6246 6247 return new ParceledListSlice<PackageInfo>(list); 6248 } 6249 } 6250 6251 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6252 String[] permissions, boolean[] tmp, int flags, int userId) { 6253 int numMatch = 0; 6254 final PermissionsState permissionsState = ps.getPermissionsState(); 6255 for (int i=0; i<permissions.length; i++) { 6256 final String permission = permissions[i]; 6257 if (permissionsState.hasPermission(permission, userId)) { 6258 tmp[i] = true; 6259 numMatch++; 6260 } else { 6261 tmp[i] = false; 6262 } 6263 } 6264 if (numMatch == 0) { 6265 return; 6266 } 6267 final PackageInfo pi; 6268 if (ps.pkg != null) { 6269 pi = generatePackageInfo(ps, flags, userId); 6270 } else { 6271 pi = generatePackageInfo(ps, flags, userId); 6272 } 6273 // The above might return null in cases of uninstalled apps or install-state 6274 // skew across users/profiles. 6275 if (pi != null) { 6276 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6277 if (numMatch == permissions.length) { 6278 pi.requestedPermissions = permissions; 6279 } else { 6280 pi.requestedPermissions = new String[numMatch]; 6281 numMatch = 0; 6282 for (int i=0; i<permissions.length; i++) { 6283 if (tmp[i]) { 6284 pi.requestedPermissions[numMatch] = permissions[i]; 6285 numMatch++; 6286 } 6287 } 6288 } 6289 } 6290 list.add(pi); 6291 } 6292 } 6293 6294 @Override 6295 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6296 String[] permissions, int flags, int userId) { 6297 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6298 flags = updateFlagsForPackage(flags, userId, permissions); 6299 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6300 6301 // writer 6302 synchronized (mPackages) { 6303 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6304 boolean[] tmpBools = new boolean[permissions.length]; 6305 if (listUninstalled) { 6306 for (PackageSetting ps : mSettings.mPackages.values()) { 6307 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6308 } 6309 } else { 6310 for (PackageParser.Package pkg : mPackages.values()) { 6311 PackageSetting ps = (PackageSetting)pkg.mExtras; 6312 if (ps != null) { 6313 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6314 userId); 6315 } 6316 } 6317 } 6318 6319 return new ParceledListSlice<PackageInfo>(list); 6320 } 6321 } 6322 6323 @Override 6324 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6325 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6326 flags = updateFlagsForApplication(flags, userId, null); 6327 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6328 6329 // writer 6330 synchronized (mPackages) { 6331 ArrayList<ApplicationInfo> list; 6332 if (listUninstalled) { 6333 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6334 for (PackageSetting ps : mSettings.mPackages.values()) { 6335 ApplicationInfo ai; 6336 if (ps.pkg != null) { 6337 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6338 ps.readUserState(userId), userId); 6339 } else { 6340 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6341 } 6342 if (ai != null) { 6343 list.add(ai); 6344 } 6345 } 6346 } else { 6347 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6348 for (PackageParser.Package p : mPackages.values()) { 6349 if (p.mExtras != null) { 6350 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6351 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6352 if (ai != null) { 6353 list.add(ai); 6354 } 6355 } 6356 } 6357 } 6358 6359 return new ParceledListSlice<ApplicationInfo>(list); 6360 } 6361 } 6362 6363 @Override 6364 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6365 if (DISABLE_EPHEMERAL_APPS) { 6366 return null; 6367 } 6368 6369 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6370 "getEphemeralApplications"); 6371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6372 true /* requireFullPermission */, false /* checkShell */, 6373 "getEphemeralApplications"); 6374 synchronized (mPackages) { 6375 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6376 .getEphemeralApplicationsLPw(userId); 6377 if (ephemeralApps != null) { 6378 return new ParceledListSlice<>(ephemeralApps); 6379 } 6380 } 6381 return null; 6382 } 6383 6384 @Override 6385 public boolean isEphemeralApplication(String packageName, int userId) { 6386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6387 true /* requireFullPermission */, false /* checkShell */, 6388 "isEphemeral"); 6389 if (DISABLE_EPHEMERAL_APPS) { 6390 return false; 6391 } 6392 6393 if (!isCallerSameApp(packageName)) { 6394 return false; 6395 } 6396 synchronized (mPackages) { 6397 PackageParser.Package pkg = mPackages.get(packageName); 6398 if (pkg != null) { 6399 return pkg.applicationInfo.isEphemeralApp(); 6400 } 6401 } 6402 return false; 6403 } 6404 6405 @Override 6406 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6407 if (DISABLE_EPHEMERAL_APPS) { 6408 return null; 6409 } 6410 6411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6412 true /* requireFullPermission */, false /* checkShell */, 6413 "getCookie"); 6414 if (!isCallerSameApp(packageName)) { 6415 return null; 6416 } 6417 synchronized (mPackages) { 6418 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6419 packageName, userId); 6420 } 6421 } 6422 6423 @Override 6424 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6425 if (DISABLE_EPHEMERAL_APPS) { 6426 return true; 6427 } 6428 6429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6430 true /* requireFullPermission */, true /* checkShell */, 6431 "setCookie"); 6432 if (!isCallerSameApp(packageName)) { 6433 return false; 6434 } 6435 synchronized (mPackages) { 6436 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6437 packageName, cookie, userId); 6438 } 6439 } 6440 6441 @Override 6442 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6443 if (DISABLE_EPHEMERAL_APPS) { 6444 return null; 6445 } 6446 6447 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6448 "getEphemeralApplicationIcon"); 6449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6450 true /* requireFullPermission */, false /* checkShell */, 6451 "getEphemeralApplicationIcon"); 6452 synchronized (mPackages) { 6453 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6454 packageName, userId); 6455 } 6456 } 6457 6458 private boolean isCallerSameApp(String packageName) { 6459 PackageParser.Package pkg = mPackages.get(packageName); 6460 return pkg != null 6461 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6462 } 6463 6464 @Override 6465 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6466 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6467 } 6468 6469 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6470 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6471 6472 // reader 6473 synchronized (mPackages) { 6474 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6475 final int userId = UserHandle.getCallingUserId(); 6476 while (i.hasNext()) { 6477 final PackageParser.Package p = i.next(); 6478 if (p.applicationInfo == null) continue; 6479 6480 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6481 && !p.applicationInfo.isDirectBootAware(); 6482 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6483 && p.applicationInfo.isDirectBootAware(); 6484 6485 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6486 && (!mSafeMode || isSystemApp(p)) 6487 && (matchesUnaware || matchesAware)) { 6488 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6489 if (ps != null) { 6490 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6491 ps.readUserState(userId), userId); 6492 if (ai != null) { 6493 finalList.add(ai); 6494 } 6495 } 6496 } 6497 } 6498 } 6499 6500 return finalList; 6501 } 6502 6503 @Override 6504 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6505 if (!sUserManager.exists(userId)) return null; 6506 flags = updateFlagsForComponent(flags, userId, name); 6507 // reader 6508 synchronized (mPackages) { 6509 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6510 PackageSetting ps = provider != null 6511 ? mSettings.mPackages.get(provider.owner.packageName) 6512 : null; 6513 return ps != null 6514 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6515 ? PackageParser.generateProviderInfo(provider, flags, 6516 ps.readUserState(userId), userId) 6517 : null; 6518 } 6519 } 6520 6521 /** 6522 * @deprecated 6523 */ 6524 @Deprecated 6525 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6526 // reader 6527 synchronized (mPackages) { 6528 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6529 .entrySet().iterator(); 6530 final int userId = UserHandle.getCallingUserId(); 6531 while (i.hasNext()) { 6532 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6533 PackageParser.Provider p = entry.getValue(); 6534 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6535 6536 if (ps != null && p.syncable 6537 && (!mSafeMode || (p.info.applicationInfo.flags 6538 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6539 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6540 ps.readUserState(userId), userId); 6541 if (info != null) { 6542 outNames.add(entry.getKey()); 6543 outInfo.add(info); 6544 } 6545 } 6546 } 6547 } 6548 } 6549 6550 @Override 6551 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6552 int uid, int flags) { 6553 final int userId = processName != null ? UserHandle.getUserId(uid) 6554 : UserHandle.getCallingUserId(); 6555 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6556 flags = updateFlagsForComponent(flags, userId, processName); 6557 6558 ArrayList<ProviderInfo> finalList = null; 6559 // reader 6560 synchronized (mPackages) { 6561 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6562 while (i.hasNext()) { 6563 final PackageParser.Provider p = i.next(); 6564 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6565 if (ps != null && p.info.authority != null 6566 && (processName == null 6567 || (p.info.processName.equals(processName) 6568 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6569 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6570 if (finalList == null) { 6571 finalList = new ArrayList<ProviderInfo>(3); 6572 } 6573 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6574 ps.readUserState(userId), userId); 6575 if (info != null) { 6576 finalList.add(info); 6577 } 6578 } 6579 } 6580 } 6581 6582 if (finalList != null) { 6583 Collections.sort(finalList, mProviderInitOrderSorter); 6584 return new ParceledListSlice<ProviderInfo>(finalList); 6585 } 6586 6587 return ParceledListSlice.emptyList(); 6588 } 6589 6590 @Override 6591 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6592 // reader 6593 synchronized (mPackages) { 6594 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6595 return PackageParser.generateInstrumentationInfo(i, flags); 6596 } 6597 } 6598 6599 @Override 6600 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6601 String targetPackage, int flags) { 6602 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6603 } 6604 6605 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6606 int flags) { 6607 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6608 6609 // reader 6610 synchronized (mPackages) { 6611 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6612 while (i.hasNext()) { 6613 final PackageParser.Instrumentation p = i.next(); 6614 if (targetPackage == null 6615 || targetPackage.equals(p.info.targetPackage)) { 6616 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6617 flags); 6618 if (ii != null) { 6619 finalList.add(ii); 6620 } 6621 } 6622 } 6623 } 6624 6625 return finalList; 6626 } 6627 6628 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6629 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6630 if (overlays == null) { 6631 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6632 return; 6633 } 6634 for (PackageParser.Package opkg : overlays.values()) { 6635 // Not much to do if idmap fails: we already logged the error 6636 // and we certainly don't want to abort installation of pkg simply 6637 // because an overlay didn't fit properly. For these reasons, 6638 // ignore the return value of createIdmapForPackagePairLI. 6639 createIdmapForPackagePairLI(pkg, opkg); 6640 } 6641 } 6642 6643 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6644 PackageParser.Package opkg) { 6645 if (!opkg.mTrustedOverlay) { 6646 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6647 opkg.baseCodePath + ": overlay not trusted"); 6648 return false; 6649 } 6650 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6651 if (overlaySet == null) { 6652 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6653 opkg.baseCodePath + " but target package has no known overlays"); 6654 return false; 6655 } 6656 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6657 // TODO: generate idmap for split APKs 6658 try { 6659 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6660 } catch (InstallerException e) { 6661 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6662 + opkg.baseCodePath); 6663 return false; 6664 } 6665 PackageParser.Package[] overlayArray = 6666 overlaySet.values().toArray(new PackageParser.Package[0]); 6667 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6668 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6669 return p1.mOverlayPriority - p2.mOverlayPriority; 6670 } 6671 }; 6672 Arrays.sort(overlayArray, cmp); 6673 6674 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6675 int i = 0; 6676 for (PackageParser.Package p : overlayArray) { 6677 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6678 } 6679 return true; 6680 } 6681 6682 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6684 try { 6685 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 } 6690 6691 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6692 final File[] files = dir.listFiles(); 6693 if (ArrayUtils.isEmpty(files)) { 6694 Log.d(TAG, "No files in app dir " + dir); 6695 return; 6696 } 6697 6698 if (DEBUG_PACKAGE_SCANNING) { 6699 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6700 + " flags=0x" + Integer.toHexString(parseFlags)); 6701 } 6702 6703 for (File file : files) { 6704 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6705 && !PackageInstallerService.isStageName(file.getName()); 6706 if (!isPackage) { 6707 // Ignore entries which are not packages 6708 continue; 6709 } 6710 try { 6711 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6712 scanFlags, currentTime, null); 6713 } catch (PackageManagerException e) { 6714 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6715 6716 // Delete invalid userdata apps 6717 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6718 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6719 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6720 removeCodePathLI(file); 6721 } 6722 } 6723 } 6724 } 6725 6726 private static File getSettingsProblemFile() { 6727 File dataDir = Environment.getDataDirectory(); 6728 File systemDir = new File(dataDir, "system"); 6729 File fname = new File(systemDir, "uiderrors.txt"); 6730 return fname; 6731 } 6732 6733 static void reportSettingsProblem(int priority, String msg) { 6734 logCriticalInfo(priority, msg); 6735 } 6736 6737 static void logCriticalInfo(int priority, String msg) { 6738 Slog.println(priority, TAG, msg); 6739 EventLogTags.writePmCriticalInfo(msg); 6740 try { 6741 File fname = getSettingsProblemFile(); 6742 FileOutputStream out = new FileOutputStream(fname, true); 6743 PrintWriter pw = new FastPrintWriter(out); 6744 SimpleDateFormat formatter = new SimpleDateFormat(); 6745 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6746 pw.println(dateString + ": " + msg); 6747 pw.close(); 6748 FileUtils.setPermissions( 6749 fname.toString(), 6750 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6751 -1, -1); 6752 } catch (java.io.IOException e) { 6753 } 6754 } 6755 6756 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6757 final int policyFlags) throws PackageManagerException { 6758 if (ps != null 6759 && ps.codePath.equals(srcFile) 6760 && ps.timeStamp == srcFile.lastModified() 6761 && !isCompatSignatureUpdateNeeded(pkg) 6762 && !isRecoverSignatureUpdateNeeded(pkg)) { 6763 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6764 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6765 ArraySet<PublicKey> signingKs; 6766 synchronized (mPackages) { 6767 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6768 } 6769 if (ps.signatures.mSignatures != null 6770 && ps.signatures.mSignatures.length != 0 6771 && signingKs != null) { 6772 // Optimization: reuse the existing cached certificates 6773 // if the package appears to be unchanged. 6774 pkg.mSignatures = ps.signatures.mSignatures; 6775 pkg.mSigningKeys = signingKs; 6776 return; 6777 } 6778 6779 Slog.w(TAG, "PackageSetting for " + ps.name 6780 + " is missing signatures. Collecting certs again to recover them."); 6781 } else { 6782 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6783 } 6784 6785 try { 6786 PackageParser.collectCertificates(pkg, policyFlags); 6787 } catch (PackageParserException e) { 6788 throw PackageManagerException.from(e); 6789 } 6790 } 6791 6792 /** 6793 * Traces a package scan. 6794 * @see #scanPackageLI(File, int, int, long, UserHandle) 6795 */ 6796 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6797 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6799 try { 6800 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6801 } finally { 6802 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6803 } 6804 } 6805 6806 /** 6807 * Scans a package and returns the newly parsed package. 6808 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6809 */ 6810 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6811 long currentTime, UserHandle user) throws PackageManagerException { 6812 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6813 PackageParser pp = new PackageParser(); 6814 pp.setSeparateProcesses(mSeparateProcesses); 6815 pp.setOnlyCoreApps(mOnlyCore); 6816 pp.setDisplayMetrics(mMetrics); 6817 6818 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6819 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6820 } 6821 6822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6823 final PackageParser.Package pkg; 6824 try { 6825 pkg = pp.parsePackage(scanFile, parseFlags); 6826 } catch (PackageParserException e) { 6827 throw PackageManagerException.from(e); 6828 } finally { 6829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6830 } 6831 6832 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6833 } 6834 6835 /** 6836 * Scans a package and returns the newly parsed package. 6837 * @throws PackageManagerException on a parse error. 6838 */ 6839 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6840 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6841 throws PackageManagerException { 6842 // If the package has children and this is the first dive in the function 6843 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6844 // packages (parent and children) would be successfully scanned before the 6845 // actual scan since scanning mutates internal state and we want to atomically 6846 // install the package and its children. 6847 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6848 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6849 scanFlags |= SCAN_CHECK_ONLY; 6850 } 6851 } else { 6852 scanFlags &= ~SCAN_CHECK_ONLY; 6853 } 6854 6855 // Scan the parent 6856 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6857 scanFlags, currentTime, user); 6858 6859 // Scan the children 6860 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6861 for (int i = 0; i < childCount; i++) { 6862 PackageParser.Package childPackage = pkg.childPackages.get(i); 6863 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6864 currentTime, user); 6865 } 6866 6867 6868 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6869 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6870 } 6871 6872 return scannedPkg; 6873 } 6874 6875 /** 6876 * Scans a package and returns the newly parsed package. 6877 * @throws PackageManagerException on a parse error. 6878 */ 6879 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6880 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6881 throws PackageManagerException { 6882 PackageSetting ps = null; 6883 PackageSetting updatedPkg; 6884 // reader 6885 synchronized (mPackages) { 6886 // Look to see if we already know about this package. 6887 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6888 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6889 // This package has been renamed to its original name. Let's 6890 // use that. 6891 ps = mSettings.peekPackageLPr(oldName); 6892 } 6893 // If there was no original package, see one for the real package name. 6894 if (ps == null) { 6895 ps = mSettings.peekPackageLPr(pkg.packageName); 6896 } 6897 // Check to see if this package could be hiding/updating a system 6898 // package. Must look for it either under the original or real 6899 // package name depending on our state. 6900 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6901 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6902 6903 // If this is a package we don't know about on the system partition, we 6904 // may need to remove disabled child packages on the system partition 6905 // or may need to not add child packages if the parent apk is updated 6906 // on the data partition and no longer defines this child package. 6907 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6908 // If this is a parent package for an updated system app and this system 6909 // app got an OTA update which no longer defines some of the child packages 6910 // we have to prune them from the disabled system packages. 6911 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6912 if (disabledPs != null) { 6913 final int scannedChildCount = (pkg.childPackages != null) 6914 ? pkg.childPackages.size() : 0; 6915 final int disabledChildCount = disabledPs.childPackageNames != null 6916 ? disabledPs.childPackageNames.size() : 0; 6917 for (int i = 0; i < disabledChildCount; i++) { 6918 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6919 boolean disabledPackageAvailable = false; 6920 for (int j = 0; j < scannedChildCount; j++) { 6921 PackageParser.Package childPkg = pkg.childPackages.get(j); 6922 if (childPkg.packageName.equals(disabledChildPackageName)) { 6923 disabledPackageAvailable = true; 6924 break; 6925 } 6926 } 6927 if (!disabledPackageAvailable) { 6928 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6929 } 6930 } 6931 } 6932 } 6933 } 6934 6935 boolean updatedPkgBetter = false; 6936 // First check if this is a system package that may involve an update 6937 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6938 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6939 // it needs to drop FLAG_PRIVILEGED. 6940 if (locationIsPrivileged(scanFile)) { 6941 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6942 } else { 6943 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6944 } 6945 6946 if (ps != null && !ps.codePath.equals(scanFile)) { 6947 // The path has changed from what was last scanned... check the 6948 // version of the new path against what we have stored to determine 6949 // what to do. 6950 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6951 if (pkg.mVersionCode <= ps.versionCode) { 6952 // The system package has been updated and the code path does not match 6953 // Ignore entry. Skip it. 6954 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6955 + " ignored: updated version " + ps.versionCode 6956 + " better than this " + pkg.mVersionCode); 6957 if (!updatedPkg.codePath.equals(scanFile)) { 6958 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6959 + ps.name + " changing from " + updatedPkg.codePathString 6960 + " to " + scanFile); 6961 updatedPkg.codePath = scanFile; 6962 updatedPkg.codePathString = scanFile.toString(); 6963 updatedPkg.resourcePath = scanFile; 6964 updatedPkg.resourcePathString = scanFile.toString(); 6965 } 6966 updatedPkg.pkg = pkg; 6967 updatedPkg.versionCode = pkg.mVersionCode; 6968 6969 // Update the disabled system child packages to point to the package too. 6970 final int childCount = updatedPkg.childPackageNames != null 6971 ? updatedPkg.childPackageNames.size() : 0; 6972 for (int i = 0; i < childCount; i++) { 6973 String childPackageName = updatedPkg.childPackageNames.get(i); 6974 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6975 childPackageName); 6976 if (updatedChildPkg != null) { 6977 updatedChildPkg.pkg = pkg; 6978 updatedChildPkg.versionCode = pkg.mVersionCode; 6979 } 6980 } 6981 6982 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6983 + scanFile + " ignored: updated version " + ps.versionCode 6984 + " better than this " + pkg.mVersionCode); 6985 } else { 6986 // The current app on the system partition is better than 6987 // what we have updated to on the data partition; switch 6988 // back to the system partition version. 6989 // At this point, its safely assumed that package installation for 6990 // apps in system partition will go through. If not there won't be a working 6991 // version of the app 6992 // writer 6993 synchronized (mPackages) { 6994 // Just remove the loaded entries from package lists. 6995 mPackages.remove(ps.name); 6996 } 6997 6998 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6999 + " reverting from " + ps.codePathString 7000 + ": new version " + pkg.mVersionCode 7001 + " better than installed " + ps.versionCode); 7002 7003 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7004 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7005 synchronized (mInstallLock) { 7006 args.cleanUpResourcesLI(); 7007 } 7008 synchronized (mPackages) { 7009 mSettings.enableSystemPackageLPw(ps.name); 7010 } 7011 updatedPkgBetter = true; 7012 } 7013 } 7014 } 7015 7016 if (updatedPkg != null) { 7017 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7018 // initially 7019 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7020 7021 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7022 // flag set initially 7023 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7024 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7025 } 7026 } 7027 7028 // Verify certificates against what was last scanned 7029 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7030 7031 /* 7032 * A new system app appeared, but we already had a non-system one of the 7033 * same name installed earlier. 7034 */ 7035 boolean shouldHideSystemApp = false; 7036 if (updatedPkg == null && ps != null 7037 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7038 /* 7039 * Check to make sure the signatures match first. If they don't, 7040 * wipe the installed application and its data. 7041 */ 7042 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7043 != PackageManager.SIGNATURE_MATCH) { 7044 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7045 + " signatures don't match existing userdata copy; removing"); 7046 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7047 "scanPackageInternalLI")) { 7048 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7049 } 7050 ps = null; 7051 } else { 7052 /* 7053 * If the newly-added system app is an older version than the 7054 * already installed version, hide it. It will be scanned later 7055 * and re-added like an update. 7056 */ 7057 if (pkg.mVersionCode <= ps.versionCode) { 7058 shouldHideSystemApp = true; 7059 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7060 + " but new version " + pkg.mVersionCode + " better than installed " 7061 + ps.versionCode + "; hiding system"); 7062 } else { 7063 /* 7064 * The newly found system app is a newer version that the 7065 * one previously installed. Simply remove the 7066 * already-installed application and replace it with our own 7067 * while keeping the application data. 7068 */ 7069 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7070 + " reverting from " + ps.codePathString + ": new version " 7071 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7072 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7073 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7074 synchronized (mInstallLock) { 7075 args.cleanUpResourcesLI(); 7076 } 7077 } 7078 } 7079 } 7080 7081 // The apk is forward locked (not public) if its code and resources 7082 // are kept in different files. (except for app in either system or 7083 // vendor path). 7084 // TODO grab this value from PackageSettings 7085 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7086 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7087 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7088 } 7089 } 7090 7091 // TODO: extend to support forward-locked splits 7092 String resourcePath = null; 7093 String baseResourcePath = null; 7094 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7095 if (ps != null && ps.resourcePathString != null) { 7096 resourcePath = ps.resourcePathString; 7097 baseResourcePath = ps.resourcePathString; 7098 } else { 7099 // Should not happen at all. Just log an error. 7100 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7101 } 7102 } else { 7103 resourcePath = pkg.codePath; 7104 baseResourcePath = pkg.baseCodePath; 7105 } 7106 7107 // Set application objects path explicitly. 7108 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7109 pkg.setApplicationInfoCodePath(pkg.codePath); 7110 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7111 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7112 pkg.setApplicationInfoResourcePath(resourcePath); 7113 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7114 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7115 7116 // Note that we invoke the following method only if we are about to unpack an application 7117 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7118 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7119 7120 /* 7121 * If the system app should be overridden by a previously installed 7122 * data, hide the system app now and let the /data/app scan pick it up 7123 * again. 7124 */ 7125 if (shouldHideSystemApp) { 7126 synchronized (mPackages) { 7127 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7128 } 7129 } 7130 7131 return scannedPkg; 7132 } 7133 7134 private static String fixProcessName(String defProcessName, 7135 String processName, int uid) { 7136 if (processName == null) { 7137 return defProcessName; 7138 } 7139 return processName; 7140 } 7141 7142 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7143 throws PackageManagerException { 7144 if (pkgSetting.signatures.mSignatures != null) { 7145 // Already existing package. Make sure signatures match 7146 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7147 == PackageManager.SIGNATURE_MATCH; 7148 if (!match) { 7149 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7150 == PackageManager.SIGNATURE_MATCH; 7151 } 7152 if (!match) { 7153 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7154 == PackageManager.SIGNATURE_MATCH; 7155 } 7156 if (!match) { 7157 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7158 + pkg.packageName + " signatures do not match the " 7159 + "previously installed version; ignoring!"); 7160 } 7161 } 7162 7163 // Check for shared user signatures 7164 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7165 // Already existing package. Make sure signatures match 7166 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7167 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7168 if (!match) { 7169 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7170 == PackageManager.SIGNATURE_MATCH; 7171 } 7172 if (!match) { 7173 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7174 == PackageManager.SIGNATURE_MATCH; 7175 } 7176 if (!match) { 7177 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7178 "Package " + pkg.packageName 7179 + " has no signatures that match those in shared user " 7180 + pkgSetting.sharedUser.name + "; ignoring!"); 7181 } 7182 } 7183 } 7184 7185 /** 7186 * Enforces that only the system UID or root's UID can call a method exposed 7187 * via Binder. 7188 * 7189 * @param message used as message if SecurityException is thrown 7190 * @throws SecurityException if the caller is not system or root 7191 */ 7192 private static final void enforceSystemOrRoot(String message) { 7193 final int uid = Binder.getCallingUid(); 7194 if (uid != Process.SYSTEM_UID && uid != 0) { 7195 throw new SecurityException(message); 7196 } 7197 } 7198 7199 @Override 7200 public void performFstrimIfNeeded() { 7201 enforceSystemOrRoot("Only the system can request fstrim"); 7202 7203 // Before everything else, see whether we need to fstrim. 7204 try { 7205 IMountService ms = PackageHelper.getMountService(); 7206 if (ms != null) { 7207 final boolean isUpgrade = isUpgrade(); 7208 boolean doTrim = isUpgrade; 7209 if (doTrim) { 7210 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7211 } else { 7212 final long interval = android.provider.Settings.Global.getLong( 7213 mContext.getContentResolver(), 7214 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7215 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7216 if (interval > 0) { 7217 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7218 if (timeSinceLast > interval) { 7219 doTrim = true; 7220 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7221 + "; running immediately"); 7222 } 7223 } 7224 } 7225 if (doTrim) { 7226 if (!isFirstBoot()) { 7227 try { 7228 ActivityManagerNative.getDefault().showBootMessage( 7229 mContext.getResources().getString( 7230 R.string.android_upgrading_fstrim), true); 7231 } catch (RemoteException e) { 7232 } 7233 } 7234 ms.runMaintenance(); 7235 } 7236 } else { 7237 Slog.e(TAG, "Mount service unavailable!"); 7238 } 7239 } catch (RemoteException e) { 7240 // Can't happen; MountService is local 7241 } 7242 } 7243 7244 @Override 7245 public void updatePackagesIfNeeded() { 7246 enforceSystemOrRoot("Only the system can request package update"); 7247 7248 // We need to re-extract after an OTA. 7249 boolean causeUpgrade = isUpgrade(); 7250 7251 // First boot or factory reset. 7252 // Note: we also handle devices that are upgrading to N right now as if it is their 7253 // first boot, as they do not have profile data. 7254 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7255 7256 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7257 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7258 7259 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7260 return; 7261 } 7262 7263 List<PackageParser.Package> pkgs; 7264 synchronized (mPackages) { 7265 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7266 } 7267 7268 final long startTime = System.nanoTime(); 7269 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7270 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7271 7272 final int elapsedTimeSeconds = 7273 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7274 7275 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7276 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7279 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7280 } 7281 7282 /** 7283 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7284 * containing statistics about the invocation. The array consists of three elements, 7285 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7286 * and {@code numberOfPackagesFailed}. 7287 */ 7288 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7289 String compilerFilter) { 7290 7291 int numberOfPackagesVisited = 0; 7292 int numberOfPackagesOptimized = 0; 7293 int numberOfPackagesSkipped = 0; 7294 int numberOfPackagesFailed = 0; 7295 final int numberOfPackagesToDexopt = pkgs.size(); 7296 7297 for (PackageParser.Package pkg : pkgs) { 7298 numberOfPackagesVisited++; 7299 7300 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7301 if (DEBUG_DEXOPT) { 7302 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7303 } 7304 numberOfPackagesSkipped++; 7305 continue; 7306 } 7307 7308 if (DEBUG_DEXOPT) { 7309 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7310 numberOfPackagesToDexopt + ": " + pkg.packageName); 7311 } 7312 7313 if (showDialog) { 7314 try { 7315 ActivityManagerNative.getDefault().showBootMessage( 7316 mContext.getResources().getString(R.string.android_upgrading_apk, 7317 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7318 } catch (RemoteException e) { 7319 } 7320 } 7321 7322 // checkProfiles is false to avoid merging profiles during boot which 7323 // might interfere with background compilation (b/28612421). 7324 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7325 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7326 // trade-off worth doing to save boot time work. 7327 int dexOptStatus = performDexOptTraced(pkg.packageName, 7328 false /* checkProfiles */, 7329 compilerFilter, 7330 false /* force */); 7331 switch (dexOptStatus) { 7332 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7333 numberOfPackagesOptimized++; 7334 break; 7335 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7336 numberOfPackagesSkipped++; 7337 break; 7338 case PackageDexOptimizer.DEX_OPT_FAILED: 7339 numberOfPackagesFailed++; 7340 break; 7341 default: 7342 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7343 break; 7344 } 7345 } 7346 7347 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7348 numberOfPackagesFailed }; 7349 } 7350 7351 @Override 7352 public void notifyPackageUse(String packageName, int reason) { 7353 synchronized (mPackages) { 7354 PackageParser.Package p = mPackages.get(packageName); 7355 if (p == null) { 7356 return; 7357 } 7358 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7359 } 7360 } 7361 7362 // TODO: this is not used nor needed. Delete it. 7363 @Override 7364 public boolean performDexOptIfNeeded(String packageName) { 7365 int dexOptStatus = performDexOptTraced(packageName, 7366 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7367 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7368 } 7369 7370 @Override 7371 public boolean performDexOpt(String packageName, 7372 boolean checkProfiles, int compileReason, boolean force) { 7373 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7374 getCompilerFilterForReason(compileReason), force); 7375 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7376 } 7377 7378 @Override 7379 public boolean performDexOptMode(String packageName, 7380 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7381 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7382 targetCompilerFilter, force); 7383 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7384 } 7385 7386 private int performDexOptTraced(String packageName, 7387 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7389 try { 7390 return performDexOptInternal(packageName, checkProfiles, 7391 targetCompilerFilter, force); 7392 } finally { 7393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7394 } 7395 } 7396 7397 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7398 // if the package can now be considered up to date for the given filter. 7399 private int performDexOptInternal(String packageName, 7400 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7401 PackageParser.Package p; 7402 synchronized (mPackages) { 7403 p = mPackages.get(packageName); 7404 if (p == null) { 7405 // Package could not be found. Report failure. 7406 return PackageDexOptimizer.DEX_OPT_FAILED; 7407 } 7408 mPackageUsage.write(false); 7409 } 7410 long callingId = Binder.clearCallingIdentity(); 7411 try { 7412 synchronized (mInstallLock) { 7413 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7414 targetCompilerFilter, force); 7415 } 7416 } finally { 7417 Binder.restoreCallingIdentity(callingId); 7418 } 7419 } 7420 7421 public ArraySet<String> getOptimizablePackages() { 7422 ArraySet<String> pkgs = new ArraySet<String>(); 7423 synchronized (mPackages) { 7424 for (PackageParser.Package p : mPackages.values()) { 7425 if (PackageDexOptimizer.canOptimizePackage(p)) { 7426 pkgs.add(p.packageName); 7427 } 7428 } 7429 } 7430 return pkgs; 7431 } 7432 7433 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7434 boolean checkProfiles, String targetCompilerFilter, 7435 boolean force) { 7436 // Select the dex optimizer based on the force parameter. 7437 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7438 // allocate an object here. 7439 PackageDexOptimizer pdo = force 7440 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7441 : mPackageDexOptimizer; 7442 7443 // Optimize all dependencies first. Note: we ignore the return value and march on 7444 // on errors. 7445 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7446 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7447 if (!deps.isEmpty()) { 7448 for (PackageParser.Package depPackage : deps) { 7449 // TODO: Analyze and investigate if we (should) profile libraries. 7450 // Currently this will do a full compilation of the library by default. 7451 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7452 false /* checkProfiles */, 7453 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7454 } 7455 } 7456 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7457 targetCompilerFilter); 7458 } 7459 7460 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7461 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7462 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7463 Set<String> collectedNames = new HashSet<>(); 7464 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7465 7466 retValue.remove(p); 7467 7468 return retValue; 7469 } else { 7470 return Collections.emptyList(); 7471 } 7472 } 7473 7474 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7475 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7476 if (!collectedNames.contains(p.packageName)) { 7477 collectedNames.add(p.packageName); 7478 collected.add(p); 7479 7480 if (p.usesLibraries != null) { 7481 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7482 } 7483 if (p.usesOptionalLibraries != null) { 7484 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7485 collectedNames); 7486 } 7487 } 7488 } 7489 7490 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7491 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7492 for (String libName : libs) { 7493 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7494 if (libPkg != null) { 7495 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7496 } 7497 } 7498 } 7499 7500 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7501 synchronized (mPackages) { 7502 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7503 if (lib != null && lib.apk != null) { 7504 return mPackages.get(lib.apk); 7505 } 7506 } 7507 return null; 7508 } 7509 7510 public void shutdown() { 7511 mPackageUsage.write(true); 7512 } 7513 7514 @Override 7515 public void dumpProfiles(String packageName) { 7516 PackageParser.Package pkg; 7517 synchronized (mPackages) { 7518 pkg = mPackages.get(packageName); 7519 if (pkg == null) { 7520 throw new IllegalArgumentException("Unknown package: " + packageName); 7521 } 7522 } 7523 /* Only the shell, root, or the app user should be able to dump profiles. */ 7524 int callingUid = Binder.getCallingUid(); 7525 if (callingUid != Process.SHELL_UID && 7526 callingUid != Process.ROOT_UID && 7527 callingUid != pkg.applicationInfo.uid) { 7528 throw new SecurityException("dumpProfiles"); 7529 } 7530 7531 synchronized (mInstallLock) { 7532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7533 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7534 try { 7535 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7536 String gid = Integer.toString(sharedGid); 7537 String codePaths = TextUtils.join(";", allCodePaths); 7538 mInstaller.dumpProfiles(gid, packageName, codePaths); 7539 } catch (InstallerException e) { 7540 Slog.w(TAG, "Failed to dump profiles", e); 7541 } 7542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7543 } 7544 } 7545 7546 @Override 7547 public void forceDexOpt(String packageName) { 7548 enforceSystemOrRoot("forceDexOpt"); 7549 7550 PackageParser.Package pkg; 7551 synchronized (mPackages) { 7552 pkg = mPackages.get(packageName); 7553 if (pkg == null) { 7554 throw new IllegalArgumentException("Unknown package: " + packageName); 7555 } 7556 } 7557 7558 synchronized (mInstallLock) { 7559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7560 7561 // Whoever is calling forceDexOpt wants a fully compiled package. 7562 // Don't use profiles since that may cause compilation to be skipped. 7563 final int res = performDexOptInternalWithDependenciesLI(pkg, 7564 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7565 true /* force */); 7566 7567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7568 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7569 throw new IllegalStateException("Failed to dexopt: " + res); 7570 } 7571 } 7572 } 7573 7574 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7575 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7576 Slog.w(TAG, "Unable to update from " + oldPkg.name 7577 + " to " + newPkg.packageName 7578 + ": old package not in system partition"); 7579 return false; 7580 } else if (mPackages.get(oldPkg.name) != null) { 7581 Slog.w(TAG, "Unable to update from " + oldPkg.name 7582 + " to " + newPkg.packageName 7583 + ": old package still exists"); 7584 return false; 7585 } 7586 return true; 7587 } 7588 7589 void removeCodePathLI(File codePath) { 7590 if (codePath.isDirectory()) { 7591 try { 7592 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7593 } catch (InstallerException e) { 7594 Slog.w(TAG, "Failed to remove code path", e); 7595 } 7596 } else { 7597 codePath.delete(); 7598 } 7599 } 7600 7601 private int[] resolveUserIds(int userId) { 7602 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7603 } 7604 7605 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7606 if (pkg == null) { 7607 Slog.wtf(TAG, "Package was null!", new Throwable()); 7608 return; 7609 } 7610 clearAppDataLeafLIF(pkg, userId, flags); 7611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7612 for (int i = 0; i < childCount; i++) { 7613 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7614 } 7615 } 7616 7617 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7618 final PackageSetting ps; 7619 synchronized (mPackages) { 7620 ps = mSettings.mPackages.get(pkg.packageName); 7621 } 7622 for (int realUserId : resolveUserIds(userId)) { 7623 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7624 try { 7625 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7626 ceDataInode); 7627 } catch (InstallerException e) { 7628 Slog.w(TAG, String.valueOf(e)); 7629 } 7630 } 7631 } 7632 7633 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7634 if (pkg == null) { 7635 Slog.wtf(TAG, "Package was null!", new Throwable()); 7636 return; 7637 } 7638 destroyAppDataLeafLIF(pkg, userId, flags); 7639 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7640 for (int i = 0; i < childCount; i++) { 7641 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7642 } 7643 } 7644 7645 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7646 final PackageSetting ps; 7647 synchronized (mPackages) { 7648 ps = mSettings.mPackages.get(pkg.packageName); 7649 } 7650 for (int realUserId : resolveUserIds(userId)) { 7651 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7652 try { 7653 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7654 ceDataInode); 7655 } catch (InstallerException e) { 7656 Slog.w(TAG, String.valueOf(e)); 7657 } 7658 } 7659 } 7660 7661 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7662 if (pkg == null) { 7663 Slog.wtf(TAG, "Package was null!", new Throwable()); 7664 return; 7665 } 7666 destroyAppProfilesLeafLIF(pkg); 7667 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7668 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7669 for (int i = 0; i < childCount; i++) { 7670 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7671 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7672 true /* removeBaseMarker */); 7673 } 7674 } 7675 7676 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7677 boolean removeBaseMarker) { 7678 if (pkg.isForwardLocked()) { 7679 return; 7680 } 7681 7682 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7683 try { 7684 path = PackageManagerServiceUtils.realpath(new File(path)); 7685 } catch (IOException e) { 7686 // TODO: Should we return early here ? 7687 Slog.w(TAG, "Failed to get canonical path", e); 7688 continue; 7689 } 7690 7691 final String useMarker = path.replace('/', '@'); 7692 for (int realUserId : resolveUserIds(userId)) { 7693 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7694 if (removeBaseMarker) { 7695 File foreignUseMark = new File(profileDir, useMarker); 7696 if (foreignUseMark.exists()) { 7697 if (!foreignUseMark.delete()) { 7698 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7699 + pkg.packageName); 7700 } 7701 } 7702 } 7703 7704 File[] markers = profileDir.listFiles(); 7705 if (markers != null) { 7706 final String searchString = "@" + pkg.packageName + "@"; 7707 // We also delete all markers that contain the package name we're 7708 // uninstalling. These are associated with secondary dex-files belonging 7709 // to the package. Reconstructing the path of these dex files is messy 7710 // in general. 7711 for (File marker : markers) { 7712 if (marker.getName().indexOf(searchString) > 0) { 7713 if (!marker.delete()) { 7714 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7715 + pkg.packageName); 7716 } 7717 } 7718 } 7719 } 7720 } 7721 } 7722 } 7723 7724 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7725 try { 7726 mInstaller.destroyAppProfiles(pkg.packageName); 7727 } catch (InstallerException e) { 7728 Slog.w(TAG, String.valueOf(e)); 7729 } 7730 } 7731 7732 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7733 if (pkg == null) { 7734 Slog.wtf(TAG, "Package was null!", new Throwable()); 7735 return; 7736 } 7737 clearAppProfilesLeafLIF(pkg); 7738 // We don't remove the base foreign use marker when clearing profiles because 7739 // we will rename it when the app is updated. Unlike the actual profile contents, 7740 // the foreign use marker is good across installs. 7741 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7742 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7743 for (int i = 0; i < childCount; i++) { 7744 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7745 } 7746 } 7747 7748 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7749 try { 7750 mInstaller.clearAppProfiles(pkg.packageName); 7751 } catch (InstallerException e) { 7752 Slog.w(TAG, String.valueOf(e)); 7753 } 7754 } 7755 7756 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7757 long lastUpdateTime) { 7758 // Set parent install/update time 7759 PackageSetting ps = (PackageSetting) pkg.mExtras; 7760 if (ps != null) { 7761 ps.firstInstallTime = firstInstallTime; 7762 ps.lastUpdateTime = lastUpdateTime; 7763 } 7764 // Set children install/update time 7765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7766 for (int i = 0; i < childCount; i++) { 7767 PackageParser.Package childPkg = pkg.childPackages.get(i); 7768 ps = (PackageSetting) childPkg.mExtras; 7769 if (ps != null) { 7770 ps.firstInstallTime = firstInstallTime; 7771 ps.lastUpdateTime = lastUpdateTime; 7772 } 7773 } 7774 } 7775 7776 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7777 PackageParser.Package changingLib) { 7778 if (file.path != null) { 7779 usesLibraryFiles.add(file.path); 7780 return; 7781 } 7782 PackageParser.Package p = mPackages.get(file.apk); 7783 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7784 // If we are doing this while in the middle of updating a library apk, 7785 // then we need to make sure to use that new apk for determining the 7786 // dependencies here. (We haven't yet finished committing the new apk 7787 // to the package manager state.) 7788 if (p == null || p.packageName.equals(changingLib.packageName)) { 7789 p = changingLib; 7790 } 7791 } 7792 if (p != null) { 7793 usesLibraryFiles.addAll(p.getAllCodePaths()); 7794 } 7795 } 7796 7797 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7798 PackageParser.Package changingLib) throws PackageManagerException { 7799 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7800 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7801 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7802 for (int i=0; i<N; i++) { 7803 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7804 if (file == null) { 7805 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7806 "Package " + pkg.packageName + " requires unavailable shared library " 7807 + pkg.usesLibraries.get(i) + "; failing!"); 7808 } 7809 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7810 } 7811 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7812 for (int i=0; i<N; i++) { 7813 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7814 if (file == null) { 7815 Slog.w(TAG, "Package " + pkg.packageName 7816 + " desires unavailable shared library " 7817 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7818 } else { 7819 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7820 } 7821 } 7822 N = usesLibraryFiles.size(); 7823 if (N > 0) { 7824 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7825 } else { 7826 pkg.usesLibraryFiles = null; 7827 } 7828 } 7829 } 7830 7831 private static boolean hasString(List<String> list, List<String> which) { 7832 if (list == null) { 7833 return false; 7834 } 7835 for (int i=list.size()-1; i>=0; i--) { 7836 for (int j=which.size()-1; j>=0; j--) { 7837 if (which.get(j).equals(list.get(i))) { 7838 return true; 7839 } 7840 } 7841 } 7842 return false; 7843 } 7844 7845 private void updateAllSharedLibrariesLPw() { 7846 for (PackageParser.Package pkg : mPackages.values()) { 7847 try { 7848 updateSharedLibrariesLPw(pkg, null); 7849 } catch (PackageManagerException e) { 7850 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7851 } 7852 } 7853 } 7854 7855 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7856 PackageParser.Package changingPkg) { 7857 ArrayList<PackageParser.Package> res = null; 7858 for (PackageParser.Package pkg : mPackages.values()) { 7859 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7860 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7861 if (res == null) { 7862 res = new ArrayList<PackageParser.Package>(); 7863 } 7864 res.add(pkg); 7865 try { 7866 updateSharedLibrariesLPw(pkg, changingPkg); 7867 } catch (PackageManagerException e) { 7868 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7869 } 7870 } 7871 } 7872 return res; 7873 } 7874 7875 /** 7876 * Derive the value of the {@code cpuAbiOverride} based on the provided 7877 * value and an optional stored value from the package settings. 7878 */ 7879 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7880 String cpuAbiOverride = null; 7881 7882 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7883 cpuAbiOverride = null; 7884 } else if (abiOverride != null) { 7885 cpuAbiOverride = abiOverride; 7886 } else if (settings != null) { 7887 cpuAbiOverride = settings.cpuAbiOverrideString; 7888 } 7889 7890 return cpuAbiOverride; 7891 } 7892 7893 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7894 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7895 throws PackageManagerException { 7896 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7897 // If the package has children and this is the first dive in the function 7898 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7899 // whether all packages (parent and children) would be successfully scanned 7900 // before the actual scan since scanning mutates internal state and we want 7901 // to atomically install the package and its children. 7902 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7903 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7904 scanFlags |= SCAN_CHECK_ONLY; 7905 } 7906 } else { 7907 scanFlags &= ~SCAN_CHECK_ONLY; 7908 } 7909 7910 final PackageParser.Package scannedPkg; 7911 try { 7912 // Scan the parent 7913 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7914 // Scan the children 7915 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7916 for (int i = 0; i < childCount; i++) { 7917 PackageParser.Package childPkg = pkg.childPackages.get(i); 7918 scanPackageLI(childPkg, policyFlags, 7919 scanFlags, currentTime, user); 7920 } 7921 } finally { 7922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7923 } 7924 7925 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7926 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7927 } 7928 7929 return scannedPkg; 7930 } 7931 7932 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7933 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7934 boolean success = false; 7935 try { 7936 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7937 currentTime, user); 7938 success = true; 7939 return res; 7940 } finally { 7941 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7942 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7943 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7944 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7945 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7946 } 7947 } 7948 } 7949 7950 /** 7951 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7952 */ 7953 private static boolean apkHasCode(String fileName) { 7954 StrictJarFile jarFile = null; 7955 try { 7956 jarFile = new StrictJarFile(fileName, 7957 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7958 return jarFile.findEntry("classes.dex") != null; 7959 } catch (IOException ignore) { 7960 } finally { 7961 try { 7962 jarFile.close(); 7963 } catch (IOException ignore) {} 7964 } 7965 return false; 7966 } 7967 7968 /** 7969 * Enforces code policy for the package. This ensures that if an APK has 7970 * declared hasCode="true" in its manifest that the APK actually contains 7971 * code. 7972 * 7973 * @throws PackageManagerException If bytecode could not be found when it should exist 7974 */ 7975 private static void enforceCodePolicy(PackageParser.Package pkg) 7976 throws PackageManagerException { 7977 final boolean shouldHaveCode = 7978 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7979 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7980 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7981 "Package " + pkg.baseCodePath + " code is missing"); 7982 } 7983 7984 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7985 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7986 final boolean splitShouldHaveCode = 7987 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7988 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7989 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7990 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7991 } 7992 } 7993 } 7994 } 7995 7996 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7997 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7998 throws PackageManagerException { 7999 final File scanFile = new File(pkg.codePath); 8000 if (pkg.applicationInfo.getCodePath() == null || 8001 pkg.applicationInfo.getResourcePath() == null) { 8002 // Bail out. The resource and code paths haven't been set. 8003 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8004 "Code and resource paths haven't been set correctly"); 8005 } 8006 8007 // Apply policy 8008 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8009 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8010 if (pkg.applicationInfo.isDirectBootAware()) { 8011 // we're direct boot aware; set for all components 8012 for (PackageParser.Service s : pkg.services) { 8013 s.info.encryptionAware = s.info.directBootAware = true; 8014 } 8015 for (PackageParser.Provider p : pkg.providers) { 8016 p.info.encryptionAware = p.info.directBootAware = true; 8017 } 8018 for (PackageParser.Activity a : pkg.activities) { 8019 a.info.encryptionAware = a.info.directBootAware = true; 8020 } 8021 for (PackageParser.Activity r : pkg.receivers) { 8022 r.info.encryptionAware = r.info.directBootAware = true; 8023 } 8024 } 8025 } else { 8026 // Only allow system apps to be flagged as core apps. 8027 pkg.coreApp = false; 8028 // clear flags not applicable to regular apps 8029 pkg.applicationInfo.privateFlags &= 8030 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8031 pkg.applicationInfo.privateFlags &= 8032 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8033 } 8034 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8035 8036 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8037 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8038 } 8039 8040 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8041 enforceCodePolicy(pkg); 8042 } 8043 8044 if (mCustomResolverComponentName != null && 8045 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8046 setUpCustomResolverActivity(pkg); 8047 } 8048 8049 if (pkg.packageName.equals("android")) { 8050 synchronized (mPackages) { 8051 if (mAndroidApplication != null) { 8052 Slog.w(TAG, "*************************************************"); 8053 Slog.w(TAG, "Core android package being redefined. Skipping."); 8054 Slog.w(TAG, " file=" + scanFile); 8055 Slog.w(TAG, "*************************************************"); 8056 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8057 "Core android package being redefined. Skipping."); 8058 } 8059 8060 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8061 // Set up information for our fall-back user intent resolution activity. 8062 mPlatformPackage = pkg; 8063 pkg.mVersionCode = mSdkVersion; 8064 mAndroidApplication = pkg.applicationInfo; 8065 8066 if (!mResolverReplaced) { 8067 mResolveActivity.applicationInfo = mAndroidApplication; 8068 mResolveActivity.name = ResolverActivity.class.getName(); 8069 mResolveActivity.packageName = mAndroidApplication.packageName; 8070 mResolveActivity.processName = "system:ui"; 8071 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8072 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8073 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8074 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8075 mResolveActivity.exported = true; 8076 mResolveActivity.enabled = true; 8077 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8078 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8079 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8080 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8081 | ActivityInfo.CONFIG_ORIENTATION 8082 | ActivityInfo.CONFIG_KEYBOARD 8083 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8084 mResolveInfo.activityInfo = mResolveActivity; 8085 mResolveInfo.priority = 0; 8086 mResolveInfo.preferredOrder = 0; 8087 mResolveInfo.match = 0; 8088 mResolveComponentName = new ComponentName( 8089 mAndroidApplication.packageName, mResolveActivity.name); 8090 } 8091 } 8092 } 8093 } 8094 8095 if (DEBUG_PACKAGE_SCANNING) { 8096 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8097 Log.d(TAG, "Scanning package " + pkg.packageName); 8098 } 8099 8100 synchronized (mPackages) { 8101 if (mPackages.containsKey(pkg.packageName) 8102 || mSharedLibraries.containsKey(pkg.packageName)) { 8103 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8104 "Application package " + pkg.packageName 8105 + " already installed. Skipping duplicate."); 8106 } 8107 8108 // If we're only installing presumed-existing packages, require that the 8109 // scanned APK is both already known and at the path previously established 8110 // for it. Previously unknown packages we pick up normally, but if we have an 8111 // a priori expectation about this package's install presence, enforce it. 8112 // With a singular exception for new system packages. When an OTA contains 8113 // a new system package, we allow the codepath to change from a system location 8114 // to the user-installed location. If we don't allow this change, any newer, 8115 // user-installed version of the application will be ignored. 8116 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8117 if (mExpectingBetter.containsKey(pkg.packageName)) { 8118 logCriticalInfo(Log.WARN, 8119 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8120 } else { 8121 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8122 if (known != null) { 8123 if (DEBUG_PACKAGE_SCANNING) { 8124 Log.d(TAG, "Examining " + pkg.codePath 8125 + " and requiring known paths " + known.codePathString 8126 + " & " + known.resourcePathString); 8127 } 8128 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8129 || !pkg.applicationInfo.getResourcePath().equals( 8130 known.resourcePathString)) { 8131 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8132 "Application package " + pkg.packageName 8133 + " found at " + pkg.applicationInfo.getCodePath() 8134 + " but expected at " + known.codePathString 8135 + "; ignoring."); 8136 } 8137 } 8138 } 8139 } 8140 } 8141 8142 // Initialize package source and resource directories 8143 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8144 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8145 8146 SharedUserSetting suid = null; 8147 PackageSetting pkgSetting = null; 8148 8149 if (!isSystemApp(pkg)) { 8150 // Only system apps can use these features. 8151 pkg.mOriginalPackages = null; 8152 pkg.mRealPackage = null; 8153 pkg.mAdoptPermissions = null; 8154 } 8155 8156 // Getting the package setting may have a side-effect, so if we 8157 // are only checking if scan would succeed, stash a copy of the 8158 // old setting to restore at the end. 8159 PackageSetting nonMutatedPs = null; 8160 8161 // writer 8162 synchronized (mPackages) { 8163 if (pkg.mSharedUserId != null) { 8164 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8165 if (suid == null) { 8166 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8167 "Creating application package " + pkg.packageName 8168 + " for shared user failed"); 8169 } 8170 if (DEBUG_PACKAGE_SCANNING) { 8171 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8172 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8173 + "): packages=" + suid.packages); 8174 } 8175 } 8176 8177 // Check if we are renaming from an original package name. 8178 PackageSetting origPackage = null; 8179 String realName = null; 8180 if (pkg.mOriginalPackages != null) { 8181 // This package may need to be renamed to a previously 8182 // installed name. Let's check on that... 8183 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8184 if (pkg.mOriginalPackages.contains(renamed)) { 8185 // This package had originally been installed as the 8186 // original name, and we have already taken care of 8187 // transitioning to the new one. Just update the new 8188 // one to continue using the old name. 8189 realName = pkg.mRealPackage; 8190 if (!pkg.packageName.equals(renamed)) { 8191 // Callers into this function may have already taken 8192 // care of renaming the package; only do it here if 8193 // it is not already done. 8194 pkg.setPackageName(renamed); 8195 } 8196 8197 } else { 8198 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8199 if ((origPackage = mSettings.peekPackageLPr( 8200 pkg.mOriginalPackages.get(i))) != null) { 8201 // We do have the package already installed under its 8202 // original name... should we use it? 8203 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8204 // New package is not compatible with original. 8205 origPackage = null; 8206 continue; 8207 } else if (origPackage.sharedUser != null) { 8208 // Make sure uid is compatible between packages. 8209 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8210 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8211 + " to " + pkg.packageName + ": old uid " 8212 + origPackage.sharedUser.name 8213 + " differs from " + pkg.mSharedUserId); 8214 origPackage = null; 8215 continue; 8216 } 8217 // TODO: Add case when shared user id is added [b/28144775] 8218 } else { 8219 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8220 + pkg.packageName + " to old name " + origPackage.name); 8221 } 8222 break; 8223 } 8224 } 8225 } 8226 } 8227 8228 if (mTransferedPackages.contains(pkg.packageName)) { 8229 Slog.w(TAG, "Package " + pkg.packageName 8230 + " was transferred to another, but its .apk remains"); 8231 } 8232 8233 // See comments in nonMutatedPs declaration 8234 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8235 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8236 if (foundPs != null) { 8237 nonMutatedPs = new PackageSetting(foundPs); 8238 } 8239 } 8240 8241 // Just create the setting, don't add it yet. For already existing packages 8242 // the PkgSetting exists already and doesn't have to be created. 8243 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8244 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8245 pkg.applicationInfo.primaryCpuAbi, 8246 pkg.applicationInfo.secondaryCpuAbi, 8247 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8248 user, false); 8249 if (pkgSetting == null) { 8250 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8251 "Creating application package " + pkg.packageName + " failed"); 8252 } 8253 8254 if (pkgSetting.origPackage != null) { 8255 // If we are first transitioning from an original package, 8256 // fix up the new package's name now. We need to do this after 8257 // looking up the package under its new name, so getPackageLP 8258 // can take care of fiddling things correctly. 8259 pkg.setPackageName(origPackage.name); 8260 8261 // File a report about this. 8262 String msg = "New package " + pkgSetting.realName 8263 + " renamed to replace old package " + pkgSetting.name; 8264 reportSettingsProblem(Log.WARN, msg); 8265 8266 // Make a note of it. 8267 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8268 mTransferedPackages.add(origPackage.name); 8269 } 8270 8271 // No longer need to retain this. 8272 pkgSetting.origPackage = null; 8273 } 8274 8275 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8276 // Make a note of it. 8277 mTransferedPackages.add(pkg.packageName); 8278 } 8279 8280 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8281 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8282 } 8283 8284 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8285 // Check all shared libraries and map to their actual file path. 8286 // We only do this here for apps not on a system dir, because those 8287 // are the only ones that can fail an install due to this. We 8288 // will take care of the system apps by updating all of their 8289 // library paths after the scan is done. 8290 updateSharedLibrariesLPw(pkg, null); 8291 } 8292 8293 if (mFoundPolicyFile) { 8294 SELinuxMMAC.assignSeinfoValue(pkg); 8295 } 8296 8297 pkg.applicationInfo.uid = pkgSetting.appId; 8298 pkg.mExtras = pkgSetting; 8299 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8300 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8301 // We just determined the app is signed correctly, so bring 8302 // over the latest parsed certs. 8303 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8304 } else { 8305 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8306 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8307 "Package " + pkg.packageName + " upgrade keys do not match the " 8308 + "previously installed version"); 8309 } else { 8310 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8311 String msg = "System package " + pkg.packageName 8312 + " signature changed; retaining data."; 8313 reportSettingsProblem(Log.WARN, msg); 8314 } 8315 } 8316 } else { 8317 try { 8318 verifySignaturesLP(pkgSetting, pkg); 8319 // We just determined the app is signed correctly, so bring 8320 // over the latest parsed certs. 8321 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8322 } catch (PackageManagerException e) { 8323 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8324 throw e; 8325 } 8326 // The signature has changed, but this package is in the system 8327 // image... let's recover! 8328 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8329 // However... if this package is part of a shared user, but it 8330 // doesn't match the signature of the shared user, let's fail. 8331 // What this means is that you can't change the signatures 8332 // associated with an overall shared user, which doesn't seem all 8333 // that unreasonable. 8334 if (pkgSetting.sharedUser != null) { 8335 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8336 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8337 throw new PackageManagerException( 8338 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8339 "Signature mismatch for shared user: " 8340 + pkgSetting.sharedUser); 8341 } 8342 } 8343 // File a report about this. 8344 String msg = "System package " + pkg.packageName 8345 + " signature changed; retaining data."; 8346 reportSettingsProblem(Log.WARN, msg); 8347 } 8348 } 8349 // Verify that this new package doesn't have any content providers 8350 // that conflict with existing packages. Only do this if the 8351 // package isn't already installed, since we don't want to break 8352 // things that are installed. 8353 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8354 final int N = pkg.providers.size(); 8355 int i; 8356 for (i=0; i<N; i++) { 8357 PackageParser.Provider p = pkg.providers.get(i); 8358 if (p.info.authority != null) { 8359 String names[] = p.info.authority.split(";"); 8360 for (int j = 0; j < names.length; j++) { 8361 if (mProvidersByAuthority.containsKey(names[j])) { 8362 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8363 final String otherPackageName = 8364 ((other != null && other.getComponentName() != null) ? 8365 other.getComponentName().getPackageName() : "?"); 8366 throw new PackageManagerException( 8367 INSTALL_FAILED_CONFLICTING_PROVIDER, 8368 "Can't install because provider name " + names[j] 8369 + " (in package " + pkg.applicationInfo.packageName 8370 + ") is already used by " + otherPackageName); 8371 } 8372 } 8373 } 8374 } 8375 } 8376 8377 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8378 // This package wants to adopt ownership of permissions from 8379 // another package. 8380 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8381 final String origName = pkg.mAdoptPermissions.get(i); 8382 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8383 if (orig != null) { 8384 if (verifyPackageUpdateLPr(orig, pkg)) { 8385 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8386 + pkg.packageName); 8387 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8388 } 8389 } 8390 } 8391 } 8392 } 8393 8394 final String pkgName = pkg.packageName; 8395 8396 final long scanFileTime = scanFile.lastModified(); 8397 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8398 pkg.applicationInfo.processName = fixProcessName( 8399 pkg.applicationInfo.packageName, 8400 pkg.applicationInfo.processName, 8401 pkg.applicationInfo.uid); 8402 8403 if (pkg != mPlatformPackage) { 8404 // Get all of our default paths setup 8405 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8406 } 8407 8408 final String path = scanFile.getPath(); 8409 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8410 8411 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8412 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8413 8414 // Some system apps still use directory structure for native libraries 8415 // in which case we might end up not detecting abi solely based on apk 8416 // structure. Try to detect abi based on directory structure. 8417 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8418 pkg.applicationInfo.primaryCpuAbi == null) { 8419 setBundledAppAbisAndRoots(pkg, pkgSetting); 8420 setNativeLibraryPaths(pkg); 8421 } 8422 8423 } else { 8424 if ((scanFlags & SCAN_MOVE) != 0) { 8425 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8426 // but we already have this packages package info in the PackageSetting. We just 8427 // use that and derive the native library path based on the new codepath. 8428 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8429 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8430 } 8431 8432 // Set native library paths again. For moves, the path will be updated based on the 8433 // ABIs we've determined above. For non-moves, the path will be updated based on the 8434 // ABIs we determined during compilation, but the path will depend on the final 8435 // package path (after the rename away from the stage path). 8436 setNativeLibraryPaths(pkg); 8437 } 8438 8439 // This is a special case for the "system" package, where the ABI is 8440 // dictated by the zygote configuration (and init.rc). We should keep track 8441 // of this ABI so that we can deal with "normal" applications that run under 8442 // the same UID correctly. 8443 if (mPlatformPackage == pkg) { 8444 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8445 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8446 } 8447 8448 // If there's a mismatch between the abi-override in the package setting 8449 // and the abiOverride specified for the install. Warn about this because we 8450 // would've already compiled the app without taking the package setting into 8451 // account. 8452 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8453 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8454 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8455 " for package " + pkg.packageName); 8456 } 8457 } 8458 8459 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8460 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8461 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8462 8463 // Copy the derived override back to the parsed package, so that we can 8464 // update the package settings accordingly. 8465 pkg.cpuAbiOverride = cpuAbiOverride; 8466 8467 if (DEBUG_ABI_SELECTION) { 8468 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8469 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8470 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8471 } 8472 8473 // Push the derived path down into PackageSettings so we know what to 8474 // clean up at uninstall time. 8475 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8476 8477 if (DEBUG_ABI_SELECTION) { 8478 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8479 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8480 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8481 } 8482 8483 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8484 // We don't do this here during boot because we can do it all 8485 // at once after scanning all existing packages. 8486 // 8487 // We also do this *before* we perform dexopt on this package, so that 8488 // we can avoid redundant dexopts, and also to make sure we've got the 8489 // code and package path correct. 8490 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8491 pkg, true /* boot complete */); 8492 } 8493 8494 if (mFactoryTest && pkg.requestedPermissions.contains( 8495 android.Manifest.permission.FACTORY_TEST)) { 8496 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8497 } 8498 8499 ArrayList<PackageParser.Package> clientLibPkgs = null; 8500 8501 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8502 if (nonMutatedPs != null) { 8503 synchronized (mPackages) { 8504 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8505 } 8506 } 8507 return pkg; 8508 } 8509 8510 // Only privileged apps and updated privileged apps can add child packages. 8511 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8512 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8513 throw new PackageManagerException("Only privileged apps and updated " 8514 + "privileged apps can add child packages. Ignoring package " 8515 + pkg.packageName); 8516 } 8517 final int childCount = pkg.childPackages.size(); 8518 for (int i = 0; i < childCount; i++) { 8519 PackageParser.Package childPkg = pkg.childPackages.get(i); 8520 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8521 childPkg.packageName)) { 8522 throw new PackageManagerException("Cannot override a child package of " 8523 + "another disabled system app. Ignoring package " + pkg.packageName); 8524 } 8525 } 8526 } 8527 8528 // writer 8529 synchronized (mPackages) { 8530 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8531 // Only system apps can add new shared libraries. 8532 if (pkg.libraryNames != null) { 8533 for (int i=0; i<pkg.libraryNames.size(); i++) { 8534 String name = pkg.libraryNames.get(i); 8535 boolean allowed = false; 8536 if (pkg.isUpdatedSystemApp()) { 8537 // New library entries can only be added through the 8538 // system image. This is important to get rid of a lot 8539 // of nasty edge cases: for example if we allowed a non- 8540 // system update of the app to add a library, then uninstalling 8541 // the update would make the library go away, and assumptions 8542 // we made such as through app install filtering would now 8543 // have allowed apps on the device which aren't compatible 8544 // with it. Better to just have the restriction here, be 8545 // conservative, and create many fewer cases that can negatively 8546 // impact the user experience. 8547 final PackageSetting sysPs = mSettings 8548 .getDisabledSystemPkgLPr(pkg.packageName); 8549 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8550 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8551 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8552 allowed = true; 8553 break; 8554 } 8555 } 8556 } 8557 } else { 8558 allowed = true; 8559 } 8560 if (allowed) { 8561 if (!mSharedLibraries.containsKey(name)) { 8562 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8563 } else if (!name.equals(pkg.packageName)) { 8564 Slog.w(TAG, "Package " + pkg.packageName + " library " 8565 + name + " already exists; skipping"); 8566 } 8567 } else { 8568 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8569 + name + " that is not declared on system image; skipping"); 8570 } 8571 } 8572 if ((scanFlags & SCAN_BOOTING) == 0) { 8573 // If we are not booting, we need to update any applications 8574 // that are clients of our shared library. If we are booting, 8575 // this will all be done once the scan is complete. 8576 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8577 } 8578 } 8579 } 8580 } 8581 8582 if ((scanFlags & SCAN_BOOTING) != 0) { 8583 // No apps can run during boot scan, so they don't need to be frozen 8584 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8585 // Caller asked to not kill app, so it's probably not frozen 8586 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8587 // Caller asked us to ignore frozen check for some reason; they 8588 // probably didn't know the package name 8589 } else { 8590 // We're doing major surgery on this package, so it better be frozen 8591 // right now to keep it from launching 8592 checkPackageFrozen(pkgName); 8593 } 8594 8595 // Also need to kill any apps that are dependent on the library. 8596 if (clientLibPkgs != null) { 8597 for (int i=0; i<clientLibPkgs.size(); i++) { 8598 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8599 killApplication(clientPkg.applicationInfo.packageName, 8600 clientPkg.applicationInfo.uid, "update lib"); 8601 } 8602 } 8603 8604 // Make sure we're not adding any bogus keyset info 8605 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8606 ksms.assertScannedPackageValid(pkg); 8607 8608 // writer 8609 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8610 8611 boolean createIdmapFailed = false; 8612 synchronized (mPackages) { 8613 // We don't expect installation to fail beyond this point 8614 8615 if (pkgSetting.pkg != null) { 8616 // Note that |user| might be null during the initial boot scan. If a codePath 8617 // for an app has changed during a boot scan, it's due to an app update that's 8618 // part of the system partition and marker changes must be applied to all users. 8619 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8620 (user != null) ? user : UserHandle.ALL); 8621 } 8622 8623 // Add the new setting to mSettings 8624 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8625 // Add the new setting to mPackages 8626 mPackages.put(pkg.applicationInfo.packageName, pkg); 8627 // Make sure we don't accidentally delete its data. 8628 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8629 while (iter.hasNext()) { 8630 PackageCleanItem item = iter.next(); 8631 if (pkgName.equals(item.packageName)) { 8632 iter.remove(); 8633 } 8634 } 8635 8636 // Take care of first install / last update times. 8637 if (currentTime != 0) { 8638 if (pkgSetting.firstInstallTime == 0) { 8639 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8640 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8641 pkgSetting.lastUpdateTime = currentTime; 8642 } 8643 } else if (pkgSetting.firstInstallTime == 0) { 8644 // We need *something*. Take time time stamp of the file. 8645 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8646 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8647 if (scanFileTime != pkgSetting.timeStamp) { 8648 // A package on the system image has changed; consider this 8649 // to be an update. 8650 pkgSetting.lastUpdateTime = scanFileTime; 8651 } 8652 } 8653 8654 // Add the package's KeySets to the global KeySetManagerService 8655 ksms.addScannedPackageLPw(pkg); 8656 8657 int N = pkg.providers.size(); 8658 StringBuilder r = null; 8659 int i; 8660 for (i=0; i<N; i++) { 8661 PackageParser.Provider p = pkg.providers.get(i); 8662 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8663 p.info.processName, pkg.applicationInfo.uid); 8664 mProviders.addProvider(p); 8665 p.syncable = p.info.isSyncable; 8666 if (p.info.authority != null) { 8667 String names[] = p.info.authority.split(";"); 8668 p.info.authority = null; 8669 for (int j = 0; j < names.length; j++) { 8670 if (j == 1 && p.syncable) { 8671 // We only want the first authority for a provider to possibly be 8672 // syncable, so if we already added this provider using a different 8673 // authority clear the syncable flag. We copy the provider before 8674 // changing it because the mProviders object contains a reference 8675 // to a provider that we don't want to change. 8676 // Only do this for the second authority since the resulting provider 8677 // object can be the same for all future authorities for this provider. 8678 p = new PackageParser.Provider(p); 8679 p.syncable = false; 8680 } 8681 if (!mProvidersByAuthority.containsKey(names[j])) { 8682 mProvidersByAuthority.put(names[j], p); 8683 if (p.info.authority == null) { 8684 p.info.authority = names[j]; 8685 } else { 8686 p.info.authority = p.info.authority + ";" + names[j]; 8687 } 8688 if (DEBUG_PACKAGE_SCANNING) { 8689 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8690 Log.d(TAG, "Registered content provider: " + names[j] 8691 + ", className = " + p.info.name + ", isSyncable = " 8692 + p.info.isSyncable); 8693 } 8694 } else { 8695 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8696 Slog.w(TAG, "Skipping provider name " + names[j] + 8697 " (in package " + pkg.applicationInfo.packageName + 8698 "): name already used by " 8699 + ((other != null && other.getComponentName() != null) 8700 ? other.getComponentName().getPackageName() : "?")); 8701 } 8702 } 8703 } 8704 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8705 if (r == null) { 8706 r = new StringBuilder(256); 8707 } else { 8708 r.append(' '); 8709 } 8710 r.append(p.info.name); 8711 } 8712 } 8713 if (r != null) { 8714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8715 } 8716 8717 N = pkg.services.size(); 8718 r = null; 8719 for (i=0; i<N; i++) { 8720 PackageParser.Service s = pkg.services.get(i); 8721 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8722 s.info.processName, pkg.applicationInfo.uid); 8723 mServices.addService(s); 8724 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8725 if (r == null) { 8726 r = new StringBuilder(256); 8727 } else { 8728 r.append(' '); 8729 } 8730 r.append(s.info.name); 8731 } 8732 } 8733 if (r != null) { 8734 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8735 } 8736 8737 N = pkg.receivers.size(); 8738 r = null; 8739 for (i=0; i<N; i++) { 8740 PackageParser.Activity a = pkg.receivers.get(i); 8741 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8742 a.info.processName, pkg.applicationInfo.uid); 8743 mReceivers.addActivity(a, "receiver"); 8744 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8745 if (r == null) { 8746 r = new StringBuilder(256); 8747 } else { 8748 r.append(' '); 8749 } 8750 r.append(a.info.name); 8751 } 8752 } 8753 if (r != null) { 8754 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8755 } 8756 8757 N = pkg.activities.size(); 8758 r = null; 8759 for (i=0; i<N; i++) { 8760 PackageParser.Activity a = pkg.activities.get(i); 8761 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8762 a.info.processName, pkg.applicationInfo.uid); 8763 mActivities.addActivity(a, "activity"); 8764 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8765 if (r == null) { 8766 r = new StringBuilder(256); 8767 } else { 8768 r.append(' '); 8769 } 8770 r.append(a.info.name); 8771 } 8772 } 8773 if (r != null) { 8774 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8775 } 8776 8777 N = pkg.permissionGroups.size(); 8778 r = null; 8779 for (i=0; i<N; i++) { 8780 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8781 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8782 if (cur == null) { 8783 mPermissionGroups.put(pg.info.name, pg); 8784 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8785 if (r == null) { 8786 r = new StringBuilder(256); 8787 } else { 8788 r.append(' '); 8789 } 8790 r.append(pg.info.name); 8791 } 8792 } else { 8793 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8794 + pg.info.packageName + " ignored: original from " 8795 + cur.info.packageName); 8796 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8797 if (r == null) { 8798 r = new StringBuilder(256); 8799 } else { 8800 r.append(' '); 8801 } 8802 r.append("DUP:"); 8803 r.append(pg.info.name); 8804 } 8805 } 8806 } 8807 if (r != null) { 8808 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8809 } 8810 8811 N = pkg.permissions.size(); 8812 r = null; 8813 for (i=0; i<N; i++) { 8814 PackageParser.Permission p = pkg.permissions.get(i); 8815 8816 // Assume by default that we did not install this permission into the system. 8817 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8818 8819 // Now that permission groups have a special meaning, we ignore permission 8820 // groups for legacy apps to prevent unexpected behavior. In particular, 8821 // permissions for one app being granted to someone just becase they happen 8822 // to be in a group defined by another app (before this had no implications). 8823 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8824 p.group = mPermissionGroups.get(p.info.group); 8825 // Warn for a permission in an unknown group. 8826 if (p.info.group != null && p.group == null) { 8827 Slog.w(TAG, "Permission " + p.info.name + " from package " 8828 + p.info.packageName + " in an unknown group " + p.info.group); 8829 } 8830 } 8831 8832 ArrayMap<String, BasePermission> permissionMap = 8833 p.tree ? mSettings.mPermissionTrees 8834 : mSettings.mPermissions; 8835 BasePermission bp = permissionMap.get(p.info.name); 8836 8837 // Allow system apps to redefine non-system permissions 8838 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8839 final boolean currentOwnerIsSystem = (bp.perm != null 8840 && isSystemApp(bp.perm.owner)); 8841 if (isSystemApp(p.owner)) { 8842 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8843 // It's a built-in permission and no owner, take ownership now 8844 bp.packageSetting = pkgSetting; 8845 bp.perm = p; 8846 bp.uid = pkg.applicationInfo.uid; 8847 bp.sourcePackage = p.info.packageName; 8848 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8849 } else if (!currentOwnerIsSystem) { 8850 String msg = "New decl " + p.owner + " of permission " 8851 + p.info.name + " is system; overriding " + bp.sourcePackage; 8852 reportSettingsProblem(Log.WARN, msg); 8853 bp = null; 8854 } 8855 } 8856 } 8857 8858 if (bp == null) { 8859 bp = new BasePermission(p.info.name, p.info.packageName, 8860 BasePermission.TYPE_NORMAL); 8861 permissionMap.put(p.info.name, bp); 8862 } 8863 8864 if (bp.perm == null) { 8865 if (bp.sourcePackage == null 8866 || bp.sourcePackage.equals(p.info.packageName)) { 8867 BasePermission tree = findPermissionTreeLP(p.info.name); 8868 if (tree == null 8869 || tree.sourcePackage.equals(p.info.packageName)) { 8870 bp.packageSetting = pkgSetting; 8871 bp.perm = p; 8872 bp.uid = pkg.applicationInfo.uid; 8873 bp.sourcePackage = p.info.packageName; 8874 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8875 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8876 if (r == null) { 8877 r = new StringBuilder(256); 8878 } else { 8879 r.append(' '); 8880 } 8881 r.append(p.info.name); 8882 } 8883 } else { 8884 Slog.w(TAG, "Permission " + p.info.name + " from package " 8885 + p.info.packageName + " ignored: base tree " 8886 + tree.name + " is from package " 8887 + tree.sourcePackage); 8888 } 8889 } else { 8890 Slog.w(TAG, "Permission " + p.info.name + " from package " 8891 + p.info.packageName + " ignored: original from " 8892 + bp.sourcePackage); 8893 } 8894 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8895 if (r == null) { 8896 r = new StringBuilder(256); 8897 } else { 8898 r.append(' '); 8899 } 8900 r.append("DUP:"); 8901 r.append(p.info.name); 8902 } 8903 if (bp.perm == p) { 8904 bp.protectionLevel = p.info.protectionLevel; 8905 } 8906 } 8907 8908 if (r != null) { 8909 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8910 } 8911 8912 N = pkg.instrumentation.size(); 8913 r = null; 8914 for (i=0; i<N; i++) { 8915 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8916 a.info.packageName = pkg.applicationInfo.packageName; 8917 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8918 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8919 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8920 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8921 a.info.dataDir = pkg.applicationInfo.dataDir; 8922 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8923 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8924 8925 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8926 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8927 mInstrumentation.put(a.getComponentName(), a); 8928 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8929 if (r == null) { 8930 r = new StringBuilder(256); 8931 } else { 8932 r.append(' '); 8933 } 8934 r.append(a.info.name); 8935 } 8936 } 8937 if (r != null) { 8938 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8939 } 8940 8941 if (pkg.protectedBroadcasts != null) { 8942 N = pkg.protectedBroadcasts.size(); 8943 for (i=0; i<N; i++) { 8944 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8945 } 8946 } 8947 8948 pkgSetting.setTimeStamp(scanFileTime); 8949 8950 // Create idmap files for pairs of (packages, overlay packages). 8951 // Note: "android", ie framework-res.apk, is handled by native layers. 8952 if (pkg.mOverlayTarget != null) { 8953 // This is an overlay package. 8954 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8955 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8956 mOverlays.put(pkg.mOverlayTarget, 8957 new ArrayMap<String, PackageParser.Package>()); 8958 } 8959 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8960 map.put(pkg.packageName, pkg); 8961 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8962 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8963 createIdmapFailed = true; 8964 } 8965 } 8966 } else if (mOverlays.containsKey(pkg.packageName) && 8967 !pkg.packageName.equals("android")) { 8968 // This is a regular package, with one or more known overlay packages. 8969 createIdmapsForPackageLI(pkg); 8970 } 8971 } 8972 8973 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8974 8975 if (createIdmapFailed) { 8976 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8977 "scanPackageLI failed to createIdmap"); 8978 } 8979 return pkg; 8980 } 8981 8982 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8983 PackageParser.Package update, UserHandle user) { 8984 if (existing.applicationInfo == null || update.applicationInfo == null) { 8985 // This isn't due to an app installation. 8986 return; 8987 } 8988 8989 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8990 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8991 8992 // The codePath hasn't changed, so there's nothing for us to do. 8993 if (Objects.equals(oldCodePath, newCodePath)) { 8994 return; 8995 } 8996 8997 File canonicalNewCodePath; 8998 try { 8999 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9000 } catch (IOException e) { 9001 Slog.w(TAG, "Failed to get canonical path.", e); 9002 return; 9003 } 9004 9005 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9006 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9007 // that the last component of the path (i.e, the name) doesn't need canonicalization 9008 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9009 // but may change in the future. Hopefully this function won't exist at that point. 9010 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9011 oldCodePath.getName()); 9012 9013 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9014 // with "@". 9015 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9016 if (!oldMarkerPrefix.endsWith("@")) { 9017 oldMarkerPrefix += "@"; 9018 } 9019 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9020 if (!newMarkerPrefix.endsWith("@")) { 9021 newMarkerPrefix += "@"; 9022 } 9023 9024 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9025 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9026 for (String updatedPath : updatedPaths) { 9027 String updatedPathName = new File(updatedPath).getName(); 9028 markerSuffixes.add(updatedPathName.replace('/', '@')); 9029 } 9030 9031 for (int userId : resolveUserIds(user.getIdentifier())) { 9032 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9033 9034 for (String markerSuffix : markerSuffixes) { 9035 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9036 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9037 if (oldForeignUseMark.exists()) { 9038 try { 9039 Os.rename(oldForeignUseMark.getAbsolutePath(), 9040 newForeignUseMark.getAbsolutePath()); 9041 } catch (ErrnoException e) { 9042 Slog.w(TAG, "Failed to rename foreign use marker", e); 9043 oldForeignUseMark.delete(); 9044 } 9045 } 9046 } 9047 } 9048 } 9049 9050 /** 9051 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9052 * is derived purely on the basis of the contents of {@code scanFile} and 9053 * {@code cpuAbiOverride}. 9054 * 9055 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9056 */ 9057 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9058 String cpuAbiOverride, boolean extractLibs) 9059 throws PackageManagerException { 9060 // TODO: We can probably be smarter about this stuff. For installed apps, 9061 // we can calculate this information at install time once and for all. For 9062 // system apps, we can probably assume that this information doesn't change 9063 // after the first boot scan. As things stand, we do lots of unnecessary work. 9064 9065 // Give ourselves some initial paths; we'll come back for another 9066 // pass once we've determined ABI below. 9067 setNativeLibraryPaths(pkg); 9068 9069 // We would never need to extract libs for forward-locked and external packages, 9070 // since the container service will do it for us. We shouldn't attempt to 9071 // extract libs from system app when it was not updated. 9072 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9073 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9074 extractLibs = false; 9075 } 9076 9077 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9078 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9079 9080 NativeLibraryHelper.Handle handle = null; 9081 try { 9082 handle = NativeLibraryHelper.Handle.create(pkg); 9083 // TODO(multiArch): This can be null for apps that didn't go through the 9084 // usual installation process. We can calculate it again, like we 9085 // do during install time. 9086 // 9087 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9088 // unnecessary. 9089 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9090 9091 // Null out the abis so that they can be recalculated. 9092 pkg.applicationInfo.primaryCpuAbi = null; 9093 pkg.applicationInfo.secondaryCpuAbi = null; 9094 if (isMultiArch(pkg.applicationInfo)) { 9095 // Warn if we've set an abiOverride for multi-lib packages.. 9096 // By definition, we need to copy both 32 and 64 bit libraries for 9097 // such packages. 9098 if (pkg.cpuAbiOverride != null 9099 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9100 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9101 } 9102 9103 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9104 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9105 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9106 if (extractLibs) { 9107 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9108 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9109 useIsaSpecificSubdirs); 9110 } else { 9111 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9112 } 9113 } 9114 9115 maybeThrowExceptionForMultiArchCopy( 9116 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9117 9118 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9119 if (extractLibs) { 9120 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9121 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9122 useIsaSpecificSubdirs); 9123 } else { 9124 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9125 } 9126 } 9127 9128 maybeThrowExceptionForMultiArchCopy( 9129 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9130 9131 if (abi64 >= 0) { 9132 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9133 } 9134 9135 if (abi32 >= 0) { 9136 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9137 if (abi64 >= 0) { 9138 if (pkg.use32bitAbi) { 9139 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9140 pkg.applicationInfo.primaryCpuAbi = abi; 9141 } else { 9142 pkg.applicationInfo.secondaryCpuAbi = abi; 9143 } 9144 } else { 9145 pkg.applicationInfo.primaryCpuAbi = abi; 9146 } 9147 } 9148 9149 } else { 9150 String[] abiList = (cpuAbiOverride != null) ? 9151 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9152 9153 // Enable gross and lame hacks for apps that are built with old 9154 // SDK tools. We must scan their APKs for renderscript bitcode and 9155 // not launch them if it's present. Don't bother checking on devices 9156 // that don't have 64 bit support. 9157 boolean needsRenderScriptOverride = false; 9158 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9159 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9160 abiList = Build.SUPPORTED_32_BIT_ABIS; 9161 needsRenderScriptOverride = true; 9162 } 9163 9164 final int copyRet; 9165 if (extractLibs) { 9166 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9167 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9168 } else { 9169 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9170 } 9171 9172 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9173 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9174 "Error unpackaging native libs for app, errorCode=" + copyRet); 9175 } 9176 9177 if (copyRet >= 0) { 9178 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9179 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9180 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9181 } else if (needsRenderScriptOverride) { 9182 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9183 } 9184 } 9185 } catch (IOException ioe) { 9186 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9187 } finally { 9188 IoUtils.closeQuietly(handle); 9189 } 9190 9191 // Now that we've calculated the ABIs and determined if it's an internal app, 9192 // we will go ahead and populate the nativeLibraryPath. 9193 setNativeLibraryPaths(pkg); 9194 } 9195 9196 /** 9197 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9198 * i.e, so that all packages can be run inside a single process if required. 9199 * 9200 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9201 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9202 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9203 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9204 * updating a package that belongs to a shared user. 9205 * 9206 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9207 * adds unnecessary complexity. 9208 */ 9209 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9210 PackageParser.Package scannedPackage, boolean bootComplete) { 9211 String requiredInstructionSet = null; 9212 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9213 requiredInstructionSet = VMRuntime.getInstructionSet( 9214 scannedPackage.applicationInfo.primaryCpuAbi); 9215 } 9216 9217 PackageSetting requirer = null; 9218 for (PackageSetting ps : packagesForUser) { 9219 // If packagesForUser contains scannedPackage, we skip it. This will happen 9220 // when scannedPackage is an update of an existing package. Without this check, 9221 // we will never be able to change the ABI of any package belonging to a shared 9222 // user, even if it's compatible with other packages. 9223 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9224 if (ps.primaryCpuAbiString == null) { 9225 continue; 9226 } 9227 9228 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9229 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9230 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9231 // this but there's not much we can do. 9232 String errorMessage = "Instruction set mismatch, " 9233 + ((requirer == null) ? "[caller]" : requirer) 9234 + " requires " + requiredInstructionSet + " whereas " + ps 9235 + " requires " + instructionSet; 9236 Slog.w(TAG, errorMessage); 9237 } 9238 9239 if (requiredInstructionSet == null) { 9240 requiredInstructionSet = instructionSet; 9241 requirer = ps; 9242 } 9243 } 9244 } 9245 9246 if (requiredInstructionSet != null) { 9247 String adjustedAbi; 9248 if (requirer != null) { 9249 // requirer != null implies that either scannedPackage was null or that scannedPackage 9250 // did not require an ABI, in which case we have to adjust scannedPackage to match 9251 // the ABI of the set (which is the same as requirer's ABI) 9252 adjustedAbi = requirer.primaryCpuAbiString; 9253 if (scannedPackage != null) { 9254 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9255 } 9256 } else { 9257 // requirer == null implies that we're updating all ABIs in the set to 9258 // match scannedPackage. 9259 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9260 } 9261 9262 for (PackageSetting ps : packagesForUser) { 9263 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9264 if (ps.primaryCpuAbiString != null) { 9265 continue; 9266 } 9267 9268 ps.primaryCpuAbiString = adjustedAbi; 9269 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9270 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9271 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9272 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9273 + " (requirer=" 9274 + (requirer == null ? "null" : requirer.pkg.packageName) 9275 + ", scannedPackage=" 9276 + (scannedPackage != null ? scannedPackage.packageName : "null") 9277 + ")"); 9278 try { 9279 mInstaller.rmdex(ps.codePathString, 9280 getDexCodeInstructionSet(getPreferredInstructionSet())); 9281 } catch (InstallerException ignored) { 9282 } 9283 } 9284 } 9285 } 9286 } 9287 } 9288 9289 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9290 synchronized (mPackages) { 9291 mResolverReplaced = true; 9292 // Set up information for custom user intent resolution activity. 9293 mResolveActivity.applicationInfo = pkg.applicationInfo; 9294 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9295 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9296 mResolveActivity.processName = pkg.applicationInfo.packageName; 9297 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9298 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9299 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9300 mResolveActivity.theme = 0; 9301 mResolveActivity.exported = true; 9302 mResolveActivity.enabled = true; 9303 mResolveInfo.activityInfo = mResolveActivity; 9304 mResolveInfo.priority = 0; 9305 mResolveInfo.preferredOrder = 0; 9306 mResolveInfo.match = 0; 9307 mResolveComponentName = mCustomResolverComponentName; 9308 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9309 mResolveComponentName); 9310 } 9311 } 9312 9313 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9314 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9315 9316 // Set up information for ephemeral installer activity 9317 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9318 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9319 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9320 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9321 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9322 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9323 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9324 mEphemeralInstallerActivity.theme = 0; 9325 mEphemeralInstallerActivity.exported = true; 9326 mEphemeralInstallerActivity.enabled = true; 9327 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9328 mEphemeralInstallerInfo.priority = 0; 9329 mEphemeralInstallerInfo.preferredOrder = 0; 9330 mEphemeralInstallerInfo.match = 0; 9331 9332 if (DEBUG_EPHEMERAL) { 9333 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9334 } 9335 } 9336 9337 private static String calculateBundledApkRoot(final String codePathString) { 9338 final File codePath = new File(codePathString); 9339 final File codeRoot; 9340 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9341 codeRoot = Environment.getRootDirectory(); 9342 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9343 codeRoot = Environment.getOemDirectory(); 9344 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9345 codeRoot = Environment.getVendorDirectory(); 9346 } else { 9347 // Unrecognized code path; take its top real segment as the apk root: 9348 // e.g. /something/app/blah.apk => /something 9349 try { 9350 File f = codePath.getCanonicalFile(); 9351 File parent = f.getParentFile(); // non-null because codePath is a file 9352 File tmp; 9353 while ((tmp = parent.getParentFile()) != null) { 9354 f = parent; 9355 parent = tmp; 9356 } 9357 codeRoot = f; 9358 Slog.w(TAG, "Unrecognized code path " 9359 + codePath + " - using " + codeRoot); 9360 } catch (IOException e) { 9361 // Can't canonicalize the code path -- shenanigans? 9362 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9363 return Environment.getRootDirectory().getPath(); 9364 } 9365 } 9366 return codeRoot.getPath(); 9367 } 9368 9369 /** 9370 * Derive and set the location of native libraries for the given package, 9371 * which varies depending on where and how the package was installed. 9372 */ 9373 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9374 final ApplicationInfo info = pkg.applicationInfo; 9375 final String codePath = pkg.codePath; 9376 final File codeFile = new File(codePath); 9377 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9378 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9379 9380 info.nativeLibraryRootDir = null; 9381 info.nativeLibraryRootRequiresIsa = false; 9382 info.nativeLibraryDir = null; 9383 info.secondaryNativeLibraryDir = null; 9384 9385 if (isApkFile(codeFile)) { 9386 // Monolithic install 9387 if (bundledApp) { 9388 // If "/system/lib64/apkname" exists, assume that is the per-package 9389 // native library directory to use; otherwise use "/system/lib/apkname". 9390 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9391 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9392 getPrimaryInstructionSet(info)); 9393 9394 // This is a bundled system app so choose the path based on the ABI. 9395 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9396 // is just the default path. 9397 final String apkName = deriveCodePathName(codePath); 9398 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9399 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9400 apkName).getAbsolutePath(); 9401 9402 if (info.secondaryCpuAbi != null) { 9403 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9404 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9405 secondaryLibDir, apkName).getAbsolutePath(); 9406 } 9407 } else if (asecApp) { 9408 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9409 .getAbsolutePath(); 9410 } else { 9411 final String apkName = deriveCodePathName(codePath); 9412 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9413 .getAbsolutePath(); 9414 } 9415 9416 info.nativeLibraryRootRequiresIsa = false; 9417 info.nativeLibraryDir = info.nativeLibraryRootDir; 9418 } else { 9419 // Cluster install 9420 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9421 info.nativeLibraryRootRequiresIsa = true; 9422 9423 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9424 getPrimaryInstructionSet(info)).getAbsolutePath(); 9425 9426 if (info.secondaryCpuAbi != null) { 9427 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9428 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9429 } 9430 } 9431 } 9432 9433 /** 9434 * Calculate the abis and roots for a bundled app. These can uniquely 9435 * be determined from the contents of the system partition, i.e whether 9436 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9437 * of this information, and instead assume that the system was built 9438 * sensibly. 9439 */ 9440 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9441 PackageSetting pkgSetting) { 9442 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9443 9444 // If "/system/lib64/apkname" exists, assume that is the per-package 9445 // native library directory to use; otherwise use "/system/lib/apkname". 9446 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9447 setBundledAppAbi(pkg, apkRoot, apkName); 9448 // pkgSetting might be null during rescan following uninstall of updates 9449 // to a bundled app, so accommodate that possibility. The settings in 9450 // that case will be established later from the parsed package. 9451 // 9452 // If the settings aren't null, sync them up with what we've just derived. 9453 // note that apkRoot isn't stored in the package settings. 9454 if (pkgSetting != null) { 9455 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9456 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9457 } 9458 } 9459 9460 /** 9461 * Deduces the ABI of a bundled app and sets the relevant fields on the 9462 * parsed pkg object. 9463 * 9464 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9465 * under which system libraries are installed. 9466 * @param apkName the name of the installed package. 9467 */ 9468 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9469 final File codeFile = new File(pkg.codePath); 9470 9471 final boolean has64BitLibs; 9472 final boolean has32BitLibs; 9473 if (isApkFile(codeFile)) { 9474 // Monolithic install 9475 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9476 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9477 } else { 9478 // Cluster install 9479 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9480 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9481 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9482 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9483 has64BitLibs = (new File(rootDir, isa)).exists(); 9484 } else { 9485 has64BitLibs = false; 9486 } 9487 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9488 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9489 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9490 has32BitLibs = (new File(rootDir, isa)).exists(); 9491 } else { 9492 has32BitLibs = false; 9493 } 9494 } 9495 9496 if (has64BitLibs && !has32BitLibs) { 9497 // The package has 64 bit libs, but not 32 bit libs. Its primary 9498 // ABI should be 64 bit. We can safely assume here that the bundled 9499 // native libraries correspond to the most preferred ABI in the list. 9500 9501 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9502 pkg.applicationInfo.secondaryCpuAbi = null; 9503 } else if (has32BitLibs && !has64BitLibs) { 9504 // The package has 32 bit libs but not 64 bit libs. Its primary 9505 // ABI should be 32 bit. 9506 9507 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9508 pkg.applicationInfo.secondaryCpuAbi = null; 9509 } else if (has32BitLibs && has64BitLibs) { 9510 // The application has both 64 and 32 bit bundled libraries. We check 9511 // here that the app declares multiArch support, and warn if it doesn't. 9512 // 9513 // We will be lenient here and record both ABIs. The primary will be the 9514 // ABI that's higher on the list, i.e, a device that's configured to prefer 9515 // 64 bit apps will see a 64 bit primary ABI, 9516 9517 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9518 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9519 } 9520 9521 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9522 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9523 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9524 } else { 9525 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9526 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9527 } 9528 } else { 9529 pkg.applicationInfo.primaryCpuAbi = null; 9530 pkg.applicationInfo.secondaryCpuAbi = null; 9531 } 9532 } 9533 9534 private void killApplication(String pkgName, int appId, String reason) { 9535 // Request the ActivityManager to kill the process(only for existing packages) 9536 // so that we do not end up in a confused state while the user is still using the older 9537 // version of the application while the new one gets installed. 9538 final long token = Binder.clearCallingIdentity(); 9539 try { 9540 IActivityManager am = ActivityManagerNative.getDefault(); 9541 if (am != null) { 9542 try { 9543 am.killApplicationWithAppId(pkgName, appId, reason); 9544 } catch (RemoteException e) { 9545 } 9546 } 9547 } finally { 9548 Binder.restoreCallingIdentity(token); 9549 } 9550 } 9551 9552 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9553 // Remove the parent package setting 9554 PackageSetting ps = (PackageSetting) pkg.mExtras; 9555 if (ps != null) { 9556 removePackageLI(ps, chatty); 9557 } 9558 // Remove the child package setting 9559 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9560 for (int i = 0; i < childCount; i++) { 9561 PackageParser.Package childPkg = pkg.childPackages.get(i); 9562 ps = (PackageSetting) childPkg.mExtras; 9563 if (ps != null) { 9564 removePackageLI(ps, chatty); 9565 } 9566 } 9567 } 9568 9569 void removePackageLI(PackageSetting ps, boolean chatty) { 9570 if (DEBUG_INSTALL) { 9571 if (chatty) 9572 Log.d(TAG, "Removing package " + ps.name); 9573 } 9574 9575 // writer 9576 synchronized (mPackages) { 9577 mPackages.remove(ps.name); 9578 final PackageParser.Package pkg = ps.pkg; 9579 if (pkg != null) { 9580 cleanPackageDataStructuresLILPw(pkg, chatty); 9581 } 9582 } 9583 } 9584 9585 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9586 if (DEBUG_INSTALL) { 9587 if (chatty) 9588 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9589 } 9590 9591 // writer 9592 synchronized (mPackages) { 9593 // Remove the parent package 9594 mPackages.remove(pkg.applicationInfo.packageName); 9595 cleanPackageDataStructuresLILPw(pkg, chatty); 9596 9597 // Remove the child packages 9598 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9599 for (int i = 0; i < childCount; i++) { 9600 PackageParser.Package childPkg = pkg.childPackages.get(i); 9601 mPackages.remove(childPkg.applicationInfo.packageName); 9602 cleanPackageDataStructuresLILPw(childPkg, chatty); 9603 } 9604 } 9605 } 9606 9607 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9608 int N = pkg.providers.size(); 9609 StringBuilder r = null; 9610 int i; 9611 for (i=0; i<N; i++) { 9612 PackageParser.Provider p = pkg.providers.get(i); 9613 mProviders.removeProvider(p); 9614 if (p.info.authority == null) { 9615 9616 /* There was another ContentProvider with this authority when 9617 * this app was installed so this authority is null, 9618 * Ignore it as we don't have to unregister the provider. 9619 */ 9620 continue; 9621 } 9622 String names[] = p.info.authority.split(";"); 9623 for (int j = 0; j < names.length; j++) { 9624 if (mProvidersByAuthority.get(names[j]) == p) { 9625 mProvidersByAuthority.remove(names[j]); 9626 if (DEBUG_REMOVE) { 9627 if (chatty) 9628 Log.d(TAG, "Unregistered content provider: " + names[j] 9629 + ", className = " + p.info.name + ", isSyncable = " 9630 + p.info.isSyncable); 9631 } 9632 } 9633 } 9634 if (DEBUG_REMOVE && chatty) { 9635 if (r == null) { 9636 r = new StringBuilder(256); 9637 } else { 9638 r.append(' '); 9639 } 9640 r.append(p.info.name); 9641 } 9642 } 9643 if (r != null) { 9644 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9645 } 9646 9647 N = pkg.services.size(); 9648 r = null; 9649 for (i=0; i<N; i++) { 9650 PackageParser.Service s = pkg.services.get(i); 9651 mServices.removeService(s); 9652 if (chatty) { 9653 if (r == null) { 9654 r = new StringBuilder(256); 9655 } else { 9656 r.append(' '); 9657 } 9658 r.append(s.info.name); 9659 } 9660 } 9661 if (r != null) { 9662 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9663 } 9664 9665 N = pkg.receivers.size(); 9666 r = null; 9667 for (i=0; i<N; i++) { 9668 PackageParser.Activity a = pkg.receivers.get(i); 9669 mReceivers.removeActivity(a, "receiver"); 9670 if (DEBUG_REMOVE && chatty) { 9671 if (r == null) { 9672 r = new StringBuilder(256); 9673 } else { 9674 r.append(' '); 9675 } 9676 r.append(a.info.name); 9677 } 9678 } 9679 if (r != null) { 9680 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9681 } 9682 9683 N = pkg.activities.size(); 9684 r = null; 9685 for (i=0; i<N; i++) { 9686 PackageParser.Activity a = pkg.activities.get(i); 9687 mActivities.removeActivity(a, "activity"); 9688 if (DEBUG_REMOVE && chatty) { 9689 if (r == null) { 9690 r = new StringBuilder(256); 9691 } else { 9692 r.append(' '); 9693 } 9694 r.append(a.info.name); 9695 } 9696 } 9697 if (r != null) { 9698 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9699 } 9700 9701 N = pkg.permissions.size(); 9702 r = null; 9703 for (i=0; i<N; i++) { 9704 PackageParser.Permission p = pkg.permissions.get(i); 9705 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9706 if (bp == null) { 9707 bp = mSettings.mPermissionTrees.get(p.info.name); 9708 } 9709 if (bp != null && bp.perm == p) { 9710 bp.perm = null; 9711 if (DEBUG_REMOVE && chatty) { 9712 if (r == null) { 9713 r = new StringBuilder(256); 9714 } else { 9715 r.append(' '); 9716 } 9717 r.append(p.info.name); 9718 } 9719 } 9720 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9721 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9722 if (appOpPkgs != null) { 9723 appOpPkgs.remove(pkg.packageName); 9724 } 9725 } 9726 } 9727 if (r != null) { 9728 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9729 } 9730 9731 N = pkg.requestedPermissions.size(); 9732 r = null; 9733 for (i=0; i<N; i++) { 9734 String perm = pkg.requestedPermissions.get(i); 9735 BasePermission bp = mSettings.mPermissions.get(perm); 9736 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9737 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9738 if (appOpPkgs != null) { 9739 appOpPkgs.remove(pkg.packageName); 9740 if (appOpPkgs.isEmpty()) { 9741 mAppOpPermissionPackages.remove(perm); 9742 } 9743 } 9744 } 9745 } 9746 if (r != null) { 9747 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9748 } 9749 9750 N = pkg.instrumentation.size(); 9751 r = null; 9752 for (i=0; i<N; i++) { 9753 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9754 mInstrumentation.remove(a.getComponentName()); 9755 if (DEBUG_REMOVE && chatty) { 9756 if (r == null) { 9757 r = new StringBuilder(256); 9758 } else { 9759 r.append(' '); 9760 } 9761 r.append(a.info.name); 9762 } 9763 } 9764 if (r != null) { 9765 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9766 } 9767 9768 r = null; 9769 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9770 // Only system apps can hold shared libraries. 9771 if (pkg.libraryNames != null) { 9772 for (i=0; i<pkg.libraryNames.size(); i++) { 9773 String name = pkg.libraryNames.get(i); 9774 SharedLibraryEntry cur = mSharedLibraries.get(name); 9775 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9776 mSharedLibraries.remove(name); 9777 if (DEBUG_REMOVE && chatty) { 9778 if (r == null) { 9779 r = new StringBuilder(256); 9780 } else { 9781 r.append(' '); 9782 } 9783 r.append(name); 9784 } 9785 } 9786 } 9787 } 9788 } 9789 if (r != null) { 9790 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9791 } 9792 } 9793 9794 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9795 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9796 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9797 return true; 9798 } 9799 } 9800 return false; 9801 } 9802 9803 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9804 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9805 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9806 9807 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9808 // Update the parent permissions 9809 updatePermissionsLPw(pkg.packageName, pkg, flags); 9810 // Update the child permissions 9811 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9812 for (int i = 0; i < childCount; i++) { 9813 PackageParser.Package childPkg = pkg.childPackages.get(i); 9814 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9815 } 9816 } 9817 9818 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9819 int flags) { 9820 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9821 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9822 } 9823 9824 private void updatePermissionsLPw(String changingPkg, 9825 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9826 // Make sure there are no dangling permission trees. 9827 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9828 while (it.hasNext()) { 9829 final BasePermission bp = it.next(); 9830 if (bp.packageSetting == null) { 9831 // We may not yet have parsed the package, so just see if 9832 // we still know about its settings. 9833 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9834 } 9835 if (bp.packageSetting == null) { 9836 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9837 + " from package " + bp.sourcePackage); 9838 it.remove(); 9839 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9840 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9841 Slog.i(TAG, "Removing old permission tree: " + bp.name 9842 + " from package " + bp.sourcePackage); 9843 flags |= UPDATE_PERMISSIONS_ALL; 9844 it.remove(); 9845 } 9846 } 9847 } 9848 9849 // Make sure all dynamic permissions have been assigned to a package, 9850 // and make sure there are no dangling permissions. 9851 it = mSettings.mPermissions.values().iterator(); 9852 while (it.hasNext()) { 9853 final BasePermission bp = it.next(); 9854 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9855 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9856 + bp.name + " pkg=" + bp.sourcePackage 9857 + " info=" + bp.pendingInfo); 9858 if (bp.packageSetting == null && bp.pendingInfo != null) { 9859 final BasePermission tree = findPermissionTreeLP(bp.name); 9860 if (tree != null && tree.perm != null) { 9861 bp.packageSetting = tree.packageSetting; 9862 bp.perm = new PackageParser.Permission(tree.perm.owner, 9863 new PermissionInfo(bp.pendingInfo)); 9864 bp.perm.info.packageName = tree.perm.info.packageName; 9865 bp.perm.info.name = bp.name; 9866 bp.uid = tree.uid; 9867 } 9868 } 9869 } 9870 if (bp.packageSetting == null) { 9871 // We may not yet have parsed the package, so just see if 9872 // we still know about its settings. 9873 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9874 } 9875 if (bp.packageSetting == null) { 9876 Slog.w(TAG, "Removing dangling permission: " + bp.name 9877 + " from package " + bp.sourcePackage); 9878 it.remove(); 9879 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9880 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9881 Slog.i(TAG, "Removing old permission: " + bp.name 9882 + " from package " + bp.sourcePackage); 9883 flags |= UPDATE_PERMISSIONS_ALL; 9884 it.remove(); 9885 } 9886 } 9887 } 9888 9889 // Now update the permissions for all packages, in particular 9890 // replace the granted permissions of the system packages. 9891 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9892 for (PackageParser.Package pkg : mPackages.values()) { 9893 if (pkg != pkgInfo) { 9894 // Only replace for packages on requested volume 9895 final String volumeUuid = getVolumeUuidForPackage(pkg); 9896 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9897 && Objects.equals(replaceVolumeUuid, volumeUuid); 9898 grantPermissionsLPw(pkg, replace, changingPkg); 9899 } 9900 } 9901 } 9902 9903 if (pkgInfo != null) { 9904 // Only replace for packages on requested volume 9905 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9906 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9907 && Objects.equals(replaceVolumeUuid, volumeUuid); 9908 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9909 } 9910 } 9911 9912 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9913 String packageOfInterest) { 9914 // IMPORTANT: There are two types of permissions: install and runtime. 9915 // Install time permissions are granted when the app is installed to 9916 // all device users and users added in the future. Runtime permissions 9917 // are granted at runtime explicitly to specific users. Normal and signature 9918 // protected permissions are install time permissions. Dangerous permissions 9919 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9920 // otherwise they are runtime permissions. This function does not manage 9921 // runtime permissions except for the case an app targeting Lollipop MR1 9922 // being upgraded to target a newer SDK, in which case dangerous permissions 9923 // are transformed from install time to runtime ones. 9924 9925 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9926 if (ps == null) { 9927 return; 9928 } 9929 9930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9931 9932 PermissionsState permissionsState = ps.getPermissionsState(); 9933 PermissionsState origPermissions = permissionsState; 9934 9935 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9936 9937 boolean runtimePermissionsRevoked = false; 9938 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9939 9940 boolean changedInstallPermission = false; 9941 9942 if (replace) { 9943 ps.installPermissionsFixed = false; 9944 if (!ps.isSharedUser()) { 9945 origPermissions = new PermissionsState(permissionsState); 9946 permissionsState.reset(); 9947 } else { 9948 // We need to know only about runtime permission changes since the 9949 // calling code always writes the install permissions state but 9950 // the runtime ones are written only if changed. The only cases of 9951 // changed runtime permissions here are promotion of an install to 9952 // runtime and revocation of a runtime from a shared user. 9953 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9954 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9955 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9956 runtimePermissionsRevoked = true; 9957 } 9958 } 9959 } 9960 9961 permissionsState.setGlobalGids(mGlobalGids); 9962 9963 final int N = pkg.requestedPermissions.size(); 9964 for (int i=0; i<N; i++) { 9965 final String name = pkg.requestedPermissions.get(i); 9966 final BasePermission bp = mSettings.mPermissions.get(name); 9967 9968 if (DEBUG_INSTALL) { 9969 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9970 } 9971 9972 if (bp == null || bp.packageSetting == null) { 9973 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9974 Slog.w(TAG, "Unknown permission " + name 9975 + " in package " + pkg.packageName); 9976 } 9977 continue; 9978 } 9979 9980 final String perm = bp.name; 9981 boolean allowedSig = false; 9982 int grant = GRANT_DENIED; 9983 9984 // Keep track of app op permissions. 9985 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9986 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9987 if (pkgs == null) { 9988 pkgs = new ArraySet<>(); 9989 mAppOpPermissionPackages.put(bp.name, pkgs); 9990 } 9991 pkgs.add(pkg.packageName); 9992 } 9993 9994 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9995 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9996 >= Build.VERSION_CODES.M; 9997 switch (level) { 9998 case PermissionInfo.PROTECTION_NORMAL: { 9999 // For all apps normal permissions are install time ones. 10000 grant = GRANT_INSTALL; 10001 } break; 10002 10003 case PermissionInfo.PROTECTION_DANGEROUS: { 10004 // If a permission review is required for legacy apps we represent 10005 // their permissions as always granted runtime ones since we need 10006 // to keep the review required permission flag per user while an 10007 // install permission's state is shared across all users. 10008 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10009 // For legacy apps dangerous permissions are install time ones. 10010 grant = GRANT_INSTALL; 10011 } else if (origPermissions.hasInstallPermission(bp.name)) { 10012 // For legacy apps that became modern, install becomes runtime. 10013 grant = GRANT_UPGRADE; 10014 } else if (mPromoteSystemApps 10015 && isSystemApp(ps) 10016 && mExistingSystemPackages.contains(ps.name)) { 10017 // For legacy system apps, install becomes runtime. 10018 // We cannot check hasInstallPermission() for system apps since those 10019 // permissions were granted implicitly and not persisted pre-M. 10020 grant = GRANT_UPGRADE; 10021 } else { 10022 // For modern apps keep runtime permissions unchanged. 10023 grant = GRANT_RUNTIME; 10024 } 10025 } break; 10026 10027 case PermissionInfo.PROTECTION_SIGNATURE: { 10028 // For all apps signature permissions are install time ones. 10029 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10030 if (allowedSig) { 10031 grant = GRANT_INSTALL; 10032 } 10033 } break; 10034 } 10035 10036 if (DEBUG_INSTALL) { 10037 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10038 } 10039 10040 if (grant != GRANT_DENIED) { 10041 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10042 // If this is an existing, non-system package, then 10043 // we can't add any new permissions to it. 10044 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10045 // Except... if this is a permission that was added 10046 // to the platform (note: need to only do this when 10047 // updating the platform). 10048 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10049 grant = GRANT_DENIED; 10050 } 10051 } 10052 } 10053 10054 switch (grant) { 10055 case GRANT_INSTALL: { 10056 // Revoke this as runtime permission to handle the case of 10057 // a runtime permission being downgraded to an install one. 10058 // Also in permission review mode we keep dangerous permissions 10059 // for legacy apps 10060 for (int userId : UserManagerService.getInstance().getUserIds()) { 10061 if (origPermissions.getRuntimePermissionState( 10062 bp.name, userId) != null) { 10063 // Revoke the runtime permission and clear the flags. 10064 origPermissions.revokeRuntimePermission(bp, userId); 10065 origPermissions.updatePermissionFlags(bp, userId, 10066 PackageManager.MASK_PERMISSION_FLAGS, 0); 10067 // If we revoked a permission permission, we have to write. 10068 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10069 changedRuntimePermissionUserIds, userId); 10070 } 10071 } 10072 // Grant an install permission. 10073 if (permissionsState.grantInstallPermission(bp) != 10074 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10075 changedInstallPermission = true; 10076 } 10077 } break; 10078 10079 case GRANT_RUNTIME: { 10080 // Grant previously granted runtime permissions. 10081 for (int userId : UserManagerService.getInstance().getUserIds()) { 10082 PermissionState permissionState = origPermissions 10083 .getRuntimePermissionState(bp.name, userId); 10084 int flags = permissionState != null 10085 ? permissionState.getFlags() : 0; 10086 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10087 if (permissionsState.grantRuntimePermission(bp, userId) == 10088 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10089 // If we cannot put the permission as it was, we have to write. 10090 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10091 changedRuntimePermissionUserIds, userId); 10092 } 10093 // If the app supports runtime permissions no need for a review. 10094 if (Build.PERMISSIONS_REVIEW_REQUIRED 10095 && appSupportsRuntimePermissions 10096 && (flags & PackageManager 10097 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10098 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10099 // Since we changed the flags, we have to write. 10100 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10101 changedRuntimePermissionUserIds, userId); 10102 } 10103 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10104 && !appSupportsRuntimePermissions) { 10105 // For legacy apps that need a permission review, every new 10106 // runtime permission is granted but it is pending a review. 10107 // We also need to review only platform defined runtime 10108 // permissions as these are the only ones the platform knows 10109 // how to disable the API to simulate revocation as legacy 10110 // apps don't expect to run with revoked permissions. 10111 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10112 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10113 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10114 // We changed the flags, hence have to write. 10115 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10116 changedRuntimePermissionUserIds, userId); 10117 } 10118 } 10119 if (permissionsState.grantRuntimePermission(bp, userId) 10120 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10121 // We changed the permission, hence have to write. 10122 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10123 changedRuntimePermissionUserIds, userId); 10124 } 10125 } 10126 // Propagate the permission flags. 10127 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10128 } 10129 } break; 10130 10131 case GRANT_UPGRADE: { 10132 // Grant runtime permissions for a previously held install permission. 10133 PermissionState permissionState = origPermissions 10134 .getInstallPermissionState(bp.name); 10135 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10136 10137 if (origPermissions.revokeInstallPermission(bp) 10138 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10139 // We will be transferring the permission flags, so clear them. 10140 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10141 PackageManager.MASK_PERMISSION_FLAGS, 0); 10142 changedInstallPermission = true; 10143 } 10144 10145 // If the permission is not to be promoted to runtime we ignore it and 10146 // also its other flags as they are not applicable to install permissions. 10147 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10148 for (int userId : currentUserIds) { 10149 if (permissionsState.grantRuntimePermission(bp, userId) != 10150 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10151 // Transfer the permission flags. 10152 permissionsState.updatePermissionFlags(bp, userId, 10153 flags, flags); 10154 // If we granted the permission, we have to write. 10155 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10156 changedRuntimePermissionUserIds, userId); 10157 } 10158 } 10159 } 10160 } break; 10161 10162 default: { 10163 if (packageOfInterest == null 10164 || packageOfInterest.equals(pkg.packageName)) { 10165 Slog.w(TAG, "Not granting permission " + perm 10166 + " to package " + pkg.packageName 10167 + " because it was previously installed without"); 10168 } 10169 } break; 10170 } 10171 } else { 10172 if (permissionsState.revokeInstallPermission(bp) != 10173 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10174 // Also drop the permission flags. 10175 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10176 PackageManager.MASK_PERMISSION_FLAGS, 0); 10177 changedInstallPermission = true; 10178 Slog.i(TAG, "Un-granting permission " + perm 10179 + " from package " + pkg.packageName 10180 + " (protectionLevel=" + bp.protectionLevel 10181 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10182 + ")"); 10183 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10184 // Don't print warning for app op permissions, since it is fine for them 10185 // not to be granted, there is a UI for the user to decide. 10186 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10187 Slog.w(TAG, "Not granting permission " + perm 10188 + " to package " + pkg.packageName 10189 + " (protectionLevel=" + bp.protectionLevel 10190 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10191 + ")"); 10192 } 10193 } 10194 } 10195 } 10196 10197 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10198 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10199 // This is the first that we have heard about this package, so the 10200 // permissions we have now selected are fixed until explicitly 10201 // changed. 10202 ps.installPermissionsFixed = true; 10203 } 10204 10205 // Persist the runtime permissions state for users with changes. If permissions 10206 // were revoked because no app in the shared user declares them we have to 10207 // write synchronously to avoid losing runtime permissions state. 10208 for (int userId : changedRuntimePermissionUserIds) { 10209 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10210 } 10211 10212 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10213 } 10214 10215 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10216 boolean allowed = false; 10217 final int NP = PackageParser.NEW_PERMISSIONS.length; 10218 for (int ip=0; ip<NP; ip++) { 10219 final PackageParser.NewPermissionInfo npi 10220 = PackageParser.NEW_PERMISSIONS[ip]; 10221 if (npi.name.equals(perm) 10222 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10223 allowed = true; 10224 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10225 + pkg.packageName); 10226 break; 10227 } 10228 } 10229 return allowed; 10230 } 10231 10232 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10233 BasePermission bp, PermissionsState origPermissions) { 10234 boolean allowed; 10235 allowed = (compareSignatures( 10236 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10237 == PackageManager.SIGNATURE_MATCH) 10238 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10239 == PackageManager.SIGNATURE_MATCH); 10240 if (!allowed && (bp.protectionLevel 10241 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10242 if (isSystemApp(pkg)) { 10243 // For updated system applications, a system permission 10244 // is granted only if it had been defined by the original application. 10245 if (pkg.isUpdatedSystemApp()) { 10246 final PackageSetting sysPs = mSettings 10247 .getDisabledSystemPkgLPr(pkg.packageName); 10248 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10249 // If the original was granted this permission, we take 10250 // that grant decision as read and propagate it to the 10251 // update. 10252 if (sysPs.isPrivileged()) { 10253 allowed = true; 10254 } 10255 } else { 10256 // The system apk may have been updated with an older 10257 // version of the one on the data partition, but which 10258 // granted a new system permission that it didn't have 10259 // before. In this case we do want to allow the app to 10260 // now get the new permission if the ancestral apk is 10261 // privileged to get it. 10262 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10263 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10264 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10265 allowed = true; 10266 break; 10267 } 10268 } 10269 } 10270 // Also if a privileged parent package on the system image or any of 10271 // its children requested a privileged permission, the updated child 10272 // packages can also get the permission. 10273 if (pkg.parentPackage != null) { 10274 final PackageSetting disabledSysParentPs = mSettings 10275 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10276 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10277 && disabledSysParentPs.isPrivileged()) { 10278 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10279 allowed = true; 10280 } else if (disabledSysParentPs.pkg.childPackages != null) { 10281 final int count = disabledSysParentPs.pkg.childPackages.size(); 10282 for (int i = 0; i < count; i++) { 10283 PackageParser.Package disabledSysChildPkg = 10284 disabledSysParentPs.pkg.childPackages.get(i); 10285 if (isPackageRequestingPermission(disabledSysChildPkg, 10286 perm)) { 10287 allowed = true; 10288 break; 10289 } 10290 } 10291 } 10292 } 10293 } 10294 } 10295 } else { 10296 allowed = isPrivilegedApp(pkg); 10297 } 10298 } 10299 } 10300 if (!allowed) { 10301 if (!allowed && (bp.protectionLevel 10302 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10303 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10304 // If this was a previously normal/dangerous permission that got moved 10305 // to a system permission as part of the runtime permission redesign, then 10306 // we still want to blindly grant it to old apps. 10307 allowed = true; 10308 } 10309 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10310 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10311 // If this permission is to be granted to the system installer and 10312 // this app is an installer, then it gets the permission. 10313 allowed = true; 10314 } 10315 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10316 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10317 // If this permission is to be granted to the system verifier and 10318 // this app is a verifier, then it gets the permission. 10319 allowed = true; 10320 } 10321 if (!allowed && (bp.protectionLevel 10322 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10323 && isSystemApp(pkg)) { 10324 // Any pre-installed system app is allowed to get this permission. 10325 allowed = true; 10326 } 10327 if (!allowed && (bp.protectionLevel 10328 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10329 // For development permissions, a development permission 10330 // is granted only if it was already granted. 10331 allowed = origPermissions.hasInstallPermission(perm); 10332 } 10333 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10334 && pkg.packageName.equals(mSetupWizardPackage)) { 10335 // If this permission is to be granted to the system setup wizard and 10336 // this app is a setup wizard, then it gets the permission. 10337 allowed = true; 10338 } 10339 } 10340 return allowed; 10341 } 10342 10343 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10344 final int permCount = pkg.requestedPermissions.size(); 10345 for (int j = 0; j < permCount; j++) { 10346 String requestedPermission = pkg.requestedPermissions.get(j); 10347 if (permission.equals(requestedPermission)) { 10348 return true; 10349 } 10350 } 10351 return false; 10352 } 10353 10354 final class ActivityIntentResolver 10355 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10356 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10357 boolean defaultOnly, int userId) { 10358 if (!sUserManager.exists(userId)) return null; 10359 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10360 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10361 } 10362 10363 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10364 int userId) { 10365 if (!sUserManager.exists(userId)) return null; 10366 mFlags = flags; 10367 return super.queryIntent(intent, resolvedType, 10368 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10369 } 10370 10371 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10372 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10373 if (!sUserManager.exists(userId)) return null; 10374 if (packageActivities == null) { 10375 return null; 10376 } 10377 mFlags = flags; 10378 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10379 final int N = packageActivities.size(); 10380 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10381 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10382 10383 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10384 for (int i = 0; i < N; ++i) { 10385 intentFilters = packageActivities.get(i).intents; 10386 if (intentFilters != null && intentFilters.size() > 0) { 10387 PackageParser.ActivityIntentInfo[] array = 10388 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10389 intentFilters.toArray(array); 10390 listCut.add(array); 10391 } 10392 } 10393 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10394 } 10395 10396 /** 10397 * Finds a privileged activity that matches the specified activity names. 10398 */ 10399 private PackageParser.Activity findMatchingActivity( 10400 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10401 for (PackageParser.Activity sysActivity : activityList) { 10402 if (sysActivity.info.name.equals(activityInfo.name)) { 10403 return sysActivity; 10404 } 10405 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10406 return sysActivity; 10407 } 10408 if (sysActivity.info.targetActivity != null) { 10409 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10410 return sysActivity; 10411 } 10412 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10413 return sysActivity; 10414 } 10415 } 10416 } 10417 return null; 10418 } 10419 10420 public class IterGenerator<E> { 10421 public Iterator<E> generate(ActivityIntentInfo info) { 10422 return null; 10423 } 10424 } 10425 10426 public class ActionIterGenerator extends IterGenerator<String> { 10427 @Override 10428 public Iterator<String> generate(ActivityIntentInfo info) { 10429 return info.actionsIterator(); 10430 } 10431 } 10432 10433 public class CategoriesIterGenerator extends IterGenerator<String> { 10434 @Override 10435 public Iterator<String> generate(ActivityIntentInfo info) { 10436 return info.categoriesIterator(); 10437 } 10438 } 10439 10440 public class SchemesIterGenerator extends IterGenerator<String> { 10441 @Override 10442 public Iterator<String> generate(ActivityIntentInfo info) { 10443 return info.schemesIterator(); 10444 } 10445 } 10446 10447 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10448 @Override 10449 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10450 return info.authoritiesIterator(); 10451 } 10452 } 10453 10454 /** 10455 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10456 * MODIFIED. Do not pass in a list that should not be changed. 10457 */ 10458 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10459 IterGenerator<T> generator, Iterator<T> searchIterator) { 10460 // loop through the set of actions; every one must be found in the intent filter 10461 while (searchIterator.hasNext()) { 10462 // we must have at least one filter in the list to consider a match 10463 if (intentList.size() == 0) { 10464 break; 10465 } 10466 10467 final T searchAction = searchIterator.next(); 10468 10469 // loop through the set of intent filters 10470 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10471 while (intentIter.hasNext()) { 10472 final ActivityIntentInfo intentInfo = intentIter.next(); 10473 boolean selectionFound = false; 10474 10475 // loop through the intent filter's selection criteria; at least one 10476 // of them must match the searched criteria 10477 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10478 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10479 final T intentSelection = intentSelectionIter.next(); 10480 if (intentSelection != null && intentSelection.equals(searchAction)) { 10481 selectionFound = true; 10482 break; 10483 } 10484 } 10485 10486 // the selection criteria wasn't found in this filter's set; this filter 10487 // is not a potential match 10488 if (!selectionFound) { 10489 intentIter.remove(); 10490 } 10491 } 10492 } 10493 } 10494 10495 private boolean isProtectedAction(ActivityIntentInfo filter) { 10496 final Iterator<String> actionsIter = filter.actionsIterator(); 10497 while (actionsIter != null && actionsIter.hasNext()) { 10498 final String filterAction = actionsIter.next(); 10499 if (PROTECTED_ACTIONS.contains(filterAction)) { 10500 return true; 10501 } 10502 } 10503 return false; 10504 } 10505 10506 /** 10507 * Adjusts the priority of the given intent filter according to policy. 10508 * <p> 10509 * <ul> 10510 * <li>The priority for non privileged applications is capped to '0'</li> 10511 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10512 * <li>The priority for unbundled updates to privileged applications is capped to the 10513 * priority defined on the system partition</li> 10514 * </ul> 10515 * <p> 10516 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10517 * allowed to obtain any priority on any action. 10518 */ 10519 private void adjustPriority( 10520 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10521 // nothing to do; priority is fine as-is 10522 if (intent.getPriority() <= 0) { 10523 return; 10524 } 10525 10526 final ActivityInfo activityInfo = intent.activity.info; 10527 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10528 10529 final boolean privilegedApp = 10530 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10531 if (!privilegedApp) { 10532 // non-privileged applications can never define a priority >0 10533 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10534 + " package: " + applicationInfo.packageName 10535 + " activity: " + intent.activity.className 10536 + " origPrio: " + intent.getPriority()); 10537 intent.setPriority(0); 10538 return; 10539 } 10540 10541 if (systemActivities == null) { 10542 // the system package is not disabled; we're parsing the system partition 10543 if (isProtectedAction(intent)) { 10544 if (mDeferProtectedFilters) { 10545 // We can't deal with these just yet. No component should ever obtain a 10546 // >0 priority for a protected actions, with ONE exception -- the setup 10547 // wizard. The setup wizard, however, cannot be known until we're able to 10548 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10549 // until all intent filters have been processed. Chicken, meet egg. 10550 // Let the filter temporarily have a high priority and rectify the 10551 // priorities after all system packages have been scanned. 10552 mProtectedFilters.add(intent); 10553 if (DEBUG_FILTERS) { 10554 Slog.i(TAG, "Protected action; save for later;" 10555 + " package: " + applicationInfo.packageName 10556 + " activity: " + intent.activity.className 10557 + " origPrio: " + intent.getPriority()); 10558 } 10559 return; 10560 } else { 10561 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10562 Slog.i(TAG, "No setup wizard;" 10563 + " All protected intents capped to priority 0"); 10564 } 10565 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10566 if (DEBUG_FILTERS) { 10567 Slog.i(TAG, "Found setup wizard;" 10568 + " allow priority " + intent.getPriority() + ";" 10569 + " package: " + intent.activity.info.packageName 10570 + " activity: " + intent.activity.className 10571 + " priority: " + intent.getPriority()); 10572 } 10573 // setup wizard gets whatever it wants 10574 return; 10575 } 10576 Slog.w(TAG, "Protected action; cap priority to 0;" 10577 + " package: " + intent.activity.info.packageName 10578 + " activity: " + intent.activity.className 10579 + " origPrio: " + intent.getPriority()); 10580 intent.setPriority(0); 10581 return; 10582 } 10583 } 10584 // privileged apps on the system image get whatever priority they request 10585 return; 10586 } 10587 10588 // privileged app unbundled update ... try to find the same activity 10589 final PackageParser.Activity foundActivity = 10590 findMatchingActivity(systemActivities, activityInfo); 10591 if (foundActivity == null) { 10592 // this is a new activity; it cannot obtain >0 priority 10593 if (DEBUG_FILTERS) { 10594 Slog.i(TAG, "New activity; cap priority to 0;" 10595 + " package: " + applicationInfo.packageName 10596 + " activity: " + intent.activity.className 10597 + " origPrio: " + intent.getPriority()); 10598 } 10599 intent.setPriority(0); 10600 return; 10601 } 10602 10603 // found activity, now check for filter equivalence 10604 10605 // a shallow copy is enough; we modify the list, not its contents 10606 final List<ActivityIntentInfo> intentListCopy = 10607 new ArrayList<>(foundActivity.intents); 10608 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10609 10610 // find matching action subsets 10611 final Iterator<String> actionsIterator = intent.actionsIterator(); 10612 if (actionsIterator != null) { 10613 getIntentListSubset( 10614 intentListCopy, new ActionIterGenerator(), actionsIterator); 10615 if (intentListCopy.size() == 0) { 10616 // no more intents to match; we're not equivalent 10617 if (DEBUG_FILTERS) { 10618 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10619 + " package: " + applicationInfo.packageName 10620 + " activity: " + intent.activity.className 10621 + " origPrio: " + intent.getPriority()); 10622 } 10623 intent.setPriority(0); 10624 return; 10625 } 10626 } 10627 10628 // find matching category subsets 10629 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10630 if (categoriesIterator != null) { 10631 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10632 categoriesIterator); 10633 if (intentListCopy.size() == 0) { 10634 // no more intents to match; we're not equivalent 10635 if (DEBUG_FILTERS) { 10636 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10637 + " package: " + applicationInfo.packageName 10638 + " activity: " + intent.activity.className 10639 + " origPrio: " + intent.getPriority()); 10640 } 10641 intent.setPriority(0); 10642 return; 10643 } 10644 } 10645 10646 // find matching schemes subsets 10647 final Iterator<String> schemesIterator = intent.schemesIterator(); 10648 if (schemesIterator != null) { 10649 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10650 schemesIterator); 10651 if (intentListCopy.size() == 0) { 10652 // no more intents to match; we're not equivalent 10653 if (DEBUG_FILTERS) { 10654 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10655 + " package: " + applicationInfo.packageName 10656 + " activity: " + intent.activity.className 10657 + " origPrio: " + intent.getPriority()); 10658 } 10659 intent.setPriority(0); 10660 return; 10661 } 10662 } 10663 10664 // find matching authorities subsets 10665 final Iterator<IntentFilter.AuthorityEntry> 10666 authoritiesIterator = intent.authoritiesIterator(); 10667 if (authoritiesIterator != null) { 10668 getIntentListSubset(intentListCopy, 10669 new AuthoritiesIterGenerator(), 10670 authoritiesIterator); 10671 if (intentListCopy.size() == 0) { 10672 // no more intents to match; we're not equivalent 10673 if (DEBUG_FILTERS) { 10674 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10675 + " package: " + applicationInfo.packageName 10676 + " activity: " + intent.activity.className 10677 + " origPrio: " + intent.getPriority()); 10678 } 10679 intent.setPriority(0); 10680 return; 10681 } 10682 } 10683 10684 // we found matching filter(s); app gets the max priority of all intents 10685 int cappedPriority = 0; 10686 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10687 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10688 } 10689 if (intent.getPriority() > cappedPriority) { 10690 if (DEBUG_FILTERS) { 10691 Slog.i(TAG, "Found matching filter(s);" 10692 + " cap priority to " + cappedPriority + ";" 10693 + " package: " + applicationInfo.packageName 10694 + " activity: " + intent.activity.className 10695 + " origPrio: " + intent.getPriority()); 10696 } 10697 intent.setPriority(cappedPriority); 10698 return; 10699 } 10700 // all this for nothing; the requested priority was <= what was on the system 10701 } 10702 10703 public final void addActivity(PackageParser.Activity a, String type) { 10704 mActivities.put(a.getComponentName(), a); 10705 if (DEBUG_SHOW_INFO) 10706 Log.v( 10707 TAG, " " + type + " " + 10708 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10709 if (DEBUG_SHOW_INFO) 10710 Log.v(TAG, " Class=" + a.info.name); 10711 final int NI = a.intents.size(); 10712 for (int j=0; j<NI; j++) { 10713 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10714 if ("activity".equals(type)) { 10715 final PackageSetting ps = 10716 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10717 final List<PackageParser.Activity> systemActivities = 10718 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10719 adjustPriority(systemActivities, intent); 10720 } 10721 if (DEBUG_SHOW_INFO) { 10722 Log.v(TAG, " IntentFilter:"); 10723 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10724 } 10725 if (!intent.debugCheck()) { 10726 Log.w(TAG, "==> For Activity " + a.info.name); 10727 } 10728 addFilter(intent); 10729 } 10730 } 10731 10732 public final void removeActivity(PackageParser.Activity a, String type) { 10733 mActivities.remove(a.getComponentName()); 10734 if (DEBUG_SHOW_INFO) { 10735 Log.v(TAG, " " + type + " " 10736 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10737 : a.info.name) + ":"); 10738 Log.v(TAG, " Class=" + a.info.name); 10739 } 10740 final int NI = a.intents.size(); 10741 for (int j=0; j<NI; j++) { 10742 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10743 if (DEBUG_SHOW_INFO) { 10744 Log.v(TAG, " IntentFilter:"); 10745 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10746 } 10747 removeFilter(intent); 10748 } 10749 } 10750 10751 @Override 10752 protected boolean allowFilterResult( 10753 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10754 ActivityInfo filterAi = filter.activity.info; 10755 for (int i=dest.size()-1; i>=0; i--) { 10756 ActivityInfo destAi = dest.get(i).activityInfo; 10757 if (destAi.name == filterAi.name 10758 && destAi.packageName == filterAi.packageName) { 10759 return false; 10760 } 10761 } 10762 return true; 10763 } 10764 10765 @Override 10766 protected ActivityIntentInfo[] newArray(int size) { 10767 return new ActivityIntentInfo[size]; 10768 } 10769 10770 @Override 10771 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10772 if (!sUserManager.exists(userId)) return true; 10773 PackageParser.Package p = filter.activity.owner; 10774 if (p != null) { 10775 PackageSetting ps = (PackageSetting)p.mExtras; 10776 if (ps != null) { 10777 // System apps are never considered stopped for purposes of 10778 // filtering, because there may be no way for the user to 10779 // actually re-launch them. 10780 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10781 && ps.getStopped(userId); 10782 } 10783 } 10784 return false; 10785 } 10786 10787 @Override 10788 protected boolean isPackageForFilter(String packageName, 10789 PackageParser.ActivityIntentInfo info) { 10790 return packageName.equals(info.activity.owner.packageName); 10791 } 10792 10793 @Override 10794 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10795 int match, int userId) { 10796 if (!sUserManager.exists(userId)) return null; 10797 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10798 return null; 10799 } 10800 final PackageParser.Activity activity = info.activity; 10801 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10802 if (ps == null) { 10803 return null; 10804 } 10805 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10806 ps.readUserState(userId), userId); 10807 if (ai == null) { 10808 return null; 10809 } 10810 final ResolveInfo res = new ResolveInfo(); 10811 res.activityInfo = ai; 10812 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10813 res.filter = info; 10814 } 10815 if (info != null) { 10816 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10817 } 10818 res.priority = info.getPriority(); 10819 res.preferredOrder = activity.owner.mPreferredOrder; 10820 //System.out.println("Result: " + res.activityInfo.className + 10821 // " = " + res.priority); 10822 res.match = match; 10823 res.isDefault = info.hasDefault; 10824 res.labelRes = info.labelRes; 10825 res.nonLocalizedLabel = info.nonLocalizedLabel; 10826 if (userNeedsBadging(userId)) { 10827 res.noResourceId = true; 10828 } else { 10829 res.icon = info.icon; 10830 } 10831 res.iconResourceId = info.icon; 10832 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10833 return res; 10834 } 10835 10836 @Override 10837 protected void sortResults(List<ResolveInfo> results) { 10838 Collections.sort(results, mResolvePrioritySorter); 10839 } 10840 10841 @Override 10842 protected void dumpFilter(PrintWriter out, String prefix, 10843 PackageParser.ActivityIntentInfo filter) { 10844 out.print(prefix); out.print( 10845 Integer.toHexString(System.identityHashCode(filter.activity))); 10846 out.print(' '); 10847 filter.activity.printComponentShortName(out); 10848 out.print(" filter "); 10849 out.println(Integer.toHexString(System.identityHashCode(filter))); 10850 } 10851 10852 @Override 10853 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10854 return filter.activity; 10855 } 10856 10857 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10858 PackageParser.Activity activity = (PackageParser.Activity)label; 10859 out.print(prefix); out.print( 10860 Integer.toHexString(System.identityHashCode(activity))); 10861 out.print(' '); 10862 activity.printComponentShortName(out); 10863 if (count > 1) { 10864 out.print(" ("); out.print(count); out.print(" filters)"); 10865 } 10866 out.println(); 10867 } 10868 10869 // Keys are String (activity class name), values are Activity. 10870 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10871 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10872 private int mFlags; 10873 } 10874 10875 private final class ServiceIntentResolver 10876 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10877 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10878 boolean defaultOnly, int userId) { 10879 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10880 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10881 } 10882 10883 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10884 int userId) { 10885 if (!sUserManager.exists(userId)) return null; 10886 mFlags = flags; 10887 return super.queryIntent(intent, resolvedType, 10888 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10889 } 10890 10891 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10892 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10893 if (!sUserManager.exists(userId)) return null; 10894 if (packageServices == null) { 10895 return null; 10896 } 10897 mFlags = flags; 10898 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10899 final int N = packageServices.size(); 10900 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10901 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10902 10903 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10904 for (int i = 0; i < N; ++i) { 10905 intentFilters = packageServices.get(i).intents; 10906 if (intentFilters != null && intentFilters.size() > 0) { 10907 PackageParser.ServiceIntentInfo[] array = 10908 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10909 intentFilters.toArray(array); 10910 listCut.add(array); 10911 } 10912 } 10913 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10914 } 10915 10916 public final void addService(PackageParser.Service s) { 10917 mServices.put(s.getComponentName(), s); 10918 if (DEBUG_SHOW_INFO) { 10919 Log.v(TAG, " " 10920 + (s.info.nonLocalizedLabel != null 10921 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10922 Log.v(TAG, " Class=" + s.info.name); 10923 } 10924 final int NI = s.intents.size(); 10925 int j; 10926 for (j=0; j<NI; j++) { 10927 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10928 if (DEBUG_SHOW_INFO) { 10929 Log.v(TAG, " IntentFilter:"); 10930 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10931 } 10932 if (!intent.debugCheck()) { 10933 Log.w(TAG, "==> For Service " + s.info.name); 10934 } 10935 addFilter(intent); 10936 } 10937 } 10938 10939 public final void removeService(PackageParser.Service s) { 10940 mServices.remove(s.getComponentName()); 10941 if (DEBUG_SHOW_INFO) { 10942 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10943 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10944 Log.v(TAG, " Class=" + s.info.name); 10945 } 10946 final int NI = s.intents.size(); 10947 int j; 10948 for (j=0; j<NI; j++) { 10949 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10950 if (DEBUG_SHOW_INFO) { 10951 Log.v(TAG, " IntentFilter:"); 10952 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10953 } 10954 removeFilter(intent); 10955 } 10956 } 10957 10958 @Override 10959 protected boolean allowFilterResult( 10960 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10961 ServiceInfo filterSi = filter.service.info; 10962 for (int i=dest.size()-1; i>=0; i--) { 10963 ServiceInfo destAi = dest.get(i).serviceInfo; 10964 if (destAi.name == filterSi.name 10965 && destAi.packageName == filterSi.packageName) { 10966 return false; 10967 } 10968 } 10969 return true; 10970 } 10971 10972 @Override 10973 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10974 return new PackageParser.ServiceIntentInfo[size]; 10975 } 10976 10977 @Override 10978 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10979 if (!sUserManager.exists(userId)) return true; 10980 PackageParser.Package p = filter.service.owner; 10981 if (p != null) { 10982 PackageSetting ps = (PackageSetting)p.mExtras; 10983 if (ps != null) { 10984 // System apps are never considered stopped for purposes of 10985 // filtering, because there may be no way for the user to 10986 // actually re-launch them. 10987 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10988 && ps.getStopped(userId); 10989 } 10990 } 10991 return false; 10992 } 10993 10994 @Override 10995 protected boolean isPackageForFilter(String packageName, 10996 PackageParser.ServiceIntentInfo info) { 10997 return packageName.equals(info.service.owner.packageName); 10998 } 10999 11000 @Override 11001 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11002 int match, int userId) { 11003 if (!sUserManager.exists(userId)) return null; 11004 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11005 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11006 return null; 11007 } 11008 final PackageParser.Service service = info.service; 11009 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11010 if (ps == null) { 11011 return null; 11012 } 11013 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11014 ps.readUserState(userId), userId); 11015 if (si == null) { 11016 return null; 11017 } 11018 final ResolveInfo res = new ResolveInfo(); 11019 res.serviceInfo = si; 11020 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11021 res.filter = filter; 11022 } 11023 res.priority = info.getPriority(); 11024 res.preferredOrder = service.owner.mPreferredOrder; 11025 res.match = match; 11026 res.isDefault = info.hasDefault; 11027 res.labelRes = info.labelRes; 11028 res.nonLocalizedLabel = info.nonLocalizedLabel; 11029 res.icon = info.icon; 11030 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11031 return res; 11032 } 11033 11034 @Override 11035 protected void sortResults(List<ResolveInfo> results) { 11036 Collections.sort(results, mResolvePrioritySorter); 11037 } 11038 11039 @Override 11040 protected void dumpFilter(PrintWriter out, String prefix, 11041 PackageParser.ServiceIntentInfo filter) { 11042 out.print(prefix); out.print( 11043 Integer.toHexString(System.identityHashCode(filter.service))); 11044 out.print(' '); 11045 filter.service.printComponentShortName(out); 11046 out.print(" filter "); 11047 out.println(Integer.toHexString(System.identityHashCode(filter))); 11048 } 11049 11050 @Override 11051 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11052 return filter.service; 11053 } 11054 11055 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11056 PackageParser.Service service = (PackageParser.Service)label; 11057 out.print(prefix); out.print( 11058 Integer.toHexString(System.identityHashCode(service))); 11059 out.print(' '); 11060 service.printComponentShortName(out); 11061 if (count > 1) { 11062 out.print(" ("); out.print(count); out.print(" filters)"); 11063 } 11064 out.println(); 11065 } 11066 11067// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11068// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11069// final List<ResolveInfo> retList = Lists.newArrayList(); 11070// while (i.hasNext()) { 11071// final ResolveInfo resolveInfo = (ResolveInfo) i; 11072// if (isEnabledLP(resolveInfo.serviceInfo)) { 11073// retList.add(resolveInfo); 11074// } 11075// } 11076// return retList; 11077// } 11078 11079 // Keys are String (activity class name), values are Activity. 11080 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11081 = new ArrayMap<ComponentName, PackageParser.Service>(); 11082 private int mFlags; 11083 }; 11084 11085 private final class ProviderIntentResolver 11086 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11087 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11088 boolean defaultOnly, int userId) { 11089 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11090 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11091 } 11092 11093 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11094 int userId) { 11095 if (!sUserManager.exists(userId)) 11096 return null; 11097 mFlags = flags; 11098 return super.queryIntent(intent, resolvedType, 11099 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11100 } 11101 11102 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11103 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11104 if (!sUserManager.exists(userId)) 11105 return null; 11106 if (packageProviders == null) { 11107 return null; 11108 } 11109 mFlags = flags; 11110 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11111 final int N = packageProviders.size(); 11112 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11113 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11114 11115 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11116 for (int i = 0; i < N; ++i) { 11117 intentFilters = packageProviders.get(i).intents; 11118 if (intentFilters != null && intentFilters.size() > 0) { 11119 PackageParser.ProviderIntentInfo[] array = 11120 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11121 intentFilters.toArray(array); 11122 listCut.add(array); 11123 } 11124 } 11125 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11126 } 11127 11128 public final void addProvider(PackageParser.Provider p) { 11129 if (mProviders.containsKey(p.getComponentName())) { 11130 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11131 return; 11132 } 11133 11134 mProviders.put(p.getComponentName(), p); 11135 if (DEBUG_SHOW_INFO) { 11136 Log.v(TAG, " " 11137 + (p.info.nonLocalizedLabel != null 11138 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11139 Log.v(TAG, " Class=" + p.info.name); 11140 } 11141 final int NI = p.intents.size(); 11142 int j; 11143 for (j = 0; j < NI; j++) { 11144 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11145 if (DEBUG_SHOW_INFO) { 11146 Log.v(TAG, " IntentFilter:"); 11147 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11148 } 11149 if (!intent.debugCheck()) { 11150 Log.w(TAG, "==> For Provider " + p.info.name); 11151 } 11152 addFilter(intent); 11153 } 11154 } 11155 11156 public final void removeProvider(PackageParser.Provider p) { 11157 mProviders.remove(p.getComponentName()); 11158 if (DEBUG_SHOW_INFO) { 11159 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11160 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11161 Log.v(TAG, " Class=" + p.info.name); 11162 } 11163 final int NI = p.intents.size(); 11164 int j; 11165 for (j = 0; j < NI; j++) { 11166 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11167 if (DEBUG_SHOW_INFO) { 11168 Log.v(TAG, " IntentFilter:"); 11169 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11170 } 11171 removeFilter(intent); 11172 } 11173 } 11174 11175 @Override 11176 protected boolean allowFilterResult( 11177 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11178 ProviderInfo filterPi = filter.provider.info; 11179 for (int i = dest.size() - 1; i >= 0; i--) { 11180 ProviderInfo destPi = dest.get(i).providerInfo; 11181 if (destPi.name == filterPi.name 11182 && destPi.packageName == filterPi.packageName) { 11183 return false; 11184 } 11185 } 11186 return true; 11187 } 11188 11189 @Override 11190 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11191 return new PackageParser.ProviderIntentInfo[size]; 11192 } 11193 11194 @Override 11195 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11196 if (!sUserManager.exists(userId)) 11197 return true; 11198 PackageParser.Package p = filter.provider.owner; 11199 if (p != null) { 11200 PackageSetting ps = (PackageSetting) p.mExtras; 11201 if (ps != null) { 11202 // System apps are never considered stopped for purposes of 11203 // filtering, because there may be no way for the user to 11204 // actually re-launch them. 11205 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11206 && ps.getStopped(userId); 11207 } 11208 } 11209 return false; 11210 } 11211 11212 @Override 11213 protected boolean isPackageForFilter(String packageName, 11214 PackageParser.ProviderIntentInfo info) { 11215 return packageName.equals(info.provider.owner.packageName); 11216 } 11217 11218 @Override 11219 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11220 int match, int userId) { 11221 if (!sUserManager.exists(userId)) 11222 return null; 11223 final PackageParser.ProviderIntentInfo info = filter; 11224 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11225 return null; 11226 } 11227 final PackageParser.Provider provider = info.provider; 11228 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11229 if (ps == null) { 11230 return null; 11231 } 11232 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11233 ps.readUserState(userId), userId); 11234 if (pi == null) { 11235 return null; 11236 } 11237 final ResolveInfo res = new ResolveInfo(); 11238 res.providerInfo = pi; 11239 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11240 res.filter = filter; 11241 } 11242 res.priority = info.getPriority(); 11243 res.preferredOrder = provider.owner.mPreferredOrder; 11244 res.match = match; 11245 res.isDefault = info.hasDefault; 11246 res.labelRes = info.labelRes; 11247 res.nonLocalizedLabel = info.nonLocalizedLabel; 11248 res.icon = info.icon; 11249 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11250 return res; 11251 } 11252 11253 @Override 11254 protected void sortResults(List<ResolveInfo> results) { 11255 Collections.sort(results, mResolvePrioritySorter); 11256 } 11257 11258 @Override 11259 protected void dumpFilter(PrintWriter out, String prefix, 11260 PackageParser.ProviderIntentInfo filter) { 11261 out.print(prefix); 11262 out.print( 11263 Integer.toHexString(System.identityHashCode(filter.provider))); 11264 out.print(' '); 11265 filter.provider.printComponentShortName(out); 11266 out.print(" filter "); 11267 out.println(Integer.toHexString(System.identityHashCode(filter))); 11268 } 11269 11270 @Override 11271 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11272 return filter.provider; 11273 } 11274 11275 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11276 PackageParser.Provider provider = (PackageParser.Provider)label; 11277 out.print(prefix); out.print( 11278 Integer.toHexString(System.identityHashCode(provider))); 11279 out.print(' '); 11280 provider.printComponentShortName(out); 11281 if (count > 1) { 11282 out.print(" ("); out.print(count); out.print(" filters)"); 11283 } 11284 out.println(); 11285 } 11286 11287 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11288 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11289 private int mFlags; 11290 } 11291 11292 private static final class EphemeralIntentResolver 11293 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11294 @Override 11295 protected EphemeralResolveIntentInfo[] newArray(int size) { 11296 return new EphemeralResolveIntentInfo[size]; 11297 } 11298 11299 @Override 11300 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11301 return true; 11302 } 11303 11304 @Override 11305 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11306 int userId) { 11307 if (!sUserManager.exists(userId)) { 11308 return null; 11309 } 11310 return info.getEphemeralResolveInfo(); 11311 } 11312 } 11313 11314 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11315 new Comparator<ResolveInfo>() { 11316 public int compare(ResolveInfo r1, ResolveInfo r2) { 11317 int v1 = r1.priority; 11318 int v2 = r2.priority; 11319 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11320 if (v1 != v2) { 11321 return (v1 > v2) ? -1 : 1; 11322 } 11323 v1 = r1.preferredOrder; 11324 v2 = r2.preferredOrder; 11325 if (v1 != v2) { 11326 return (v1 > v2) ? -1 : 1; 11327 } 11328 if (r1.isDefault != r2.isDefault) { 11329 return r1.isDefault ? -1 : 1; 11330 } 11331 v1 = r1.match; 11332 v2 = r2.match; 11333 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11334 if (v1 != v2) { 11335 return (v1 > v2) ? -1 : 1; 11336 } 11337 if (r1.system != r2.system) { 11338 return r1.system ? -1 : 1; 11339 } 11340 if (r1.activityInfo != null) { 11341 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11342 } 11343 if (r1.serviceInfo != null) { 11344 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11345 } 11346 if (r1.providerInfo != null) { 11347 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11348 } 11349 return 0; 11350 } 11351 }; 11352 11353 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11354 new Comparator<ProviderInfo>() { 11355 public int compare(ProviderInfo p1, ProviderInfo p2) { 11356 final int v1 = p1.initOrder; 11357 final int v2 = p2.initOrder; 11358 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11359 } 11360 }; 11361 11362 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11363 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11364 final int[] userIds) { 11365 mHandler.post(new Runnable() { 11366 @Override 11367 public void run() { 11368 try { 11369 final IActivityManager am = ActivityManagerNative.getDefault(); 11370 if (am == null) return; 11371 final int[] resolvedUserIds; 11372 if (userIds == null) { 11373 resolvedUserIds = am.getRunningUserIds(); 11374 } else { 11375 resolvedUserIds = userIds; 11376 } 11377 for (int id : resolvedUserIds) { 11378 final Intent intent = new Intent(action, 11379 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11380 if (extras != null) { 11381 intent.putExtras(extras); 11382 } 11383 if (targetPkg != null) { 11384 intent.setPackage(targetPkg); 11385 } 11386 // Modify the UID when posting to other users 11387 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11388 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11389 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11390 intent.putExtra(Intent.EXTRA_UID, uid); 11391 } 11392 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11393 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11394 if (DEBUG_BROADCASTS) { 11395 RuntimeException here = new RuntimeException("here"); 11396 here.fillInStackTrace(); 11397 Slog.d(TAG, "Sending to user " + id + ": " 11398 + intent.toShortString(false, true, false, false) 11399 + " " + intent.getExtras(), here); 11400 } 11401 am.broadcastIntent(null, intent, null, finishedReceiver, 11402 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11403 null, finishedReceiver != null, false, id); 11404 } 11405 } catch (RemoteException ex) { 11406 } 11407 } 11408 }); 11409 } 11410 11411 /** 11412 * Check if the external storage media is available. This is true if there 11413 * is a mounted external storage medium or if the external storage is 11414 * emulated. 11415 */ 11416 private boolean isExternalMediaAvailable() { 11417 return mMediaMounted || Environment.isExternalStorageEmulated(); 11418 } 11419 11420 @Override 11421 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11422 // writer 11423 synchronized (mPackages) { 11424 if (!isExternalMediaAvailable()) { 11425 // If the external storage is no longer mounted at this point, 11426 // the caller may not have been able to delete all of this 11427 // packages files and can not delete any more. Bail. 11428 return null; 11429 } 11430 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11431 if (lastPackage != null) { 11432 pkgs.remove(lastPackage); 11433 } 11434 if (pkgs.size() > 0) { 11435 return pkgs.get(0); 11436 } 11437 } 11438 return null; 11439 } 11440 11441 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11442 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11443 userId, andCode ? 1 : 0, packageName); 11444 if (mSystemReady) { 11445 msg.sendToTarget(); 11446 } else { 11447 if (mPostSystemReadyMessages == null) { 11448 mPostSystemReadyMessages = new ArrayList<>(); 11449 } 11450 mPostSystemReadyMessages.add(msg); 11451 } 11452 } 11453 11454 void startCleaningPackages() { 11455 // reader 11456 if (!isExternalMediaAvailable()) { 11457 return; 11458 } 11459 synchronized (mPackages) { 11460 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11461 return; 11462 } 11463 } 11464 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11465 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11466 IActivityManager am = ActivityManagerNative.getDefault(); 11467 if (am != null) { 11468 try { 11469 am.startService(null, intent, null, mContext.getOpPackageName(), 11470 UserHandle.USER_SYSTEM); 11471 } catch (RemoteException e) { 11472 } 11473 } 11474 } 11475 11476 @Override 11477 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11478 int installFlags, String installerPackageName, int userId) { 11479 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11480 11481 final int callingUid = Binder.getCallingUid(); 11482 enforceCrossUserPermission(callingUid, userId, 11483 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11484 11485 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11486 try { 11487 if (observer != null) { 11488 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11489 } 11490 } catch (RemoteException re) { 11491 } 11492 return; 11493 } 11494 11495 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11496 installFlags |= PackageManager.INSTALL_FROM_ADB; 11497 11498 } else { 11499 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11500 // about installerPackageName. 11501 11502 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11503 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11504 } 11505 11506 UserHandle user; 11507 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11508 user = UserHandle.ALL; 11509 } else { 11510 user = new UserHandle(userId); 11511 } 11512 11513 // Only system components can circumvent runtime permissions when installing. 11514 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11515 && mContext.checkCallingOrSelfPermission(Manifest.permission 11516 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11517 throw new SecurityException("You need the " 11518 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11519 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11520 } 11521 11522 final File originFile = new File(originPath); 11523 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11524 11525 final Message msg = mHandler.obtainMessage(INIT_COPY); 11526 final VerificationInfo verificationInfo = new VerificationInfo( 11527 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11528 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11529 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11530 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11531 null /*certificates*/); 11532 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11533 msg.obj = params; 11534 11535 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11536 System.identityHashCode(msg.obj)); 11537 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11538 System.identityHashCode(msg.obj)); 11539 11540 mHandler.sendMessage(msg); 11541 } 11542 11543 void installStage(String packageName, File stagedDir, String stagedCid, 11544 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11545 String installerPackageName, int installerUid, UserHandle user, 11546 Certificate[][] certificates) { 11547 if (DEBUG_EPHEMERAL) { 11548 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11549 Slog.d(TAG, "Ephemeral install of " + packageName); 11550 } 11551 } 11552 final VerificationInfo verificationInfo = new VerificationInfo( 11553 sessionParams.originatingUri, sessionParams.referrerUri, 11554 sessionParams.originatingUid, installerUid); 11555 11556 final OriginInfo origin; 11557 if (stagedDir != null) { 11558 origin = OriginInfo.fromStagedFile(stagedDir); 11559 } else { 11560 origin = OriginInfo.fromStagedContainer(stagedCid); 11561 } 11562 11563 final Message msg = mHandler.obtainMessage(INIT_COPY); 11564 final InstallParams params = new InstallParams(origin, null, observer, 11565 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11566 verificationInfo, user, sessionParams.abiOverride, 11567 sessionParams.grantedRuntimePermissions, certificates); 11568 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11569 msg.obj = params; 11570 11571 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11572 System.identityHashCode(msg.obj)); 11573 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11574 System.identityHashCode(msg.obj)); 11575 11576 mHandler.sendMessage(msg); 11577 } 11578 11579 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11580 int userId) { 11581 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11582 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11583 } 11584 11585 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11586 int appId, int userId) { 11587 Bundle extras = new Bundle(1); 11588 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11589 11590 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11591 packageName, extras, 0, null, null, new int[] {userId}); 11592 try { 11593 IActivityManager am = ActivityManagerNative.getDefault(); 11594 if (isSystem && am.isUserRunning(userId, 0)) { 11595 // The just-installed/enabled app is bundled on the system, so presumed 11596 // to be able to run automatically without needing an explicit launch. 11597 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11598 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11599 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11600 .setPackage(packageName); 11601 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11602 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11603 } 11604 } catch (RemoteException e) { 11605 // shouldn't happen 11606 Slog.w(TAG, "Unable to bootstrap installed package", e); 11607 } 11608 } 11609 11610 @Override 11611 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11612 int userId) { 11613 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11614 PackageSetting pkgSetting; 11615 final int uid = Binder.getCallingUid(); 11616 enforceCrossUserPermission(uid, userId, 11617 true /* requireFullPermission */, true /* checkShell */, 11618 "setApplicationHiddenSetting for user " + userId); 11619 11620 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11621 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11622 return false; 11623 } 11624 11625 long callingId = Binder.clearCallingIdentity(); 11626 try { 11627 boolean sendAdded = false; 11628 boolean sendRemoved = false; 11629 // writer 11630 synchronized (mPackages) { 11631 pkgSetting = mSettings.mPackages.get(packageName); 11632 if (pkgSetting == null) { 11633 return false; 11634 } 11635 if (pkgSetting.getHidden(userId) != hidden) { 11636 pkgSetting.setHidden(hidden, userId); 11637 mSettings.writePackageRestrictionsLPr(userId); 11638 if (hidden) { 11639 sendRemoved = true; 11640 } else { 11641 sendAdded = true; 11642 } 11643 } 11644 } 11645 if (sendAdded) { 11646 sendPackageAddedForUser(packageName, pkgSetting, userId); 11647 return true; 11648 } 11649 if (sendRemoved) { 11650 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11651 "hiding pkg"); 11652 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11653 return true; 11654 } 11655 } finally { 11656 Binder.restoreCallingIdentity(callingId); 11657 } 11658 return false; 11659 } 11660 11661 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11662 int userId) { 11663 final PackageRemovedInfo info = new PackageRemovedInfo(); 11664 info.removedPackage = packageName; 11665 info.removedUsers = new int[] {userId}; 11666 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11667 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11668 } 11669 11670 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11671 if (pkgList.length > 0) { 11672 Bundle extras = new Bundle(1); 11673 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11674 11675 sendPackageBroadcast( 11676 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11677 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11678 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11679 new int[] {userId}); 11680 } 11681 } 11682 11683 /** 11684 * Returns true if application is not found or there was an error. Otherwise it returns 11685 * the hidden state of the package for the given user. 11686 */ 11687 @Override 11688 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11690 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11691 true /* requireFullPermission */, false /* checkShell */, 11692 "getApplicationHidden for user " + userId); 11693 PackageSetting pkgSetting; 11694 long callingId = Binder.clearCallingIdentity(); 11695 try { 11696 // writer 11697 synchronized (mPackages) { 11698 pkgSetting = mSettings.mPackages.get(packageName); 11699 if (pkgSetting == null) { 11700 return true; 11701 } 11702 return pkgSetting.getHidden(userId); 11703 } 11704 } finally { 11705 Binder.restoreCallingIdentity(callingId); 11706 } 11707 } 11708 11709 /** 11710 * @hide 11711 */ 11712 @Override 11713 public int installExistingPackageAsUser(String packageName, int userId) { 11714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11715 null); 11716 PackageSetting pkgSetting; 11717 final int uid = Binder.getCallingUid(); 11718 enforceCrossUserPermission(uid, userId, 11719 true /* requireFullPermission */, true /* checkShell */, 11720 "installExistingPackage for user " + userId); 11721 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11722 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11723 } 11724 11725 long callingId = Binder.clearCallingIdentity(); 11726 try { 11727 boolean installed = false; 11728 11729 // writer 11730 synchronized (mPackages) { 11731 pkgSetting = mSettings.mPackages.get(packageName); 11732 if (pkgSetting == null) { 11733 return PackageManager.INSTALL_FAILED_INVALID_URI; 11734 } 11735 if (!pkgSetting.getInstalled(userId)) { 11736 pkgSetting.setInstalled(true, userId); 11737 pkgSetting.setHidden(false, userId); 11738 mSettings.writePackageRestrictionsLPr(userId); 11739 installed = true; 11740 } 11741 } 11742 11743 if (installed) { 11744 if (pkgSetting.pkg != null) { 11745 synchronized (mInstallLock) { 11746 // We don't need to freeze for a brand new install 11747 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11748 } 11749 } 11750 sendPackageAddedForUser(packageName, pkgSetting, userId); 11751 } 11752 } finally { 11753 Binder.restoreCallingIdentity(callingId); 11754 } 11755 11756 return PackageManager.INSTALL_SUCCEEDED; 11757 } 11758 11759 boolean isUserRestricted(int userId, String restrictionKey) { 11760 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11761 if (restrictions.getBoolean(restrictionKey, false)) { 11762 Log.w(TAG, "User is restricted: " + restrictionKey); 11763 return true; 11764 } 11765 return false; 11766 } 11767 11768 @Override 11769 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11770 int userId) { 11771 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11773 true /* requireFullPermission */, true /* checkShell */, 11774 "setPackagesSuspended for user " + userId); 11775 11776 if (ArrayUtils.isEmpty(packageNames)) { 11777 return packageNames; 11778 } 11779 11780 // List of package names for whom the suspended state has changed. 11781 List<String> changedPackages = new ArrayList<>(packageNames.length); 11782 // List of package names for whom the suspended state is not set as requested in this 11783 // method. 11784 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11785 long callingId = Binder.clearCallingIdentity(); 11786 try { 11787 for (int i = 0; i < packageNames.length; i++) { 11788 String packageName = packageNames[i]; 11789 boolean changed = false; 11790 final int appId; 11791 synchronized (mPackages) { 11792 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11793 if (pkgSetting == null) { 11794 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11795 + "\". Skipping suspending/un-suspending."); 11796 unactionedPackages.add(packageName); 11797 continue; 11798 } 11799 appId = pkgSetting.appId; 11800 if (pkgSetting.getSuspended(userId) != suspended) { 11801 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11802 unactionedPackages.add(packageName); 11803 continue; 11804 } 11805 pkgSetting.setSuspended(suspended, userId); 11806 mSettings.writePackageRestrictionsLPr(userId); 11807 changed = true; 11808 changedPackages.add(packageName); 11809 } 11810 } 11811 11812 if (changed && suspended) { 11813 killApplication(packageName, UserHandle.getUid(userId, appId), 11814 "suspending package"); 11815 } 11816 } 11817 } finally { 11818 Binder.restoreCallingIdentity(callingId); 11819 } 11820 11821 if (!changedPackages.isEmpty()) { 11822 sendPackagesSuspendedForUser(changedPackages.toArray( 11823 new String[changedPackages.size()]), userId, suspended); 11824 } 11825 11826 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11827 } 11828 11829 @Override 11830 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11831 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11832 true /* requireFullPermission */, false /* checkShell */, 11833 "isPackageSuspendedForUser for user " + userId); 11834 synchronized (mPackages) { 11835 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11836 if (pkgSetting == null) { 11837 throw new IllegalArgumentException("Unknown target package: " + packageName); 11838 } 11839 return pkgSetting.getSuspended(userId); 11840 } 11841 } 11842 11843 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11844 if (isPackageDeviceAdmin(packageName, userId)) { 11845 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11846 + "\": has an active device admin"); 11847 return false; 11848 } 11849 11850 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11851 if (packageName.equals(activeLauncherPackageName)) { 11852 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11853 + "\": contains the active launcher"); 11854 return false; 11855 } 11856 11857 if (packageName.equals(mRequiredInstallerPackage)) { 11858 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11859 + "\": required for package installation"); 11860 return false; 11861 } 11862 11863 if (packageName.equals(mRequiredVerifierPackage)) { 11864 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11865 + "\": required for package verification"); 11866 return false; 11867 } 11868 11869 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11870 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11871 + "\": is the default dialer"); 11872 return false; 11873 } 11874 11875 return true; 11876 } 11877 11878 private String getActiveLauncherPackageName(int userId) { 11879 Intent intent = new Intent(Intent.ACTION_MAIN); 11880 intent.addCategory(Intent.CATEGORY_HOME); 11881 ResolveInfo resolveInfo = resolveIntent( 11882 intent, 11883 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11884 PackageManager.MATCH_DEFAULT_ONLY, 11885 userId); 11886 11887 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11888 } 11889 11890 private String getDefaultDialerPackageName(int userId) { 11891 synchronized (mPackages) { 11892 return mSettings.getDefaultDialerPackageNameLPw(userId); 11893 } 11894 } 11895 11896 @Override 11897 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11898 mContext.enforceCallingOrSelfPermission( 11899 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11900 "Only package verification agents can verify applications"); 11901 11902 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11903 final PackageVerificationResponse response = new PackageVerificationResponse( 11904 verificationCode, Binder.getCallingUid()); 11905 msg.arg1 = id; 11906 msg.obj = response; 11907 mHandler.sendMessage(msg); 11908 } 11909 11910 @Override 11911 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11912 long millisecondsToDelay) { 11913 mContext.enforceCallingOrSelfPermission( 11914 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11915 "Only package verification agents can extend verification timeouts"); 11916 11917 final PackageVerificationState state = mPendingVerification.get(id); 11918 final PackageVerificationResponse response = new PackageVerificationResponse( 11919 verificationCodeAtTimeout, Binder.getCallingUid()); 11920 11921 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11922 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11923 } 11924 if (millisecondsToDelay < 0) { 11925 millisecondsToDelay = 0; 11926 } 11927 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11928 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11929 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11930 } 11931 11932 if ((state != null) && !state.timeoutExtended()) { 11933 state.extendTimeout(); 11934 11935 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11936 msg.arg1 = id; 11937 msg.obj = response; 11938 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11939 } 11940 } 11941 11942 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11943 int verificationCode, UserHandle user) { 11944 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11945 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11946 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11947 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11948 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11949 11950 mContext.sendBroadcastAsUser(intent, user, 11951 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11952 } 11953 11954 private ComponentName matchComponentForVerifier(String packageName, 11955 List<ResolveInfo> receivers) { 11956 ActivityInfo targetReceiver = null; 11957 11958 final int NR = receivers.size(); 11959 for (int i = 0; i < NR; i++) { 11960 final ResolveInfo info = receivers.get(i); 11961 if (info.activityInfo == null) { 11962 continue; 11963 } 11964 11965 if (packageName.equals(info.activityInfo.packageName)) { 11966 targetReceiver = info.activityInfo; 11967 break; 11968 } 11969 } 11970 11971 if (targetReceiver == null) { 11972 return null; 11973 } 11974 11975 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11976 } 11977 11978 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11979 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11980 if (pkgInfo.verifiers.length == 0) { 11981 return null; 11982 } 11983 11984 final int N = pkgInfo.verifiers.length; 11985 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11986 for (int i = 0; i < N; i++) { 11987 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11988 11989 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11990 receivers); 11991 if (comp == null) { 11992 continue; 11993 } 11994 11995 final int verifierUid = getUidForVerifier(verifierInfo); 11996 if (verifierUid == -1) { 11997 continue; 11998 } 11999 12000 if (DEBUG_VERIFY) { 12001 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12002 + " with the correct signature"); 12003 } 12004 sufficientVerifiers.add(comp); 12005 verificationState.addSufficientVerifier(verifierUid); 12006 } 12007 12008 return sufficientVerifiers; 12009 } 12010 12011 private int getUidForVerifier(VerifierInfo verifierInfo) { 12012 synchronized (mPackages) { 12013 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12014 if (pkg == null) { 12015 return -1; 12016 } else if (pkg.mSignatures.length != 1) { 12017 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12018 + " has more than one signature; ignoring"); 12019 return -1; 12020 } 12021 12022 /* 12023 * If the public key of the package's signature does not match 12024 * our expected public key, then this is a different package and 12025 * we should skip. 12026 */ 12027 12028 final byte[] expectedPublicKey; 12029 try { 12030 final Signature verifierSig = pkg.mSignatures[0]; 12031 final PublicKey publicKey = verifierSig.getPublicKey(); 12032 expectedPublicKey = publicKey.getEncoded(); 12033 } catch (CertificateException e) { 12034 return -1; 12035 } 12036 12037 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12038 12039 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12040 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12041 + " does not have the expected public key; ignoring"); 12042 return -1; 12043 } 12044 12045 return pkg.applicationInfo.uid; 12046 } 12047 } 12048 12049 @Override 12050 public void finishPackageInstall(int token, boolean didLaunch) { 12051 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12052 12053 if (DEBUG_INSTALL) { 12054 Slog.v(TAG, "BM finishing package install for " + token); 12055 } 12056 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12057 12058 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12059 mHandler.sendMessage(msg); 12060 } 12061 12062 /** 12063 * Get the verification agent timeout. 12064 * 12065 * @return verification timeout in milliseconds 12066 */ 12067 private long getVerificationTimeout() { 12068 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12069 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12070 DEFAULT_VERIFICATION_TIMEOUT); 12071 } 12072 12073 /** 12074 * Get the default verification agent response code. 12075 * 12076 * @return default verification response code 12077 */ 12078 private int getDefaultVerificationResponse() { 12079 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12080 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12081 DEFAULT_VERIFICATION_RESPONSE); 12082 } 12083 12084 /** 12085 * Check whether or not package verification has been enabled. 12086 * 12087 * @return true if verification should be performed 12088 */ 12089 private boolean isVerificationEnabled(int userId, int installFlags) { 12090 if (!DEFAULT_VERIFY_ENABLE) { 12091 return false; 12092 } 12093 // Ephemeral apps don't get the full verification treatment 12094 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12095 if (DEBUG_EPHEMERAL) { 12096 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12097 } 12098 return false; 12099 } 12100 12101 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12102 12103 // Check if installing from ADB 12104 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12105 // Do not run verification in a test harness environment 12106 if (ActivityManager.isRunningInTestHarness()) { 12107 return false; 12108 } 12109 if (ensureVerifyAppsEnabled) { 12110 return true; 12111 } 12112 // Check if the developer does not want package verification for ADB installs 12113 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12114 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12115 return false; 12116 } 12117 } 12118 12119 if (ensureVerifyAppsEnabled) { 12120 return true; 12121 } 12122 12123 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12124 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12125 } 12126 12127 @Override 12128 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12129 throws RemoteException { 12130 mContext.enforceCallingOrSelfPermission( 12131 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12132 "Only intentfilter verification agents can verify applications"); 12133 12134 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12135 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12136 Binder.getCallingUid(), verificationCode, failedDomains); 12137 msg.arg1 = id; 12138 msg.obj = response; 12139 mHandler.sendMessage(msg); 12140 } 12141 12142 @Override 12143 public int getIntentVerificationStatus(String packageName, int userId) { 12144 synchronized (mPackages) { 12145 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12146 } 12147 } 12148 12149 @Override 12150 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12151 mContext.enforceCallingOrSelfPermission( 12152 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12153 12154 boolean result = false; 12155 synchronized (mPackages) { 12156 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12157 } 12158 if (result) { 12159 scheduleWritePackageRestrictionsLocked(userId); 12160 } 12161 return result; 12162 } 12163 12164 @Override 12165 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12166 String packageName) { 12167 synchronized (mPackages) { 12168 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12169 } 12170 } 12171 12172 @Override 12173 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12174 if (TextUtils.isEmpty(packageName)) { 12175 return ParceledListSlice.emptyList(); 12176 } 12177 synchronized (mPackages) { 12178 PackageParser.Package pkg = mPackages.get(packageName); 12179 if (pkg == null || pkg.activities == null) { 12180 return ParceledListSlice.emptyList(); 12181 } 12182 final int count = pkg.activities.size(); 12183 ArrayList<IntentFilter> result = new ArrayList<>(); 12184 for (int n=0; n<count; n++) { 12185 PackageParser.Activity activity = pkg.activities.get(n); 12186 if (activity.intents != null && activity.intents.size() > 0) { 12187 result.addAll(activity.intents); 12188 } 12189 } 12190 return new ParceledListSlice<>(result); 12191 } 12192 } 12193 12194 @Override 12195 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12196 mContext.enforceCallingOrSelfPermission( 12197 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12198 12199 synchronized (mPackages) { 12200 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12201 if (packageName != null) { 12202 result |= updateIntentVerificationStatus(packageName, 12203 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12204 userId); 12205 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12206 packageName, userId); 12207 } 12208 return result; 12209 } 12210 } 12211 12212 @Override 12213 public String getDefaultBrowserPackageName(int userId) { 12214 synchronized (mPackages) { 12215 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12216 } 12217 } 12218 12219 /** 12220 * Get the "allow unknown sources" setting. 12221 * 12222 * @return the current "allow unknown sources" setting 12223 */ 12224 private int getUnknownSourcesSettings() { 12225 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12226 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12227 -1); 12228 } 12229 12230 @Override 12231 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12232 final int uid = Binder.getCallingUid(); 12233 // writer 12234 synchronized (mPackages) { 12235 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12236 if (targetPackageSetting == null) { 12237 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12238 } 12239 12240 PackageSetting installerPackageSetting; 12241 if (installerPackageName != null) { 12242 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12243 if (installerPackageSetting == null) { 12244 throw new IllegalArgumentException("Unknown installer package: " 12245 + installerPackageName); 12246 } 12247 } else { 12248 installerPackageSetting = null; 12249 } 12250 12251 Signature[] callerSignature; 12252 Object obj = mSettings.getUserIdLPr(uid); 12253 if (obj != null) { 12254 if (obj instanceof SharedUserSetting) { 12255 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12256 } else if (obj instanceof PackageSetting) { 12257 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12258 } else { 12259 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12260 } 12261 } else { 12262 throw new SecurityException("Unknown calling UID: " + uid); 12263 } 12264 12265 // Verify: can't set installerPackageName to a package that is 12266 // not signed with the same cert as the caller. 12267 if (installerPackageSetting != null) { 12268 if (compareSignatures(callerSignature, 12269 installerPackageSetting.signatures.mSignatures) 12270 != PackageManager.SIGNATURE_MATCH) { 12271 throw new SecurityException( 12272 "Caller does not have same cert as new installer package " 12273 + installerPackageName); 12274 } 12275 } 12276 12277 // Verify: if target already has an installer package, it must 12278 // be signed with the same cert as the caller. 12279 if (targetPackageSetting.installerPackageName != null) { 12280 PackageSetting setting = mSettings.mPackages.get( 12281 targetPackageSetting.installerPackageName); 12282 // If the currently set package isn't valid, then it's always 12283 // okay to change it. 12284 if (setting != null) { 12285 if (compareSignatures(callerSignature, 12286 setting.signatures.mSignatures) 12287 != PackageManager.SIGNATURE_MATCH) { 12288 throw new SecurityException( 12289 "Caller does not have same cert as old installer package " 12290 + targetPackageSetting.installerPackageName); 12291 } 12292 } 12293 } 12294 12295 // Okay! 12296 targetPackageSetting.installerPackageName = installerPackageName; 12297 if (installerPackageName != null) { 12298 mSettings.mInstallerPackages.add(installerPackageName); 12299 } 12300 scheduleWriteSettingsLocked(); 12301 } 12302 } 12303 12304 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12305 // Queue up an async operation since the package installation may take a little while. 12306 mHandler.post(new Runnable() { 12307 public void run() { 12308 mHandler.removeCallbacks(this); 12309 // Result object to be returned 12310 PackageInstalledInfo res = new PackageInstalledInfo(); 12311 res.setReturnCode(currentStatus); 12312 res.uid = -1; 12313 res.pkg = null; 12314 res.removedInfo = null; 12315 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12316 args.doPreInstall(res.returnCode); 12317 synchronized (mInstallLock) { 12318 installPackageTracedLI(args, res); 12319 } 12320 args.doPostInstall(res.returnCode, res.uid); 12321 } 12322 12323 // A restore should be performed at this point if (a) the install 12324 // succeeded, (b) the operation is not an update, and (c) the new 12325 // package has not opted out of backup participation. 12326 final boolean update = res.removedInfo != null 12327 && res.removedInfo.removedPackage != null; 12328 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12329 boolean doRestore = !update 12330 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12331 12332 // Set up the post-install work request bookkeeping. This will be used 12333 // and cleaned up by the post-install event handling regardless of whether 12334 // there's a restore pass performed. Token values are >= 1. 12335 int token; 12336 if (mNextInstallToken < 0) mNextInstallToken = 1; 12337 token = mNextInstallToken++; 12338 12339 PostInstallData data = new PostInstallData(args, res); 12340 mRunningInstalls.put(token, data); 12341 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12342 12343 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12344 // Pass responsibility to the Backup Manager. It will perform a 12345 // restore if appropriate, then pass responsibility back to the 12346 // Package Manager to run the post-install observer callbacks 12347 // and broadcasts. 12348 IBackupManager bm = IBackupManager.Stub.asInterface( 12349 ServiceManager.getService(Context.BACKUP_SERVICE)); 12350 if (bm != null) { 12351 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12352 + " to BM for possible restore"); 12353 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12354 try { 12355 // TODO: http://b/22388012 12356 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12357 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12358 } else { 12359 doRestore = false; 12360 } 12361 } catch (RemoteException e) { 12362 // can't happen; the backup manager is local 12363 } catch (Exception e) { 12364 Slog.e(TAG, "Exception trying to enqueue restore", e); 12365 doRestore = false; 12366 } 12367 } else { 12368 Slog.e(TAG, "Backup Manager not found!"); 12369 doRestore = false; 12370 } 12371 } 12372 12373 if (!doRestore) { 12374 // No restore possible, or the Backup Manager was mysteriously not 12375 // available -- just fire the post-install work request directly. 12376 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12377 12378 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12379 12380 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12381 mHandler.sendMessage(msg); 12382 } 12383 } 12384 }); 12385 } 12386 12387 /** 12388 * Callback from PackageSettings whenever an app is first transitioned out of the 12389 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12390 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12391 * here whether the app is the target of an ongoing install, and only send the 12392 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12393 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12394 * handling. 12395 */ 12396 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12397 // Serialize this with the rest of the install-process message chain. In the 12398 // restore-at-install case, this Runnable will necessarily run before the 12399 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12400 // are coherent. In the non-restore case, the app has already completed install 12401 // and been launched through some other means, so it is not in a problematic 12402 // state for observers to see the FIRST_LAUNCH signal. 12403 mHandler.post(new Runnable() { 12404 @Override 12405 public void run() { 12406 for (int i = 0; i < mRunningInstalls.size(); i++) { 12407 final PostInstallData data = mRunningInstalls.valueAt(i); 12408 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12409 // right package; but is it for the right user? 12410 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12411 if (userId == data.res.newUsers[uIndex]) { 12412 if (DEBUG_BACKUP) { 12413 Slog.i(TAG, "Package " + pkgName 12414 + " being restored so deferring FIRST_LAUNCH"); 12415 } 12416 return; 12417 } 12418 } 12419 } 12420 } 12421 // didn't find it, so not being restored 12422 if (DEBUG_BACKUP) { 12423 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12424 } 12425 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12426 } 12427 }); 12428 } 12429 12430 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12431 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12432 installerPkg, null, userIds); 12433 } 12434 12435 private abstract class HandlerParams { 12436 private static final int MAX_RETRIES = 4; 12437 12438 /** 12439 * Number of times startCopy() has been attempted and had a non-fatal 12440 * error. 12441 */ 12442 private int mRetries = 0; 12443 12444 /** User handle for the user requesting the information or installation. */ 12445 private final UserHandle mUser; 12446 String traceMethod; 12447 int traceCookie; 12448 12449 HandlerParams(UserHandle user) { 12450 mUser = user; 12451 } 12452 12453 UserHandle getUser() { 12454 return mUser; 12455 } 12456 12457 HandlerParams setTraceMethod(String traceMethod) { 12458 this.traceMethod = traceMethod; 12459 return this; 12460 } 12461 12462 HandlerParams setTraceCookie(int traceCookie) { 12463 this.traceCookie = traceCookie; 12464 return this; 12465 } 12466 12467 final boolean startCopy() { 12468 boolean res; 12469 try { 12470 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12471 12472 if (++mRetries > MAX_RETRIES) { 12473 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12474 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12475 handleServiceError(); 12476 return false; 12477 } else { 12478 handleStartCopy(); 12479 res = true; 12480 } 12481 } catch (RemoteException e) { 12482 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12483 mHandler.sendEmptyMessage(MCS_RECONNECT); 12484 res = false; 12485 } 12486 handleReturnCode(); 12487 return res; 12488 } 12489 12490 final void serviceError() { 12491 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12492 handleServiceError(); 12493 handleReturnCode(); 12494 } 12495 12496 abstract void handleStartCopy() throws RemoteException; 12497 abstract void handleServiceError(); 12498 abstract void handleReturnCode(); 12499 } 12500 12501 class MeasureParams extends HandlerParams { 12502 private final PackageStats mStats; 12503 private boolean mSuccess; 12504 12505 private final IPackageStatsObserver mObserver; 12506 12507 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12508 super(new UserHandle(stats.userHandle)); 12509 mObserver = observer; 12510 mStats = stats; 12511 } 12512 12513 @Override 12514 public String toString() { 12515 return "MeasureParams{" 12516 + Integer.toHexString(System.identityHashCode(this)) 12517 + " " + mStats.packageName + "}"; 12518 } 12519 12520 @Override 12521 void handleStartCopy() throws RemoteException { 12522 synchronized (mInstallLock) { 12523 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12524 } 12525 12526 if (mSuccess) { 12527 final boolean mounted; 12528 if (Environment.isExternalStorageEmulated()) { 12529 mounted = true; 12530 } else { 12531 final String status = Environment.getExternalStorageState(); 12532 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12533 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12534 } 12535 12536 if (mounted) { 12537 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12538 12539 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12540 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12541 12542 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12543 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12544 12545 // Always subtract cache size, since it's a subdirectory 12546 mStats.externalDataSize -= mStats.externalCacheSize; 12547 12548 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12549 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12550 12551 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12552 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12553 } 12554 } 12555 } 12556 12557 @Override 12558 void handleReturnCode() { 12559 if (mObserver != null) { 12560 try { 12561 mObserver.onGetStatsCompleted(mStats, mSuccess); 12562 } catch (RemoteException e) { 12563 Slog.i(TAG, "Observer no longer exists."); 12564 } 12565 } 12566 } 12567 12568 @Override 12569 void handleServiceError() { 12570 Slog.e(TAG, "Could not measure application " + mStats.packageName 12571 + " external storage"); 12572 } 12573 } 12574 12575 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12576 throws RemoteException { 12577 long result = 0; 12578 for (File path : paths) { 12579 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12580 } 12581 return result; 12582 } 12583 12584 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12585 for (File path : paths) { 12586 try { 12587 mcs.clearDirectory(path.getAbsolutePath()); 12588 } catch (RemoteException e) { 12589 } 12590 } 12591 } 12592 12593 static class OriginInfo { 12594 /** 12595 * Location where install is coming from, before it has been 12596 * copied/renamed into place. This could be a single monolithic APK 12597 * file, or a cluster directory. This location may be untrusted. 12598 */ 12599 final File file; 12600 final String cid; 12601 12602 /** 12603 * Flag indicating that {@link #file} or {@link #cid} has already been 12604 * staged, meaning downstream users don't need to defensively copy the 12605 * contents. 12606 */ 12607 final boolean staged; 12608 12609 /** 12610 * Flag indicating that {@link #file} or {@link #cid} is an already 12611 * installed app that is being moved. 12612 */ 12613 final boolean existing; 12614 12615 final String resolvedPath; 12616 final File resolvedFile; 12617 12618 static OriginInfo fromNothing() { 12619 return new OriginInfo(null, null, false, false); 12620 } 12621 12622 static OriginInfo fromUntrustedFile(File file) { 12623 return new OriginInfo(file, null, false, false); 12624 } 12625 12626 static OriginInfo fromExistingFile(File file) { 12627 return new OriginInfo(file, null, false, true); 12628 } 12629 12630 static OriginInfo fromStagedFile(File file) { 12631 return new OriginInfo(file, null, true, false); 12632 } 12633 12634 static OriginInfo fromStagedContainer(String cid) { 12635 return new OriginInfo(null, cid, true, false); 12636 } 12637 12638 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12639 this.file = file; 12640 this.cid = cid; 12641 this.staged = staged; 12642 this.existing = existing; 12643 12644 if (cid != null) { 12645 resolvedPath = PackageHelper.getSdDir(cid); 12646 resolvedFile = new File(resolvedPath); 12647 } else if (file != null) { 12648 resolvedPath = file.getAbsolutePath(); 12649 resolvedFile = file; 12650 } else { 12651 resolvedPath = null; 12652 resolvedFile = null; 12653 } 12654 } 12655 } 12656 12657 static class MoveInfo { 12658 final int moveId; 12659 final String fromUuid; 12660 final String toUuid; 12661 final String packageName; 12662 final String dataAppName; 12663 final int appId; 12664 final String seinfo; 12665 final int targetSdkVersion; 12666 12667 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12668 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12669 this.moveId = moveId; 12670 this.fromUuid = fromUuid; 12671 this.toUuid = toUuid; 12672 this.packageName = packageName; 12673 this.dataAppName = dataAppName; 12674 this.appId = appId; 12675 this.seinfo = seinfo; 12676 this.targetSdkVersion = targetSdkVersion; 12677 } 12678 } 12679 12680 static class VerificationInfo { 12681 /** A constant used to indicate that a uid value is not present. */ 12682 public static final int NO_UID = -1; 12683 12684 /** URI referencing where the package was downloaded from. */ 12685 final Uri originatingUri; 12686 12687 /** HTTP referrer URI associated with the originatingURI. */ 12688 final Uri referrer; 12689 12690 /** UID of the application that the install request originated from. */ 12691 final int originatingUid; 12692 12693 /** UID of application requesting the install */ 12694 final int installerUid; 12695 12696 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12697 this.originatingUri = originatingUri; 12698 this.referrer = referrer; 12699 this.originatingUid = originatingUid; 12700 this.installerUid = installerUid; 12701 } 12702 } 12703 12704 class InstallParams extends HandlerParams { 12705 final OriginInfo origin; 12706 final MoveInfo move; 12707 final IPackageInstallObserver2 observer; 12708 int installFlags; 12709 final String installerPackageName; 12710 final String volumeUuid; 12711 private InstallArgs mArgs; 12712 private int mRet; 12713 final String packageAbiOverride; 12714 final String[] grantedRuntimePermissions; 12715 final VerificationInfo verificationInfo; 12716 final Certificate[][] certificates; 12717 12718 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12719 int installFlags, String installerPackageName, String volumeUuid, 12720 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12721 String[] grantedPermissions, Certificate[][] certificates) { 12722 super(user); 12723 this.origin = origin; 12724 this.move = move; 12725 this.observer = observer; 12726 this.installFlags = installFlags; 12727 this.installerPackageName = installerPackageName; 12728 this.volumeUuid = volumeUuid; 12729 this.verificationInfo = verificationInfo; 12730 this.packageAbiOverride = packageAbiOverride; 12731 this.grantedRuntimePermissions = grantedPermissions; 12732 this.certificates = certificates; 12733 } 12734 12735 @Override 12736 public String toString() { 12737 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12738 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12739 } 12740 12741 private int installLocationPolicy(PackageInfoLite pkgLite) { 12742 String packageName = pkgLite.packageName; 12743 int installLocation = pkgLite.installLocation; 12744 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12745 // reader 12746 synchronized (mPackages) { 12747 // Currently installed package which the new package is attempting to replace or 12748 // null if no such package is installed. 12749 PackageParser.Package installedPkg = mPackages.get(packageName); 12750 // Package which currently owns the data which the new package will own if installed. 12751 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12752 // will be null whereas dataOwnerPkg will contain information about the package 12753 // which was uninstalled while keeping its data. 12754 PackageParser.Package dataOwnerPkg = installedPkg; 12755 if (dataOwnerPkg == null) { 12756 PackageSetting ps = mSettings.mPackages.get(packageName); 12757 if (ps != null) { 12758 dataOwnerPkg = ps.pkg; 12759 } 12760 } 12761 12762 if (dataOwnerPkg != null) { 12763 // If installed, the package will get access to data left on the device by its 12764 // predecessor. As a security measure, this is permited only if this is not a 12765 // version downgrade or if the predecessor package is marked as debuggable and 12766 // a downgrade is explicitly requested. 12767 // 12768 // On debuggable platform builds, downgrades are permitted even for 12769 // non-debuggable packages to make testing easier. Debuggable platform builds do 12770 // not offer security guarantees and thus it's OK to disable some security 12771 // mechanisms to make debugging/testing easier on those builds. However, even on 12772 // debuggable builds downgrades of packages are permitted only if requested via 12773 // installFlags. This is because we aim to keep the behavior of debuggable 12774 // platform builds as close as possible to the behavior of non-debuggable 12775 // platform builds. 12776 final boolean downgradeRequested = 12777 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12778 final boolean packageDebuggable = 12779 (dataOwnerPkg.applicationInfo.flags 12780 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12781 final boolean downgradePermitted = 12782 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12783 if (!downgradePermitted) { 12784 try { 12785 checkDowngrade(dataOwnerPkg, pkgLite); 12786 } catch (PackageManagerException e) { 12787 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12788 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12789 } 12790 } 12791 } 12792 12793 if (installedPkg != null) { 12794 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12795 // Check for updated system application. 12796 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12797 if (onSd) { 12798 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12799 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12800 } 12801 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12802 } else { 12803 if (onSd) { 12804 // Install flag overrides everything. 12805 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12806 } 12807 // If current upgrade specifies particular preference 12808 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12809 // Application explicitly specified internal. 12810 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12811 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12812 // App explictly prefers external. Let policy decide 12813 } else { 12814 // Prefer previous location 12815 if (isExternal(installedPkg)) { 12816 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12817 } 12818 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12819 } 12820 } 12821 } else { 12822 // Invalid install. Return error code 12823 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12824 } 12825 } 12826 } 12827 // All the special cases have been taken care of. 12828 // Return result based on recommended install location. 12829 if (onSd) { 12830 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12831 } 12832 return pkgLite.recommendedInstallLocation; 12833 } 12834 12835 /* 12836 * Invoke remote method to get package information and install 12837 * location values. Override install location based on default 12838 * policy if needed and then create install arguments based 12839 * on the install location. 12840 */ 12841 public void handleStartCopy() throws RemoteException { 12842 int ret = PackageManager.INSTALL_SUCCEEDED; 12843 12844 // If we're already staged, we've firmly committed to an install location 12845 if (origin.staged) { 12846 if (origin.file != null) { 12847 installFlags |= PackageManager.INSTALL_INTERNAL; 12848 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12849 } else if (origin.cid != null) { 12850 installFlags |= PackageManager.INSTALL_EXTERNAL; 12851 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12852 } else { 12853 throw new IllegalStateException("Invalid stage location"); 12854 } 12855 } 12856 12857 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12858 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12859 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12860 PackageInfoLite pkgLite = null; 12861 12862 if (onInt && onSd) { 12863 // Check if both bits are set. 12864 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12865 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12866 } else if (onSd && ephemeral) { 12867 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12868 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12869 } else { 12870 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12871 packageAbiOverride); 12872 12873 if (DEBUG_EPHEMERAL && ephemeral) { 12874 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12875 } 12876 12877 /* 12878 * If we have too little free space, try to free cache 12879 * before giving up. 12880 */ 12881 if (!origin.staged && pkgLite.recommendedInstallLocation 12882 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12883 // TODO: focus freeing disk space on the target device 12884 final StorageManager storage = StorageManager.from(mContext); 12885 final long lowThreshold = storage.getStorageLowBytes( 12886 Environment.getDataDirectory()); 12887 12888 final long sizeBytes = mContainerService.calculateInstalledSize( 12889 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12890 12891 try { 12892 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12893 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12894 installFlags, packageAbiOverride); 12895 } catch (InstallerException e) { 12896 Slog.w(TAG, "Failed to free cache", e); 12897 } 12898 12899 /* 12900 * The cache free must have deleted the file we 12901 * downloaded to install. 12902 * 12903 * TODO: fix the "freeCache" call to not delete 12904 * the file we care about. 12905 */ 12906 if (pkgLite.recommendedInstallLocation 12907 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12908 pkgLite.recommendedInstallLocation 12909 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12910 } 12911 } 12912 } 12913 12914 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12915 int loc = pkgLite.recommendedInstallLocation; 12916 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12917 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12918 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12919 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12920 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12921 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12922 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12923 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12924 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12925 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12926 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12927 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12928 } else { 12929 // Override with defaults if needed. 12930 loc = installLocationPolicy(pkgLite); 12931 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12932 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12933 } else if (!onSd && !onInt) { 12934 // Override install location with flags 12935 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12936 // Set the flag to install on external media. 12937 installFlags |= PackageManager.INSTALL_EXTERNAL; 12938 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12939 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12940 if (DEBUG_EPHEMERAL) { 12941 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12942 } 12943 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12944 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12945 |PackageManager.INSTALL_INTERNAL); 12946 } else { 12947 // Make sure the flag for installing on external 12948 // media is unset 12949 installFlags |= PackageManager.INSTALL_INTERNAL; 12950 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12951 } 12952 } 12953 } 12954 } 12955 12956 final InstallArgs args = createInstallArgs(this); 12957 mArgs = args; 12958 12959 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12960 // TODO: http://b/22976637 12961 // Apps installed for "all" users use the device owner to verify the app 12962 UserHandle verifierUser = getUser(); 12963 if (verifierUser == UserHandle.ALL) { 12964 verifierUser = UserHandle.SYSTEM; 12965 } 12966 12967 /* 12968 * Determine if we have any installed package verifiers. If we 12969 * do, then we'll defer to them to verify the packages. 12970 */ 12971 final int requiredUid = mRequiredVerifierPackage == null ? -1 12972 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12973 verifierUser.getIdentifier()); 12974 if (!origin.existing && requiredUid != -1 12975 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12976 final Intent verification = new Intent( 12977 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12978 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12979 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12980 PACKAGE_MIME_TYPE); 12981 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12982 12983 // Query all live verifiers based on current user state 12984 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12985 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12986 12987 if (DEBUG_VERIFY) { 12988 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12989 + verification.toString() + " with " + pkgLite.verifiers.length 12990 + " optional verifiers"); 12991 } 12992 12993 final int verificationId = mPendingVerificationToken++; 12994 12995 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12996 12997 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12998 installerPackageName); 12999 13000 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13001 installFlags); 13002 13003 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13004 pkgLite.packageName); 13005 13006 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13007 pkgLite.versionCode); 13008 13009 if (verificationInfo != null) { 13010 if (verificationInfo.originatingUri != null) { 13011 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13012 verificationInfo.originatingUri); 13013 } 13014 if (verificationInfo.referrer != null) { 13015 verification.putExtra(Intent.EXTRA_REFERRER, 13016 verificationInfo.referrer); 13017 } 13018 if (verificationInfo.originatingUid >= 0) { 13019 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13020 verificationInfo.originatingUid); 13021 } 13022 if (verificationInfo.installerUid >= 0) { 13023 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13024 verificationInfo.installerUid); 13025 } 13026 } 13027 13028 final PackageVerificationState verificationState = new PackageVerificationState( 13029 requiredUid, args); 13030 13031 mPendingVerification.append(verificationId, verificationState); 13032 13033 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13034 receivers, verificationState); 13035 13036 /* 13037 * If any sufficient verifiers were listed in the package 13038 * manifest, attempt to ask them. 13039 */ 13040 if (sufficientVerifiers != null) { 13041 final int N = sufficientVerifiers.size(); 13042 if (N == 0) { 13043 Slog.i(TAG, "Additional verifiers required, but none installed."); 13044 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13045 } else { 13046 for (int i = 0; i < N; i++) { 13047 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13048 13049 final Intent sufficientIntent = new Intent(verification); 13050 sufficientIntent.setComponent(verifierComponent); 13051 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13052 } 13053 } 13054 } 13055 13056 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13057 mRequiredVerifierPackage, receivers); 13058 if (ret == PackageManager.INSTALL_SUCCEEDED 13059 && mRequiredVerifierPackage != null) { 13060 Trace.asyncTraceBegin( 13061 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13062 /* 13063 * Send the intent to the required verification agent, 13064 * but only start the verification timeout after the 13065 * target BroadcastReceivers have run. 13066 */ 13067 verification.setComponent(requiredVerifierComponent); 13068 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13069 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13070 new BroadcastReceiver() { 13071 @Override 13072 public void onReceive(Context context, Intent intent) { 13073 final Message msg = mHandler 13074 .obtainMessage(CHECK_PENDING_VERIFICATION); 13075 msg.arg1 = verificationId; 13076 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13077 } 13078 }, null, 0, null, null); 13079 13080 /* 13081 * We don't want the copy to proceed until verification 13082 * succeeds, so null out this field. 13083 */ 13084 mArgs = null; 13085 } 13086 } else { 13087 /* 13088 * No package verification is enabled, so immediately start 13089 * the remote call to initiate copy using temporary file. 13090 */ 13091 ret = args.copyApk(mContainerService, true); 13092 } 13093 } 13094 13095 mRet = ret; 13096 } 13097 13098 @Override 13099 void handleReturnCode() { 13100 // If mArgs is null, then MCS couldn't be reached. When it 13101 // reconnects, it will try again to install. At that point, this 13102 // will succeed. 13103 if (mArgs != null) { 13104 processPendingInstall(mArgs, mRet); 13105 } 13106 } 13107 13108 @Override 13109 void handleServiceError() { 13110 mArgs = createInstallArgs(this); 13111 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13112 } 13113 13114 public boolean isForwardLocked() { 13115 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13116 } 13117 } 13118 13119 /** 13120 * Used during creation of InstallArgs 13121 * 13122 * @param installFlags package installation flags 13123 * @return true if should be installed on external storage 13124 */ 13125 private static boolean installOnExternalAsec(int installFlags) { 13126 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13127 return false; 13128 } 13129 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13130 return true; 13131 } 13132 return false; 13133 } 13134 13135 /** 13136 * Used during creation of InstallArgs 13137 * 13138 * @param installFlags package installation flags 13139 * @return true if should be installed as forward locked 13140 */ 13141 private static boolean installForwardLocked(int installFlags) { 13142 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13143 } 13144 13145 private InstallArgs createInstallArgs(InstallParams params) { 13146 if (params.move != null) { 13147 return new MoveInstallArgs(params); 13148 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13149 return new AsecInstallArgs(params); 13150 } else { 13151 return new FileInstallArgs(params); 13152 } 13153 } 13154 13155 /** 13156 * Create args that describe an existing installed package. Typically used 13157 * when cleaning up old installs, or used as a move source. 13158 */ 13159 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13160 String resourcePath, String[] instructionSets) { 13161 final boolean isInAsec; 13162 if (installOnExternalAsec(installFlags)) { 13163 /* Apps on SD card are always in ASEC containers. */ 13164 isInAsec = true; 13165 } else if (installForwardLocked(installFlags) 13166 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13167 /* 13168 * Forward-locked apps are only in ASEC containers if they're the 13169 * new style 13170 */ 13171 isInAsec = true; 13172 } else { 13173 isInAsec = false; 13174 } 13175 13176 if (isInAsec) { 13177 return new AsecInstallArgs(codePath, instructionSets, 13178 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13179 } else { 13180 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13181 } 13182 } 13183 13184 static abstract class InstallArgs { 13185 /** @see InstallParams#origin */ 13186 final OriginInfo origin; 13187 /** @see InstallParams#move */ 13188 final MoveInfo move; 13189 13190 final IPackageInstallObserver2 observer; 13191 // Always refers to PackageManager flags only 13192 final int installFlags; 13193 final String installerPackageName; 13194 final String volumeUuid; 13195 final UserHandle user; 13196 final String abiOverride; 13197 final String[] installGrantPermissions; 13198 /** If non-null, drop an async trace when the install completes */ 13199 final String traceMethod; 13200 final int traceCookie; 13201 final Certificate[][] certificates; 13202 13203 // The list of instruction sets supported by this app. This is currently 13204 // only used during the rmdex() phase to clean up resources. We can get rid of this 13205 // if we move dex files under the common app path. 13206 /* nullable */ String[] instructionSets; 13207 13208 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13209 int installFlags, String installerPackageName, String volumeUuid, 13210 UserHandle user, String[] instructionSets, 13211 String abiOverride, String[] installGrantPermissions, 13212 String traceMethod, int traceCookie, Certificate[][] certificates) { 13213 this.origin = origin; 13214 this.move = move; 13215 this.installFlags = installFlags; 13216 this.observer = observer; 13217 this.installerPackageName = installerPackageName; 13218 this.volumeUuid = volumeUuid; 13219 this.user = user; 13220 this.instructionSets = instructionSets; 13221 this.abiOverride = abiOverride; 13222 this.installGrantPermissions = installGrantPermissions; 13223 this.traceMethod = traceMethod; 13224 this.traceCookie = traceCookie; 13225 this.certificates = certificates; 13226 } 13227 13228 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13229 abstract int doPreInstall(int status); 13230 13231 /** 13232 * Rename package into final resting place. All paths on the given 13233 * scanned package should be updated to reflect the rename. 13234 */ 13235 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13236 abstract int doPostInstall(int status, int uid); 13237 13238 /** @see PackageSettingBase#codePathString */ 13239 abstract String getCodePath(); 13240 /** @see PackageSettingBase#resourcePathString */ 13241 abstract String getResourcePath(); 13242 13243 // Need installer lock especially for dex file removal. 13244 abstract void cleanUpResourcesLI(); 13245 abstract boolean doPostDeleteLI(boolean delete); 13246 13247 /** 13248 * Called before the source arguments are copied. This is used mostly 13249 * for MoveParams when it needs to read the source file to put it in the 13250 * destination. 13251 */ 13252 int doPreCopy() { 13253 return PackageManager.INSTALL_SUCCEEDED; 13254 } 13255 13256 /** 13257 * Called after the source arguments are copied. This is used mostly for 13258 * MoveParams when it needs to read the source file to put it in the 13259 * destination. 13260 */ 13261 int doPostCopy(int uid) { 13262 return PackageManager.INSTALL_SUCCEEDED; 13263 } 13264 13265 protected boolean isFwdLocked() { 13266 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13267 } 13268 13269 protected boolean isExternalAsec() { 13270 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13271 } 13272 13273 protected boolean isEphemeral() { 13274 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13275 } 13276 13277 UserHandle getUser() { 13278 return user; 13279 } 13280 } 13281 13282 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13283 if (!allCodePaths.isEmpty()) { 13284 if (instructionSets == null) { 13285 throw new IllegalStateException("instructionSet == null"); 13286 } 13287 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13288 for (String codePath : allCodePaths) { 13289 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13290 try { 13291 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13292 } catch (InstallerException ignored) { 13293 } 13294 } 13295 } 13296 } 13297 } 13298 13299 /** 13300 * Logic to handle installation of non-ASEC applications, including copying 13301 * and renaming logic. 13302 */ 13303 class FileInstallArgs extends InstallArgs { 13304 private File codeFile; 13305 private File resourceFile; 13306 13307 // Example topology: 13308 // /data/app/com.example/base.apk 13309 // /data/app/com.example/split_foo.apk 13310 // /data/app/com.example/lib/arm/libfoo.so 13311 // /data/app/com.example/lib/arm64/libfoo.so 13312 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13313 13314 /** New install */ 13315 FileInstallArgs(InstallParams params) { 13316 super(params.origin, params.move, params.observer, params.installFlags, 13317 params.installerPackageName, params.volumeUuid, 13318 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13319 params.grantedRuntimePermissions, 13320 params.traceMethod, params.traceCookie, params.certificates); 13321 if (isFwdLocked()) { 13322 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13323 } 13324 } 13325 13326 /** Existing install */ 13327 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13328 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13329 null, null, null, 0, null /*certificates*/); 13330 this.codeFile = (codePath != null) ? new File(codePath) : null; 13331 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13332 } 13333 13334 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13336 try { 13337 return doCopyApk(imcs, temp); 13338 } finally { 13339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13340 } 13341 } 13342 13343 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13344 if (origin.staged) { 13345 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13346 codeFile = origin.file; 13347 resourceFile = origin.file; 13348 return PackageManager.INSTALL_SUCCEEDED; 13349 } 13350 13351 try { 13352 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13353 final File tempDir = 13354 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13355 codeFile = tempDir; 13356 resourceFile = tempDir; 13357 } catch (IOException e) { 13358 Slog.w(TAG, "Failed to create copy file: " + e); 13359 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13360 } 13361 13362 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13363 @Override 13364 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13365 if (!FileUtils.isValidExtFilename(name)) { 13366 throw new IllegalArgumentException("Invalid filename: " + name); 13367 } 13368 try { 13369 final File file = new File(codeFile, name); 13370 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13371 O_RDWR | O_CREAT, 0644); 13372 Os.chmod(file.getAbsolutePath(), 0644); 13373 return new ParcelFileDescriptor(fd); 13374 } catch (ErrnoException e) { 13375 throw new RemoteException("Failed to open: " + e.getMessage()); 13376 } 13377 } 13378 }; 13379 13380 int ret = PackageManager.INSTALL_SUCCEEDED; 13381 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13382 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13383 Slog.e(TAG, "Failed to copy package"); 13384 return ret; 13385 } 13386 13387 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13388 NativeLibraryHelper.Handle handle = null; 13389 try { 13390 handle = NativeLibraryHelper.Handle.create(codeFile); 13391 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13392 abiOverride); 13393 } catch (IOException e) { 13394 Slog.e(TAG, "Copying native libraries failed", e); 13395 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13396 } finally { 13397 IoUtils.closeQuietly(handle); 13398 } 13399 13400 return ret; 13401 } 13402 13403 int doPreInstall(int status) { 13404 if (status != PackageManager.INSTALL_SUCCEEDED) { 13405 cleanUp(); 13406 } 13407 return status; 13408 } 13409 13410 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13411 if (status != PackageManager.INSTALL_SUCCEEDED) { 13412 cleanUp(); 13413 return false; 13414 } 13415 13416 final File targetDir = codeFile.getParentFile(); 13417 final File beforeCodeFile = codeFile; 13418 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13419 13420 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13421 try { 13422 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13423 } catch (ErrnoException e) { 13424 Slog.w(TAG, "Failed to rename", e); 13425 return false; 13426 } 13427 13428 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13429 Slog.w(TAG, "Failed to restorecon"); 13430 return false; 13431 } 13432 13433 // Reflect the rename internally 13434 codeFile = afterCodeFile; 13435 resourceFile = afterCodeFile; 13436 13437 // Reflect the rename in scanned details 13438 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13439 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13440 afterCodeFile, pkg.baseCodePath)); 13441 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13442 afterCodeFile, pkg.splitCodePaths)); 13443 13444 // Reflect the rename in app info 13445 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13446 pkg.setApplicationInfoCodePath(pkg.codePath); 13447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13449 pkg.setApplicationInfoResourcePath(pkg.codePath); 13450 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13452 13453 return true; 13454 } 13455 13456 int doPostInstall(int status, int uid) { 13457 if (status != PackageManager.INSTALL_SUCCEEDED) { 13458 cleanUp(); 13459 } 13460 return status; 13461 } 13462 13463 @Override 13464 String getCodePath() { 13465 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13466 } 13467 13468 @Override 13469 String getResourcePath() { 13470 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13471 } 13472 13473 private boolean cleanUp() { 13474 if (codeFile == null || !codeFile.exists()) { 13475 return false; 13476 } 13477 13478 removeCodePathLI(codeFile); 13479 13480 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13481 resourceFile.delete(); 13482 } 13483 13484 return true; 13485 } 13486 13487 void cleanUpResourcesLI() { 13488 // Try enumerating all code paths before deleting 13489 List<String> allCodePaths = Collections.EMPTY_LIST; 13490 if (codeFile != null && codeFile.exists()) { 13491 try { 13492 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13493 allCodePaths = pkg.getAllCodePaths(); 13494 } catch (PackageParserException e) { 13495 // Ignored; we tried our best 13496 } 13497 } 13498 13499 cleanUp(); 13500 removeDexFiles(allCodePaths, instructionSets); 13501 } 13502 13503 boolean doPostDeleteLI(boolean delete) { 13504 // XXX err, shouldn't we respect the delete flag? 13505 cleanUpResourcesLI(); 13506 return true; 13507 } 13508 } 13509 13510 private boolean isAsecExternal(String cid) { 13511 final String asecPath = PackageHelper.getSdFilesystem(cid); 13512 return !asecPath.startsWith(mAsecInternalPath); 13513 } 13514 13515 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13516 PackageManagerException { 13517 if (copyRet < 0) { 13518 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13519 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13520 throw new PackageManagerException(copyRet, message); 13521 } 13522 } 13523 } 13524 13525 /** 13526 * Extract the MountService "container ID" from the full code path of an 13527 * .apk. 13528 */ 13529 static String cidFromCodePath(String fullCodePath) { 13530 int eidx = fullCodePath.lastIndexOf("/"); 13531 String subStr1 = fullCodePath.substring(0, eidx); 13532 int sidx = subStr1.lastIndexOf("/"); 13533 return subStr1.substring(sidx+1, eidx); 13534 } 13535 13536 /** 13537 * Logic to handle installation of ASEC applications, including copying and 13538 * renaming logic. 13539 */ 13540 class AsecInstallArgs extends InstallArgs { 13541 static final String RES_FILE_NAME = "pkg.apk"; 13542 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13543 13544 String cid; 13545 String packagePath; 13546 String resourcePath; 13547 13548 /** New install */ 13549 AsecInstallArgs(InstallParams params) { 13550 super(params.origin, params.move, params.observer, params.installFlags, 13551 params.installerPackageName, params.volumeUuid, 13552 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13553 params.grantedRuntimePermissions, 13554 params.traceMethod, params.traceCookie, params.certificates); 13555 } 13556 13557 /** Existing install */ 13558 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13559 boolean isExternal, boolean isForwardLocked) { 13560 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13561 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13562 instructionSets, null, null, null, 0, null /*certificates*/); 13563 // Hackily pretend we're still looking at a full code path 13564 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13565 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13566 } 13567 13568 // Extract cid from fullCodePath 13569 int eidx = fullCodePath.lastIndexOf("/"); 13570 String subStr1 = fullCodePath.substring(0, eidx); 13571 int sidx = subStr1.lastIndexOf("/"); 13572 cid = subStr1.substring(sidx+1, eidx); 13573 setMountPath(subStr1); 13574 } 13575 13576 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13577 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13578 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13579 instructionSets, null, null, null, 0, null /*certificates*/); 13580 this.cid = cid; 13581 setMountPath(PackageHelper.getSdDir(cid)); 13582 } 13583 13584 void createCopyFile() { 13585 cid = mInstallerService.allocateExternalStageCidLegacy(); 13586 } 13587 13588 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13589 if (origin.staged && origin.cid != null) { 13590 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13591 cid = origin.cid; 13592 setMountPath(PackageHelper.getSdDir(cid)); 13593 return PackageManager.INSTALL_SUCCEEDED; 13594 } 13595 13596 if (temp) { 13597 createCopyFile(); 13598 } else { 13599 /* 13600 * Pre-emptively destroy the container since it's destroyed if 13601 * copying fails due to it existing anyway. 13602 */ 13603 PackageHelper.destroySdDir(cid); 13604 } 13605 13606 final String newMountPath = imcs.copyPackageToContainer( 13607 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13608 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13609 13610 if (newMountPath != null) { 13611 setMountPath(newMountPath); 13612 return PackageManager.INSTALL_SUCCEEDED; 13613 } else { 13614 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13615 } 13616 } 13617 13618 @Override 13619 String getCodePath() { 13620 return packagePath; 13621 } 13622 13623 @Override 13624 String getResourcePath() { 13625 return resourcePath; 13626 } 13627 13628 int doPreInstall(int status) { 13629 if (status != PackageManager.INSTALL_SUCCEEDED) { 13630 // Destroy container 13631 PackageHelper.destroySdDir(cid); 13632 } else { 13633 boolean mounted = PackageHelper.isContainerMounted(cid); 13634 if (!mounted) { 13635 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13636 Process.SYSTEM_UID); 13637 if (newMountPath != null) { 13638 setMountPath(newMountPath); 13639 } else { 13640 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13641 } 13642 } 13643 } 13644 return status; 13645 } 13646 13647 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13648 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13649 String newMountPath = null; 13650 if (PackageHelper.isContainerMounted(cid)) { 13651 // Unmount the container 13652 if (!PackageHelper.unMountSdDir(cid)) { 13653 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13654 return false; 13655 } 13656 } 13657 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13658 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13659 " which might be stale. Will try to clean up."); 13660 // Clean up the stale container and proceed to recreate. 13661 if (!PackageHelper.destroySdDir(newCacheId)) { 13662 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13663 return false; 13664 } 13665 // Successfully cleaned up stale container. Try to rename again. 13666 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13667 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13668 + " inspite of cleaning it up."); 13669 return false; 13670 } 13671 } 13672 if (!PackageHelper.isContainerMounted(newCacheId)) { 13673 Slog.w(TAG, "Mounting container " + newCacheId); 13674 newMountPath = PackageHelper.mountSdDir(newCacheId, 13675 getEncryptKey(), Process.SYSTEM_UID); 13676 } else { 13677 newMountPath = PackageHelper.getSdDir(newCacheId); 13678 } 13679 if (newMountPath == null) { 13680 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13681 return false; 13682 } 13683 Log.i(TAG, "Succesfully renamed " + cid + 13684 " to " + newCacheId + 13685 " at new path: " + newMountPath); 13686 cid = newCacheId; 13687 13688 final File beforeCodeFile = new File(packagePath); 13689 setMountPath(newMountPath); 13690 final File afterCodeFile = new File(packagePath); 13691 13692 // Reflect the rename in scanned details 13693 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13694 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13695 afterCodeFile, pkg.baseCodePath)); 13696 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13697 afterCodeFile, pkg.splitCodePaths)); 13698 13699 // Reflect the rename in app info 13700 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13701 pkg.setApplicationInfoCodePath(pkg.codePath); 13702 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13703 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13704 pkg.setApplicationInfoResourcePath(pkg.codePath); 13705 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13706 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13707 13708 return true; 13709 } 13710 13711 private void setMountPath(String mountPath) { 13712 final File mountFile = new File(mountPath); 13713 13714 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13715 if (monolithicFile.exists()) { 13716 packagePath = monolithicFile.getAbsolutePath(); 13717 if (isFwdLocked()) { 13718 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13719 } else { 13720 resourcePath = packagePath; 13721 } 13722 } else { 13723 packagePath = mountFile.getAbsolutePath(); 13724 resourcePath = packagePath; 13725 } 13726 } 13727 13728 int doPostInstall(int status, int uid) { 13729 if (status != PackageManager.INSTALL_SUCCEEDED) { 13730 cleanUp(); 13731 } else { 13732 final int groupOwner; 13733 final String protectedFile; 13734 if (isFwdLocked()) { 13735 groupOwner = UserHandle.getSharedAppGid(uid); 13736 protectedFile = RES_FILE_NAME; 13737 } else { 13738 groupOwner = -1; 13739 protectedFile = null; 13740 } 13741 13742 if (uid < Process.FIRST_APPLICATION_UID 13743 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13744 Slog.e(TAG, "Failed to finalize " + cid); 13745 PackageHelper.destroySdDir(cid); 13746 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13747 } 13748 13749 boolean mounted = PackageHelper.isContainerMounted(cid); 13750 if (!mounted) { 13751 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13752 } 13753 } 13754 return status; 13755 } 13756 13757 private void cleanUp() { 13758 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13759 13760 // Destroy secure container 13761 PackageHelper.destroySdDir(cid); 13762 } 13763 13764 private List<String> getAllCodePaths() { 13765 final File codeFile = new File(getCodePath()); 13766 if (codeFile != null && codeFile.exists()) { 13767 try { 13768 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13769 return pkg.getAllCodePaths(); 13770 } catch (PackageParserException e) { 13771 // Ignored; we tried our best 13772 } 13773 } 13774 return Collections.EMPTY_LIST; 13775 } 13776 13777 void cleanUpResourcesLI() { 13778 // Enumerate all code paths before deleting 13779 cleanUpResourcesLI(getAllCodePaths()); 13780 } 13781 13782 private void cleanUpResourcesLI(List<String> allCodePaths) { 13783 cleanUp(); 13784 removeDexFiles(allCodePaths, instructionSets); 13785 } 13786 13787 String getPackageName() { 13788 return getAsecPackageName(cid); 13789 } 13790 13791 boolean doPostDeleteLI(boolean delete) { 13792 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13793 final List<String> allCodePaths = getAllCodePaths(); 13794 boolean mounted = PackageHelper.isContainerMounted(cid); 13795 if (mounted) { 13796 // Unmount first 13797 if (PackageHelper.unMountSdDir(cid)) { 13798 mounted = false; 13799 } 13800 } 13801 if (!mounted && delete) { 13802 cleanUpResourcesLI(allCodePaths); 13803 } 13804 return !mounted; 13805 } 13806 13807 @Override 13808 int doPreCopy() { 13809 if (isFwdLocked()) { 13810 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13811 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13812 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13813 } 13814 } 13815 13816 return PackageManager.INSTALL_SUCCEEDED; 13817 } 13818 13819 @Override 13820 int doPostCopy(int uid) { 13821 if (isFwdLocked()) { 13822 if (uid < Process.FIRST_APPLICATION_UID 13823 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13824 RES_FILE_NAME)) { 13825 Slog.e(TAG, "Failed to finalize " + cid); 13826 PackageHelper.destroySdDir(cid); 13827 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13828 } 13829 } 13830 13831 return PackageManager.INSTALL_SUCCEEDED; 13832 } 13833 } 13834 13835 /** 13836 * Logic to handle movement of existing installed applications. 13837 */ 13838 class MoveInstallArgs extends InstallArgs { 13839 private File codeFile; 13840 private File resourceFile; 13841 13842 /** New install */ 13843 MoveInstallArgs(InstallParams params) { 13844 super(params.origin, params.move, params.observer, params.installFlags, 13845 params.installerPackageName, params.volumeUuid, 13846 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13847 params.grantedRuntimePermissions, 13848 params.traceMethod, params.traceCookie, params.certificates); 13849 } 13850 13851 int copyApk(IMediaContainerService imcs, boolean temp) { 13852 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13853 + move.fromUuid + " to " + move.toUuid); 13854 synchronized (mInstaller) { 13855 try { 13856 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13857 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13858 } catch (InstallerException e) { 13859 Slog.w(TAG, "Failed to move app", e); 13860 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13861 } 13862 } 13863 13864 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13865 resourceFile = codeFile; 13866 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13867 13868 return PackageManager.INSTALL_SUCCEEDED; 13869 } 13870 13871 int doPreInstall(int status) { 13872 if (status != PackageManager.INSTALL_SUCCEEDED) { 13873 cleanUp(move.toUuid); 13874 } 13875 return status; 13876 } 13877 13878 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13879 if (status != PackageManager.INSTALL_SUCCEEDED) { 13880 cleanUp(move.toUuid); 13881 return false; 13882 } 13883 13884 // Reflect the move in app info 13885 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13886 pkg.setApplicationInfoCodePath(pkg.codePath); 13887 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13888 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13889 pkg.setApplicationInfoResourcePath(pkg.codePath); 13890 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13891 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13892 13893 return true; 13894 } 13895 13896 int doPostInstall(int status, int uid) { 13897 if (status == PackageManager.INSTALL_SUCCEEDED) { 13898 cleanUp(move.fromUuid); 13899 } else { 13900 cleanUp(move.toUuid); 13901 } 13902 return status; 13903 } 13904 13905 @Override 13906 String getCodePath() { 13907 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13908 } 13909 13910 @Override 13911 String getResourcePath() { 13912 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13913 } 13914 13915 private boolean cleanUp(String volumeUuid) { 13916 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13917 move.dataAppName); 13918 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13919 final int[] userIds = sUserManager.getUserIds(); 13920 synchronized (mInstallLock) { 13921 // Clean up both app data and code 13922 // All package moves are frozen until finished 13923 for (int userId : userIds) { 13924 try { 13925 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13926 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13927 } catch (InstallerException e) { 13928 Slog.w(TAG, String.valueOf(e)); 13929 } 13930 } 13931 removeCodePathLI(codeFile); 13932 } 13933 return true; 13934 } 13935 13936 void cleanUpResourcesLI() { 13937 throw new UnsupportedOperationException(); 13938 } 13939 13940 boolean doPostDeleteLI(boolean delete) { 13941 throw new UnsupportedOperationException(); 13942 } 13943 } 13944 13945 static String getAsecPackageName(String packageCid) { 13946 int idx = packageCid.lastIndexOf("-"); 13947 if (idx == -1) { 13948 return packageCid; 13949 } 13950 return packageCid.substring(0, idx); 13951 } 13952 13953 // Utility method used to create code paths based on package name and available index. 13954 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13955 String idxStr = ""; 13956 int idx = 1; 13957 // Fall back to default value of idx=1 if prefix is not 13958 // part of oldCodePath 13959 if (oldCodePath != null) { 13960 String subStr = oldCodePath; 13961 // Drop the suffix right away 13962 if (suffix != null && subStr.endsWith(suffix)) { 13963 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13964 } 13965 // If oldCodePath already contains prefix find out the 13966 // ending index to either increment or decrement. 13967 int sidx = subStr.lastIndexOf(prefix); 13968 if (sidx != -1) { 13969 subStr = subStr.substring(sidx + prefix.length()); 13970 if (subStr != null) { 13971 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13972 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13973 } 13974 try { 13975 idx = Integer.parseInt(subStr); 13976 if (idx <= 1) { 13977 idx++; 13978 } else { 13979 idx--; 13980 } 13981 } catch(NumberFormatException e) { 13982 } 13983 } 13984 } 13985 } 13986 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13987 return prefix + idxStr; 13988 } 13989 13990 private File getNextCodePath(File targetDir, String packageName) { 13991 int suffix = 1; 13992 File result; 13993 do { 13994 result = new File(targetDir, packageName + "-" + suffix); 13995 suffix++; 13996 } while (result.exists()); 13997 return result; 13998 } 13999 14000 // Utility method that returns the relative package path with respect 14001 // to the installation directory. Like say for /data/data/com.test-1.apk 14002 // string com.test-1 is returned. 14003 static String deriveCodePathName(String codePath) { 14004 if (codePath == null) { 14005 return null; 14006 } 14007 final File codeFile = new File(codePath); 14008 final String name = codeFile.getName(); 14009 if (codeFile.isDirectory()) { 14010 return name; 14011 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14012 final int lastDot = name.lastIndexOf('.'); 14013 return name.substring(0, lastDot); 14014 } else { 14015 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14016 return null; 14017 } 14018 } 14019 14020 static class PackageInstalledInfo { 14021 String name; 14022 int uid; 14023 // The set of users that originally had this package installed. 14024 int[] origUsers; 14025 // The set of users that now have this package installed. 14026 int[] newUsers; 14027 PackageParser.Package pkg; 14028 int returnCode; 14029 String returnMsg; 14030 PackageRemovedInfo removedInfo; 14031 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14032 14033 public void setError(int code, String msg) { 14034 setReturnCode(code); 14035 setReturnMessage(msg); 14036 Slog.w(TAG, msg); 14037 } 14038 14039 public void setError(String msg, PackageParserException e) { 14040 setReturnCode(e.error); 14041 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14042 Slog.w(TAG, msg, e); 14043 } 14044 14045 public void setError(String msg, PackageManagerException e) { 14046 returnCode = e.error; 14047 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14048 Slog.w(TAG, msg, e); 14049 } 14050 14051 public void setReturnCode(int returnCode) { 14052 this.returnCode = returnCode; 14053 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14054 for (int i = 0; i < childCount; i++) { 14055 addedChildPackages.valueAt(i).returnCode = returnCode; 14056 } 14057 } 14058 14059 private void setReturnMessage(String returnMsg) { 14060 this.returnMsg = returnMsg; 14061 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14062 for (int i = 0; i < childCount; i++) { 14063 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14064 } 14065 } 14066 14067 // In some error cases we want to convey more info back to the observer 14068 String origPackage; 14069 String origPermission; 14070 } 14071 14072 /* 14073 * Install a non-existing package. 14074 */ 14075 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14076 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14077 PackageInstalledInfo res) { 14078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14079 14080 // Remember this for later, in case we need to rollback this install 14081 String pkgName = pkg.packageName; 14082 14083 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14084 14085 synchronized(mPackages) { 14086 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14087 // A package with the same name is already installed, though 14088 // it has been renamed to an older name. The package we 14089 // are trying to install should be installed as an update to 14090 // the existing one, but that has not been requested, so bail. 14091 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14092 + " without first uninstalling package running as " 14093 + mSettings.mRenamedPackages.get(pkgName)); 14094 return; 14095 } 14096 if (mPackages.containsKey(pkgName)) { 14097 // Don't allow installation over an existing package with the same name. 14098 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14099 + " without first uninstalling."); 14100 return; 14101 } 14102 } 14103 14104 try { 14105 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14106 System.currentTimeMillis(), user); 14107 14108 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14109 14110 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14111 prepareAppDataAfterInstallLIF(newPackage); 14112 14113 } else { 14114 // Remove package from internal structures, but keep around any 14115 // data that might have already existed 14116 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14117 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14118 } 14119 } catch (PackageManagerException e) { 14120 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14121 } 14122 14123 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14124 } 14125 14126 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14127 // Can't rotate keys during boot or if sharedUser. 14128 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14129 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14130 return false; 14131 } 14132 // app is using upgradeKeySets; make sure all are valid 14133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14134 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14135 for (int i = 0; i < upgradeKeySets.length; i++) { 14136 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14137 Slog.wtf(TAG, "Package " 14138 + (oldPs.name != null ? oldPs.name : "<null>") 14139 + " contains upgrade-key-set reference to unknown key-set: " 14140 + upgradeKeySets[i] 14141 + " reverting to signatures check."); 14142 return false; 14143 } 14144 } 14145 return true; 14146 } 14147 14148 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14149 // Upgrade keysets are being used. Determine if new package has a superset of the 14150 // required keys. 14151 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14152 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14153 for (int i = 0; i < upgradeKeySets.length; i++) { 14154 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14155 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14156 return true; 14157 } 14158 } 14159 return false; 14160 } 14161 14162 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14163 try (DigestInputStream digestStream = 14164 new DigestInputStream(new FileInputStream(file), digest)) { 14165 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14166 } 14167 } 14168 14169 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14170 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14171 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14172 14173 final PackageParser.Package oldPackage; 14174 final String pkgName = pkg.packageName; 14175 final int[] allUsers; 14176 final int[] installedUsers; 14177 14178 synchronized(mPackages) { 14179 oldPackage = mPackages.get(pkgName); 14180 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14181 14182 // don't allow upgrade to target a release SDK from a pre-release SDK 14183 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14184 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14185 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14186 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14187 if (oldTargetsPreRelease 14188 && !newTargetsPreRelease 14189 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14190 Slog.w(TAG, "Can't install package targeting released sdk"); 14191 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14192 return; 14193 } 14194 14195 // don't allow an upgrade from full to ephemeral 14196 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14197 if (isEphemeral && !oldIsEphemeral) { 14198 // can't downgrade from full to ephemeral 14199 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14200 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14201 return; 14202 } 14203 14204 // verify signatures are valid 14205 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14206 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14207 if (!checkUpgradeKeySetLP(ps, pkg)) { 14208 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14209 "New package not signed by keys specified by upgrade-keysets: " 14210 + pkgName); 14211 return; 14212 } 14213 } else { 14214 // default to original signature matching 14215 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14216 != PackageManager.SIGNATURE_MATCH) { 14217 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14218 "New package has a different signature: " + pkgName); 14219 return; 14220 } 14221 } 14222 14223 // don't allow a system upgrade unless the upgrade hash matches 14224 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14225 byte[] digestBytes = null; 14226 try { 14227 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14228 updateDigest(digest, new File(pkg.baseCodePath)); 14229 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14230 for (String path : pkg.splitCodePaths) { 14231 updateDigest(digest, new File(path)); 14232 } 14233 } 14234 digestBytes = digest.digest(); 14235 } catch (NoSuchAlgorithmException | IOException e) { 14236 res.setError(INSTALL_FAILED_INVALID_APK, 14237 "Could not compute hash: " + pkgName); 14238 return; 14239 } 14240 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14241 res.setError(INSTALL_FAILED_INVALID_APK, 14242 "New package fails restrict-update check: " + pkgName); 14243 return; 14244 } 14245 // retain upgrade restriction 14246 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14247 } 14248 14249 // Check for shared user id changes 14250 String invalidPackageName = 14251 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14252 if (invalidPackageName != null) { 14253 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14254 "Package " + invalidPackageName + " tried to change user " 14255 + oldPackage.mSharedUserId); 14256 return; 14257 } 14258 14259 // In case of rollback, remember per-user/profile install state 14260 allUsers = sUserManager.getUserIds(); 14261 installedUsers = ps.queryInstalledUsers(allUsers, true); 14262 } 14263 14264 // Update what is removed 14265 res.removedInfo = new PackageRemovedInfo(); 14266 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14267 res.removedInfo.removedPackage = oldPackage.packageName; 14268 res.removedInfo.isUpdate = true; 14269 res.removedInfo.origUsers = installedUsers; 14270 final int childCount = (oldPackage.childPackages != null) 14271 ? oldPackage.childPackages.size() : 0; 14272 for (int i = 0; i < childCount; i++) { 14273 boolean childPackageUpdated = false; 14274 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14275 if (res.addedChildPackages != null) { 14276 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14277 if (childRes != null) { 14278 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14279 childRes.removedInfo.removedPackage = childPkg.packageName; 14280 childRes.removedInfo.isUpdate = true; 14281 childPackageUpdated = true; 14282 } 14283 } 14284 if (!childPackageUpdated) { 14285 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14286 childRemovedRes.removedPackage = childPkg.packageName; 14287 childRemovedRes.isUpdate = false; 14288 childRemovedRes.dataRemoved = true; 14289 synchronized (mPackages) { 14290 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14291 if (childPs != null) { 14292 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14293 } 14294 } 14295 if (res.removedInfo.removedChildPackages == null) { 14296 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14297 } 14298 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14299 } 14300 } 14301 14302 boolean sysPkg = (isSystemApp(oldPackage)); 14303 if (sysPkg) { 14304 // Set the system/privileged flags as needed 14305 final boolean privileged = 14306 (oldPackage.applicationInfo.privateFlags 14307 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14308 final int systemPolicyFlags = policyFlags 14309 | PackageParser.PARSE_IS_SYSTEM 14310 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14311 14312 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14313 user, allUsers, installerPackageName, res); 14314 } else { 14315 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14316 user, allUsers, installerPackageName, res); 14317 } 14318 } 14319 14320 public List<String> getPreviousCodePaths(String packageName) { 14321 final PackageSetting ps = mSettings.mPackages.get(packageName); 14322 final List<String> result = new ArrayList<String>(); 14323 if (ps != null && ps.oldCodePaths != null) { 14324 result.addAll(ps.oldCodePaths); 14325 } 14326 return result; 14327 } 14328 14329 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14330 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14331 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14332 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14333 + deletedPackage); 14334 14335 String pkgName = deletedPackage.packageName; 14336 boolean deletedPkg = true; 14337 boolean addedPkg = false; 14338 boolean updatedSettings = false; 14339 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14340 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14341 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14342 14343 final long origUpdateTime = (pkg.mExtras != null) 14344 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14345 14346 // First delete the existing package while retaining the data directory 14347 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14348 res.removedInfo, true, pkg)) { 14349 // If the existing package wasn't successfully deleted 14350 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14351 deletedPkg = false; 14352 } else { 14353 // Successfully deleted the old package; proceed with replace. 14354 14355 // If deleted package lived in a container, give users a chance to 14356 // relinquish resources before killing. 14357 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14358 if (DEBUG_INSTALL) { 14359 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14360 } 14361 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14362 final ArrayList<String> pkgList = new ArrayList<String>(1); 14363 pkgList.add(deletedPackage.applicationInfo.packageName); 14364 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14365 } 14366 14367 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14368 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14369 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14370 14371 try { 14372 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14373 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14374 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14375 14376 // Update the in-memory copy of the previous code paths. 14377 PackageSetting ps = mSettings.mPackages.get(pkgName); 14378 if (!killApp) { 14379 if (ps.oldCodePaths == null) { 14380 ps.oldCodePaths = new ArraySet<>(); 14381 } 14382 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14383 if (deletedPackage.splitCodePaths != null) { 14384 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14385 } 14386 } else { 14387 ps.oldCodePaths = null; 14388 } 14389 if (ps.childPackageNames != null) { 14390 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14391 final String childPkgName = ps.childPackageNames.get(i); 14392 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14393 childPs.oldCodePaths = ps.oldCodePaths; 14394 } 14395 } 14396 prepareAppDataAfterInstallLIF(newPackage); 14397 addedPkg = true; 14398 } catch (PackageManagerException e) { 14399 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14400 } 14401 } 14402 14403 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14404 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14405 14406 // Revert all internal state mutations and added folders for the failed install 14407 if (addedPkg) { 14408 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14409 res.removedInfo, true, null); 14410 } 14411 14412 // Restore the old package 14413 if (deletedPkg) { 14414 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14415 File restoreFile = new File(deletedPackage.codePath); 14416 // Parse old package 14417 boolean oldExternal = isExternal(deletedPackage); 14418 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14419 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14420 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14421 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14422 try { 14423 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14424 null); 14425 } catch (PackageManagerException e) { 14426 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14427 + e.getMessage()); 14428 return; 14429 } 14430 14431 synchronized (mPackages) { 14432 // Ensure the installer package name up to date 14433 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14434 14435 // Update permissions for restored package 14436 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14437 14438 mSettings.writeLPr(); 14439 } 14440 14441 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14442 } 14443 } else { 14444 synchronized (mPackages) { 14445 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14446 if (ps != null) { 14447 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14448 if (res.removedInfo.removedChildPackages != null) { 14449 final int childCount = res.removedInfo.removedChildPackages.size(); 14450 // Iterate in reverse as we may modify the collection 14451 for (int i = childCount - 1; i >= 0; i--) { 14452 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14453 if (res.addedChildPackages.containsKey(childPackageName)) { 14454 res.removedInfo.removedChildPackages.removeAt(i); 14455 } else { 14456 PackageRemovedInfo childInfo = res.removedInfo 14457 .removedChildPackages.valueAt(i); 14458 childInfo.removedForAllUsers = mPackages.get( 14459 childInfo.removedPackage) == null; 14460 } 14461 } 14462 } 14463 } 14464 } 14465 } 14466 } 14467 14468 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14469 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14470 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14471 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14472 + ", old=" + deletedPackage); 14473 14474 final boolean disabledSystem; 14475 14476 // Remove existing system package 14477 removePackageLI(deletedPackage, true); 14478 14479 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14480 if (!disabledSystem) { 14481 // We didn't need to disable the .apk as a current system package, 14482 // which means we are replacing another update that is already 14483 // installed. We need to make sure to delete the older one's .apk. 14484 res.removedInfo.args = createInstallArgsForExisting(0, 14485 deletedPackage.applicationInfo.getCodePath(), 14486 deletedPackage.applicationInfo.getResourcePath(), 14487 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14488 } else { 14489 res.removedInfo.args = null; 14490 } 14491 14492 // Successfully disabled the old package. Now proceed with re-installation 14493 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14494 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14495 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14496 14497 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14498 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14499 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14500 14501 PackageParser.Package newPackage = null; 14502 try { 14503 // Add the package to the internal data structures 14504 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14505 14506 // Set the update and install times 14507 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14508 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14509 System.currentTimeMillis()); 14510 14511 // Update the package dynamic state if succeeded 14512 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14513 // Now that the install succeeded make sure we remove data 14514 // directories for any child package the update removed. 14515 final int deletedChildCount = (deletedPackage.childPackages != null) 14516 ? deletedPackage.childPackages.size() : 0; 14517 final int newChildCount = (newPackage.childPackages != null) 14518 ? newPackage.childPackages.size() : 0; 14519 for (int i = 0; i < deletedChildCount; i++) { 14520 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14521 boolean childPackageDeleted = true; 14522 for (int j = 0; j < newChildCount; j++) { 14523 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14524 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14525 childPackageDeleted = false; 14526 break; 14527 } 14528 } 14529 if (childPackageDeleted) { 14530 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14531 deletedChildPkg.packageName); 14532 if (ps != null && res.removedInfo.removedChildPackages != null) { 14533 PackageRemovedInfo removedChildRes = res.removedInfo 14534 .removedChildPackages.get(deletedChildPkg.packageName); 14535 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14536 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14537 } 14538 } 14539 } 14540 14541 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14542 prepareAppDataAfterInstallLIF(newPackage); 14543 } 14544 } catch (PackageManagerException e) { 14545 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14546 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14547 } 14548 14549 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14550 // Re installation failed. Restore old information 14551 // Remove new pkg information 14552 if (newPackage != null) { 14553 removeInstalledPackageLI(newPackage, true); 14554 } 14555 // Add back the old system package 14556 try { 14557 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14558 } catch (PackageManagerException e) { 14559 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14560 } 14561 14562 synchronized (mPackages) { 14563 if (disabledSystem) { 14564 enableSystemPackageLPw(deletedPackage); 14565 } 14566 14567 // Ensure the installer package name up to date 14568 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14569 14570 // Update permissions for restored package 14571 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14572 14573 mSettings.writeLPr(); 14574 } 14575 14576 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14577 + " after failed upgrade"); 14578 } 14579 } 14580 14581 /** 14582 * Checks whether the parent or any of the child packages have a change shared 14583 * user. For a package to be a valid update the shred users of the parent and 14584 * the children should match. We may later support changing child shared users. 14585 * @param oldPkg The updated package. 14586 * @param newPkg The update package. 14587 * @return The shared user that change between the versions. 14588 */ 14589 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14590 PackageParser.Package newPkg) { 14591 // Check parent shared user 14592 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14593 return newPkg.packageName; 14594 } 14595 // Check child shared users 14596 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14597 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14598 for (int i = 0; i < newChildCount; i++) { 14599 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14600 // If this child was present, did it have the same shared user? 14601 for (int j = 0; j < oldChildCount; j++) { 14602 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14603 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14604 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14605 return newChildPkg.packageName; 14606 } 14607 } 14608 } 14609 return null; 14610 } 14611 14612 private void removeNativeBinariesLI(PackageSetting ps) { 14613 // Remove the lib path for the parent package 14614 if (ps != null) { 14615 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14616 // Remove the lib path for the child packages 14617 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14618 for (int i = 0; i < childCount; i++) { 14619 PackageSetting childPs = null; 14620 synchronized (mPackages) { 14621 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14622 } 14623 if (childPs != null) { 14624 NativeLibraryHelper.removeNativeBinariesLI(childPs 14625 .legacyNativeLibraryPathString); 14626 } 14627 } 14628 } 14629 } 14630 14631 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14632 // Enable the parent package 14633 mSettings.enableSystemPackageLPw(pkg.packageName); 14634 // Enable the child packages 14635 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14636 for (int i = 0; i < childCount; i++) { 14637 PackageParser.Package childPkg = pkg.childPackages.get(i); 14638 mSettings.enableSystemPackageLPw(childPkg.packageName); 14639 } 14640 } 14641 14642 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14643 PackageParser.Package newPkg) { 14644 // Disable the parent package (parent always replaced) 14645 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14646 // Disable the child packages 14647 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14648 for (int i = 0; i < childCount; i++) { 14649 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14650 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14651 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14652 } 14653 return disabled; 14654 } 14655 14656 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14657 String installerPackageName) { 14658 // Enable the parent package 14659 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14660 // Enable the child packages 14661 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14662 for (int i = 0; i < childCount; i++) { 14663 PackageParser.Package childPkg = pkg.childPackages.get(i); 14664 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14665 } 14666 } 14667 14668 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14669 // Collect all used permissions in the UID 14670 ArraySet<String> usedPermissions = new ArraySet<>(); 14671 final int packageCount = su.packages.size(); 14672 for (int i = 0; i < packageCount; i++) { 14673 PackageSetting ps = su.packages.valueAt(i); 14674 if (ps.pkg == null) { 14675 continue; 14676 } 14677 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14678 for (int j = 0; j < requestedPermCount; j++) { 14679 String permission = ps.pkg.requestedPermissions.get(j); 14680 BasePermission bp = mSettings.mPermissions.get(permission); 14681 if (bp != null) { 14682 usedPermissions.add(permission); 14683 } 14684 } 14685 } 14686 14687 PermissionsState permissionsState = su.getPermissionsState(); 14688 // Prune install permissions 14689 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14690 final int installPermCount = installPermStates.size(); 14691 for (int i = installPermCount - 1; i >= 0; i--) { 14692 PermissionState permissionState = installPermStates.get(i); 14693 if (!usedPermissions.contains(permissionState.getName())) { 14694 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14695 if (bp != null) { 14696 permissionsState.revokeInstallPermission(bp); 14697 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14698 PackageManager.MASK_PERMISSION_FLAGS, 0); 14699 } 14700 } 14701 } 14702 14703 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14704 14705 // Prune runtime permissions 14706 for (int userId : allUserIds) { 14707 List<PermissionState> runtimePermStates = permissionsState 14708 .getRuntimePermissionStates(userId); 14709 final int runtimePermCount = runtimePermStates.size(); 14710 for (int i = runtimePermCount - 1; i >= 0; i--) { 14711 PermissionState permissionState = runtimePermStates.get(i); 14712 if (!usedPermissions.contains(permissionState.getName())) { 14713 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14714 if (bp != null) { 14715 permissionsState.revokeRuntimePermission(bp, userId); 14716 permissionsState.updatePermissionFlags(bp, userId, 14717 PackageManager.MASK_PERMISSION_FLAGS, 0); 14718 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14719 runtimePermissionChangedUserIds, userId); 14720 } 14721 } 14722 } 14723 } 14724 14725 return runtimePermissionChangedUserIds; 14726 } 14727 14728 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14729 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14730 // Update the parent package setting 14731 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14732 res, user); 14733 // Update the child packages setting 14734 final int childCount = (newPackage.childPackages != null) 14735 ? newPackage.childPackages.size() : 0; 14736 for (int i = 0; i < childCount; i++) { 14737 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14738 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14739 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14740 childRes.origUsers, childRes, user); 14741 } 14742 } 14743 14744 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14745 String installerPackageName, int[] allUsers, int[] installedForUsers, 14746 PackageInstalledInfo res, UserHandle user) { 14747 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14748 14749 String pkgName = newPackage.packageName; 14750 synchronized (mPackages) { 14751 //write settings. the installStatus will be incomplete at this stage. 14752 //note that the new package setting would have already been 14753 //added to mPackages. It hasn't been persisted yet. 14754 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14755 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14756 mSettings.writeLPr(); 14757 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14758 } 14759 14760 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14761 synchronized (mPackages) { 14762 updatePermissionsLPw(newPackage.packageName, newPackage, 14763 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14764 ? UPDATE_PERMISSIONS_ALL : 0)); 14765 // For system-bundled packages, we assume that installing an upgraded version 14766 // of the package implies that the user actually wants to run that new code, 14767 // so we enable the package. 14768 PackageSetting ps = mSettings.mPackages.get(pkgName); 14769 final int userId = user.getIdentifier(); 14770 if (ps != null) { 14771 if (isSystemApp(newPackage)) { 14772 if (DEBUG_INSTALL) { 14773 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14774 } 14775 // Enable system package for requested users 14776 if (res.origUsers != null) { 14777 for (int origUserId : res.origUsers) { 14778 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14779 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14780 origUserId, installerPackageName); 14781 } 14782 } 14783 } 14784 // Also convey the prior install/uninstall state 14785 if (allUsers != null && installedForUsers != null) { 14786 for (int currentUserId : allUsers) { 14787 final boolean installed = ArrayUtils.contains( 14788 installedForUsers, currentUserId); 14789 if (DEBUG_INSTALL) { 14790 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14791 } 14792 ps.setInstalled(installed, currentUserId); 14793 } 14794 // these install state changes will be persisted in the 14795 // upcoming call to mSettings.writeLPr(). 14796 } 14797 } 14798 // It's implied that when a user requests installation, they want the app to be 14799 // installed and enabled. 14800 if (userId != UserHandle.USER_ALL) { 14801 ps.setInstalled(true, userId); 14802 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14803 } 14804 } 14805 res.name = pkgName; 14806 res.uid = newPackage.applicationInfo.uid; 14807 res.pkg = newPackage; 14808 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14809 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14810 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14811 //to update install status 14812 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14813 mSettings.writeLPr(); 14814 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14815 } 14816 14817 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14818 } 14819 14820 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14821 try { 14822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14823 installPackageLI(args, res); 14824 } finally { 14825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14826 } 14827 } 14828 14829 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14830 final int installFlags = args.installFlags; 14831 final String installerPackageName = args.installerPackageName; 14832 final String volumeUuid = args.volumeUuid; 14833 final File tmpPackageFile = new File(args.getCodePath()); 14834 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14835 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14836 || (args.volumeUuid != null)); 14837 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14838 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14839 boolean replace = false; 14840 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14841 if (args.move != null) { 14842 // moving a complete application; perform an initial scan on the new install location 14843 scanFlags |= SCAN_INITIAL; 14844 } 14845 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14846 scanFlags |= SCAN_DONT_KILL_APP; 14847 } 14848 14849 // Result object to be returned 14850 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14851 14852 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14853 14854 // Sanity check 14855 if (ephemeral && (forwardLocked || onExternal)) { 14856 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14857 + " external=" + onExternal); 14858 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14859 return; 14860 } 14861 14862 // Retrieve PackageSettings and parse package 14863 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14864 | PackageParser.PARSE_ENFORCE_CODE 14865 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14866 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14867 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14868 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14869 PackageParser pp = new PackageParser(); 14870 pp.setSeparateProcesses(mSeparateProcesses); 14871 pp.setDisplayMetrics(mMetrics); 14872 14873 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14874 final PackageParser.Package pkg; 14875 try { 14876 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14877 } catch (PackageParserException e) { 14878 res.setError("Failed parse during installPackageLI", e); 14879 return; 14880 } finally { 14881 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14882 } 14883 14884 // If we are installing a clustered package add results for the children 14885 if (pkg.childPackages != null) { 14886 synchronized (mPackages) { 14887 final int childCount = pkg.childPackages.size(); 14888 for (int i = 0; i < childCount; i++) { 14889 PackageParser.Package childPkg = pkg.childPackages.get(i); 14890 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14891 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14892 childRes.pkg = childPkg; 14893 childRes.name = childPkg.packageName; 14894 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14895 if (childPs != null) { 14896 childRes.origUsers = childPs.queryInstalledUsers( 14897 sUserManager.getUserIds(), true); 14898 } 14899 if ((mPackages.containsKey(childPkg.packageName))) { 14900 childRes.removedInfo = new PackageRemovedInfo(); 14901 childRes.removedInfo.removedPackage = childPkg.packageName; 14902 } 14903 if (res.addedChildPackages == null) { 14904 res.addedChildPackages = new ArrayMap<>(); 14905 } 14906 res.addedChildPackages.put(childPkg.packageName, childRes); 14907 } 14908 } 14909 } 14910 14911 // If package doesn't declare API override, mark that we have an install 14912 // time CPU ABI override. 14913 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14914 pkg.cpuAbiOverride = args.abiOverride; 14915 } 14916 14917 String pkgName = res.name = pkg.packageName; 14918 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14919 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14920 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14921 return; 14922 } 14923 } 14924 14925 try { 14926 // either use what we've been given or parse directly from the APK 14927 if (args.certificates != null) { 14928 try { 14929 PackageParser.populateCertificates(pkg, args.certificates); 14930 } catch (PackageParserException e) { 14931 // there was something wrong with the certificates we were given; 14932 // try to pull them from the APK 14933 PackageParser.collectCertificates(pkg, parseFlags); 14934 } 14935 } else { 14936 PackageParser.collectCertificates(pkg, parseFlags); 14937 } 14938 } catch (PackageParserException e) { 14939 res.setError("Failed collect during installPackageLI", e); 14940 return; 14941 } 14942 14943 // Get rid of all references to package scan path via parser. 14944 pp = null; 14945 String oldCodePath = null; 14946 boolean systemApp = false; 14947 synchronized (mPackages) { 14948 // Check if installing already existing package 14949 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14950 String oldName = mSettings.mRenamedPackages.get(pkgName); 14951 if (pkg.mOriginalPackages != null 14952 && pkg.mOriginalPackages.contains(oldName) 14953 && mPackages.containsKey(oldName)) { 14954 // This package is derived from an original package, 14955 // and this device has been updating from that original 14956 // name. We must continue using the original name, so 14957 // rename the new package here. 14958 pkg.setPackageName(oldName); 14959 pkgName = pkg.packageName; 14960 replace = true; 14961 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14962 + oldName + " pkgName=" + pkgName); 14963 } else if (mPackages.containsKey(pkgName)) { 14964 // This package, under its official name, already exists 14965 // on the device; we should replace it. 14966 replace = true; 14967 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14968 } 14969 14970 // Child packages are installed through the parent package 14971 if (pkg.parentPackage != null) { 14972 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14973 "Package " + pkg.packageName + " is child of package " 14974 + pkg.parentPackage.parentPackage + ". Child packages " 14975 + "can be updated only through the parent package."); 14976 return; 14977 } 14978 14979 if (replace) { 14980 // Prevent apps opting out from runtime permissions 14981 PackageParser.Package oldPackage = mPackages.get(pkgName); 14982 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14983 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14984 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14985 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14986 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14987 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14988 + " doesn't support runtime permissions but the old" 14989 + " target SDK " + oldTargetSdk + " does."); 14990 return; 14991 } 14992 14993 // Prevent installing of child packages 14994 if (oldPackage.parentPackage != null) { 14995 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14996 "Package " + pkg.packageName + " is child of package " 14997 + oldPackage.parentPackage + ". Child packages " 14998 + "can be updated only through the parent package."); 14999 return; 15000 } 15001 } 15002 } 15003 15004 PackageSetting ps = mSettings.mPackages.get(pkgName); 15005 if (ps != null) { 15006 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15007 15008 // Quick sanity check that we're signed correctly if updating; 15009 // we'll check this again later when scanning, but we want to 15010 // bail early here before tripping over redefined permissions. 15011 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15012 if (!checkUpgradeKeySetLP(ps, pkg)) { 15013 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15014 + pkg.packageName + " upgrade keys do not match the " 15015 + "previously installed version"); 15016 return; 15017 } 15018 } else { 15019 try { 15020 verifySignaturesLP(ps, pkg); 15021 } catch (PackageManagerException e) { 15022 res.setError(e.error, e.getMessage()); 15023 return; 15024 } 15025 } 15026 15027 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15028 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15029 systemApp = (ps.pkg.applicationInfo.flags & 15030 ApplicationInfo.FLAG_SYSTEM) != 0; 15031 } 15032 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15033 } 15034 15035 // Check whether the newly-scanned package wants to define an already-defined perm 15036 int N = pkg.permissions.size(); 15037 for (int i = N-1; i >= 0; i--) { 15038 PackageParser.Permission perm = pkg.permissions.get(i); 15039 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15040 if (bp != null) { 15041 // If the defining package is signed with our cert, it's okay. This 15042 // also includes the "updating the same package" case, of course. 15043 // "updating same package" could also involve key-rotation. 15044 final boolean sigsOk; 15045 if (bp.sourcePackage.equals(pkg.packageName) 15046 && (bp.packageSetting instanceof PackageSetting) 15047 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15048 scanFlags))) { 15049 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15050 } else { 15051 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15052 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15053 } 15054 if (!sigsOk) { 15055 // If the owning package is the system itself, we log but allow 15056 // install to proceed; we fail the install on all other permission 15057 // redefinitions. 15058 if (!bp.sourcePackage.equals("android")) { 15059 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15060 + pkg.packageName + " attempting to redeclare permission " 15061 + perm.info.name + " already owned by " + bp.sourcePackage); 15062 res.origPermission = perm.info.name; 15063 res.origPackage = bp.sourcePackage; 15064 return; 15065 } else { 15066 Slog.w(TAG, "Package " + pkg.packageName 15067 + " attempting to redeclare system permission " 15068 + perm.info.name + "; ignoring new declaration"); 15069 pkg.permissions.remove(i); 15070 } 15071 } 15072 } 15073 } 15074 } 15075 15076 if (systemApp) { 15077 if (onExternal) { 15078 // Abort update; system app can't be replaced with app on sdcard 15079 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15080 "Cannot install updates to system apps on sdcard"); 15081 return; 15082 } else if (ephemeral) { 15083 // Abort update; system app can't be replaced with an ephemeral app 15084 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15085 "Cannot update a system app with an ephemeral app"); 15086 return; 15087 } 15088 } 15089 15090 if (args.move != null) { 15091 // We did an in-place move, so dex is ready to roll 15092 scanFlags |= SCAN_NO_DEX; 15093 scanFlags |= SCAN_MOVE; 15094 15095 synchronized (mPackages) { 15096 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15097 if (ps == null) { 15098 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15099 "Missing settings for moved package " + pkgName); 15100 } 15101 15102 // We moved the entire application as-is, so bring over the 15103 // previously derived ABI information. 15104 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15105 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15106 } 15107 15108 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15109 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15110 scanFlags |= SCAN_NO_DEX; 15111 15112 try { 15113 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15114 args.abiOverride : pkg.cpuAbiOverride); 15115 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15116 true /* extract libs */); 15117 } catch (PackageManagerException pme) { 15118 Slog.e(TAG, "Error deriving application ABI", pme); 15119 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15120 return; 15121 } 15122 15123 // Shared libraries for the package need to be updated. 15124 synchronized (mPackages) { 15125 try { 15126 updateSharedLibrariesLPw(pkg, null); 15127 } catch (PackageManagerException e) { 15128 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15129 } 15130 } 15131 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15132 // Do not run PackageDexOptimizer through the local performDexOpt 15133 // method because `pkg` is not in `mPackages` yet. 15134 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15135 null /* instructionSets */, false /* checkProfiles */, 15136 getCompilerFilterForReason(REASON_INSTALL)); 15137 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15138 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15139 String msg = "Extracting package failed for " + pkgName; 15140 res.setError(INSTALL_FAILED_DEXOPT, msg); 15141 return; 15142 } 15143 15144 // Notify BackgroundDexOptService that the package has been changed. 15145 // If this is an update of a package which used to fail to compile, 15146 // BDOS will remove it from its blacklist. 15147 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15148 } 15149 15150 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15151 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15152 return; 15153 } 15154 15155 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15156 15157 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15158 "installPackageLI")) { 15159 if (replace) { 15160 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15161 installerPackageName, res); 15162 } else { 15163 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15164 args.user, installerPackageName, volumeUuid, res); 15165 } 15166 } 15167 synchronized (mPackages) { 15168 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15169 if (ps != null) { 15170 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15171 } 15172 15173 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15174 for (int i = 0; i < childCount; i++) { 15175 PackageParser.Package childPkg = pkg.childPackages.get(i); 15176 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15177 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15178 if (childPs != null) { 15179 childRes.newUsers = childPs.queryInstalledUsers( 15180 sUserManager.getUserIds(), true); 15181 } 15182 } 15183 } 15184 } 15185 15186 private void startIntentFilterVerifications(int userId, boolean replacing, 15187 PackageParser.Package pkg) { 15188 if (mIntentFilterVerifierComponent == null) { 15189 Slog.w(TAG, "No IntentFilter verification will not be done as " 15190 + "there is no IntentFilterVerifier available!"); 15191 return; 15192 } 15193 15194 final int verifierUid = getPackageUid( 15195 mIntentFilterVerifierComponent.getPackageName(), 15196 MATCH_DEBUG_TRIAGED_MISSING, 15197 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15198 15199 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15200 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15201 mHandler.sendMessage(msg); 15202 15203 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15204 for (int i = 0; i < childCount; i++) { 15205 PackageParser.Package childPkg = pkg.childPackages.get(i); 15206 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15207 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15208 mHandler.sendMessage(msg); 15209 } 15210 } 15211 15212 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15213 PackageParser.Package pkg) { 15214 int size = pkg.activities.size(); 15215 if (size == 0) { 15216 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15217 "No activity, so no need to verify any IntentFilter!"); 15218 return; 15219 } 15220 15221 final boolean hasDomainURLs = hasDomainURLs(pkg); 15222 if (!hasDomainURLs) { 15223 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15224 "No domain URLs, so no need to verify any IntentFilter!"); 15225 return; 15226 } 15227 15228 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15229 + " if any IntentFilter from the " + size 15230 + " Activities needs verification ..."); 15231 15232 int count = 0; 15233 final String packageName = pkg.packageName; 15234 15235 synchronized (mPackages) { 15236 // If this is a new install and we see that we've already run verification for this 15237 // package, we have nothing to do: it means the state was restored from backup. 15238 if (!replacing) { 15239 IntentFilterVerificationInfo ivi = 15240 mSettings.getIntentFilterVerificationLPr(packageName); 15241 if (ivi != null) { 15242 if (DEBUG_DOMAIN_VERIFICATION) { 15243 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15244 + ivi.getStatusString()); 15245 } 15246 return; 15247 } 15248 } 15249 15250 // If any filters need to be verified, then all need to be. 15251 boolean needToVerify = false; 15252 for (PackageParser.Activity a : pkg.activities) { 15253 for (ActivityIntentInfo filter : a.intents) { 15254 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15255 if (DEBUG_DOMAIN_VERIFICATION) { 15256 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15257 } 15258 needToVerify = true; 15259 break; 15260 } 15261 } 15262 } 15263 15264 if (needToVerify) { 15265 final int verificationId = mIntentFilterVerificationToken++; 15266 for (PackageParser.Activity a : pkg.activities) { 15267 for (ActivityIntentInfo filter : a.intents) { 15268 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15269 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15270 "Verification needed for IntentFilter:" + filter.toString()); 15271 mIntentFilterVerifier.addOneIntentFilterVerification( 15272 verifierUid, userId, verificationId, filter, packageName); 15273 count++; 15274 } 15275 } 15276 } 15277 } 15278 } 15279 15280 if (count > 0) { 15281 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15282 + " IntentFilter verification" + (count > 1 ? "s" : "") 15283 + " for userId:" + userId); 15284 mIntentFilterVerifier.startVerifications(userId); 15285 } else { 15286 if (DEBUG_DOMAIN_VERIFICATION) { 15287 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15288 } 15289 } 15290 } 15291 15292 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15293 final ComponentName cn = filter.activity.getComponentName(); 15294 final String packageName = cn.getPackageName(); 15295 15296 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15297 packageName); 15298 if (ivi == null) { 15299 return true; 15300 } 15301 int status = ivi.getStatus(); 15302 switch (status) { 15303 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15304 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15305 return true; 15306 15307 default: 15308 // Nothing to do 15309 return false; 15310 } 15311 } 15312 15313 private static boolean isMultiArch(ApplicationInfo info) { 15314 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15315 } 15316 15317 private static boolean isExternal(PackageParser.Package pkg) { 15318 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15319 } 15320 15321 private static boolean isExternal(PackageSetting ps) { 15322 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15323 } 15324 15325 private static boolean isEphemeral(PackageParser.Package pkg) { 15326 return pkg.applicationInfo.isEphemeralApp(); 15327 } 15328 15329 private static boolean isEphemeral(PackageSetting ps) { 15330 return ps.pkg != null && isEphemeral(ps.pkg); 15331 } 15332 15333 private static boolean isSystemApp(PackageParser.Package pkg) { 15334 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15335 } 15336 15337 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15338 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15339 } 15340 15341 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15342 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15343 } 15344 15345 private static boolean isSystemApp(PackageSetting ps) { 15346 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15347 } 15348 15349 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15350 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15351 } 15352 15353 private int packageFlagsToInstallFlags(PackageSetting ps) { 15354 int installFlags = 0; 15355 if (isEphemeral(ps)) { 15356 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15357 } 15358 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15359 // This existing package was an external ASEC install when we have 15360 // the external flag without a UUID 15361 installFlags |= PackageManager.INSTALL_EXTERNAL; 15362 } 15363 if (ps.isForwardLocked()) { 15364 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15365 } 15366 return installFlags; 15367 } 15368 15369 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15370 if (isExternal(pkg)) { 15371 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15372 return StorageManager.UUID_PRIMARY_PHYSICAL; 15373 } else { 15374 return pkg.volumeUuid; 15375 } 15376 } else { 15377 return StorageManager.UUID_PRIVATE_INTERNAL; 15378 } 15379 } 15380 15381 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15382 if (isExternal(pkg)) { 15383 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15384 return mSettings.getExternalVersion(); 15385 } else { 15386 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15387 } 15388 } else { 15389 return mSettings.getInternalVersion(); 15390 } 15391 } 15392 15393 private void deleteTempPackageFiles() { 15394 final FilenameFilter filter = new FilenameFilter() { 15395 public boolean accept(File dir, String name) { 15396 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15397 } 15398 }; 15399 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15400 file.delete(); 15401 } 15402 } 15403 15404 @Override 15405 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15406 int flags) { 15407 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15408 flags); 15409 } 15410 15411 @Override 15412 public void deletePackage(final String packageName, 15413 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15414 mContext.enforceCallingOrSelfPermission( 15415 android.Manifest.permission.DELETE_PACKAGES, null); 15416 Preconditions.checkNotNull(packageName); 15417 Preconditions.checkNotNull(observer); 15418 final int uid = Binder.getCallingUid(); 15419 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15420 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15421 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15422 mContext.enforceCallingOrSelfPermission( 15423 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15424 "deletePackage for user " + userId); 15425 } 15426 15427 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15428 try { 15429 observer.onPackageDeleted(packageName, 15430 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15431 } catch (RemoteException re) { 15432 } 15433 return; 15434 } 15435 15436 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15437 try { 15438 observer.onPackageDeleted(packageName, 15439 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15440 } catch (RemoteException re) { 15441 } 15442 return; 15443 } 15444 15445 if (DEBUG_REMOVE) { 15446 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15447 + " deleteAllUsers: " + deleteAllUsers ); 15448 } 15449 // Queue up an async operation since the package deletion may take a little while. 15450 mHandler.post(new Runnable() { 15451 public void run() { 15452 mHandler.removeCallbacks(this); 15453 int returnCode; 15454 if (!deleteAllUsers) { 15455 returnCode = deletePackageX(packageName, userId, deleteFlags); 15456 } else { 15457 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15458 // If nobody is blocking uninstall, proceed with delete for all users 15459 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15460 returnCode = deletePackageX(packageName, userId, deleteFlags); 15461 } else { 15462 // Otherwise uninstall individually for users with blockUninstalls=false 15463 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15464 for (int userId : users) { 15465 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15466 returnCode = deletePackageX(packageName, userId, userFlags); 15467 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15468 Slog.w(TAG, "Package delete failed for user " + userId 15469 + ", returnCode " + returnCode); 15470 } 15471 } 15472 } 15473 // The app has only been marked uninstalled for certain users. 15474 // We still need to report that delete was blocked 15475 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15476 } 15477 } 15478 try { 15479 observer.onPackageDeleted(packageName, returnCode, null); 15480 } catch (RemoteException e) { 15481 Log.i(TAG, "Observer no longer exists."); 15482 } //end catch 15483 } //end run 15484 }); 15485 } 15486 15487 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15488 int[] result = EMPTY_INT_ARRAY; 15489 for (int userId : userIds) { 15490 if (getBlockUninstallForUser(packageName, userId)) { 15491 result = ArrayUtils.appendInt(result, userId); 15492 } 15493 } 15494 return result; 15495 } 15496 15497 @Override 15498 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15499 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15500 } 15501 15502 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15503 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15504 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15505 try { 15506 if (dpm != null) { 15507 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15508 /* callingUserOnly =*/ false); 15509 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15510 : deviceOwnerComponentName.getPackageName(); 15511 // Does the package contains the device owner? 15512 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15513 // this check is probably not needed, since DO should be registered as a device 15514 // admin on some user too. (Original bug for this: b/17657954) 15515 if (packageName.equals(deviceOwnerPackageName)) { 15516 return true; 15517 } 15518 // Does it contain a device admin for any user? 15519 int[] users; 15520 if (userId == UserHandle.USER_ALL) { 15521 users = sUserManager.getUserIds(); 15522 } else { 15523 users = new int[]{userId}; 15524 } 15525 for (int i = 0; i < users.length; ++i) { 15526 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15527 return true; 15528 } 15529 } 15530 } 15531 } catch (RemoteException e) { 15532 } 15533 return false; 15534 } 15535 15536 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15537 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15538 } 15539 15540 /** 15541 * This method is an internal method that could be get invoked either 15542 * to delete an installed package or to clean up a failed installation. 15543 * After deleting an installed package, a broadcast is sent to notify any 15544 * listeners that the package has been removed. For cleaning up a failed 15545 * installation, the broadcast is not necessary since the package's 15546 * installation wouldn't have sent the initial broadcast either 15547 * The key steps in deleting a package are 15548 * deleting the package information in internal structures like mPackages, 15549 * deleting the packages base directories through installd 15550 * updating mSettings to reflect current status 15551 * persisting settings for later use 15552 * sending a broadcast if necessary 15553 */ 15554 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15555 final PackageRemovedInfo info = new PackageRemovedInfo(); 15556 final boolean res; 15557 15558 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15559 ? UserHandle.ALL : new UserHandle(userId); 15560 15561 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15562 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15563 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15564 } 15565 15566 PackageSetting uninstalledPs = null; 15567 15568 // for the uninstall-updates case and restricted profiles, remember the per- 15569 // user handle installed state 15570 int[] allUsers; 15571 synchronized (mPackages) { 15572 uninstalledPs = mSettings.mPackages.get(packageName); 15573 if (uninstalledPs == null) { 15574 Slog.w(TAG, "Not removing non-existent package " + packageName); 15575 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15576 } 15577 allUsers = sUserManager.getUserIds(); 15578 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15579 } 15580 15581 synchronized (mInstallLock) { 15582 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15583 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15584 "deletePackageX")) { 15585 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15586 deleteFlags | REMOVE_CHATTY, info, true, null); 15587 } 15588 synchronized (mPackages) { 15589 if (res) { 15590 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15591 } 15592 } 15593 } 15594 15595 if (res) { 15596 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15597 info.sendPackageRemovedBroadcasts(killApp); 15598 info.sendSystemPackageUpdatedBroadcasts(); 15599 info.sendSystemPackageAppearedBroadcasts(); 15600 } 15601 // Force a gc here. 15602 Runtime.getRuntime().gc(); 15603 // Delete the resources here after sending the broadcast to let 15604 // other processes clean up before deleting resources. 15605 if (info.args != null) { 15606 synchronized (mInstallLock) { 15607 info.args.doPostDeleteLI(true); 15608 } 15609 } 15610 15611 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15612 } 15613 15614 class PackageRemovedInfo { 15615 String removedPackage; 15616 int uid = -1; 15617 int removedAppId = -1; 15618 int[] origUsers; 15619 int[] removedUsers = null; 15620 boolean isRemovedPackageSystemUpdate = false; 15621 boolean isUpdate; 15622 boolean dataRemoved; 15623 boolean removedForAllUsers; 15624 // Clean up resources deleted packages. 15625 InstallArgs args = null; 15626 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15627 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15628 15629 void sendPackageRemovedBroadcasts(boolean killApp) { 15630 sendPackageRemovedBroadcastInternal(killApp); 15631 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15632 for (int i = 0; i < childCount; i++) { 15633 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15634 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15635 } 15636 } 15637 15638 void sendSystemPackageUpdatedBroadcasts() { 15639 if (isRemovedPackageSystemUpdate) { 15640 sendSystemPackageUpdatedBroadcastsInternal(); 15641 final int childCount = (removedChildPackages != null) 15642 ? removedChildPackages.size() : 0; 15643 for (int i = 0; i < childCount; i++) { 15644 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15645 if (childInfo.isRemovedPackageSystemUpdate) { 15646 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15647 } 15648 } 15649 } 15650 } 15651 15652 void sendSystemPackageAppearedBroadcasts() { 15653 final int packageCount = (appearedChildPackages != null) 15654 ? appearedChildPackages.size() : 0; 15655 for (int i = 0; i < packageCount; i++) { 15656 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15657 for (int userId : installedInfo.newUsers) { 15658 sendPackageAddedForUser(installedInfo.name, true, 15659 UserHandle.getAppId(installedInfo.uid), userId); 15660 } 15661 } 15662 } 15663 15664 private void sendSystemPackageUpdatedBroadcastsInternal() { 15665 Bundle extras = new Bundle(2); 15666 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15667 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15669 extras, 0, null, null, null); 15670 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15671 extras, 0, null, null, null); 15672 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15673 null, 0, removedPackage, null, null); 15674 } 15675 15676 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15677 Bundle extras = new Bundle(2); 15678 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15679 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15680 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15681 if (isUpdate || isRemovedPackageSystemUpdate) { 15682 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15683 } 15684 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15685 if (removedPackage != null) { 15686 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15687 extras, 0, null, null, removedUsers); 15688 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15689 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15690 removedPackage, extras, 0, null, null, removedUsers); 15691 } 15692 } 15693 if (removedAppId >= 0) { 15694 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15695 removedUsers); 15696 } 15697 } 15698 } 15699 15700 /* 15701 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15702 * flag is not set, the data directory is removed as well. 15703 * make sure this flag is set for partially installed apps. If not its meaningless to 15704 * delete a partially installed application. 15705 */ 15706 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15707 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15708 String packageName = ps.name; 15709 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15710 // Retrieve object to delete permissions for shared user later on 15711 final PackageParser.Package deletedPkg; 15712 final PackageSetting deletedPs; 15713 // reader 15714 synchronized (mPackages) { 15715 deletedPkg = mPackages.get(packageName); 15716 deletedPs = mSettings.mPackages.get(packageName); 15717 if (outInfo != null) { 15718 outInfo.removedPackage = packageName; 15719 outInfo.removedUsers = deletedPs != null 15720 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15721 : null; 15722 } 15723 } 15724 15725 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15726 15727 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15728 final PackageParser.Package resolvedPkg; 15729 if (deletedPkg != null) { 15730 resolvedPkg = deletedPkg; 15731 } else { 15732 // We don't have a parsed package when it lives on an ejected 15733 // adopted storage device, so fake something together 15734 resolvedPkg = new PackageParser.Package(ps.name); 15735 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15736 } 15737 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15738 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15739 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15740 if (outInfo != null) { 15741 outInfo.dataRemoved = true; 15742 } 15743 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15744 } 15745 15746 // writer 15747 synchronized (mPackages) { 15748 if (deletedPs != null) { 15749 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15750 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15751 clearDefaultBrowserIfNeeded(packageName); 15752 if (outInfo != null) { 15753 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15754 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15755 } 15756 updatePermissionsLPw(deletedPs.name, null, 0); 15757 if (deletedPs.sharedUser != null) { 15758 // Remove permissions associated with package. Since runtime 15759 // permissions are per user we have to kill the removed package 15760 // or packages running under the shared user of the removed 15761 // package if revoking the permissions requested only by the removed 15762 // package is successful and this causes a change in gids. 15763 for (int userId : UserManagerService.getInstance().getUserIds()) { 15764 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15765 userId); 15766 if (userIdToKill == UserHandle.USER_ALL 15767 || userIdToKill >= UserHandle.USER_SYSTEM) { 15768 // If gids changed for this user, kill all affected packages. 15769 mHandler.post(new Runnable() { 15770 @Override 15771 public void run() { 15772 // This has to happen with no lock held. 15773 killApplication(deletedPs.name, deletedPs.appId, 15774 KILL_APP_REASON_GIDS_CHANGED); 15775 } 15776 }); 15777 break; 15778 } 15779 } 15780 } 15781 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15782 } 15783 // make sure to preserve per-user disabled state if this removal was just 15784 // a downgrade of a system app to the factory package 15785 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15786 if (DEBUG_REMOVE) { 15787 Slog.d(TAG, "Propagating install state across downgrade"); 15788 } 15789 for (int userId : allUserHandles) { 15790 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15791 if (DEBUG_REMOVE) { 15792 Slog.d(TAG, " user " + userId + " => " + installed); 15793 } 15794 ps.setInstalled(installed, userId); 15795 } 15796 } 15797 } 15798 // can downgrade to reader 15799 if (writeSettings) { 15800 // Save settings now 15801 mSettings.writeLPr(); 15802 } 15803 } 15804 if (outInfo != null) { 15805 // A user ID was deleted here. Go through all users and remove it 15806 // from KeyStore. 15807 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15808 } 15809 } 15810 15811 static boolean locationIsPrivileged(File path) { 15812 try { 15813 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15814 .getCanonicalPath(); 15815 return path.getCanonicalPath().startsWith(privilegedAppDir); 15816 } catch (IOException e) { 15817 Slog.e(TAG, "Unable to access code path " + path); 15818 } 15819 return false; 15820 } 15821 15822 /* 15823 * Tries to delete system package. 15824 */ 15825 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15826 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15827 boolean writeSettings) { 15828 if (deletedPs.parentPackageName != null) { 15829 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15830 return false; 15831 } 15832 15833 final boolean applyUserRestrictions 15834 = (allUserHandles != null) && (outInfo.origUsers != null); 15835 final PackageSetting disabledPs; 15836 // Confirm if the system package has been updated 15837 // An updated system app can be deleted. This will also have to restore 15838 // the system pkg from system partition 15839 // reader 15840 synchronized (mPackages) { 15841 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15842 } 15843 15844 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15845 + " disabledPs=" + disabledPs); 15846 15847 if (disabledPs == null) { 15848 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15849 return false; 15850 } else if (DEBUG_REMOVE) { 15851 Slog.d(TAG, "Deleting system pkg from data partition"); 15852 } 15853 15854 if (DEBUG_REMOVE) { 15855 if (applyUserRestrictions) { 15856 Slog.d(TAG, "Remembering install states:"); 15857 for (int userId : allUserHandles) { 15858 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15859 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15860 } 15861 } 15862 } 15863 15864 // Delete the updated package 15865 outInfo.isRemovedPackageSystemUpdate = true; 15866 if (outInfo.removedChildPackages != null) { 15867 final int childCount = (deletedPs.childPackageNames != null) 15868 ? deletedPs.childPackageNames.size() : 0; 15869 for (int i = 0; i < childCount; i++) { 15870 String childPackageName = deletedPs.childPackageNames.get(i); 15871 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15872 .contains(childPackageName)) { 15873 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15874 childPackageName); 15875 if (childInfo != null) { 15876 childInfo.isRemovedPackageSystemUpdate = true; 15877 } 15878 } 15879 } 15880 } 15881 15882 if (disabledPs.versionCode < deletedPs.versionCode) { 15883 // Delete data for downgrades 15884 flags &= ~PackageManager.DELETE_KEEP_DATA; 15885 } else { 15886 // Preserve data by setting flag 15887 flags |= PackageManager.DELETE_KEEP_DATA; 15888 } 15889 15890 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15891 outInfo, writeSettings, disabledPs.pkg); 15892 if (!ret) { 15893 return false; 15894 } 15895 15896 // writer 15897 synchronized (mPackages) { 15898 // Reinstate the old system package 15899 enableSystemPackageLPw(disabledPs.pkg); 15900 // Remove any native libraries from the upgraded package. 15901 removeNativeBinariesLI(deletedPs); 15902 } 15903 15904 // Install the system package 15905 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15906 int parseFlags = mDefParseFlags 15907 | PackageParser.PARSE_MUST_BE_APK 15908 | PackageParser.PARSE_IS_SYSTEM 15909 | PackageParser.PARSE_IS_SYSTEM_DIR; 15910 if (locationIsPrivileged(disabledPs.codePath)) { 15911 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15912 } 15913 15914 final PackageParser.Package newPkg; 15915 try { 15916 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15917 } catch (PackageManagerException e) { 15918 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15919 + e.getMessage()); 15920 return false; 15921 } 15922 15923 prepareAppDataAfterInstallLIF(newPkg); 15924 15925 // writer 15926 synchronized (mPackages) { 15927 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15928 15929 // Propagate the permissions state as we do not want to drop on the floor 15930 // runtime permissions. The update permissions method below will take 15931 // care of removing obsolete permissions and grant install permissions. 15932 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15933 updatePermissionsLPw(newPkg.packageName, newPkg, 15934 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15935 15936 if (applyUserRestrictions) { 15937 if (DEBUG_REMOVE) { 15938 Slog.d(TAG, "Propagating install state across reinstall"); 15939 } 15940 for (int userId : allUserHandles) { 15941 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15942 if (DEBUG_REMOVE) { 15943 Slog.d(TAG, " user " + userId + " => " + installed); 15944 } 15945 ps.setInstalled(installed, userId); 15946 15947 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15948 } 15949 // Regardless of writeSettings we need to ensure that this restriction 15950 // state propagation is persisted 15951 mSettings.writeAllUsersPackageRestrictionsLPr(); 15952 } 15953 // can downgrade to reader here 15954 if (writeSettings) { 15955 mSettings.writeLPr(); 15956 } 15957 } 15958 return true; 15959 } 15960 15961 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15962 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15963 PackageRemovedInfo outInfo, boolean writeSettings, 15964 PackageParser.Package replacingPackage) { 15965 synchronized (mPackages) { 15966 if (outInfo != null) { 15967 outInfo.uid = ps.appId; 15968 } 15969 15970 if (outInfo != null && outInfo.removedChildPackages != null) { 15971 final int childCount = (ps.childPackageNames != null) 15972 ? ps.childPackageNames.size() : 0; 15973 for (int i = 0; i < childCount; i++) { 15974 String childPackageName = ps.childPackageNames.get(i); 15975 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15976 if (childPs == null) { 15977 return false; 15978 } 15979 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15980 childPackageName); 15981 if (childInfo != null) { 15982 childInfo.uid = childPs.appId; 15983 } 15984 } 15985 } 15986 } 15987 15988 // Delete package data from internal structures and also remove data if flag is set 15989 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15990 15991 // Delete the child packages data 15992 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15993 for (int i = 0; i < childCount; i++) { 15994 PackageSetting childPs; 15995 synchronized (mPackages) { 15996 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15997 } 15998 if (childPs != null) { 15999 PackageRemovedInfo childOutInfo = (outInfo != null 16000 && outInfo.removedChildPackages != null) 16001 ? outInfo.removedChildPackages.get(childPs.name) : null; 16002 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16003 && (replacingPackage != null 16004 && !replacingPackage.hasChildPackage(childPs.name)) 16005 ? flags & ~DELETE_KEEP_DATA : flags; 16006 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16007 deleteFlags, writeSettings); 16008 } 16009 } 16010 16011 // Delete application code and resources only for parent packages 16012 if (ps.parentPackageName == null) { 16013 if (deleteCodeAndResources && (outInfo != null)) { 16014 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16015 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16016 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16017 } 16018 } 16019 16020 return true; 16021 } 16022 16023 @Override 16024 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16025 int userId) { 16026 mContext.enforceCallingOrSelfPermission( 16027 android.Manifest.permission.DELETE_PACKAGES, null); 16028 synchronized (mPackages) { 16029 PackageSetting ps = mSettings.mPackages.get(packageName); 16030 if (ps == null) { 16031 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16032 return false; 16033 } 16034 if (!ps.getInstalled(userId)) { 16035 // Can't block uninstall for an app that is not installed or enabled. 16036 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16037 return false; 16038 } 16039 ps.setBlockUninstall(blockUninstall, userId); 16040 mSettings.writePackageRestrictionsLPr(userId); 16041 } 16042 return true; 16043 } 16044 16045 @Override 16046 public boolean getBlockUninstallForUser(String packageName, int userId) { 16047 synchronized (mPackages) { 16048 PackageSetting ps = mSettings.mPackages.get(packageName); 16049 if (ps == null) { 16050 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16051 return false; 16052 } 16053 return ps.getBlockUninstall(userId); 16054 } 16055 } 16056 16057 @Override 16058 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16059 int callingUid = Binder.getCallingUid(); 16060 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16061 throw new SecurityException( 16062 "setRequiredForSystemUser can only be run by the system or root"); 16063 } 16064 synchronized (mPackages) { 16065 PackageSetting ps = mSettings.mPackages.get(packageName); 16066 if (ps == null) { 16067 Log.w(TAG, "Package doesn't exist: " + packageName); 16068 return false; 16069 } 16070 if (systemUserApp) { 16071 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16072 } else { 16073 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16074 } 16075 mSettings.writeLPr(); 16076 } 16077 return true; 16078 } 16079 16080 /* 16081 * This method handles package deletion in general 16082 */ 16083 private boolean deletePackageLIF(String packageName, UserHandle user, 16084 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16085 PackageRemovedInfo outInfo, boolean writeSettings, 16086 PackageParser.Package replacingPackage) { 16087 if (packageName == null) { 16088 Slog.w(TAG, "Attempt to delete null packageName."); 16089 return false; 16090 } 16091 16092 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16093 16094 PackageSetting ps; 16095 16096 synchronized (mPackages) { 16097 ps = mSettings.mPackages.get(packageName); 16098 if (ps == null) { 16099 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16100 return false; 16101 } 16102 16103 if (ps.parentPackageName != null && (!isSystemApp(ps) 16104 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16105 if (DEBUG_REMOVE) { 16106 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16107 + ((user == null) ? UserHandle.USER_ALL : user)); 16108 } 16109 final int removedUserId = (user != null) ? user.getIdentifier() 16110 : UserHandle.USER_ALL; 16111 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16112 return false; 16113 } 16114 markPackageUninstalledForUserLPw(ps, user); 16115 scheduleWritePackageRestrictionsLocked(user); 16116 return true; 16117 } 16118 } 16119 16120 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16121 && user.getIdentifier() != UserHandle.USER_ALL)) { 16122 // The caller is asking that the package only be deleted for a single 16123 // user. To do this, we just mark its uninstalled state and delete 16124 // its data. If this is a system app, we only allow this to happen if 16125 // they have set the special DELETE_SYSTEM_APP which requests different 16126 // semantics than normal for uninstalling system apps. 16127 markPackageUninstalledForUserLPw(ps, user); 16128 16129 if (!isSystemApp(ps)) { 16130 // Do not uninstall the APK if an app should be cached 16131 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16132 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16133 // Other user still have this package installed, so all 16134 // we need to do is clear this user's data and save that 16135 // it is uninstalled. 16136 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16137 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16138 return false; 16139 } 16140 scheduleWritePackageRestrictionsLocked(user); 16141 return true; 16142 } else { 16143 // We need to set it back to 'installed' so the uninstall 16144 // broadcasts will be sent correctly. 16145 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16146 ps.setInstalled(true, user.getIdentifier()); 16147 } 16148 } else { 16149 // This is a system app, so we assume that the 16150 // other users still have this package installed, so all 16151 // we need to do is clear this user's data and save that 16152 // it is uninstalled. 16153 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16154 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16155 return false; 16156 } 16157 scheduleWritePackageRestrictionsLocked(user); 16158 return true; 16159 } 16160 } 16161 16162 // If we are deleting a composite package for all users, keep track 16163 // of result for each child. 16164 if (ps.childPackageNames != null && outInfo != null) { 16165 synchronized (mPackages) { 16166 final int childCount = ps.childPackageNames.size(); 16167 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16168 for (int i = 0; i < childCount; i++) { 16169 String childPackageName = ps.childPackageNames.get(i); 16170 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16171 childInfo.removedPackage = childPackageName; 16172 outInfo.removedChildPackages.put(childPackageName, childInfo); 16173 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16174 if (childPs != null) { 16175 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16176 } 16177 } 16178 } 16179 } 16180 16181 boolean ret = false; 16182 if (isSystemApp(ps)) { 16183 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16184 // When an updated system application is deleted we delete the existing resources 16185 // as well and fall back to existing code in system partition 16186 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16187 } else { 16188 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16189 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16190 outInfo, writeSettings, replacingPackage); 16191 } 16192 16193 // Take a note whether we deleted the package for all users 16194 if (outInfo != null) { 16195 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16196 if (outInfo.removedChildPackages != null) { 16197 synchronized (mPackages) { 16198 final int childCount = outInfo.removedChildPackages.size(); 16199 for (int i = 0; i < childCount; i++) { 16200 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16201 if (childInfo != null) { 16202 childInfo.removedForAllUsers = mPackages.get( 16203 childInfo.removedPackage) == null; 16204 } 16205 } 16206 } 16207 } 16208 // If we uninstalled an update to a system app there may be some 16209 // child packages that appeared as they are declared in the system 16210 // app but were not declared in the update. 16211 if (isSystemApp(ps)) { 16212 synchronized (mPackages) { 16213 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16214 final int childCount = (updatedPs.childPackageNames != null) 16215 ? updatedPs.childPackageNames.size() : 0; 16216 for (int i = 0; i < childCount; i++) { 16217 String childPackageName = updatedPs.childPackageNames.get(i); 16218 if (outInfo.removedChildPackages == null 16219 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16220 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16221 if (childPs == null) { 16222 continue; 16223 } 16224 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16225 installRes.name = childPackageName; 16226 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16227 installRes.pkg = mPackages.get(childPackageName); 16228 installRes.uid = childPs.pkg.applicationInfo.uid; 16229 if (outInfo.appearedChildPackages == null) { 16230 outInfo.appearedChildPackages = new ArrayMap<>(); 16231 } 16232 outInfo.appearedChildPackages.put(childPackageName, installRes); 16233 } 16234 } 16235 } 16236 } 16237 } 16238 16239 return ret; 16240 } 16241 16242 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16243 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16244 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16245 for (int nextUserId : userIds) { 16246 if (DEBUG_REMOVE) { 16247 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16248 } 16249 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16250 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16251 false /*hidden*/, false /*suspended*/, null, null, null, 16252 false /*blockUninstall*/, 16253 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16254 } 16255 } 16256 16257 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16258 PackageRemovedInfo outInfo) { 16259 final PackageParser.Package pkg; 16260 synchronized (mPackages) { 16261 pkg = mPackages.get(ps.name); 16262 } 16263 16264 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16265 : new int[] {userId}; 16266 for (int nextUserId : userIds) { 16267 if (DEBUG_REMOVE) { 16268 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16269 + nextUserId); 16270 } 16271 16272 destroyAppDataLIF(pkg, userId, 16273 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16274 destroyAppProfilesLIF(pkg, userId); 16275 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16276 schedulePackageCleaning(ps.name, nextUserId, false); 16277 synchronized (mPackages) { 16278 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16279 scheduleWritePackageRestrictionsLocked(nextUserId); 16280 } 16281 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16282 } 16283 } 16284 16285 if (outInfo != null) { 16286 outInfo.removedPackage = ps.name; 16287 outInfo.removedAppId = ps.appId; 16288 outInfo.removedUsers = userIds; 16289 } 16290 16291 return true; 16292 } 16293 16294 private final class ClearStorageConnection implements ServiceConnection { 16295 IMediaContainerService mContainerService; 16296 16297 @Override 16298 public void onServiceConnected(ComponentName name, IBinder service) { 16299 synchronized (this) { 16300 mContainerService = IMediaContainerService.Stub.asInterface(service); 16301 notifyAll(); 16302 } 16303 } 16304 16305 @Override 16306 public void onServiceDisconnected(ComponentName name) { 16307 } 16308 } 16309 16310 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16311 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16312 16313 final boolean mounted; 16314 if (Environment.isExternalStorageEmulated()) { 16315 mounted = true; 16316 } else { 16317 final String status = Environment.getExternalStorageState(); 16318 16319 mounted = status.equals(Environment.MEDIA_MOUNTED) 16320 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16321 } 16322 16323 if (!mounted) { 16324 return; 16325 } 16326 16327 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16328 int[] users; 16329 if (userId == UserHandle.USER_ALL) { 16330 users = sUserManager.getUserIds(); 16331 } else { 16332 users = new int[] { userId }; 16333 } 16334 final ClearStorageConnection conn = new ClearStorageConnection(); 16335 if (mContext.bindServiceAsUser( 16336 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16337 try { 16338 for (int curUser : users) { 16339 long timeout = SystemClock.uptimeMillis() + 5000; 16340 synchronized (conn) { 16341 long now = SystemClock.uptimeMillis(); 16342 while (conn.mContainerService == null && now < timeout) { 16343 try { 16344 conn.wait(timeout - now); 16345 } catch (InterruptedException e) { 16346 } 16347 } 16348 } 16349 if (conn.mContainerService == null) { 16350 return; 16351 } 16352 16353 final UserEnvironment userEnv = new UserEnvironment(curUser); 16354 clearDirectory(conn.mContainerService, 16355 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16356 if (allData) { 16357 clearDirectory(conn.mContainerService, 16358 userEnv.buildExternalStorageAppDataDirs(packageName)); 16359 clearDirectory(conn.mContainerService, 16360 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16361 } 16362 } 16363 } finally { 16364 mContext.unbindService(conn); 16365 } 16366 } 16367 } 16368 16369 @Override 16370 public void clearApplicationProfileData(String packageName) { 16371 enforceSystemOrRoot("Only the system can clear all profile data"); 16372 16373 final PackageParser.Package pkg; 16374 synchronized (mPackages) { 16375 pkg = mPackages.get(packageName); 16376 } 16377 16378 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16379 synchronized (mInstallLock) { 16380 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16381 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16382 true /* removeBaseMarker */); 16383 } 16384 } 16385 } 16386 16387 @Override 16388 public void clearApplicationUserData(final String packageName, 16389 final IPackageDataObserver observer, final int userId) { 16390 mContext.enforceCallingOrSelfPermission( 16391 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16392 16393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16394 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16395 16396 final DevicePolicyManagerInternal dpmi = LocalServices 16397 .getService(DevicePolicyManagerInternal.class); 16398 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16399 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16400 } 16401 // Queue up an async operation since the package deletion may take a little while. 16402 mHandler.post(new Runnable() { 16403 public void run() { 16404 mHandler.removeCallbacks(this); 16405 final boolean succeeded; 16406 try (PackageFreezer freezer = freezePackage(packageName, 16407 "clearApplicationUserData")) { 16408 synchronized (mInstallLock) { 16409 succeeded = clearApplicationUserDataLIF(packageName, userId); 16410 } 16411 clearExternalStorageDataSync(packageName, userId, true); 16412 } 16413 if (succeeded) { 16414 // invoke DeviceStorageMonitor's update method to clear any notifications 16415 DeviceStorageMonitorInternal dsm = LocalServices 16416 .getService(DeviceStorageMonitorInternal.class); 16417 if (dsm != null) { 16418 dsm.checkMemory(); 16419 } 16420 } 16421 if(observer != null) { 16422 try { 16423 observer.onRemoveCompleted(packageName, succeeded); 16424 } catch (RemoteException e) { 16425 Log.i(TAG, "Observer no longer exists."); 16426 } 16427 } //end if observer 16428 } //end run 16429 }); 16430 } 16431 16432 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16433 if (packageName == null) { 16434 Slog.w(TAG, "Attempt to delete null packageName."); 16435 return false; 16436 } 16437 16438 // Try finding details about the requested package 16439 PackageParser.Package pkg; 16440 synchronized (mPackages) { 16441 pkg = mPackages.get(packageName); 16442 if (pkg == null) { 16443 final PackageSetting ps = mSettings.mPackages.get(packageName); 16444 if (ps != null) { 16445 pkg = ps.pkg; 16446 } 16447 } 16448 16449 if (pkg == null) { 16450 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16451 return false; 16452 } 16453 16454 PackageSetting ps = (PackageSetting) pkg.mExtras; 16455 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16456 } 16457 16458 clearAppDataLIF(pkg, userId, 16459 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16460 16461 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16462 removeKeystoreDataIfNeeded(userId, appId); 16463 16464 UserManagerInternal umInternal = getUserManagerInternal(); 16465 final int flags; 16466 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16467 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16468 } else if (umInternal.isUserRunning(userId)) { 16469 flags = StorageManager.FLAG_STORAGE_DE; 16470 } else { 16471 flags = 0; 16472 } 16473 prepareAppDataContentsLIF(pkg, userId, flags); 16474 16475 return true; 16476 } 16477 16478 /** 16479 * Reverts user permission state changes (permissions and flags) in 16480 * all packages for a given user. 16481 * 16482 * @param userId The device user for which to do a reset. 16483 */ 16484 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16485 final int packageCount = mPackages.size(); 16486 for (int i = 0; i < packageCount; i++) { 16487 PackageParser.Package pkg = mPackages.valueAt(i); 16488 PackageSetting ps = (PackageSetting) pkg.mExtras; 16489 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16490 } 16491 } 16492 16493 private void resetNetworkPolicies(int userId) { 16494 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16495 } 16496 16497 /** 16498 * Reverts user permission state changes (permissions and flags). 16499 * 16500 * @param ps The package for which to reset. 16501 * @param userId The device user for which to do a reset. 16502 */ 16503 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16504 final PackageSetting ps, final int userId) { 16505 if (ps.pkg == null) { 16506 return; 16507 } 16508 16509 // These are flags that can change base on user actions. 16510 final int userSettableMask = FLAG_PERMISSION_USER_SET 16511 | FLAG_PERMISSION_USER_FIXED 16512 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16513 | FLAG_PERMISSION_REVIEW_REQUIRED; 16514 16515 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16516 | FLAG_PERMISSION_POLICY_FIXED; 16517 16518 boolean writeInstallPermissions = false; 16519 boolean writeRuntimePermissions = false; 16520 16521 final int permissionCount = ps.pkg.requestedPermissions.size(); 16522 for (int i = 0; i < permissionCount; i++) { 16523 String permission = ps.pkg.requestedPermissions.get(i); 16524 16525 BasePermission bp = mSettings.mPermissions.get(permission); 16526 if (bp == null) { 16527 continue; 16528 } 16529 16530 // If shared user we just reset the state to which only this app contributed. 16531 if (ps.sharedUser != null) { 16532 boolean used = false; 16533 final int packageCount = ps.sharedUser.packages.size(); 16534 for (int j = 0; j < packageCount; j++) { 16535 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16536 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16537 && pkg.pkg.requestedPermissions.contains(permission)) { 16538 used = true; 16539 break; 16540 } 16541 } 16542 if (used) { 16543 continue; 16544 } 16545 } 16546 16547 PermissionsState permissionsState = ps.getPermissionsState(); 16548 16549 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16550 16551 // Always clear the user settable flags. 16552 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16553 bp.name) != null; 16554 // If permission review is enabled and this is a legacy app, mark the 16555 // permission as requiring a review as this is the initial state. 16556 int flags = 0; 16557 if (Build.PERMISSIONS_REVIEW_REQUIRED 16558 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16559 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16560 } 16561 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16562 if (hasInstallState) { 16563 writeInstallPermissions = true; 16564 } else { 16565 writeRuntimePermissions = true; 16566 } 16567 } 16568 16569 // Below is only runtime permission handling. 16570 if (!bp.isRuntime()) { 16571 continue; 16572 } 16573 16574 // Never clobber system or policy. 16575 if ((oldFlags & policyOrSystemFlags) != 0) { 16576 continue; 16577 } 16578 16579 // If this permission was granted by default, make sure it is. 16580 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16581 if (permissionsState.grantRuntimePermission(bp, userId) 16582 != PERMISSION_OPERATION_FAILURE) { 16583 writeRuntimePermissions = true; 16584 } 16585 // If permission review is enabled the permissions for a legacy apps 16586 // are represented as constantly granted runtime ones, so don't revoke. 16587 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16588 // Otherwise, reset the permission. 16589 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16590 switch (revokeResult) { 16591 case PERMISSION_OPERATION_SUCCESS: 16592 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16593 writeRuntimePermissions = true; 16594 final int appId = ps.appId; 16595 mHandler.post(new Runnable() { 16596 @Override 16597 public void run() { 16598 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16599 } 16600 }); 16601 } break; 16602 } 16603 } 16604 } 16605 16606 // Synchronously write as we are taking permissions away. 16607 if (writeRuntimePermissions) { 16608 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16609 } 16610 16611 // Synchronously write as we are taking permissions away. 16612 if (writeInstallPermissions) { 16613 mSettings.writeLPr(); 16614 } 16615 } 16616 16617 /** 16618 * Remove entries from the keystore daemon. Will only remove it if the 16619 * {@code appId} is valid. 16620 */ 16621 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16622 if (appId < 0) { 16623 return; 16624 } 16625 16626 final KeyStore keyStore = KeyStore.getInstance(); 16627 if (keyStore != null) { 16628 if (userId == UserHandle.USER_ALL) { 16629 for (final int individual : sUserManager.getUserIds()) { 16630 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16631 } 16632 } else { 16633 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16634 } 16635 } else { 16636 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16637 } 16638 } 16639 16640 @Override 16641 public void deleteApplicationCacheFiles(final String packageName, 16642 final IPackageDataObserver observer) { 16643 final int userId = UserHandle.getCallingUserId(); 16644 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16645 } 16646 16647 @Override 16648 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16649 final IPackageDataObserver observer) { 16650 mContext.enforceCallingOrSelfPermission( 16651 android.Manifest.permission.DELETE_CACHE_FILES, null); 16652 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16653 /* requireFullPermission= */ true, /* checkShell= */ false, 16654 "delete application cache files"); 16655 16656 final PackageParser.Package pkg; 16657 synchronized (mPackages) { 16658 pkg = mPackages.get(packageName); 16659 } 16660 16661 // Queue up an async operation since the package deletion may take a little while. 16662 mHandler.post(new Runnable() { 16663 public void run() { 16664 synchronized (mInstallLock) { 16665 final int flags = StorageManager.FLAG_STORAGE_DE 16666 | StorageManager.FLAG_STORAGE_CE; 16667 // We're only clearing cache files, so we don't care if the 16668 // app is unfrozen and still able to run 16669 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16670 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16671 } 16672 clearExternalStorageDataSync(packageName, userId, false); 16673 if (observer != null) { 16674 try { 16675 observer.onRemoveCompleted(packageName, true); 16676 } catch (RemoteException e) { 16677 Log.i(TAG, "Observer no longer exists."); 16678 } 16679 } 16680 } 16681 }); 16682 } 16683 16684 @Override 16685 public void getPackageSizeInfo(final String packageName, int userHandle, 16686 final IPackageStatsObserver observer) { 16687 mContext.enforceCallingOrSelfPermission( 16688 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16689 if (packageName == null) { 16690 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16691 } 16692 16693 PackageStats stats = new PackageStats(packageName, userHandle); 16694 16695 /* 16696 * Queue up an async operation since the package measurement may take a 16697 * little while. 16698 */ 16699 Message msg = mHandler.obtainMessage(INIT_COPY); 16700 msg.obj = new MeasureParams(stats, observer); 16701 mHandler.sendMessage(msg); 16702 } 16703 16704 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16705 final PackageSetting ps; 16706 synchronized (mPackages) { 16707 ps = mSettings.mPackages.get(packageName); 16708 if (ps == null) { 16709 Slog.w(TAG, "Failed to find settings for " + packageName); 16710 return false; 16711 } 16712 } 16713 try { 16714 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16715 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16716 ps.getCeDataInode(userId), ps.codePathString, stats); 16717 } catch (InstallerException e) { 16718 Slog.w(TAG, String.valueOf(e)); 16719 return false; 16720 } 16721 16722 // For now, ignore code size of packages on system partition 16723 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16724 stats.codeSize = 0; 16725 } 16726 16727 return true; 16728 } 16729 16730 private int getUidTargetSdkVersionLockedLPr(int uid) { 16731 Object obj = mSettings.getUserIdLPr(uid); 16732 if (obj instanceof SharedUserSetting) { 16733 final SharedUserSetting sus = (SharedUserSetting) obj; 16734 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16735 final Iterator<PackageSetting> it = sus.packages.iterator(); 16736 while (it.hasNext()) { 16737 final PackageSetting ps = it.next(); 16738 if (ps.pkg != null) { 16739 int v = ps.pkg.applicationInfo.targetSdkVersion; 16740 if (v < vers) vers = v; 16741 } 16742 } 16743 return vers; 16744 } else if (obj instanceof PackageSetting) { 16745 final PackageSetting ps = (PackageSetting) obj; 16746 if (ps.pkg != null) { 16747 return ps.pkg.applicationInfo.targetSdkVersion; 16748 } 16749 } 16750 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16751 } 16752 16753 @Override 16754 public void addPreferredActivity(IntentFilter filter, int match, 16755 ComponentName[] set, ComponentName activity, int userId) { 16756 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16757 "Adding preferred"); 16758 } 16759 16760 private void addPreferredActivityInternal(IntentFilter filter, int match, 16761 ComponentName[] set, ComponentName activity, boolean always, int userId, 16762 String opname) { 16763 // writer 16764 int callingUid = Binder.getCallingUid(); 16765 enforceCrossUserPermission(callingUid, userId, 16766 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16767 if (filter.countActions() == 0) { 16768 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16769 return; 16770 } 16771 synchronized (mPackages) { 16772 if (mContext.checkCallingOrSelfPermission( 16773 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16774 != PackageManager.PERMISSION_GRANTED) { 16775 if (getUidTargetSdkVersionLockedLPr(callingUid) 16776 < Build.VERSION_CODES.FROYO) { 16777 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16778 + callingUid); 16779 return; 16780 } 16781 mContext.enforceCallingOrSelfPermission( 16782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16783 } 16784 16785 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16786 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16787 + userId + ":"); 16788 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16789 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16790 scheduleWritePackageRestrictionsLocked(userId); 16791 } 16792 } 16793 16794 @Override 16795 public void replacePreferredActivity(IntentFilter filter, int match, 16796 ComponentName[] set, ComponentName activity, int userId) { 16797 if (filter.countActions() != 1) { 16798 throw new IllegalArgumentException( 16799 "replacePreferredActivity expects filter to have only 1 action."); 16800 } 16801 if (filter.countDataAuthorities() != 0 16802 || filter.countDataPaths() != 0 16803 || filter.countDataSchemes() > 1 16804 || filter.countDataTypes() != 0) { 16805 throw new IllegalArgumentException( 16806 "replacePreferredActivity expects filter to have no data authorities, " + 16807 "paths, or types; and at most one scheme."); 16808 } 16809 16810 final int callingUid = Binder.getCallingUid(); 16811 enforceCrossUserPermission(callingUid, userId, 16812 true /* requireFullPermission */, false /* checkShell */, 16813 "replace preferred activity"); 16814 synchronized (mPackages) { 16815 if (mContext.checkCallingOrSelfPermission( 16816 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16817 != PackageManager.PERMISSION_GRANTED) { 16818 if (getUidTargetSdkVersionLockedLPr(callingUid) 16819 < Build.VERSION_CODES.FROYO) { 16820 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16821 + Binder.getCallingUid()); 16822 return; 16823 } 16824 mContext.enforceCallingOrSelfPermission( 16825 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16826 } 16827 16828 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16829 if (pir != null) { 16830 // Get all of the existing entries that exactly match this filter. 16831 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16832 if (existing != null && existing.size() == 1) { 16833 PreferredActivity cur = existing.get(0); 16834 if (DEBUG_PREFERRED) { 16835 Slog.i(TAG, "Checking replace of preferred:"); 16836 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16837 if (!cur.mPref.mAlways) { 16838 Slog.i(TAG, " -- CUR; not mAlways!"); 16839 } else { 16840 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16841 Slog.i(TAG, " -- CUR: mSet=" 16842 + Arrays.toString(cur.mPref.mSetComponents)); 16843 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16844 Slog.i(TAG, " -- NEW: mMatch=" 16845 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16846 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16847 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16848 } 16849 } 16850 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16851 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16852 && cur.mPref.sameSet(set)) { 16853 // Setting the preferred activity to what it happens to be already 16854 if (DEBUG_PREFERRED) { 16855 Slog.i(TAG, "Replacing with same preferred activity " 16856 + cur.mPref.mShortComponent + " for user " 16857 + userId + ":"); 16858 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16859 } 16860 return; 16861 } 16862 } 16863 16864 if (existing != null) { 16865 if (DEBUG_PREFERRED) { 16866 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16867 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16868 } 16869 for (int i = 0; i < existing.size(); i++) { 16870 PreferredActivity pa = existing.get(i); 16871 if (DEBUG_PREFERRED) { 16872 Slog.i(TAG, "Removing existing preferred activity " 16873 + pa.mPref.mComponent + ":"); 16874 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16875 } 16876 pir.removeFilter(pa); 16877 } 16878 } 16879 } 16880 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16881 "Replacing preferred"); 16882 } 16883 } 16884 16885 @Override 16886 public void clearPackagePreferredActivities(String packageName) { 16887 final int uid = Binder.getCallingUid(); 16888 // writer 16889 synchronized (mPackages) { 16890 PackageParser.Package pkg = mPackages.get(packageName); 16891 if (pkg == null || pkg.applicationInfo.uid != uid) { 16892 if (mContext.checkCallingOrSelfPermission( 16893 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16894 != PackageManager.PERMISSION_GRANTED) { 16895 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16896 < Build.VERSION_CODES.FROYO) { 16897 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16898 + Binder.getCallingUid()); 16899 return; 16900 } 16901 mContext.enforceCallingOrSelfPermission( 16902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16903 } 16904 } 16905 16906 int user = UserHandle.getCallingUserId(); 16907 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16908 scheduleWritePackageRestrictionsLocked(user); 16909 } 16910 } 16911 } 16912 16913 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16914 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16915 ArrayList<PreferredActivity> removed = null; 16916 boolean changed = false; 16917 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16918 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16919 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16920 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16921 continue; 16922 } 16923 Iterator<PreferredActivity> it = pir.filterIterator(); 16924 while (it.hasNext()) { 16925 PreferredActivity pa = it.next(); 16926 // Mark entry for removal only if it matches the package name 16927 // and the entry is of type "always". 16928 if (packageName == null || 16929 (pa.mPref.mComponent.getPackageName().equals(packageName) 16930 && pa.mPref.mAlways)) { 16931 if (removed == null) { 16932 removed = new ArrayList<PreferredActivity>(); 16933 } 16934 removed.add(pa); 16935 } 16936 } 16937 if (removed != null) { 16938 for (int j=0; j<removed.size(); j++) { 16939 PreferredActivity pa = removed.get(j); 16940 pir.removeFilter(pa); 16941 } 16942 changed = true; 16943 } 16944 } 16945 return changed; 16946 } 16947 16948 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16949 private void clearIntentFilterVerificationsLPw(int userId) { 16950 final int packageCount = mPackages.size(); 16951 for (int i = 0; i < packageCount; i++) { 16952 PackageParser.Package pkg = mPackages.valueAt(i); 16953 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16954 } 16955 } 16956 16957 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16958 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16959 if (userId == UserHandle.USER_ALL) { 16960 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16961 sUserManager.getUserIds())) { 16962 for (int oneUserId : sUserManager.getUserIds()) { 16963 scheduleWritePackageRestrictionsLocked(oneUserId); 16964 } 16965 } 16966 } else { 16967 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16968 scheduleWritePackageRestrictionsLocked(userId); 16969 } 16970 } 16971 } 16972 16973 void clearDefaultBrowserIfNeeded(String packageName) { 16974 for (int oneUserId : sUserManager.getUserIds()) { 16975 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16976 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16977 if (packageName.equals(defaultBrowserPackageName)) { 16978 setDefaultBrowserPackageName(null, oneUserId); 16979 } 16980 } 16981 } 16982 16983 @Override 16984 public void resetApplicationPreferences(int userId) { 16985 mContext.enforceCallingOrSelfPermission( 16986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16987 final long identity = Binder.clearCallingIdentity(); 16988 // writer 16989 try { 16990 synchronized (mPackages) { 16991 clearPackagePreferredActivitiesLPw(null, userId); 16992 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16993 // TODO: We have to reset the default SMS and Phone. This requires 16994 // significant refactoring to keep all default apps in the package 16995 // manager (cleaner but more work) or have the services provide 16996 // callbacks to the package manager to request a default app reset. 16997 applyFactoryDefaultBrowserLPw(userId); 16998 clearIntentFilterVerificationsLPw(userId); 16999 primeDomainVerificationsLPw(userId); 17000 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17001 scheduleWritePackageRestrictionsLocked(userId); 17002 } 17003 resetNetworkPolicies(userId); 17004 } finally { 17005 Binder.restoreCallingIdentity(identity); 17006 } 17007 } 17008 17009 @Override 17010 public int getPreferredActivities(List<IntentFilter> outFilters, 17011 List<ComponentName> outActivities, String packageName) { 17012 17013 int num = 0; 17014 final int userId = UserHandle.getCallingUserId(); 17015 // reader 17016 synchronized (mPackages) { 17017 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17018 if (pir != null) { 17019 final Iterator<PreferredActivity> it = pir.filterIterator(); 17020 while (it.hasNext()) { 17021 final PreferredActivity pa = it.next(); 17022 if (packageName == null 17023 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17024 && pa.mPref.mAlways)) { 17025 if (outFilters != null) { 17026 outFilters.add(new IntentFilter(pa)); 17027 } 17028 if (outActivities != null) { 17029 outActivities.add(pa.mPref.mComponent); 17030 } 17031 } 17032 } 17033 } 17034 } 17035 17036 return num; 17037 } 17038 17039 @Override 17040 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17041 int userId) { 17042 int callingUid = Binder.getCallingUid(); 17043 if (callingUid != Process.SYSTEM_UID) { 17044 throw new SecurityException( 17045 "addPersistentPreferredActivity can only be run by the system"); 17046 } 17047 if (filter.countActions() == 0) { 17048 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17049 return; 17050 } 17051 synchronized (mPackages) { 17052 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17053 ":"); 17054 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17055 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17056 new PersistentPreferredActivity(filter, activity)); 17057 scheduleWritePackageRestrictionsLocked(userId); 17058 } 17059 } 17060 17061 @Override 17062 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17063 int callingUid = Binder.getCallingUid(); 17064 if (callingUid != Process.SYSTEM_UID) { 17065 throw new SecurityException( 17066 "clearPackagePersistentPreferredActivities can only be run by the system"); 17067 } 17068 ArrayList<PersistentPreferredActivity> removed = null; 17069 boolean changed = false; 17070 synchronized (mPackages) { 17071 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17072 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17073 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17074 .valueAt(i); 17075 if (userId != thisUserId) { 17076 continue; 17077 } 17078 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17079 while (it.hasNext()) { 17080 PersistentPreferredActivity ppa = it.next(); 17081 // Mark entry for removal only if it matches the package name. 17082 if (ppa.mComponent.getPackageName().equals(packageName)) { 17083 if (removed == null) { 17084 removed = new ArrayList<PersistentPreferredActivity>(); 17085 } 17086 removed.add(ppa); 17087 } 17088 } 17089 if (removed != null) { 17090 for (int j=0; j<removed.size(); j++) { 17091 PersistentPreferredActivity ppa = removed.get(j); 17092 ppir.removeFilter(ppa); 17093 } 17094 changed = true; 17095 } 17096 } 17097 17098 if (changed) { 17099 scheduleWritePackageRestrictionsLocked(userId); 17100 } 17101 } 17102 } 17103 17104 /** 17105 * Common machinery for picking apart a restored XML blob and passing 17106 * it to a caller-supplied functor to be applied to the running system. 17107 */ 17108 private void restoreFromXml(XmlPullParser parser, int userId, 17109 String expectedStartTag, BlobXmlRestorer functor) 17110 throws IOException, XmlPullParserException { 17111 int type; 17112 while ((type = parser.next()) != XmlPullParser.START_TAG 17113 && type != XmlPullParser.END_DOCUMENT) { 17114 } 17115 if (type != XmlPullParser.START_TAG) { 17116 // oops didn't find a start tag?! 17117 if (DEBUG_BACKUP) { 17118 Slog.e(TAG, "Didn't find start tag during restore"); 17119 } 17120 return; 17121 } 17122Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17123 // this is supposed to be TAG_PREFERRED_BACKUP 17124 if (!expectedStartTag.equals(parser.getName())) { 17125 if (DEBUG_BACKUP) { 17126 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17127 } 17128 return; 17129 } 17130 17131 // skip interfering stuff, then we're aligned with the backing implementation 17132 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17133Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17134 functor.apply(parser, userId); 17135 } 17136 17137 private interface BlobXmlRestorer { 17138 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17139 } 17140 17141 /** 17142 * Non-Binder method, support for the backup/restore mechanism: write the 17143 * full set of preferred activities in its canonical XML format. Returns the 17144 * XML output as a byte array, or null if there is none. 17145 */ 17146 @Override 17147 public byte[] getPreferredActivityBackup(int userId) { 17148 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17149 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17150 } 17151 17152 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17153 try { 17154 final XmlSerializer serializer = new FastXmlSerializer(); 17155 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17156 serializer.startDocument(null, true); 17157 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17158 17159 synchronized (mPackages) { 17160 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17161 } 17162 17163 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17164 serializer.endDocument(); 17165 serializer.flush(); 17166 } catch (Exception e) { 17167 if (DEBUG_BACKUP) { 17168 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17169 } 17170 return null; 17171 } 17172 17173 return dataStream.toByteArray(); 17174 } 17175 17176 @Override 17177 public void restorePreferredActivities(byte[] backup, int userId) { 17178 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17179 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17180 } 17181 17182 try { 17183 final XmlPullParser parser = Xml.newPullParser(); 17184 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17185 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17186 new BlobXmlRestorer() { 17187 @Override 17188 public void apply(XmlPullParser parser, int userId) 17189 throws XmlPullParserException, IOException { 17190 synchronized (mPackages) { 17191 mSettings.readPreferredActivitiesLPw(parser, userId); 17192 } 17193 } 17194 } ); 17195 } catch (Exception e) { 17196 if (DEBUG_BACKUP) { 17197 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17198 } 17199 } 17200 } 17201 17202 /** 17203 * Non-Binder method, support for the backup/restore mechanism: write the 17204 * default browser (etc) settings in its canonical XML format. Returns the default 17205 * browser XML representation as a byte array, or null if there is none. 17206 */ 17207 @Override 17208 public byte[] getDefaultAppsBackup(int userId) { 17209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17210 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17211 } 17212 17213 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17214 try { 17215 final XmlSerializer serializer = new FastXmlSerializer(); 17216 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17217 serializer.startDocument(null, true); 17218 serializer.startTag(null, TAG_DEFAULT_APPS); 17219 17220 synchronized (mPackages) { 17221 mSettings.writeDefaultAppsLPr(serializer, userId); 17222 } 17223 17224 serializer.endTag(null, TAG_DEFAULT_APPS); 17225 serializer.endDocument(); 17226 serializer.flush(); 17227 } catch (Exception e) { 17228 if (DEBUG_BACKUP) { 17229 Slog.e(TAG, "Unable to write default apps for backup", e); 17230 } 17231 return null; 17232 } 17233 17234 return dataStream.toByteArray(); 17235 } 17236 17237 @Override 17238 public void restoreDefaultApps(byte[] backup, int userId) { 17239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17240 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17241 } 17242 17243 try { 17244 final XmlPullParser parser = Xml.newPullParser(); 17245 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17246 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17247 new BlobXmlRestorer() { 17248 @Override 17249 public void apply(XmlPullParser parser, int userId) 17250 throws XmlPullParserException, IOException { 17251 synchronized (mPackages) { 17252 mSettings.readDefaultAppsLPw(parser, userId); 17253 } 17254 } 17255 } ); 17256 } catch (Exception e) { 17257 if (DEBUG_BACKUP) { 17258 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17259 } 17260 } 17261 } 17262 17263 @Override 17264 public byte[] getIntentFilterVerificationBackup(int userId) { 17265 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17266 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17267 } 17268 17269 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17270 try { 17271 final XmlSerializer serializer = new FastXmlSerializer(); 17272 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17273 serializer.startDocument(null, true); 17274 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17275 17276 synchronized (mPackages) { 17277 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17278 } 17279 17280 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17281 serializer.endDocument(); 17282 serializer.flush(); 17283 } catch (Exception e) { 17284 if (DEBUG_BACKUP) { 17285 Slog.e(TAG, "Unable to write default apps for backup", e); 17286 } 17287 return null; 17288 } 17289 17290 return dataStream.toByteArray(); 17291 } 17292 17293 @Override 17294 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17295 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17296 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17297 } 17298 17299 try { 17300 final XmlPullParser parser = Xml.newPullParser(); 17301 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17302 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17303 new BlobXmlRestorer() { 17304 @Override 17305 public void apply(XmlPullParser parser, int userId) 17306 throws XmlPullParserException, IOException { 17307 synchronized (mPackages) { 17308 mSettings.readAllDomainVerificationsLPr(parser, userId); 17309 mSettings.writeLPr(); 17310 } 17311 } 17312 } ); 17313 } catch (Exception e) { 17314 if (DEBUG_BACKUP) { 17315 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17316 } 17317 } 17318 } 17319 17320 @Override 17321 public byte[] getPermissionGrantBackup(int userId) { 17322 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17323 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17324 } 17325 17326 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17327 try { 17328 final XmlSerializer serializer = new FastXmlSerializer(); 17329 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17330 serializer.startDocument(null, true); 17331 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17332 17333 synchronized (mPackages) { 17334 serializeRuntimePermissionGrantsLPr(serializer, userId); 17335 } 17336 17337 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17338 serializer.endDocument(); 17339 serializer.flush(); 17340 } catch (Exception e) { 17341 if (DEBUG_BACKUP) { 17342 Slog.e(TAG, "Unable to write default apps for backup", e); 17343 } 17344 return null; 17345 } 17346 17347 return dataStream.toByteArray(); 17348 } 17349 17350 @Override 17351 public void restorePermissionGrants(byte[] backup, int userId) { 17352 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17353 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17354 } 17355 17356 try { 17357 final XmlPullParser parser = Xml.newPullParser(); 17358 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17359 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17360 new BlobXmlRestorer() { 17361 @Override 17362 public void apply(XmlPullParser parser, int userId) 17363 throws XmlPullParserException, IOException { 17364 synchronized (mPackages) { 17365 processRestoredPermissionGrantsLPr(parser, userId); 17366 } 17367 } 17368 } ); 17369 } catch (Exception e) { 17370 if (DEBUG_BACKUP) { 17371 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17372 } 17373 } 17374 } 17375 17376 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17377 throws IOException { 17378 serializer.startTag(null, TAG_ALL_GRANTS); 17379 17380 final int N = mSettings.mPackages.size(); 17381 for (int i = 0; i < N; i++) { 17382 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17383 boolean pkgGrantsKnown = false; 17384 17385 PermissionsState packagePerms = ps.getPermissionsState(); 17386 17387 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17388 final int grantFlags = state.getFlags(); 17389 // only look at grants that are not system/policy fixed 17390 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17391 final boolean isGranted = state.isGranted(); 17392 // And only back up the user-twiddled state bits 17393 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17394 final String packageName = mSettings.mPackages.keyAt(i); 17395 if (!pkgGrantsKnown) { 17396 serializer.startTag(null, TAG_GRANT); 17397 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17398 pkgGrantsKnown = true; 17399 } 17400 17401 final boolean userSet = 17402 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17403 final boolean userFixed = 17404 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17405 final boolean revoke = 17406 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17407 17408 serializer.startTag(null, TAG_PERMISSION); 17409 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17410 if (isGranted) { 17411 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17412 } 17413 if (userSet) { 17414 serializer.attribute(null, ATTR_USER_SET, "true"); 17415 } 17416 if (userFixed) { 17417 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17418 } 17419 if (revoke) { 17420 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17421 } 17422 serializer.endTag(null, TAG_PERMISSION); 17423 } 17424 } 17425 } 17426 17427 if (pkgGrantsKnown) { 17428 serializer.endTag(null, TAG_GRANT); 17429 } 17430 } 17431 17432 serializer.endTag(null, TAG_ALL_GRANTS); 17433 } 17434 17435 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17436 throws XmlPullParserException, IOException { 17437 String pkgName = null; 17438 int outerDepth = parser.getDepth(); 17439 int type; 17440 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17441 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17442 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17443 continue; 17444 } 17445 17446 final String tagName = parser.getName(); 17447 if (tagName.equals(TAG_GRANT)) { 17448 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17449 if (DEBUG_BACKUP) { 17450 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17451 } 17452 } else if (tagName.equals(TAG_PERMISSION)) { 17453 17454 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17455 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17456 17457 int newFlagSet = 0; 17458 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17459 newFlagSet |= FLAG_PERMISSION_USER_SET; 17460 } 17461 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17462 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17463 } 17464 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17465 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17466 } 17467 if (DEBUG_BACKUP) { 17468 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17469 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17470 } 17471 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17472 if (ps != null) { 17473 // Already installed so we apply the grant immediately 17474 if (DEBUG_BACKUP) { 17475 Slog.v(TAG, " + already installed; applying"); 17476 } 17477 PermissionsState perms = ps.getPermissionsState(); 17478 BasePermission bp = mSettings.mPermissions.get(permName); 17479 if (bp != null) { 17480 if (isGranted) { 17481 perms.grantRuntimePermission(bp, userId); 17482 } 17483 if (newFlagSet != 0) { 17484 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17485 } 17486 } 17487 } else { 17488 // Need to wait for post-restore install to apply the grant 17489 if (DEBUG_BACKUP) { 17490 Slog.v(TAG, " - not yet installed; saving for later"); 17491 } 17492 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17493 isGranted, newFlagSet, userId); 17494 } 17495 } else { 17496 PackageManagerService.reportSettingsProblem(Log.WARN, 17497 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17498 XmlUtils.skipCurrentTag(parser); 17499 } 17500 } 17501 17502 scheduleWriteSettingsLocked(); 17503 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17504 } 17505 17506 @Override 17507 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17508 int sourceUserId, int targetUserId, int flags) { 17509 mContext.enforceCallingOrSelfPermission( 17510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17511 int callingUid = Binder.getCallingUid(); 17512 enforceOwnerRights(ownerPackage, callingUid); 17513 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17514 if (intentFilter.countActions() == 0) { 17515 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17516 return; 17517 } 17518 synchronized (mPackages) { 17519 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17520 ownerPackage, targetUserId, flags); 17521 CrossProfileIntentResolver resolver = 17522 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17523 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17524 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17525 if (existing != null) { 17526 int size = existing.size(); 17527 for (int i = 0; i < size; i++) { 17528 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17529 return; 17530 } 17531 } 17532 } 17533 resolver.addFilter(newFilter); 17534 scheduleWritePackageRestrictionsLocked(sourceUserId); 17535 } 17536 } 17537 17538 @Override 17539 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17540 mContext.enforceCallingOrSelfPermission( 17541 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17542 int callingUid = Binder.getCallingUid(); 17543 enforceOwnerRights(ownerPackage, callingUid); 17544 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17545 synchronized (mPackages) { 17546 CrossProfileIntentResolver resolver = 17547 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17548 ArraySet<CrossProfileIntentFilter> set = 17549 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17550 for (CrossProfileIntentFilter filter : set) { 17551 if (filter.getOwnerPackage().equals(ownerPackage)) { 17552 resolver.removeFilter(filter); 17553 } 17554 } 17555 scheduleWritePackageRestrictionsLocked(sourceUserId); 17556 } 17557 } 17558 17559 // Enforcing that callingUid is owning pkg on userId 17560 private void enforceOwnerRights(String pkg, int callingUid) { 17561 // The system owns everything. 17562 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17563 return; 17564 } 17565 int callingUserId = UserHandle.getUserId(callingUid); 17566 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17567 if (pi == null) { 17568 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17569 + callingUserId); 17570 } 17571 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17572 throw new SecurityException("Calling uid " + callingUid 17573 + " does not own package " + pkg); 17574 } 17575 } 17576 17577 @Override 17578 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17579 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17580 } 17581 17582 private Intent getHomeIntent() { 17583 Intent intent = new Intent(Intent.ACTION_MAIN); 17584 intent.addCategory(Intent.CATEGORY_HOME); 17585 return intent; 17586 } 17587 17588 private IntentFilter getHomeFilter() { 17589 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17590 filter.addCategory(Intent.CATEGORY_HOME); 17591 filter.addCategory(Intent.CATEGORY_DEFAULT); 17592 return filter; 17593 } 17594 17595 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17596 int userId) { 17597 Intent intent = getHomeIntent(); 17598 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17599 PackageManager.GET_META_DATA, userId); 17600 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17601 true, false, false, userId); 17602 17603 allHomeCandidates.clear(); 17604 if (list != null) { 17605 for (ResolveInfo ri : list) { 17606 allHomeCandidates.add(ri); 17607 } 17608 } 17609 return (preferred == null || preferred.activityInfo == null) 17610 ? null 17611 : new ComponentName(preferred.activityInfo.packageName, 17612 preferred.activityInfo.name); 17613 } 17614 17615 @Override 17616 public void setHomeActivity(ComponentName comp, int userId) { 17617 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17618 getHomeActivitiesAsUser(homeActivities, userId); 17619 17620 boolean found = false; 17621 17622 final int size = homeActivities.size(); 17623 final ComponentName[] set = new ComponentName[size]; 17624 for (int i = 0; i < size; i++) { 17625 final ResolveInfo candidate = homeActivities.get(i); 17626 final ActivityInfo info = candidate.activityInfo; 17627 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17628 set[i] = activityName; 17629 if (!found && activityName.equals(comp)) { 17630 found = true; 17631 } 17632 } 17633 if (!found) { 17634 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17635 + userId); 17636 } 17637 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17638 set, comp, userId); 17639 } 17640 17641 private @Nullable String getSetupWizardPackageName() { 17642 final Intent intent = new Intent(Intent.ACTION_MAIN); 17643 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17644 17645 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17646 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17647 | MATCH_DISABLED_COMPONENTS, 17648 UserHandle.myUserId()); 17649 if (matches.size() == 1) { 17650 return matches.get(0).getComponentInfo().packageName; 17651 } else { 17652 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17653 + ": matches=" + matches); 17654 return null; 17655 } 17656 } 17657 17658 @Override 17659 public void setApplicationEnabledSetting(String appPackageName, 17660 int newState, int flags, int userId, String callingPackage) { 17661 if (!sUserManager.exists(userId)) return; 17662 if (callingPackage == null) { 17663 callingPackage = Integer.toString(Binder.getCallingUid()); 17664 } 17665 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17666 } 17667 17668 @Override 17669 public void setComponentEnabledSetting(ComponentName componentName, 17670 int newState, int flags, int userId) { 17671 if (!sUserManager.exists(userId)) return; 17672 setEnabledSetting(componentName.getPackageName(), 17673 componentName.getClassName(), newState, flags, userId, null); 17674 } 17675 17676 private void setEnabledSetting(final String packageName, String className, int newState, 17677 final int flags, int userId, String callingPackage) { 17678 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17679 || newState == COMPONENT_ENABLED_STATE_ENABLED 17680 || newState == COMPONENT_ENABLED_STATE_DISABLED 17681 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17682 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17683 throw new IllegalArgumentException("Invalid new component state: " 17684 + newState); 17685 } 17686 PackageSetting pkgSetting; 17687 final int uid = Binder.getCallingUid(); 17688 final int permission; 17689 if (uid == Process.SYSTEM_UID) { 17690 permission = PackageManager.PERMISSION_GRANTED; 17691 } else { 17692 permission = mContext.checkCallingOrSelfPermission( 17693 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17694 } 17695 enforceCrossUserPermission(uid, userId, 17696 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17697 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17698 boolean sendNow = false; 17699 boolean isApp = (className == null); 17700 String componentName = isApp ? packageName : className; 17701 int packageUid = -1; 17702 ArrayList<String> components; 17703 17704 // writer 17705 synchronized (mPackages) { 17706 pkgSetting = mSettings.mPackages.get(packageName); 17707 if (pkgSetting == null) { 17708 if (className == null) { 17709 throw new IllegalArgumentException("Unknown package: " + packageName); 17710 } 17711 throw new IllegalArgumentException( 17712 "Unknown component: " + packageName + "/" + className); 17713 } 17714 } 17715 17716 // Limit who can change which apps 17717 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17718 // Don't allow apps that don't have permission to modify other apps 17719 if (!allowedByPermission) { 17720 throw new SecurityException( 17721 "Permission Denial: attempt to change component state from pid=" 17722 + Binder.getCallingPid() 17723 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17724 } 17725 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17726 final DevicePolicyManagerInternal dpmi = LocalServices 17727 .getService(DevicePolicyManagerInternal.class); 17728 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17729 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17730 } 17731 } 17732 17733 synchronized (mPackages) { 17734 if (uid == Process.SHELL_UID) { 17735 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17736 int oldState = pkgSetting.getEnabled(userId); 17737 if (className == null 17738 && 17739 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17740 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17741 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17742 && 17743 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17744 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17745 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17746 // ok 17747 } else { 17748 throw new SecurityException( 17749 "Shell cannot change component state for " + packageName + "/" 17750 + className + " to " + newState); 17751 } 17752 } 17753 if (className == null) { 17754 // We're dealing with an application/package level state change 17755 if (pkgSetting.getEnabled(userId) == newState) { 17756 // Nothing to do 17757 return; 17758 } 17759 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17760 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17761 // Don't care about who enables an app. 17762 callingPackage = null; 17763 } 17764 pkgSetting.setEnabled(newState, userId, callingPackage); 17765 // pkgSetting.pkg.mSetEnabled = newState; 17766 } else { 17767 // We're dealing with a component level state change 17768 // First, verify that this is a valid class name. 17769 PackageParser.Package pkg = pkgSetting.pkg; 17770 if (pkg == null || !pkg.hasComponentClassName(className)) { 17771 if (pkg != null && 17772 pkg.applicationInfo.targetSdkVersion >= 17773 Build.VERSION_CODES.JELLY_BEAN) { 17774 throw new IllegalArgumentException("Component class " + className 17775 + " does not exist in " + packageName); 17776 } else { 17777 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17778 + className + " does not exist in " + packageName); 17779 } 17780 } 17781 switch (newState) { 17782 case COMPONENT_ENABLED_STATE_ENABLED: 17783 if (!pkgSetting.enableComponentLPw(className, userId)) { 17784 return; 17785 } 17786 break; 17787 case COMPONENT_ENABLED_STATE_DISABLED: 17788 if (!pkgSetting.disableComponentLPw(className, userId)) { 17789 return; 17790 } 17791 break; 17792 case COMPONENT_ENABLED_STATE_DEFAULT: 17793 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17794 return; 17795 } 17796 break; 17797 default: 17798 Slog.e(TAG, "Invalid new component state: " + newState); 17799 return; 17800 } 17801 } 17802 scheduleWritePackageRestrictionsLocked(userId); 17803 components = mPendingBroadcasts.get(userId, packageName); 17804 final boolean newPackage = components == null; 17805 if (newPackage) { 17806 components = new ArrayList<String>(); 17807 } 17808 if (!components.contains(componentName)) { 17809 components.add(componentName); 17810 } 17811 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17812 sendNow = true; 17813 // Purge entry from pending broadcast list if another one exists already 17814 // since we are sending one right away. 17815 mPendingBroadcasts.remove(userId, packageName); 17816 } else { 17817 if (newPackage) { 17818 mPendingBroadcasts.put(userId, packageName, components); 17819 } 17820 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17821 // Schedule a message 17822 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17823 } 17824 } 17825 } 17826 17827 long callingId = Binder.clearCallingIdentity(); 17828 try { 17829 if (sendNow) { 17830 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17831 sendPackageChangedBroadcast(packageName, 17832 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17833 } 17834 } finally { 17835 Binder.restoreCallingIdentity(callingId); 17836 } 17837 } 17838 17839 @Override 17840 public void flushPackageRestrictionsAsUser(int userId) { 17841 if (!sUserManager.exists(userId)) { 17842 return; 17843 } 17844 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17845 false /* checkShell */, "flushPackageRestrictions"); 17846 synchronized (mPackages) { 17847 mSettings.writePackageRestrictionsLPr(userId); 17848 mDirtyUsers.remove(userId); 17849 if (mDirtyUsers.isEmpty()) { 17850 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17851 } 17852 } 17853 } 17854 17855 private void sendPackageChangedBroadcast(String packageName, 17856 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17857 if (DEBUG_INSTALL) 17858 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17859 + componentNames); 17860 Bundle extras = new Bundle(4); 17861 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17862 String nameList[] = new String[componentNames.size()]; 17863 componentNames.toArray(nameList); 17864 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17865 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17866 extras.putInt(Intent.EXTRA_UID, packageUid); 17867 // If this is not reporting a change of the overall package, then only send it 17868 // to registered receivers. We don't want to launch a swath of apps for every 17869 // little component state change. 17870 final int flags = !componentNames.contains(packageName) 17871 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17872 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17873 new int[] {UserHandle.getUserId(packageUid)}); 17874 } 17875 17876 @Override 17877 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17878 if (!sUserManager.exists(userId)) return; 17879 final int uid = Binder.getCallingUid(); 17880 final int permission = mContext.checkCallingOrSelfPermission( 17881 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17882 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17883 enforceCrossUserPermission(uid, userId, 17884 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17885 // writer 17886 synchronized (mPackages) { 17887 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17888 allowedByPermission, uid, userId)) { 17889 scheduleWritePackageRestrictionsLocked(userId); 17890 } 17891 } 17892 } 17893 17894 @Override 17895 public String getInstallerPackageName(String packageName) { 17896 // reader 17897 synchronized (mPackages) { 17898 return mSettings.getInstallerPackageNameLPr(packageName); 17899 } 17900 } 17901 17902 public boolean isOrphaned(String packageName) { 17903 // reader 17904 synchronized (mPackages) { 17905 return mSettings.isOrphaned(packageName); 17906 } 17907 } 17908 17909 @Override 17910 public int getApplicationEnabledSetting(String packageName, int userId) { 17911 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17912 int uid = Binder.getCallingUid(); 17913 enforceCrossUserPermission(uid, userId, 17914 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17915 // reader 17916 synchronized (mPackages) { 17917 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17918 } 17919 } 17920 17921 @Override 17922 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17923 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17924 int uid = Binder.getCallingUid(); 17925 enforceCrossUserPermission(uid, userId, 17926 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17927 // reader 17928 synchronized (mPackages) { 17929 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17930 } 17931 } 17932 17933 @Override 17934 public void enterSafeMode() { 17935 enforceSystemOrRoot("Only the system can request entering safe mode"); 17936 17937 if (!mSystemReady) { 17938 mSafeMode = true; 17939 } 17940 } 17941 17942 @Override 17943 public void systemReady() { 17944 mSystemReady = true; 17945 17946 // Read the compatibilty setting when the system is ready. 17947 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17948 mContext.getContentResolver(), 17949 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17950 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17951 if (DEBUG_SETTINGS) { 17952 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17953 } 17954 17955 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17956 17957 synchronized (mPackages) { 17958 // Verify that all of the preferred activity components actually 17959 // exist. It is possible for applications to be updated and at 17960 // that point remove a previously declared activity component that 17961 // had been set as a preferred activity. We try to clean this up 17962 // the next time we encounter that preferred activity, but it is 17963 // possible for the user flow to never be able to return to that 17964 // situation so here we do a sanity check to make sure we haven't 17965 // left any junk around. 17966 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17967 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17968 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17969 removed.clear(); 17970 for (PreferredActivity pa : pir.filterSet()) { 17971 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17972 removed.add(pa); 17973 } 17974 } 17975 if (removed.size() > 0) { 17976 for (int r=0; r<removed.size(); r++) { 17977 PreferredActivity pa = removed.get(r); 17978 Slog.w(TAG, "Removing dangling preferred activity: " 17979 + pa.mPref.mComponent); 17980 pir.removeFilter(pa); 17981 } 17982 mSettings.writePackageRestrictionsLPr( 17983 mSettings.mPreferredActivities.keyAt(i)); 17984 } 17985 } 17986 17987 for (int userId : UserManagerService.getInstance().getUserIds()) { 17988 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17989 grantPermissionsUserIds = ArrayUtils.appendInt( 17990 grantPermissionsUserIds, userId); 17991 } 17992 } 17993 } 17994 sUserManager.systemReady(); 17995 17996 // If we upgraded grant all default permissions before kicking off. 17997 for (int userId : grantPermissionsUserIds) { 17998 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17999 } 18000 18001 // Kick off any messages waiting for system ready 18002 if (mPostSystemReadyMessages != null) { 18003 for (Message msg : mPostSystemReadyMessages) { 18004 msg.sendToTarget(); 18005 } 18006 mPostSystemReadyMessages = null; 18007 } 18008 18009 // Watch for external volumes that come and go over time 18010 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18011 storage.registerListener(mStorageListener); 18012 18013 mInstallerService.systemReady(); 18014 mPackageDexOptimizer.systemReady(); 18015 18016 MountServiceInternal mountServiceInternal = LocalServices.getService( 18017 MountServiceInternal.class); 18018 mountServiceInternal.addExternalStoragePolicy( 18019 new MountServiceInternal.ExternalStorageMountPolicy() { 18020 @Override 18021 public int getMountMode(int uid, String packageName) { 18022 if (Process.isIsolated(uid)) { 18023 return Zygote.MOUNT_EXTERNAL_NONE; 18024 } 18025 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18026 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18027 } 18028 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18029 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18030 } 18031 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18032 return Zygote.MOUNT_EXTERNAL_READ; 18033 } 18034 return Zygote.MOUNT_EXTERNAL_WRITE; 18035 } 18036 18037 @Override 18038 public boolean hasExternalStorage(int uid, String packageName) { 18039 return true; 18040 } 18041 }); 18042 18043 // Now that we're mostly running, clean up stale users and apps 18044 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18045 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18046 } 18047 18048 @Override 18049 public boolean isSafeMode() { 18050 return mSafeMode; 18051 } 18052 18053 @Override 18054 public boolean hasSystemUidErrors() { 18055 return mHasSystemUidErrors; 18056 } 18057 18058 static String arrayToString(int[] array) { 18059 StringBuffer buf = new StringBuffer(128); 18060 buf.append('['); 18061 if (array != null) { 18062 for (int i=0; i<array.length; i++) { 18063 if (i > 0) buf.append(", "); 18064 buf.append(array[i]); 18065 } 18066 } 18067 buf.append(']'); 18068 return buf.toString(); 18069 } 18070 18071 static class DumpState { 18072 public static final int DUMP_LIBS = 1 << 0; 18073 public static final int DUMP_FEATURES = 1 << 1; 18074 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18075 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18076 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18077 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18078 public static final int DUMP_PERMISSIONS = 1 << 6; 18079 public static final int DUMP_PACKAGES = 1 << 7; 18080 public static final int DUMP_SHARED_USERS = 1 << 8; 18081 public static final int DUMP_MESSAGES = 1 << 9; 18082 public static final int DUMP_PROVIDERS = 1 << 10; 18083 public static final int DUMP_VERIFIERS = 1 << 11; 18084 public static final int DUMP_PREFERRED = 1 << 12; 18085 public static final int DUMP_PREFERRED_XML = 1 << 13; 18086 public static final int DUMP_KEYSETS = 1 << 14; 18087 public static final int DUMP_VERSION = 1 << 15; 18088 public static final int DUMP_INSTALLS = 1 << 16; 18089 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18090 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18091 public static final int DUMP_FROZEN = 1 << 19; 18092 public static final int DUMP_DEXOPT = 1 << 20; 18093 18094 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18095 18096 private int mTypes; 18097 18098 private int mOptions; 18099 18100 private boolean mTitlePrinted; 18101 18102 private SharedUserSetting mSharedUser; 18103 18104 public boolean isDumping(int type) { 18105 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18106 return true; 18107 } 18108 18109 return (mTypes & type) != 0; 18110 } 18111 18112 public void setDump(int type) { 18113 mTypes |= type; 18114 } 18115 18116 public boolean isOptionEnabled(int option) { 18117 return (mOptions & option) != 0; 18118 } 18119 18120 public void setOptionEnabled(int option) { 18121 mOptions |= option; 18122 } 18123 18124 public boolean onTitlePrinted() { 18125 final boolean printed = mTitlePrinted; 18126 mTitlePrinted = true; 18127 return printed; 18128 } 18129 18130 public boolean getTitlePrinted() { 18131 return mTitlePrinted; 18132 } 18133 18134 public void setTitlePrinted(boolean enabled) { 18135 mTitlePrinted = enabled; 18136 } 18137 18138 public SharedUserSetting getSharedUser() { 18139 return mSharedUser; 18140 } 18141 18142 public void setSharedUser(SharedUserSetting user) { 18143 mSharedUser = user; 18144 } 18145 } 18146 18147 @Override 18148 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18149 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18150 (new PackageManagerShellCommand(this)).exec( 18151 this, in, out, err, args, resultReceiver); 18152 } 18153 18154 @Override 18155 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18156 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18157 != PackageManager.PERMISSION_GRANTED) { 18158 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18159 + Binder.getCallingPid() 18160 + ", uid=" + Binder.getCallingUid() 18161 + " without permission " 18162 + android.Manifest.permission.DUMP); 18163 return; 18164 } 18165 18166 DumpState dumpState = new DumpState(); 18167 boolean fullPreferred = false; 18168 boolean checkin = false; 18169 18170 String packageName = null; 18171 ArraySet<String> permissionNames = null; 18172 18173 int opti = 0; 18174 while (opti < args.length) { 18175 String opt = args[opti]; 18176 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18177 break; 18178 } 18179 opti++; 18180 18181 if ("-a".equals(opt)) { 18182 // Right now we only know how to print all. 18183 } else if ("-h".equals(opt)) { 18184 pw.println("Package manager dump options:"); 18185 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18186 pw.println(" --checkin: dump for a checkin"); 18187 pw.println(" -f: print details of intent filters"); 18188 pw.println(" -h: print this help"); 18189 pw.println(" cmd may be one of:"); 18190 pw.println(" l[ibraries]: list known shared libraries"); 18191 pw.println(" f[eatures]: list device features"); 18192 pw.println(" k[eysets]: print known keysets"); 18193 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18194 pw.println(" perm[issions]: dump permissions"); 18195 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18196 pw.println(" pref[erred]: print preferred package settings"); 18197 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18198 pw.println(" prov[iders]: dump content providers"); 18199 pw.println(" p[ackages]: dump installed packages"); 18200 pw.println(" s[hared-users]: dump shared user IDs"); 18201 pw.println(" m[essages]: print collected runtime messages"); 18202 pw.println(" v[erifiers]: print package verifier info"); 18203 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18204 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18205 pw.println(" version: print database version info"); 18206 pw.println(" write: write current settings now"); 18207 pw.println(" installs: details about install sessions"); 18208 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18209 pw.println(" dexopt: dump dexopt state"); 18210 pw.println(" <package.name>: info about given package"); 18211 return; 18212 } else if ("--checkin".equals(opt)) { 18213 checkin = true; 18214 } else if ("-f".equals(opt)) { 18215 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18216 } else { 18217 pw.println("Unknown argument: " + opt + "; use -h for help"); 18218 } 18219 } 18220 18221 // Is the caller requesting to dump a particular piece of data? 18222 if (opti < args.length) { 18223 String cmd = args[opti]; 18224 opti++; 18225 // Is this a package name? 18226 if ("android".equals(cmd) || cmd.contains(".")) { 18227 packageName = cmd; 18228 // When dumping a single package, we always dump all of its 18229 // filter information since the amount of data will be reasonable. 18230 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18231 } else if ("check-permission".equals(cmd)) { 18232 if (opti >= args.length) { 18233 pw.println("Error: check-permission missing permission argument"); 18234 return; 18235 } 18236 String perm = args[opti]; 18237 opti++; 18238 if (opti >= args.length) { 18239 pw.println("Error: check-permission missing package argument"); 18240 return; 18241 } 18242 String pkg = args[opti]; 18243 opti++; 18244 int user = UserHandle.getUserId(Binder.getCallingUid()); 18245 if (opti < args.length) { 18246 try { 18247 user = Integer.parseInt(args[opti]); 18248 } catch (NumberFormatException e) { 18249 pw.println("Error: check-permission user argument is not a number: " 18250 + args[opti]); 18251 return; 18252 } 18253 } 18254 pw.println(checkPermission(perm, pkg, user)); 18255 return; 18256 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18257 dumpState.setDump(DumpState.DUMP_LIBS); 18258 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18259 dumpState.setDump(DumpState.DUMP_FEATURES); 18260 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18261 if (opti >= args.length) { 18262 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18263 | DumpState.DUMP_SERVICE_RESOLVERS 18264 | DumpState.DUMP_RECEIVER_RESOLVERS 18265 | DumpState.DUMP_CONTENT_RESOLVERS); 18266 } else { 18267 while (opti < args.length) { 18268 String name = args[opti]; 18269 if ("a".equals(name) || "activity".equals(name)) { 18270 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18271 } else if ("s".equals(name) || "service".equals(name)) { 18272 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18273 } else if ("r".equals(name) || "receiver".equals(name)) { 18274 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18275 } else if ("c".equals(name) || "content".equals(name)) { 18276 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18277 } else { 18278 pw.println("Error: unknown resolver table type: " + name); 18279 return; 18280 } 18281 opti++; 18282 } 18283 } 18284 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18285 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18286 } else if ("permission".equals(cmd)) { 18287 if (opti >= args.length) { 18288 pw.println("Error: permission requires permission name"); 18289 return; 18290 } 18291 permissionNames = new ArraySet<>(); 18292 while (opti < args.length) { 18293 permissionNames.add(args[opti]); 18294 opti++; 18295 } 18296 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18297 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18298 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18299 dumpState.setDump(DumpState.DUMP_PREFERRED); 18300 } else if ("preferred-xml".equals(cmd)) { 18301 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18302 if (opti < args.length && "--full".equals(args[opti])) { 18303 fullPreferred = true; 18304 opti++; 18305 } 18306 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18308 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18309 dumpState.setDump(DumpState.DUMP_PACKAGES); 18310 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18311 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18312 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18313 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18314 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18315 dumpState.setDump(DumpState.DUMP_MESSAGES); 18316 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18317 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18318 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18319 || "intent-filter-verifiers".equals(cmd)) { 18320 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18321 } else if ("version".equals(cmd)) { 18322 dumpState.setDump(DumpState.DUMP_VERSION); 18323 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18324 dumpState.setDump(DumpState.DUMP_KEYSETS); 18325 } else if ("installs".equals(cmd)) { 18326 dumpState.setDump(DumpState.DUMP_INSTALLS); 18327 } else if ("frozen".equals(cmd)) { 18328 dumpState.setDump(DumpState.DUMP_FROZEN); 18329 } else if ("dexopt".equals(cmd)) { 18330 dumpState.setDump(DumpState.DUMP_DEXOPT); 18331 } else if ("write".equals(cmd)) { 18332 synchronized (mPackages) { 18333 mSettings.writeLPr(); 18334 pw.println("Settings written."); 18335 return; 18336 } 18337 } 18338 } 18339 18340 if (checkin) { 18341 pw.println("vers,1"); 18342 } 18343 18344 // reader 18345 synchronized (mPackages) { 18346 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18347 if (!checkin) { 18348 if (dumpState.onTitlePrinted()) 18349 pw.println(); 18350 pw.println("Database versions:"); 18351 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18352 } 18353 } 18354 18355 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18356 if (!checkin) { 18357 if (dumpState.onTitlePrinted()) 18358 pw.println(); 18359 pw.println("Verifiers:"); 18360 pw.print(" Required: "); 18361 pw.print(mRequiredVerifierPackage); 18362 pw.print(" (uid="); 18363 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18364 UserHandle.USER_SYSTEM)); 18365 pw.println(")"); 18366 } else if (mRequiredVerifierPackage != null) { 18367 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18368 pw.print(","); 18369 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18370 UserHandle.USER_SYSTEM)); 18371 } 18372 } 18373 18374 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18375 packageName == null) { 18376 if (mIntentFilterVerifierComponent != null) { 18377 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18378 if (!checkin) { 18379 if (dumpState.onTitlePrinted()) 18380 pw.println(); 18381 pw.println("Intent Filter Verifier:"); 18382 pw.print(" Using: "); 18383 pw.print(verifierPackageName); 18384 pw.print(" (uid="); 18385 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18386 UserHandle.USER_SYSTEM)); 18387 pw.println(")"); 18388 } else if (verifierPackageName != null) { 18389 pw.print("ifv,"); pw.print(verifierPackageName); 18390 pw.print(","); 18391 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18392 UserHandle.USER_SYSTEM)); 18393 } 18394 } else { 18395 pw.println(); 18396 pw.println("No Intent Filter Verifier available!"); 18397 } 18398 } 18399 18400 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18401 boolean printedHeader = false; 18402 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18403 while (it.hasNext()) { 18404 String name = it.next(); 18405 SharedLibraryEntry ent = mSharedLibraries.get(name); 18406 if (!checkin) { 18407 if (!printedHeader) { 18408 if (dumpState.onTitlePrinted()) 18409 pw.println(); 18410 pw.println("Libraries:"); 18411 printedHeader = true; 18412 } 18413 pw.print(" "); 18414 } else { 18415 pw.print("lib,"); 18416 } 18417 pw.print(name); 18418 if (!checkin) { 18419 pw.print(" -> "); 18420 } 18421 if (ent.path != null) { 18422 if (!checkin) { 18423 pw.print("(jar) "); 18424 pw.print(ent.path); 18425 } else { 18426 pw.print(",jar,"); 18427 pw.print(ent.path); 18428 } 18429 } else { 18430 if (!checkin) { 18431 pw.print("(apk) "); 18432 pw.print(ent.apk); 18433 } else { 18434 pw.print(",apk,"); 18435 pw.print(ent.apk); 18436 } 18437 } 18438 pw.println(); 18439 } 18440 } 18441 18442 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18443 if (dumpState.onTitlePrinted()) 18444 pw.println(); 18445 if (!checkin) { 18446 pw.println("Features:"); 18447 } 18448 18449 for (FeatureInfo feat : mAvailableFeatures.values()) { 18450 if (checkin) { 18451 pw.print("feat,"); 18452 pw.print(feat.name); 18453 pw.print(","); 18454 pw.println(feat.version); 18455 } else { 18456 pw.print(" "); 18457 pw.print(feat.name); 18458 if (feat.version > 0) { 18459 pw.print(" version="); 18460 pw.print(feat.version); 18461 } 18462 pw.println(); 18463 } 18464 } 18465 } 18466 18467 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18468 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18469 : "Activity Resolver Table:", " ", packageName, 18470 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18471 dumpState.setTitlePrinted(true); 18472 } 18473 } 18474 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18475 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18476 : "Receiver Resolver Table:", " ", packageName, 18477 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18478 dumpState.setTitlePrinted(true); 18479 } 18480 } 18481 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18482 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18483 : "Service Resolver Table:", " ", packageName, 18484 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18485 dumpState.setTitlePrinted(true); 18486 } 18487 } 18488 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18489 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18490 : "Provider Resolver Table:", " ", packageName, 18491 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18492 dumpState.setTitlePrinted(true); 18493 } 18494 } 18495 18496 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18497 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18498 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18499 int user = mSettings.mPreferredActivities.keyAt(i); 18500 if (pir.dump(pw, 18501 dumpState.getTitlePrinted() 18502 ? "\nPreferred Activities User " + user + ":" 18503 : "Preferred Activities User " + user + ":", " ", 18504 packageName, true, false)) { 18505 dumpState.setTitlePrinted(true); 18506 } 18507 } 18508 } 18509 18510 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18511 pw.flush(); 18512 FileOutputStream fout = new FileOutputStream(fd); 18513 BufferedOutputStream str = new BufferedOutputStream(fout); 18514 XmlSerializer serializer = new FastXmlSerializer(); 18515 try { 18516 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18517 serializer.startDocument(null, true); 18518 serializer.setFeature( 18519 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18520 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18521 serializer.endDocument(); 18522 serializer.flush(); 18523 } catch (IllegalArgumentException e) { 18524 pw.println("Failed writing: " + e); 18525 } catch (IllegalStateException e) { 18526 pw.println("Failed writing: " + e); 18527 } catch (IOException e) { 18528 pw.println("Failed writing: " + e); 18529 } 18530 } 18531 18532 if (!checkin 18533 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18534 && packageName == null) { 18535 pw.println(); 18536 int count = mSettings.mPackages.size(); 18537 if (count == 0) { 18538 pw.println("No applications!"); 18539 pw.println(); 18540 } else { 18541 final String prefix = " "; 18542 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18543 if (allPackageSettings.size() == 0) { 18544 pw.println("No domain preferred apps!"); 18545 pw.println(); 18546 } else { 18547 pw.println("App verification status:"); 18548 pw.println(); 18549 count = 0; 18550 for (PackageSetting ps : allPackageSettings) { 18551 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18552 if (ivi == null || ivi.getPackageName() == null) continue; 18553 pw.println(prefix + "Package: " + ivi.getPackageName()); 18554 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18555 pw.println(prefix + "Status: " + ivi.getStatusString()); 18556 pw.println(); 18557 count++; 18558 } 18559 if (count == 0) { 18560 pw.println(prefix + "No app verification established."); 18561 pw.println(); 18562 } 18563 for (int userId : sUserManager.getUserIds()) { 18564 pw.println("App linkages for user " + userId + ":"); 18565 pw.println(); 18566 count = 0; 18567 for (PackageSetting ps : allPackageSettings) { 18568 final long status = ps.getDomainVerificationStatusForUser(userId); 18569 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18570 continue; 18571 } 18572 pw.println(prefix + "Package: " + ps.name); 18573 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18574 String statusStr = IntentFilterVerificationInfo. 18575 getStatusStringFromValue(status); 18576 pw.println(prefix + "Status: " + statusStr); 18577 pw.println(); 18578 count++; 18579 } 18580 if (count == 0) { 18581 pw.println(prefix + "No configured app linkages."); 18582 pw.println(); 18583 } 18584 } 18585 } 18586 } 18587 } 18588 18589 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18590 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18591 if (packageName == null && permissionNames == null) { 18592 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18593 if (iperm == 0) { 18594 if (dumpState.onTitlePrinted()) 18595 pw.println(); 18596 pw.println("AppOp Permissions:"); 18597 } 18598 pw.print(" AppOp Permission "); 18599 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18600 pw.println(":"); 18601 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18602 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18603 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18604 } 18605 } 18606 } 18607 } 18608 18609 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18610 boolean printedSomething = false; 18611 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18612 if (packageName != null && !packageName.equals(p.info.packageName)) { 18613 continue; 18614 } 18615 if (!printedSomething) { 18616 if (dumpState.onTitlePrinted()) 18617 pw.println(); 18618 pw.println("Registered ContentProviders:"); 18619 printedSomething = true; 18620 } 18621 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18622 pw.print(" "); pw.println(p.toString()); 18623 } 18624 printedSomething = false; 18625 for (Map.Entry<String, PackageParser.Provider> entry : 18626 mProvidersByAuthority.entrySet()) { 18627 PackageParser.Provider p = entry.getValue(); 18628 if (packageName != null && !packageName.equals(p.info.packageName)) { 18629 continue; 18630 } 18631 if (!printedSomething) { 18632 if (dumpState.onTitlePrinted()) 18633 pw.println(); 18634 pw.println("ContentProvider Authorities:"); 18635 printedSomething = true; 18636 } 18637 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18638 pw.print(" "); pw.println(p.toString()); 18639 if (p.info != null && p.info.applicationInfo != null) { 18640 final String appInfo = p.info.applicationInfo.toString(); 18641 pw.print(" applicationInfo="); pw.println(appInfo); 18642 } 18643 } 18644 } 18645 18646 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18647 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18648 } 18649 18650 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18651 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18652 } 18653 18654 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18655 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18656 } 18657 18658 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18659 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18660 } 18661 18662 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18663 // XXX should handle packageName != null by dumping only install data that 18664 // the given package is involved with. 18665 if (dumpState.onTitlePrinted()) pw.println(); 18666 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18667 } 18668 18669 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18670 // XXX should handle packageName != null by dumping only install data that 18671 // the given package is involved with. 18672 if (dumpState.onTitlePrinted()) pw.println(); 18673 18674 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18675 ipw.println(); 18676 ipw.println("Frozen packages:"); 18677 ipw.increaseIndent(); 18678 if (mFrozenPackages.size() == 0) { 18679 ipw.println("(none)"); 18680 } else { 18681 for (int i = 0; i < mFrozenPackages.size(); i++) { 18682 ipw.println(mFrozenPackages.valueAt(i)); 18683 } 18684 } 18685 ipw.decreaseIndent(); 18686 } 18687 18688 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18689 if (dumpState.onTitlePrinted()) pw.println(); 18690 dumpDexoptStateLPr(pw, packageName); 18691 } 18692 18693 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18694 if (dumpState.onTitlePrinted()) pw.println(); 18695 mSettings.dumpReadMessagesLPr(pw, dumpState); 18696 18697 pw.println(); 18698 pw.println("Package warning messages:"); 18699 BufferedReader in = null; 18700 String line = null; 18701 try { 18702 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18703 while ((line = in.readLine()) != null) { 18704 if (line.contains("ignored: updated version")) continue; 18705 pw.println(line); 18706 } 18707 } catch (IOException ignored) { 18708 } finally { 18709 IoUtils.closeQuietly(in); 18710 } 18711 } 18712 18713 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18714 BufferedReader in = null; 18715 String line = null; 18716 try { 18717 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18718 while ((line = in.readLine()) != null) { 18719 if (line.contains("ignored: updated version")) continue; 18720 pw.print("msg,"); 18721 pw.println(line); 18722 } 18723 } catch (IOException ignored) { 18724 } finally { 18725 IoUtils.closeQuietly(in); 18726 } 18727 } 18728 } 18729 } 18730 18731 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18732 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18733 ipw.println(); 18734 ipw.println("Dexopt state:"); 18735 ipw.increaseIndent(); 18736 Collection<PackageParser.Package> packages = null; 18737 if (packageName != null) { 18738 PackageParser.Package targetPackage = mPackages.get(packageName); 18739 if (targetPackage != null) { 18740 packages = Collections.singletonList(targetPackage); 18741 } else { 18742 ipw.println("Unable to find package: " + packageName); 18743 return; 18744 } 18745 } else { 18746 packages = mPackages.values(); 18747 } 18748 18749 for (PackageParser.Package pkg : packages) { 18750 ipw.println("[" + pkg.packageName + "]"); 18751 ipw.increaseIndent(); 18752 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18753 ipw.decreaseIndent(); 18754 } 18755 } 18756 18757 private String dumpDomainString(String packageName) { 18758 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18759 .getList(); 18760 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18761 18762 ArraySet<String> result = new ArraySet<>(); 18763 if (iviList.size() > 0) { 18764 for (IntentFilterVerificationInfo ivi : iviList) { 18765 for (String host : ivi.getDomains()) { 18766 result.add(host); 18767 } 18768 } 18769 } 18770 if (filters != null && filters.size() > 0) { 18771 for (IntentFilter filter : filters) { 18772 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18773 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18774 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18775 result.addAll(filter.getHostsList()); 18776 } 18777 } 18778 } 18779 18780 StringBuilder sb = new StringBuilder(result.size() * 16); 18781 for (String domain : result) { 18782 if (sb.length() > 0) sb.append(" "); 18783 sb.append(domain); 18784 } 18785 return sb.toString(); 18786 } 18787 18788 // ------- apps on sdcard specific code ------- 18789 static final boolean DEBUG_SD_INSTALL = false; 18790 18791 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18792 18793 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18794 18795 private boolean mMediaMounted = false; 18796 18797 static String getEncryptKey() { 18798 try { 18799 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18800 SD_ENCRYPTION_KEYSTORE_NAME); 18801 if (sdEncKey == null) { 18802 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18803 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18804 if (sdEncKey == null) { 18805 Slog.e(TAG, "Failed to create encryption keys"); 18806 return null; 18807 } 18808 } 18809 return sdEncKey; 18810 } catch (NoSuchAlgorithmException nsae) { 18811 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18812 return null; 18813 } catch (IOException ioe) { 18814 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18815 return null; 18816 } 18817 } 18818 18819 /* 18820 * Update media status on PackageManager. 18821 */ 18822 @Override 18823 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18824 int callingUid = Binder.getCallingUid(); 18825 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18826 throw new SecurityException("Media status can only be updated by the system"); 18827 } 18828 // reader; this apparently protects mMediaMounted, but should probably 18829 // be a different lock in that case. 18830 synchronized (mPackages) { 18831 Log.i(TAG, "Updating external media status from " 18832 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18833 + (mediaStatus ? "mounted" : "unmounted")); 18834 if (DEBUG_SD_INSTALL) 18835 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18836 + ", mMediaMounted=" + mMediaMounted); 18837 if (mediaStatus == mMediaMounted) { 18838 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18839 : 0, -1); 18840 mHandler.sendMessage(msg); 18841 return; 18842 } 18843 mMediaMounted = mediaStatus; 18844 } 18845 // Queue up an async operation since the package installation may take a 18846 // little while. 18847 mHandler.post(new Runnable() { 18848 public void run() { 18849 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18850 } 18851 }); 18852 } 18853 18854 /** 18855 * Called by MountService when the initial ASECs to scan are available. 18856 * Should block until all the ASEC containers are finished being scanned. 18857 */ 18858 public void scanAvailableAsecs() { 18859 updateExternalMediaStatusInner(true, false, false); 18860 } 18861 18862 /* 18863 * Collect information of applications on external media, map them against 18864 * existing containers and update information based on current mount status. 18865 * Please note that we always have to report status if reportStatus has been 18866 * set to true especially when unloading packages. 18867 */ 18868 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18869 boolean externalStorage) { 18870 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18871 int[] uidArr = EmptyArray.INT; 18872 18873 final String[] list = PackageHelper.getSecureContainerList(); 18874 if (ArrayUtils.isEmpty(list)) { 18875 Log.i(TAG, "No secure containers found"); 18876 } else { 18877 // Process list of secure containers and categorize them 18878 // as active or stale based on their package internal state. 18879 18880 // reader 18881 synchronized (mPackages) { 18882 for (String cid : list) { 18883 // Leave stages untouched for now; installer service owns them 18884 if (PackageInstallerService.isStageName(cid)) continue; 18885 18886 if (DEBUG_SD_INSTALL) 18887 Log.i(TAG, "Processing container " + cid); 18888 String pkgName = getAsecPackageName(cid); 18889 if (pkgName == null) { 18890 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18891 continue; 18892 } 18893 if (DEBUG_SD_INSTALL) 18894 Log.i(TAG, "Looking for pkg : " + pkgName); 18895 18896 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18897 if (ps == null) { 18898 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18899 continue; 18900 } 18901 18902 /* 18903 * Skip packages that are not external if we're unmounting 18904 * external storage. 18905 */ 18906 if (externalStorage && !isMounted && !isExternal(ps)) { 18907 continue; 18908 } 18909 18910 final AsecInstallArgs args = new AsecInstallArgs(cid, 18911 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18912 // The package status is changed only if the code path 18913 // matches between settings and the container id. 18914 if (ps.codePathString != null 18915 && ps.codePathString.startsWith(args.getCodePath())) { 18916 if (DEBUG_SD_INSTALL) { 18917 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18918 + " at code path: " + ps.codePathString); 18919 } 18920 18921 // We do have a valid package installed on sdcard 18922 processCids.put(args, ps.codePathString); 18923 final int uid = ps.appId; 18924 if (uid != -1) { 18925 uidArr = ArrayUtils.appendInt(uidArr, uid); 18926 } 18927 } else { 18928 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18929 + ps.codePathString); 18930 } 18931 } 18932 } 18933 18934 Arrays.sort(uidArr); 18935 } 18936 18937 // Process packages with valid entries. 18938 if (isMounted) { 18939 if (DEBUG_SD_INSTALL) 18940 Log.i(TAG, "Loading packages"); 18941 loadMediaPackages(processCids, uidArr, externalStorage); 18942 startCleaningPackages(); 18943 mInstallerService.onSecureContainersAvailable(); 18944 } else { 18945 if (DEBUG_SD_INSTALL) 18946 Log.i(TAG, "Unloading packages"); 18947 unloadMediaPackages(processCids, uidArr, reportStatus); 18948 } 18949 } 18950 18951 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18952 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18953 final int size = infos.size(); 18954 final String[] packageNames = new String[size]; 18955 final int[] packageUids = new int[size]; 18956 for (int i = 0; i < size; i++) { 18957 final ApplicationInfo info = infos.get(i); 18958 packageNames[i] = info.packageName; 18959 packageUids[i] = info.uid; 18960 } 18961 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18962 finishedReceiver); 18963 } 18964 18965 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18966 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18967 sendResourcesChangedBroadcast(mediaStatus, replacing, 18968 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18969 } 18970 18971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18972 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18973 int size = pkgList.length; 18974 if (size > 0) { 18975 // Send broadcasts here 18976 Bundle extras = new Bundle(); 18977 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18978 if (uidArr != null) { 18979 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18980 } 18981 if (replacing) { 18982 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18983 } 18984 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18985 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18986 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18987 } 18988 } 18989 18990 /* 18991 * Look at potentially valid container ids from processCids If package 18992 * information doesn't match the one on record or package scanning fails, 18993 * the cid is added to list of removeCids. We currently don't delete stale 18994 * containers. 18995 */ 18996 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18997 boolean externalStorage) { 18998 ArrayList<String> pkgList = new ArrayList<String>(); 18999 Set<AsecInstallArgs> keys = processCids.keySet(); 19000 19001 for (AsecInstallArgs args : keys) { 19002 String codePath = processCids.get(args); 19003 if (DEBUG_SD_INSTALL) 19004 Log.i(TAG, "Loading container : " + args.cid); 19005 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19006 try { 19007 // Make sure there are no container errors first. 19008 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19009 Slog.e(TAG, "Failed to mount cid : " + args.cid 19010 + " when installing from sdcard"); 19011 continue; 19012 } 19013 // Check code path here. 19014 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19015 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19016 + " does not match one in settings " + codePath); 19017 continue; 19018 } 19019 // Parse package 19020 int parseFlags = mDefParseFlags; 19021 if (args.isExternalAsec()) { 19022 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19023 } 19024 if (args.isFwdLocked()) { 19025 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19026 } 19027 19028 synchronized (mInstallLock) { 19029 PackageParser.Package pkg = null; 19030 try { 19031 // Sadly we don't know the package name yet to freeze it 19032 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19033 SCAN_IGNORE_FROZEN, 0, null); 19034 } catch (PackageManagerException e) { 19035 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19036 } 19037 // Scan the package 19038 if (pkg != null) { 19039 /* 19040 * TODO why is the lock being held? doPostInstall is 19041 * called in other places without the lock. This needs 19042 * to be straightened out. 19043 */ 19044 // writer 19045 synchronized (mPackages) { 19046 retCode = PackageManager.INSTALL_SUCCEEDED; 19047 pkgList.add(pkg.packageName); 19048 // Post process args 19049 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19050 pkg.applicationInfo.uid); 19051 } 19052 } else { 19053 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19054 } 19055 } 19056 19057 } finally { 19058 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19059 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19060 } 19061 } 19062 } 19063 // writer 19064 synchronized (mPackages) { 19065 // If the platform SDK has changed since the last time we booted, 19066 // we need to re-grant app permission to catch any new ones that 19067 // appear. This is really a hack, and means that apps can in some 19068 // cases get permissions that the user didn't initially explicitly 19069 // allow... it would be nice to have some better way to handle 19070 // this situation. 19071 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19072 : mSettings.getInternalVersion(); 19073 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19074 : StorageManager.UUID_PRIVATE_INTERNAL; 19075 19076 int updateFlags = UPDATE_PERMISSIONS_ALL; 19077 if (ver.sdkVersion != mSdkVersion) { 19078 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19079 + mSdkVersion + "; regranting permissions for external"); 19080 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19081 } 19082 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19083 19084 // Yay, everything is now upgraded 19085 ver.forceCurrent(); 19086 19087 // can downgrade to reader 19088 // Persist settings 19089 mSettings.writeLPr(); 19090 } 19091 // Send a broadcast to let everyone know we are done processing 19092 if (pkgList.size() > 0) { 19093 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19094 } 19095 } 19096 19097 /* 19098 * Utility method to unload a list of specified containers 19099 */ 19100 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19101 // Just unmount all valid containers. 19102 for (AsecInstallArgs arg : cidArgs) { 19103 synchronized (mInstallLock) { 19104 arg.doPostDeleteLI(false); 19105 } 19106 } 19107 } 19108 19109 /* 19110 * Unload packages mounted on external media. This involves deleting package 19111 * data from internal structures, sending broadcasts about disabled packages, 19112 * gc'ing to free up references, unmounting all secure containers 19113 * corresponding to packages on external media, and posting a 19114 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19115 * that we always have to post this message if status has been requested no 19116 * matter what. 19117 */ 19118 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19119 final boolean reportStatus) { 19120 if (DEBUG_SD_INSTALL) 19121 Log.i(TAG, "unloading media packages"); 19122 ArrayList<String> pkgList = new ArrayList<String>(); 19123 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19124 final Set<AsecInstallArgs> keys = processCids.keySet(); 19125 for (AsecInstallArgs args : keys) { 19126 String pkgName = args.getPackageName(); 19127 if (DEBUG_SD_INSTALL) 19128 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19129 // Delete package internally 19130 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19131 synchronized (mInstallLock) { 19132 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19133 final boolean res; 19134 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19135 "unloadMediaPackages")) { 19136 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19137 null); 19138 } 19139 if (res) { 19140 pkgList.add(pkgName); 19141 } else { 19142 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19143 failedList.add(args); 19144 } 19145 } 19146 } 19147 19148 // reader 19149 synchronized (mPackages) { 19150 // We didn't update the settings after removing each package; 19151 // write them now for all packages. 19152 mSettings.writeLPr(); 19153 } 19154 19155 // We have to absolutely send UPDATED_MEDIA_STATUS only 19156 // after confirming that all the receivers processed the ordered 19157 // broadcast when packages get disabled, force a gc to clean things up. 19158 // and unload all the containers. 19159 if (pkgList.size() > 0) { 19160 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19161 new IIntentReceiver.Stub() { 19162 public void performReceive(Intent intent, int resultCode, String data, 19163 Bundle extras, boolean ordered, boolean sticky, 19164 int sendingUser) throws RemoteException { 19165 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19166 reportStatus ? 1 : 0, 1, keys); 19167 mHandler.sendMessage(msg); 19168 } 19169 }); 19170 } else { 19171 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19172 keys); 19173 mHandler.sendMessage(msg); 19174 } 19175 } 19176 19177 private void loadPrivatePackages(final VolumeInfo vol) { 19178 mHandler.post(new Runnable() { 19179 @Override 19180 public void run() { 19181 loadPrivatePackagesInner(vol); 19182 } 19183 }); 19184 } 19185 19186 private void loadPrivatePackagesInner(VolumeInfo vol) { 19187 final String volumeUuid = vol.fsUuid; 19188 if (TextUtils.isEmpty(volumeUuid)) { 19189 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19190 return; 19191 } 19192 19193 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19194 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19195 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19196 19197 final VersionInfo ver; 19198 final List<PackageSetting> packages; 19199 synchronized (mPackages) { 19200 ver = mSettings.findOrCreateVersion(volumeUuid); 19201 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19202 } 19203 19204 for (PackageSetting ps : packages) { 19205 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19206 synchronized (mInstallLock) { 19207 final PackageParser.Package pkg; 19208 try { 19209 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19210 loaded.add(pkg.applicationInfo); 19211 19212 } catch (PackageManagerException e) { 19213 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19214 } 19215 19216 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19217 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19218 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19219 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19220 } 19221 } 19222 } 19223 19224 // Reconcile app data for all started/unlocked users 19225 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19226 final UserManager um = mContext.getSystemService(UserManager.class); 19227 UserManagerInternal umInternal = getUserManagerInternal(); 19228 for (UserInfo user : um.getUsers()) { 19229 final int flags; 19230 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19231 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19232 } else if (umInternal.isUserRunning(user.id)) { 19233 flags = StorageManager.FLAG_STORAGE_DE; 19234 } else { 19235 continue; 19236 } 19237 19238 try { 19239 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19240 synchronized (mInstallLock) { 19241 reconcileAppsDataLI(volumeUuid, user.id, flags); 19242 } 19243 } catch (IllegalStateException e) { 19244 // Device was probably ejected, and we'll process that event momentarily 19245 Slog.w(TAG, "Failed to prepare storage: " + e); 19246 } 19247 } 19248 19249 synchronized (mPackages) { 19250 int updateFlags = UPDATE_PERMISSIONS_ALL; 19251 if (ver.sdkVersion != mSdkVersion) { 19252 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19253 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19254 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19255 } 19256 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19257 19258 // Yay, everything is now upgraded 19259 ver.forceCurrent(); 19260 19261 mSettings.writeLPr(); 19262 } 19263 19264 for (PackageFreezer freezer : freezers) { 19265 freezer.close(); 19266 } 19267 19268 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19269 sendResourcesChangedBroadcast(true, false, loaded, null); 19270 } 19271 19272 private void unloadPrivatePackages(final VolumeInfo vol) { 19273 mHandler.post(new Runnable() { 19274 @Override 19275 public void run() { 19276 unloadPrivatePackagesInner(vol); 19277 } 19278 }); 19279 } 19280 19281 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19282 final String volumeUuid = vol.fsUuid; 19283 if (TextUtils.isEmpty(volumeUuid)) { 19284 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19285 return; 19286 } 19287 19288 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19289 synchronized (mInstallLock) { 19290 synchronized (mPackages) { 19291 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19292 for (PackageSetting ps : packages) { 19293 if (ps.pkg == null) continue; 19294 19295 final ApplicationInfo info = ps.pkg.applicationInfo; 19296 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19297 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19298 19299 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19300 "unloadPrivatePackagesInner")) { 19301 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19302 false, null)) { 19303 unloaded.add(info); 19304 } else { 19305 Slog.w(TAG, "Failed to unload " + ps.codePath); 19306 } 19307 } 19308 19309 // Try very hard to release any references to this package 19310 // so we don't risk the system server being killed due to 19311 // open FDs 19312 AttributeCache.instance().removePackage(ps.name); 19313 } 19314 19315 mSettings.writeLPr(); 19316 } 19317 } 19318 19319 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19320 sendResourcesChangedBroadcast(false, false, unloaded, null); 19321 19322 // Try very hard to release any references to this path so we don't risk 19323 // the system server being killed due to open FDs 19324 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19325 19326 for (int i = 0; i < 3; i++) { 19327 System.gc(); 19328 System.runFinalization(); 19329 } 19330 } 19331 19332 /** 19333 * Prepare storage areas for given user on all mounted devices. 19334 */ 19335 void prepareUserData(int userId, int userSerial, int flags) { 19336 synchronized (mInstallLock) { 19337 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19338 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19339 final String volumeUuid = vol.getFsUuid(); 19340 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19341 } 19342 } 19343 } 19344 19345 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19346 boolean allowRecover) { 19347 // Prepare storage and verify that serial numbers are consistent; if 19348 // there's a mismatch we need to destroy to avoid leaking data 19349 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19350 try { 19351 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19352 19353 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19354 UserManagerService.enforceSerialNumber( 19355 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19356 } 19357 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19358 UserManagerService.enforceSerialNumber( 19359 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19360 } 19361 19362 synchronized (mInstallLock) { 19363 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19364 } 19365 } catch (Exception e) { 19366 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19367 + " because we failed to prepare: " + e); 19368 destroyUserDataLI(volumeUuid, userId, 19369 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19370 19371 if (allowRecover) { 19372 // Try one last time; if we fail again we're really in trouble 19373 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19374 } 19375 } 19376 } 19377 19378 /** 19379 * Destroy storage areas for given user on all mounted devices. 19380 */ 19381 void destroyUserData(int userId, int flags) { 19382 synchronized (mInstallLock) { 19383 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19384 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19385 final String volumeUuid = vol.getFsUuid(); 19386 destroyUserDataLI(volumeUuid, userId, flags); 19387 } 19388 } 19389 } 19390 19391 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19392 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19393 try { 19394 // Clean up app data, profile data, and media data 19395 mInstaller.destroyUserData(volumeUuid, userId, flags); 19396 19397 // Clean up system data 19398 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19399 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19400 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19401 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19402 } 19403 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19404 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19405 } 19406 } 19407 19408 // Data with special labels is now gone, so finish the job 19409 storage.destroyUserStorage(volumeUuid, userId, flags); 19410 19411 } catch (Exception e) { 19412 logCriticalInfo(Log.WARN, 19413 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19414 } 19415 } 19416 19417 /** 19418 * Examine all users present on given mounted volume, and destroy data 19419 * belonging to users that are no longer valid, or whose user ID has been 19420 * recycled. 19421 */ 19422 private void reconcileUsers(String volumeUuid) { 19423 final List<File> files = new ArrayList<>(); 19424 Collections.addAll(files, FileUtils 19425 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19426 Collections.addAll(files, FileUtils 19427 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19428 for (File file : files) { 19429 if (!file.isDirectory()) continue; 19430 19431 final int userId; 19432 final UserInfo info; 19433 try { 19434 userId = Integer.parseInt(file.getName()); 19435 info = sUserManager.getUserInfo(userId); 19436 } catch (NumberFormatException e) { 19437 Slog.w(TAG, "Invalid user directory " + file); 19438 continue; 19439 } 19440 19441 boolean destroyUser = false; 19442 if (info == null) { 19443 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19444 + " because no matching user was found"); 19445 destroyUser = true; 19446 } else if (!mOnlyCore) { 19447 try { 19448 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19449 } catch (IOException e) { 19450 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19451 + " because we failed to enforce serial number: " + e); 19452 destroyUser = true; 19453 } 19454 } 19455 19456 if (destroyUser) { 19457 synchronized (mInstallLock) { 19458 destroyUserDataLI(volumeUuid, userId, 19459 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19460 } 19461 } 19462 } 19463 } 19464 19465 private void assertPackageKnown(String volumeUuid, String packageName) 19466 throws PackageManagerException { 19467 synchronized (mPackages) { 19468 final PackageSetting ps = mSettings.mPackages.get(packageName); 19469 if (ps == null) { 19470 throw new PackageManagerException("Package " + packageName + " is unknown"); 19471 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19472 throw new PackageManagerException( 19473 "Package " + packageName + " found on unknown volume " + volumeUuid 19474 + "; expected volume " + ps.volumeUuid); 19475 } 19476 } 19477 } 19478 19479 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19480 throws PackageManagerException { 19481 synchronized (mPackages) { 19482 final PackageSetting ps = mSettings.mPackages.get(packageName); 19483 if (ps == null) { 19484 throw new PackageManagerException("Package " + packageName + " is unknown"); 19485 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19486 throw new PackageManagerException( 19487 "Package " + packageName + " found on unknown volume " + volumeUuid 19488 + "; expected volume " + ps.volumeUuid); 19489 } else if (!ps.getInstalled(userId)) { 19490 throw new PackageManagerException( 19491 "Package " + packageName + " not installed for user " + userId); 19492 } 19493 } 19494 } 19495 19496 /** 19497 * Examine all apps present on given mounted volume, and destroy apps that 19498 * aren't expected, either due to uninstallation or reinstallation on 19499 * another volume. 19500 */ 19501 private void reconcileApps(String volumeUuid) { 19502 final File[] files = FileUtils 19503 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19504 for (File file : files) { 19505 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19506 && !PackageInstallerService.isStageName(file.getName()); 19507 if (!isPackage) { 19508 // Ignore entries which are not packages 19509 continue; 19510 } 19511 19512 try { 19513 final PackageLite pkg = PackageParser.parsePackageLite(file, 19514 PackageParser.PARSE_MUST_BE_APK); 19515 assertPackageKnown(volumeUuid, pkg.packageName); 19516 19517 } catch (PackageParserException | PackageManagerException e) { 19518 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19519 synchronized (mInstallLock) { 19520 removeCodePathLI(file); 19521 } 19522 } 19523 } 19524 } 19525 19526 /** 19527 * Reconcile all app data for the given user. 19528 * <p> 19529 * Verifies that directories exist and that ownership and labeling is 19530 * correct for all installed apps on all mounted volumes. 19531 */ 19532 void reconcileAppsData(int userId, int flags) { 19533 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19534 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19535 final String volumeUuid = vol.getFsUuid(); 19536 synchronized (mInstallLock) { 19537 reconcileAppsDataLI(volumeUuid, userId, flags); 19538 } 19539 } 19540 } 19541 19542 /** 19543 * Reconcile all app data on given mounted volume. 19544 * <p> 19545 * Destroys app data that isn't expected, either due to uninstallation or 19546 * reinstallation on another volume. 19547 * <p> 19548 * Verifies that directories exist and that ownership and labeling is 19549 * correct for all installed apps. 19550 */ 19551 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19552 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19553 + Integer.toHexString(flags)); 19554 19555 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19556 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19557 19558 boolean restoreconNeeded = false; 19559 19560 // First look for stale data that doesn't belong, and check if things 19561 // have changed since we did our last restorecon 19562 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19563 if (StorageManager.isFileEncryptedNativeOrEmulated() 19564 && !StorageManager.isUserKeyUnlocked(userId)) { 19565 throw new RuntimeException( 19566 "Yikes, someone asked us to reconcile CE storage while " + userId 19567 + " was still locked; this would have caused massive data loss!"); 19568 } 19569 19570 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19571 19572 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19573 for (File file : files) { 19574 final String packageName = file.getName(); 19575 try { 19576 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19577 } catch (PackageManagerException e) { 19578 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19579 try { 19580 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19581 StorageManager.FLAG_STORAGE_CE, 0); 19582 } catch (InstallerException e2) { 19583 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19584 } 19585 } 19586 } 19587 } 19588 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19589 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19590 19591 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19592 for (File file : files) { 19593 final String packageName = file.getName(); 19594 try { 19595 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19596 } catch (PackageManagerException e) { 19597 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19598 try { 19599 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19600 StorageManager.FLAG_STORAGE_DE, 0); 19601 } catch (InstallerException e2) { 19602 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19603 } 19604 } 19605 } 19606 } 19607 19608 // Ensure that data directories are ready to roll for all packages 19609 // installed for this volume and user 19610 final List<PackageSetting> packages; 19611 synchronized (mPackages) { 19612 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19613 } 19614 int preparedCount = 0; 19615 for (PackageSetting ps : packages) { 19616 final String packageName = ps.name; 19617 if (ps.pkg == null) { 19618 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19619 // TODO: might be due to legacy ASEC apps; we should circle back 19620 // and reconcile again once they're scanned 19621 continue; 19622 } 19623 19624 if (ps.getInstalled(userId)) { 19625 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19626 19627 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19628 // We may have just shuffled around app data directories, so 19629 // prepare them one more time 19630 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19631 } 19632 19633 preparedCount++; 19634 } 19635 } 19636 19637 if (restoreconNeeded) { 19638 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19639 SELinuxMMAC.setRestoreconDone(ceDir); 19640 } 19641 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19642 SELinuxMMAC.setRestoreconDone(deDir); 19643 } 19644 } 19645 19646 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19647 + " packages; restoreconNeeded was " + restoreconNeeded); 19648 } 19649 19650 /** 19651 * Prepare app data for the given app just after it was installed or 19652 * upgraded. This method carefully only touches users that it's installed 19653 * for, and it forces a restorecon to handle any seinfo changes. 19654 * <p> 19655 * Verifies that directories exist and that ownership and labeling is 19656 * correct for all installed apps. If there is an ownership mismatch, it 19657 * will try recovering system apps by wiping data; third-party app data is 19658 * left intact. 19659 * <p> 19660 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19661 */ 19662 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19663 final PackageSetting ps; 19664 synchronized (mPackages) { 19665 ps = mSettings.mPackages.get(pkg.packageName); 19666 mSettings.writeKernelMappingLPr(ps); 19667 } 19668 19669 final UserManager um = mContext.getSystemService(UserManager.class); 19670 UserManagerInternal umInternal = getUserManagerInternal(); 19671 for (UserInfo user : um.getUsers()) { 19672 final int flags; 19673 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19674 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19675 } else if (umInternal.isUserRunning(user.id)) { 19676 flags = StorageManager.FLAG_STORAGE_DE; 19677 } else { 19678 continue; 19679 } 19680 19681 if (ps.getInstalled(user.id)) { 19682 // Whenever an app changes, force a restorecon of its data 19683 // TODO: when user data is locked, mark that we're still dirty 19684 prepareAppDataLIF(pkg, user.id, flags, true); 19685 } 19686 } 19687 } 19688 19689 /** 19690 * Prepare app data for the given app. 19691 * <p> 19692 * Verifies that directories exist and that ownership and labeling is 19693 * correct for all installed apps. If there is an ownership mismatch, this 19694 * will try recovering system apps by wiping data; third-party app data is 19695 * left intact. 19696 */ 19697 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19698 boolean restoreconNeeded) { 19699 if (pkg == null) { 19700 Slog.wtf(TAG, "Package was null!", new Throwable()); 19701 return; 19702 } 19703 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19704 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19705 for (int i = 0; i < childCount; i++) { 19706 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19707 } 19708 } 19709 19710 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19711 boolean restoreconNeeded) { 19712 if (DEBUG_APP_DATA) { 19713 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19714 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19715 } 19716 19717 final String volumeUuid = pkg.volumeUuid; 19718 final String packageName = pkg.packageName; 19719 final ApplicationInfo app = pkg.applicationInfo; 19720 final int appId = UserHandle.getAppId(app.uid); 19721 19722 Preconditions.checkNotNull(app.seinfo); 19723 19724 try { 19725 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19726 appId, app.seinfo, app.targetSdkVersion); 19727 } catch (InstallerException e) { 19728 if (app.isSystemApp()) { 19729 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19730 + ", but trying to recover: " + e); 19731 destroyAppDataLeafLIF(pkg, userId, flags); 19732 try { 19733 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19734 appId, app.seinfo, app.targetSdkVersion); 19735 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19736 } catch (InstallerException e2) { 19737 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19738 } 19739 } else { 19740 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19741 } 19742 } 19743 19744 if (restoreconNeeded) { 19745 try { 19746 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19747 app.seinfo); 19748 } catch (InstallerException e) { 19749 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19750 } 19751 } 19752 19753 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19754 try { 19755 // CE storage is unlocked right now, so read out the inode and 19756 // remember for use later when it's locked 19757 // TODO: mark this structure as dirty so we persist it! 19758 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19759 StorageManager.FLAG_STORAGE_CE); 19760 synchronized (mPackages) { 19761 final PackageSetting ps = mSettings.mPackages.get(packageName); 19762 if (ps != null) { 19763 ps.setCeDataInode(ceDataInode, userId); 19764 } 19765 } 19766 } catch (InstallerException e) { 19767 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19768 } 19769 } 19770 19771 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19772 } 19773 19774 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19775 if (pkg == null) { 19776 Slog.wtf(TAG, "Package was null!", new Throwable()); 19777 return; 19778 } 19779 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19780 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19781 for (int i = 0; i < childCount; i++) { 19782 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19783 } 19784 } 19785 19786 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19787 final String volumeUuid = pkg.volumeUuid; 19788 final String packageName = pkg.packageName; 19789 final ApplicationInfo app = pkg.applicationInfo; 19790 19791 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19792 // Create a native library symlink only if we have native libraries 19793 // and if the native libraries are 32 bit libraries. We do not provide 19794 // this symlink for 64 bit libraries. 19795 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19796 final String nativeLibPath = app.nativeLibraryDir; 19797 try { 19798 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19799 nativeLibPath, userId); 19800 } catch (InstallerException e) { 19801 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19802 } 19803 } 19804 } 19805 } 19806 19807 /** 19808 * For system apps on non-FBE devices, this method migrates any existing 19809 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19810 * requested by the app. 19811 */ 19812 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19813 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19814 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19815 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19816 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19817 try { 19818 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19819 storageTarget); 19820 } catch (InstallerException e) { 19821 logCriticalInfo(Log.WARN, 19822 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19823 } 19824 return true; 19825 } else { 19826 return false; 19827 } 19828 } 19829 19830 public PackageFreezer freezePackage(String packageName, String killReason) { 19831 return new PackageFreezer(packageName, killReason); 19832 } 19833 19834 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19835 String killReason) { 19836 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19837 return new PackageFreezer(); 19838 } else { 19839 return freezePackage(packageName, killReason); 19840 } 19841 } 19842 19843 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19844 String killReason) { 19845 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19846 return new PackageFreezer(); 19847 } else { 19848 return freezePackage(packageName, killReason); 19849 } 19850 } 19851 19852 /** 19853 * Class that freezes and kills the given package upon creation, and 19854 * unfreezes it upon closing. This is typically used when doing surgery on 19855 * app code/data to prevent the app from running while you're working. 19856 */ 19857 private class PackageFreezer implements AutoCloseable { 19858 private final String mPackageName; 19859 private final PackageFreezer[] mChildren; 19860 19861 private final boolean mWeFroze; 19862 19863 private final AtomicBoolean mClosed = new AtomicBoolean(); 19864 private final CloseGuard mCloseGuard = CloseGuard.get(); 19865 19866 /** 19867 * Create and return a stub freezer that doesn't actually do anything, 19868 * typically used when someone requested 19869 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19870 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19871 */ 19872 public PackageFreezer() { 19873 mPackageName = null; 19874 mChildren = null; 19875 mWeFroze = false; 19876 mCloseGuard.open("close"); 19877 } 19878 19879 public PackageFreezer(String packageName, String killReason) { 19880 synchronized (mPackages) { 19881 mPackageName = packageName; 19882 mWeFroze = mFrozenPackages.add(mPackageName); 19883 19884 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19885 if (ps != null) { 19886 killApplication(ps.name, ps.appId, killReason); 19887 } 19888 19889 final PackageParser.Package p = mPackages.get(packageName); 19890 if (p != null && p.childPackages != null) { 19891 final int N = p.childPackages.size(); 19892 mChildren = new PackageFreezer[N]; 19893 for (int i = 0; i < N; i++) { 19894 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19895 killReason); 19896 } 19897 } else { 19898 mChildren = null; 19899 } 19900 } 19901 mCloseGuard.open("close"); 19902 } 19903 19904 @Override 19905 protected void finalize() throws Throwable { 19906 try { 19907 mCloseGuard.warnIfOpen(); 19908 close(); 19909 } finally { 19910 super.finalize(); 19911 } 19912 } 19913 19914 @Override 19915 public void close() { 19916 mCloseGuard.close(); 19917 if (mClosed.compareAndSet(false, true)) { 19918 synchronized (mPackages) { 19919 if (mWeFroze) { 19920 mFrozenPackages.remove(mPackageName); 19921 } 19922 19923 if (mChildren != null) { 19924 for (PackageFreezer freezer : mChildren) { 19925 freezer.close(); 19926 } 19927 } 19928 } 19929 } 19930 } 19931 } 19932 19933 /** 19934 * Verify that given package is currently frozen. 19935 */ 19936 private void checkPackageFrozen(String packageName) { 19937 synchronized (mPackages) { 19938 if (!mFrozenPackages.contains(packageName)) { 19939 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19940 } 19941 } 19942 } 19943 19944 @Override 19945 public int movePackage(final String packageName, final String volumeUuid) { 19946 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19947 19948 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19949 final int moveId = mNextMoveId.getAndIncrement(); 19950 mHandler.post(new Runnable() { 19951 @Override 19952 public void run() { 19953 try { 19954 movePackageInternal(packageName, volumeUuid, moveId, user); 19955 } catch (PackageManagerException e) { 19956 Slog.w(TAG, "Failed to move " + packageName, e); 19957 mMoveCallbacks.notifyStatusChanged(moveId, 19958 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19959 } 19960 } 19961 }); 19962 return moveId; 19963 } 19964 19965 private void movePackageInternal(final String packageName, final String volumeUuid, 19966 final int moveId, UserHandle user) throws PackageManagerException { 19967 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19968 final PackageManager pm = mContext.getPackageManager(); 19969 19970 final boolean currentAsec; 19971 final String currentVolumeUuid; 19972 final File codeFile; 19973 final String installerPackageName; 19974 final String packageAbiOverride; 19975 final int appId; 19976 final String seinfo; 19977 final String label; 19978 final int targetSdkVersion; 19979 final PackageFreezer freezer; 19980 final int[] installedUserIds; 19981 19982 // reader 19983 synchronized (mPackages) { 19984 final PackageParser.Package pkg = mPackages.get(packageName); 19985 final PackageSetting ps = mSettings.mPackages.get(packageName); 19986 if (pkg == null || ps == null) { 19987 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19988 } 19989 19990 if (pkg.applicationInfo.isSystemApp()) { 19991 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19992 "Cannot move system application"); 19993 } 19994 19995 if (pkg.applicationInfo.isExternalAsec()) { 19996 currentAsec = true; 19997 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19998 } else if (pkg.applicationInfo.isForwardLocked()) { 19999 currentAsec = true; 20000 currentVolumeUuid = "forward_locked"; 20001 } else { 20002 currentAsec = false; 20003 currentVolumeUuid = ps.volumeUuid; 20004 20005 final File probe = new File(pkg.codePath); 20006 final File probeOat = new File(probe, "oat"); 20007 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20008 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20009 "Move only supported for modern cluster style installs"); 20010 } 20011 } 20012 20013 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20014 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20015 "Package already moved to " + volumeUuid); 20016 } 20017 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20018 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20019 "Device admin cannot be moved"); 20020 } 20021 20022 if (mFrozenPackages.contains(packageName)) { 20023 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20024 "Failed to move already frozen package"); 20025 } 20026 20027 codeFile = new File(pkg.codePath); 20028 installerPackageName = ps.installerPackageName; 20029 packageAbiOverride = ps.cpuAbiOverrideString; 20030 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20031 seinfo = pkg.applicationInfo.seinfo; 20032 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20033 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20034 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20035 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20036 } 20037 20038 final Bundle extras = new Bundle(); 20039 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20040 extras.putString(Intent.EXTRA_TITLE, label); 20041 mMoveCallbacks.notifyCreated(moveId, extras); 20042 20043 int installFlags; 20044 final boolean moveCompleteApp; 20045 final File measurePath; 20046 20047 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20048 installFlags = INSTALL_INTERNAL; 20049 moveCompleteApp = !currentAsec; 20050 measurePath = Environment.getDataAppDirectory(volumeUuid); 20051 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20052 installFlags = INSTALL_EXTERNAL; 20053 moveCompleteApp = false; 20054 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20055 } else { 20056 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20057 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20058 || !volume.isMountedWritable()) { 20059 freezer.close(); 20060 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20061 "Move location not mounted private volume"); 20062 } 20063 20064 Preconditions.checkState(!currentAsec); 20065 20066 installFlags = INSTALL_INTERNAL; 20067 moveCompleteApp = true; 20068 measurePath = Environment.getDataAppDirectory(volumeUuid); 20069 } 20070 20071 final PackageStats stats = new PackageStats(null, -1); 20072 synchronized (mInstaller) { 20073 for (int userId : installedUserIds) { 20074 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20075 freezer.close(); 20076 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20077 "Failed to measure package size"); 20078 } 20079 } 20080 } 20081 20082 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20083 + stats.dataSize); 20084 20085 final long startFreeBytes = measurePath.getFreeSpace(); 20086 final long sizeBytes; 20087 if (moveCompleteApp) { 20088 sizeBytes = stats.codeSize + stats.dataSize; 20089 } else { 20090 sizeBytes = stats.codeSize; 20091 } 20092 20093 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20094 freezer.close(); 20095 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20096 "Not enough free space to move"); 20097 } 20098 20099 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20100 20101 final CountDownLatch installedLatch = new CountDownLatch(1); 20102 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20103 @Override 20104 public void onUserActionRequired(Intent intent) throws RemoteException { 20105 throw new IllegalStateException(); 20106 } 20107 20108 @Override 20109 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20110 Bundle extras) throws RemoteException { 20111 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20112 + PackageManager.installStatusToString(returnCode, msg)); 20113 20114 installedLatch.countDown(); 20115 freezer.close(); 20116 20117 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20118 switch (status) { 20119 case PackageInstaller.STATUS_SUCCESS: 20120 mMoveCallbacks.notifyStatusChanged(moveId, 20121 PackageManager.MOVE_SUCCEEDED); 20122 break; 20123 case PackageInstaller.STATUS_FAILURE_STORAGE: 20124 mMoveCallbacks.notifyStatusChanged(moveId, 20125 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20126 break; 20127 default: 20128 mMoveCallbacks.notifyStatusChanged(moveId, 20129 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20130 break; 20131 } 20132 } 20133 }; 20134 20135 final MoveInfo move; 20136 if (moveCompleteApp) { 20137 // Kick off a thread to report progress estimates 20138 new Thread() { 20139 @Override 20140 public void run() { 20141 while (true) { 20142 try { 20143 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20144 break; 20145 } 20146 } catch (InterruptedException ignored) { 20147 } 20148 20149 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20150 final int progress = 10 + (int) MathUtils.constrain( 20151 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20152 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20153 } 20154 } 20155 }.start(); 20156 20157 final String dataAppName = codeFile.getName(); 20158 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20159 dataAppName, appId, seinfo, targetSdkVersion); 20160 } else { 20161 move = null; 20162 } 20163 20164 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20165 20166 final Message msg = mHandler.obtainMessage(INIT_COPY); 20167 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20168 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20169 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20170 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20171 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20172 msg.obj = params; 20173 20174 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20175 System.identityHashCode(msg.obj)); 20176 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20177 System.identityHashCode(msg.obj)); 20178 20179 mHandler.sendMessage(msg); 20180 } 20181 20182 @Override 20183 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20184 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20185 20186 final int realMoveId = mNextMoveId.getAndIncrement(); 20187 final Bundle extras = new Bundle(); 20188 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20189 mMoveCallbacks.notifyCreated(realMoveId, extras); 20190 20191 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20192 @Override 20193 public void onCreated(int moveId, Bundle extras) { 20194 // Ignored 20195 } 20196 20197 @Override 20198 public void onStatusChanged(int moveId, int status, long estMillis) { 20199 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20200 } 20201 }; 20202 20203 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20204 storage.setPrimaryStorageUuid(volumeUuid, callback); 20205 return realMoveId; 20206 } 20207 20208 @Override 20209 public int getMoveStatus(int moveId) { 20210 mContext.enforceCallingOrSelfPermission( 20211 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20212 return mMoveCallbacks.mLastStatus.get(moveId); 20213 } 20214 20215 @Override 20216 public void registerMoveCallback(IPackageMoveObserver callback) { 20217 mContext.enforceCallingOrSelfPermission( 20218 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20219 mMoveCallbacks.register(callback); 20220 } 20221 20222 @Override 20223 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20224 mContext.enforceCallingOrSelfPermission( 20225 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20226 mMoveCallbacks.unregister(callback); 20227 } 20228 20229 @Override 20230 public boolean setInstallLocation(int loc) { 20231 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20232 null); 20233 if (getInstallLocation() == loc) { 20234 return true; 20235 } 20236 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20237 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20238 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20239 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20240 return true; 20241 } 20242 return false; 20243 } 20244 20245 @Override 20246 public int getInstallLocation() { 20247 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20248 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20249 PackageHelper.APP_INSTALL_AUTO); 20250 } 20251 20252 /** Called by UserManagerService */ 20253 void cleanUpUser(UserManagerService userManager, int userHandle) { 20254 synchronized (mPackages) { 20255 mDirtyUsers.remove(userHandle); 20256 mUserNeedsBadging.delete(userHandle); 20257 mSettings.removeUserLPw(userHandle); 20258 mPendingBroadcasts.remove(userHandle); 20259 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20260 removeUnusedPackagesLPw(userManager, userHandle); 20261 } 20262 } 20263 20264 /** 20265 * We're removing userHandle and would like to remove any downloaded packages 20266 * that are no longer in use by any other user. 20267 * @param userHandle the user being removed 20268 */ 20269 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20270 final boolean DEBUG_CLEAN_APKS = false; 20271 int [] users = userManager.getUserIds(); 20272 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20273 while (psit.hasNext()) { 20274 PackageSetting ps = psit.next(); 20275 if (ps.pkg == null) { 20276 continue; 20277 } 20278 final String packageName = ps.pkg.packageName; 20279 // Skip over if system app 20280 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20281 continue; 20282 } 20283 if (DEBUG_CLEAN_APKS) { 20284 Slog.i(TAG, "Checking package " + packageName); 20285 } 20286 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20287 if (keep) { 20288 if (DEBUG_CLEAN_APKS) { 20289 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20290 } 20291 } else { 20292 for (int i = 0; i < users.length; i++) { 20293 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20294 keep = true; 20295 if (DEBUG_CLEAN_APKS) { 20296 Slog.i(TAG, " Keeping package " + packageName + " for user " 20297 + users[i]); 20298 } 20299 break; 20300 } 20301 } 20302 } 20303 if (!keep) { 20304 if (DEBUG_CLEAN_APKS) { 20305 Slog.i(TAG, " Removing package " + packageName); 20306 } 20307 mHandler.post(new Runnable() { 20308 public void run() { 20309 deletePackageX(packageName, userHandle, 0); 20310 } //end run 20311 }); 20312 } 20313 } 20314 } 20315 20316 /** Called by UserManagerService */ 20317 void createNewUser(int userId) { 20318 synchronized (mInstallLock) { 20319 mSettings.createNewUserLI(this, mInstaller, userId); 20320 } 20321 synchronized (mPackages) { 20322 scheduleWritePackageRestrictionsLocked(userId); 20323 scheduleWritePackageListLocked(userId); 20324 applyFactoryDefaultBrowserLPw(userId); 20325 primeDomainVerificationsLPw(userId); 20326 } 20327 } 20328 20329 void onBeforeUserStartUninitialized(final int userId) { 20330 synchronized (mPackages) { 20331 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20332 return; 20333 } 20334 } 20335 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20336 // If permission review for legacy apps is required, we represent 20337 // dagerous permissions for such apps as always granted runtime 20338 // permissions to keep per user flag state whether review is needed. 20339 // Hence, if a new user is added we have to propagate dangerous 20340 // permission grants for these legacy apps. 20341 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20342 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20343 | UPDATE_PERMISSIONS_REPLACE_ALL); 20344 } 20345 } 20346 20347 @Override 20348 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20349 mContext.enforceCallingOrSelfPermission( 20350 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20351 "Only package verification agents can read the verifier device identity"); 20352 20353 synchronized (mPackages) { 20354 return mSettings.getVerifierDeviceIdentityLPw(); 20355 } 20356 } 20357 20358 @Override 20359 public void setPermissionEnforced(String permission, boolean enforced) { 20360 // TODO: Now that we no longer change GID for storage, this should to away. 20361 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20362 "setPermissionEnforced"); 20363 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20364 synchronized (mPackages) { 20365 if (mSettings.mReadExternalStorageEnforced == null 20366 || mSettings.mReadExternalStorageEnforced != enforced) { 20367 mSettings.mReadExternalStorageEnforced = enforced; 20368 mSettings.writeLPr(); 20369 } 20370 } 20371 // kill any non-foreground processes so we restart them and 20372 // grant/revoke the GID. 20373 final IActivityManager am = ActivityManagerNative.getDefault(); 20374 if (am != null) { 20375 final long token = Binder.clearCallingIdentity(); 20376 try { 20377 am.killProcessesBelowForeground("setPermissionEnforcement"); 20378 } catch (RemoteException e) { 20379 } finally { 20380 Binder.restoreCallingIdentity(token); 20381 } 20382 } 20383 } else { 20384 throw new IllegalArgumentException("No selective enforcement for " + permission); 20385 } 20386 } 20387 20388 @Override 20389 @Deprecated 20390 public boolean isPermissionEnforced(String permission) { 20391 return true; 20392 } 20393 20394 @Override 20395 public boolean isStorageLow() { 20396 final long token = Binder.clearCallingIdentity(); 20397 try { 20398 final DeviceStorageMonitorInternal 20399 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20400 if (dsm != null) { 20401 return dsm.isMemoryLow(); 20402 } else { 20403 return false; 20404 } 20405 } finally { 20406 Binder.restoreCallingIdentity(token); 20407 } 20408 } 20409 20410 @Override 20411 public IPackageInstaller getPackageInstaller() { 20412 return mInstallerService; 20413 } 20414 20415 private boolean userNeedsBadging(int userId) { 20416 int index = mUserNeedsBadging.indexOfKey(userId); 20417 if (index < 0) { 20418 final UserInfo userInfo; 20419 final long token = Binder.clearCallingIdentity(); 20420 try { 20421 userInfo = sUserManager.getUserInfo(userId); 20422 } finally { 20423 Binder.restoreCallingIdentity(token); 20424 } 20425 final boolean b; 20426 if (userInfo != null && userInfo.isManagedProfile()) { 20427 b = true; 20428 } else { 20429 b = false; 20430 } 20431 mUserNeedsBadging.put(userId, b); 20432 return b; 20433 } 20434 return mUserNeedsBadging.valueAt(index); 20435 } 20436 20437 @Override 20438 public KeySet getKeySetByAlias(String packageName, String alias) { 20439 if (packageName == null || alias == null) { 20440 return null; 20441 } 20442 synchronized(mPackages) { 20443 final PackageParser.Package pkg = mPackages.get(packageName); 20444 if (pkg == null) { 20445 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20446 throw new IllegalArgumentException("Unknown package: " + packageName); 20447 } 20448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20449 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20450 } 20451 } 20452 20453 @Override 20454 public KeySet getSigningKeySet(String packageName) { 20455 if (packageName == null) { 20456 return null; 20457 } 20458 synchronized(mPackages) { 20459 final PackageParser.Package pkg = mPackages.get(packageName); 20460 if (pkg == null) { 20461 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20462 throw new IllegalArgumentException("Unknown package: " + packageName); 20463 } 20464 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20465 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20466 throw new SecurityException("May not access signing KeySet of other apps."); 20467 } 20468 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20469 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20470 } 20471 } 20472 20473 @Override 20474 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20475 if (packageName == null || ks == null) { 20476 return false; 20477 } 20478 synchronized(mPackages) { 20479 final PackageParser.Package pkg = mPackages.get(packageName); 20480 if (pkg == null) { 20481 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20482 throw new IllegalArgumentException("Unknown package: " + packageName); 20483 } 20484 IBinder ksh = ks.getToken(); 20485 if (ksh instanceof KeySetHandle) { 20486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20487 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20488 } 20489 return false; 20490 } 20491 } 20492 20493 @Override 20494 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20495 if (packageName == null || ks == null) { 20496 return false; 20497 } 20498 synchronized(mPackages) { 20499 final PackageParser.Package pkg = mPackages.get(packageName); 20500 if (pkg == null) { 20501 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20502 throw new IllegalArgumentException("Unknown package: " + packageName); 20503 } 20504 IBinder ksh = ks.getToken(); 20505 if (ksh instanceof KeySetHandle) { 20506 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20507 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20508 } 20509 return false; 20510 } 20511 } 20512 20513 private void deletePackageIfUnusedLPr(final String packageName) { 20514 PackageSetting ps = mSettings.mPackages.get(packageName); 20515 if (ps == null) { 20516 return; 20517 } 20518 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20519 // TODO Implement atomic delete if package is unused 20520 // It is currently possible that the package will be deleted even if it is installed 20521 // after this method returns. 20522 mHandler.post(new Runnable() { 20523 public void run() { 20524 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20525 } 20526 }); 20527 } 20528 } 20529 20530 /** 20531 * Check and throw if the given before/after packages would be considered a 20532 * downgrade. 20533 */ 20534 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20535 throws PackageManagerException { 20536 if (after.versionCode < before.mVersionCode) { 20537 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20538 "Update version code " + after.versionCode + " is older than current " 20539 + before.mVersionCode); 20540 } else if (after.versionCode == before.mVersionCode) { 20541 if (after.baseRevisionCode < before.baseRevisionCode) { 20542 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20543 "Update base revision code " + after.baseRevisionCode 20544 + " is older than current " + before.baseRevisionCode); 20545 } 20546 20547 if (!ArrayUtils.isEmpty(after.splitNames)) { 20548 for (int i = 0; i < after.splitNames.length; i++) { 20549 final String splitName = after.splitNames[i]; 20550 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20551 if (j != -1) { 20552 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20553 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20554 "Update split " + splitName + " revision code " 20555 + after.splitRevisionCodes[i] + " is older than current " 20556 + before.splitRevisionCodes[j]); 20557 } 20558 } 20559 } 20560 } 20561 } 20562 } 20563 20564 private static class MoveCallbacks extends Handler { 20565 private static final int MSG_CREATED = 1; 20566 private static final int MSG_STATUS_CHANGED = 2; 20567 20568 private final RemoteCallbackList<IPackageMoveObserver> 20569 mCallbacks = new RemoteCallbackList<>(); 20570 20571 private final SparseIntArray mLastStatus = new SparseIntArray(); 20572 20573 public MoveCallbacks(Looper looper) { 20574 super(looper); 20575 } 20576 20577 public void register(IPackageMoveObserver callback) { 20578 mCallbacks.register(callback); 20579 } 20580 20581 public void unregister(IPackageMoveObserver callback) { 20582 mCallbacks.unregister(callback); 20583 } 20584 20585 @Override 20586 public void handleMessage(Message msg) { 20587 final SomeArgs args = (SomeArgs) msg.obj; 20588 final int n = mCallbacks.beginBroadcast(); 20589 for (int i = 0; i < n; i++) { 20590 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20591 try { 20592 invokeCallback(callback, msg.what, args); 20593 } catch (RemoteException ignored) { 20594 } 20595 } 20596 mCallbacks.finishBroadcast(); 20597 args.recycle(); 20598 } 20599 20600 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20601 throws RemoteException { 20602 switch (what) { 20603 case MSG_CREATED: { 20604 callback.onCreated(args.argi1, (Bundle) args.arg2); 20605 break; 20606 } 20607 case MSG_STATUS_CHANGED: { 20608 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20609 break; 20610 } 20611 } 20612 } 20613 20614 private void notifyCreated(int moveId, Bundle extras) { 20615 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20616 20617 final SomeArgs args = SomeArgs.obtain(); 20618 args.argi1 = moveId; 20619 args.arg2 = extras; 20620 obtainMessage(MSG_CREATED, args).sendToTarget(); 20621 } 20622 20623 private void notifyStatusChanged(int moveId, int status) { 20624 notifyStatusChanged(moveId, status, -1); 20625 } 20626 20627 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20628 Slog.v(TAG, "Move " + moveId + " status " + status); 20629 20630 final SomeArgs args = SomeArgs.obtain(); 20631 args.argi1 = moveId; 20632 args.argi2 = status; 20633 args.arg3 = estMillis; 20634 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20635 20636 synchronized (mLastStatus) { 20637 mLastStatus.put(moveId, status); 20638 } 20639 } 20640 } 20641 20642 private final static class OnPermissionChangeListeners extends Handler { 20643 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20644 20645 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20646 new RemoteCallbackList<>(); 20647 20648 public OnPermissionChangeListeners(Looper looper) { 20649 super(looper); 20650 } 20651 20652 @Override 20653 public void handleMessage(Message msg) { 20654 switch (msg.what) { 20655 case MSG_ON_PERMISSIONS_CHANGED: { 20656 final int uid = msg.arg1; 20657 handleOnPermissionsChanged(uid); 20658 } break; 20659 } 20660 } 20661 20662 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20663 mPermissionListeners.register(listener); 20664 20665 } 20666 20667 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20668 mPermissionListeners.unregister(listener); 20669 } 20670 20671 public void onPermissionsChanged(int uid) { 20672 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20673 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20674 } 20675 } 20676 20677 private void handleOnPermissionsChanged(int uid) { 20678 final int count = mPermissionListeners.beginBroadcast(); 20679 try { 20680 for (int i = 0; i < count; i++) { 20681 IOnPermissionsChangeListener callback = mPermissionListeners 20682 .getBroadcastItem(i); 20683 try { 20684 callback.onPermissionsChanged(uid); 20685 } catch (RemoteException e) { 20686 Log.e(TAG, "Permission listener is dead", e); 20687 } 20688 } 20689 } finally { 20690 mPermissionListeners.finishBroadcast(); 20691 } 20692 } 20693 } 20694 20695 private class PackageManagerInternalImpl extends PackageManagerInternal { 20696 @Override 20697 public void setLocationPackagesProvider(PackagesProvider provider) { 20698 synchronized (mPackages) { 20699 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20700 } 20701 } 20702 20703 @Override 20704 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20705 synchronized (mPackages) { 20706 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20707 } 20708 } 20709 20710 @Override 20711 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20712 synchronized (mPackages) { 20713 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20714 } 20715 } 20716 20717 @Override 20718 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20719 synchronized (mPackages) { 20720 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20721 } 20722 } 20723 20724 @Override 20725 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20726 synchronized (mPackages) { 20727 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20728 } 20729 } 20730 20731 @Override 20732 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20733 synchronized (mPackages) { 20734 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20735 } 20736 } 20737 20738 @Override 20739 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20740 synchronized (mPackages) { 20741 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20742 packageName, userId); 20743 } 20744 } 20745 20746 @Override 20747 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20748 synchronized (mPackages) { 20749 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20750 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20751 packageName, userId); 20752 } 20753 } 20754 20755 @Override 20756 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20757 synchronized (mPackages) { 20758 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20759 packageName, userId); 20760 } 20761 } 20762 20763 @Override 20764 public void setKeepUninstalledPackages(final List<String> packageList) { 20765 Preconditions.checkNotNull(packageList); 20766 List<String> removedFromList = null; 20767 synchronized (mPackages) { 20768 if (mKeepUninstalledPackages != null) { 20769 final int packagesCount = mKeepUninstalledPackages.size(); 20770 for (int i = 0; i < packagesCount; i++) { 20771 String oldPackage = mKeepUninstalledPackages.get(i); 20772 if (packageList != null && packageList.contains(oldPackage)) { 20773 continue; 20774 } 20775 if (removedFromList == null) { 20776 removedFromList = new ArrayList<>(); 20777 } 20778 removedFromList.add(oldPackage); 20779 } 20780 } 20781 mKeepUninstalledPackages = new ArrayList<>(packageList); 20782 if (removedFromList != null) { 20783 final int removedCount = removedFromList.size(); 20784 for (int i = 0; i < removedCount; i++) { 20785 deletePackageIfUnusedLPr(removedFromList.get(i)); 20786 } 20787 } 20788 } 20789 } 20790 20791 @Override 20792 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20793 synchronized (mPackages) { 20794 // If we do not support permission review, done. 20795 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20796 return false; 20797 } 20798 20799 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20800 if (packageSetting == null) { 20801 return false; 20802 } 20803 20804 // Permission review applies only to apps not supporting the new permission model. 20805 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20806 return false; 20807 } 20808 20809 // Legacy apps have the permission and get user consent on launch. 20810 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20811 return permissionsState.isPermissionReviewRequired(userId); 20812 } 20813 } 20814 20815 @Override 20816 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20817 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20818 } 20819 20820 @Override 20821 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20822 int userId) { 20823 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20824 } 20825 } 20826 20827 @Override 20828 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20829 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20830 synchronized (mPackages) { 20831 final long identity = Binder.clearCallingIdentity(); 20832 try { 20833 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20834 packageNames, userId); 20835 } finally { 20836 Binder.restoreCallingIdentity(identity); 20837 } 20838 } 20839 } 20840 20841 private static void enforceSystemOrPhoneCaller(String tag) { 20842 int callingUid = Binder.getCallingUid(); 20843 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20844 throw new SecurityException( 20845 "Cannot call " + tag + " from UID " + callingUid); 20846 } 20847 } 20848 20849 boolean isHistoricalPackageUsageAvailable() { 20850 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20851 } 20852 20853 /** 20854 * Return a <b>copy</b> of the collection of packages known to the package manager. 20855 * @return A copy of the values of mPackages. 20856 */ 20857 Collection<PackageParser.Package> getPackages() { 20858 synchronized (mPackages) { 20859 return new ArrayList<>(mPackages.values()); 20860 } 20861 } 20862 20863 /** 20864 * Logs process start information (including base APK hash) to the security log. 20865 * @hide 20866 */ 20867 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20868 String apkFile, int pid) { 20869 if (!SecurityLog.isLoggingEnabled()) { 20870 return; 20871 } 20872 Bundle data = new Bundle(); 20873 data.putLong("startTimestamp", System.currentTimeMillis()); 20874 data.putString("processName", processName); 20875 data.putInt("uid", uid); 20876 data.putString("seinfo", seinfo); 20877 data.putString("apkFile", apkFile); 20878 data.putInt("pid", pid); 20879 Message msg = mProcessLoggingHandler.obtainMessage( 20880 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20881 msg.setData(data); 20882 mProcessLoggingHandler.sendMessage(msg); 20883 } 20884} 20885