PackageManagerService.java revision 11f197c3fe24c5fdccf3c2feacb22bc16d73d5fc
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.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.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 final ProtectedPackages mProtectedPackages = new ProtectedPackages(); 626 627 boolean mRestoredSettings; 628 629 // System configuration read by SystemConfig. 630 final int[] mGlobalGids; 631 final SparseArray<ArraySet<String>> mSystemPermissions; 632 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 633 634 // If mac_permissions.xml was found for seinfo labeling. 635 boolean mFoundPolicyFile; 636 637 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 638 639 public static final class SharedLibraryEntry { 640 public final String path; 641 public final String apk; 642 643 SharedLibraryEntry(String _path, String _apk) { 644 path = _path; 645 apk = _apk; 646 } 647 } 648 649 // Currently known shared libraries. 650 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 651 new ArrayMap<String, SharedLibraryEntry>(); 652 653 // All available activities, for your resolving pleasure. 654 final ActivityIntentResolver mActivities = 655 new ActivityIntentResolver(); 656 657 // All available receivers, for your resolving pleasure. 658 final ActivityIntentResolver mReceivers = 659 new ActivityIntentResolver(); 660 661 // All available services, for your resolving pleasure. 662 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 663 664 // All available providers, for your resolving pleasure. 665 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 666 667 // Mapping from provider base names (first directory in content URI codePath) 668 // to the provider information. 669 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 670 new ArrayMap<String, PackageParser.Provider>(); 671 672 // Mapping from instrumentation class names to info about them. 673 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 674 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 675 676 // Mapping from permission names to info about them. 677 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 678 new ArrayMap<String, PackageParser.PermissionGroup>(); 679 680 // Packages whose data we have transfered into another package, thus 681 // should no longer exist. 682 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 683 684 // Broadcast actions that are only available to the system. 685 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 686 687 /** List of packages waiting for verification. */ 688 final SparseArray<PackageVerificationState> mPendingVerification 689 = new SparseArray<PackageVerificationState>(); 690 691 /** Set of packages associated with each app op permission. */ 692 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 693 694 final PackageInstallerService mInstallerService; 695 696 private final PackageDexOptimizer mPackageDexOptimizer; 697 698 private AtomicInteger mNextMoveId = new AtomicInteger(); 699 private final MoveCallbacks mMoveCallbacks; 700 701 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 702 703 // Cache of users who need badging. 704 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 705 706 /** Token for keys in mPendingVerification. */ 707 private int mPendingVerificationToken = 0; 708 709 volatile boolean mSystemReady; 710 volatile boolean mSafeMode; 711 volatile boolean mHasSystemUidErrors; 712 713 ApplicationInfo mAndroidApplication; 714 final ActivityInfo mResolveActivity = new ActivityInfo(); 715 final ResolveInfo mResolveInfo = new ResolveInfo(); 716 ComponentName mResolveComponentName; 717 PackageParser.Package mPlatformPackage; 718 ComponentName mCustomResolverComponentName; 719 720 boolean mResolverReplaced = false; 721 722 private final @Nullable ComponentName mIntentFilterVerifierComponent; 723 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 724 725 private int mIntentFilterVerificationToken = 0; 726 727 /** Component that knows whether or not an ephemeral application exists */ 728 final ComponentName mEphemeralResolverComponent; 729 /** The service connection to the ephemeral resolver */ 730 final EphemeralResolverConnection mEphemeralResolverConnection; 731 732 /** Component used to install ephemeral applications */ 733 final ComponentName mEphemeralInstallerComponent; 734 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 735 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 736 737 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 738 = new SparseArray<IntentFilterVerificationState>(); 739 740 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 741 new DefaultPermissionGrantPolicy(this); 742 743 // List of packages names to keep cached, even if they are uninstalled for all users 744 private List<String> mKeepUninstalledPackages; 745 746 private UserManagerInternal mUserManagerInternal; 747 748 private static class IFVerificationParams { 749 PackageParser.Package pkg; 750 boolean replacing; 751 int userId; 752 int verifierUid; 753 754 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 755 int _userId, int _verifierUid) { 756 pkg = _pkg; 757 replacing = _replacing; 758 userId = _userId; 759 replacing = _replacing; 760 verifierUid = _verifierUid; 761 } 762 } 763 764 private interface IntentFilterVerifier<T extends IntentFilter> { 765 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 766 T filter, String packageName); 767 void startVerifications(int userId); 768 void receiveVerificationResponse(int verificationId); 769 } 770 771 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 772 private Context mContext; 773 private ComponentName mIntentFilterVerifierComponent; 774 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 775 776 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 777 mContext = context; 778 mIntentFilterVerifierComponent = verifierComponent; 779 } 780 781 private String getDefaultScheme() { 782 return IntentFilter.SCHEME_HTTPS; 783 } 784 785 @Override 786 public void startVerifications(int userId) { 787 // Launch verifications requests 788 int count = mCurrentIntentFilterVerifications.size(); 789 for (int n=0; n<count; n++) { 790 int verificationId = mCurrentIntentFilterVerifications.get(n); 791 final IntentFilterVerificationState ivs = 792 mIntentFilterVerificationStates.get(verificationId); 793 794 String packageName = ivs.getPackageName(); 795 796 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 797 final int filterCount = filters.size(); 798 ArraySet<String> domainsSet = new ArraySet<>(); 799 for (int m=0; m<filterCount; m++) { 800 PackageParser.ActivityIntentInfo filter = filters.get(m); 801 domainsSet.addAll(filter.getHostsList()); 802 } 803 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 804 synchronized (mPackages) { 805 if (mSettings.createIntentFilterVerificationIfNeededLPw( 806 packageName, domainsList) != null) { 807 scheduleWriteSettingsLocked(); 808 } 809 } 810 sendVerificationRequest(userId, verificationId, ivs); 811 } 812 mCurrentIntentFilterVerifications.clear(); 813 } 814 815 private void sendVerificationRequest(int userId, int verificationId, 816 IntentFilterVerificationState ivs) { 817 818 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 821 verificationId); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 824 getDefaultScheme()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 827 ivs.getHostsString()); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 830 ivs.getPackageName()); 831 verificationIntent.setComponent(mIntentFilterVerifierComponent); 832 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 833 834 UserHandle user = new UserHandle(userId); 835 mContext.sendBroadcastAsUser(verificationIntent, user); 836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 837 "Sending IntentFilter verification broadcast"); 838 } 839 840 public void receiveVerificationResponse(int verificationId) { 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 843 final boolean verified = ivs.isVerified(); 844 845 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 846 final int count = filters.size(); 847 if (DEBUG_DOMAIN_VERIFICATION) { 848 Slog.i(TAG, "Received verification response " + verificationId 849 + " for " + count + " filters, verified=" + verified); 850 } 851 for (int n=0; n<count; n++) { 852 PackageParser.ActivityIntentInfo filter = filters.get(n); 853 filter.setVerified(verified); 854 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 856 + " verified with result:" + verified + " and hosts:" 857 + ivs.getHostsString()); 858 } 859 860 mIntentFilterVerificationStates.remove(verificationId); 861 862 final String packageName = ivs.getPackageName(); 863 IntentFilterVerificationInfo ivi = null; 864 865 synchronized (mPackages) { 866 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 867 } 868 if (ivi == null) { 869 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 870 + verificationId + " packageName:" + packageName); 871 return; 872 } 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 874 "Updating IntentFilterVerificationInfo for package " + packageName 875 +" verificationId:" + verificationId); 876 877 synchronized (mPackages) { 878 if (verified) { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 880 } else { 881 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 882 } 883 scheduleWriteSettingsLocked(); 884 885 final int userId = ivs.getUserId(); 886 if (userId != UserHandle.USER_ALL) { 887 final int userStatus = 888 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 889 890 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 891 boolean needUpdate = false; 892 893 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 894 // already been set by the User thru the Disambiguation dialog 895 switch (userStatus) { 896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 897 if (verified) { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 899 } else { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 901 } 902 needUpdate = true; 903 break; 904 905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 906 if (verified) { 907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 908 needUpdate = true; 909 } 910 break; 911 912 default: 913 // Nothing to do 914 } 915 916 if (needUpdate) { 917 mSettings.updateIntentFilterVerificationStatusLPw( 918 packageName, updatedStatus, userId); 919 scheduleWritePackageRestrictionsLocked(userId); 920 } 921 } 922 } 923 } 924 925 @Override 926 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 927 ActivityIntentInfo filter, String packageName) { 928 if (!hasValidDomains(filter)) { 929 return false; 930 } 931 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 932 if (ivs == null) { 933 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 934 packageName); 935 } 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 938 } 939 ivs.addFilter(filter); 940 return true; 941 } 942 943 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 944 int userId, int verificationId, String packageName) { 945 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 946 verifierUid, userId, packageName); 947 ivs.setPendingState(); 948 synchronized (mPackages) { 949 mIntentFilterVerificationStates.append(verificationId, ivs); 950 mCurrentIntentFilterVerifications.add(verificationId); 951 } 952 return ivs; 953 } 954 } 955 956 private static boolean hasValidDomains(ActivityIntentInfo filter) { 957 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 960 } 961 962 // Set of pending broadcasts for aggregating enable/disable of components. 963 static class PendingPackageBroadcasts { 964 // for each user id, a map of <package name -> components within that package> 965 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 966 967 public PendingPackageBroadcasts() { 968 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 969 } 970 971 public ArrayList<String> get(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 return packages.get(packageName); 974 } 975 976 public void put(int userId, String packageName, ArrayList<String> components) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 packages.put(packageName, components); 979 } 980 981 public void remove(int userId, String packageName) { 982 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 983 if (packages != null) { 984 packages.remove(packageName); 985 } 986 } 987 988 public void remove(int userId) { 989 mUidMap.remove(userId); 990 } 991 992 public int userIdCount() { 993 return mUidMap.size(); 994 } 995 996 public int userIdAt(int n) { 997 return mUidMap.keyAt(n); 998 } 999 1000 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1001 return mUidMap.get(userId); 1002 } 1003 1004 public int size() { 1005 // total number of pending broadcast entries across all userIds 1006 int num = 0; 1007 for (int i = 0; i< mUidMap.size(); i++) { 1008 num += mUidMap.valueAt(i).size(); 1009 } 1010 return num; 1011 } 1012 1013 public void clear() { 1014 mUidMap.clear(); 1015 } 1016 1017 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1018 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1019 if (map == null) { 1020 map = new ArrayMap<String, ArrayList<String>>(); 1021 mUidMap.put(userId, map); 1022 } 1023 return map; 1024 } 1025 } 1026 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1027 1028 // Service Connection to remote media container service to copy 1029 // package uri's from external media onto secure containers 1030 // or internal storage. 1031 private IMediaContainerService mContainerService = null; 1032 1033 static final int SEND_PENDING_BROADCAST = 1; 1034 static final int MCS_BOUND = 3; 1035 static final int END_COPY = 4; 1036 static final int INIT_COPY = 5; 1037 static final int MCS_UNBIND = 6; 1038 static final int START_CLEANING_PACKAGE = 7; 1039 static final int FIND_INSTALL_LOC = 8; 1040 static final int POST_INSTALL = 9; 1041 static final int MCS_RECONNECT = 10; 1042 static final int MCS_GIVE_UP = 11; 1043 static final int UPDATED_MEDIA_STATUS = 12; 1044 static final int WRITE_SETTINGS = 13; 1045 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1046 static final int PACKAGE_VERIFIED = 15; 1047 static final int CHECK_PENDING_VERIFICATION = 16; 1048 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1049 static final int INTENT_FILTER_VERIFIED = 18; 1050 static final int WRITE_PACKAGE_LIST = 19; 1051 1052 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1053 1054 // Delay time in millisecs 1055 static final int BROADCAST_DELAY = 10 * 1000; 1056 1057 static UserManagerService sUserManager; 1058 1059 // Stores a list of users whose package restrictions file needs to be updated 1060 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1061 1062 final private DefaultContainerConnection mDefContainerConn = 1063 new DefaultContainerConnection(); 1064 class DefaultContainerConnection implements ServiceConnection { 1065 public void onServiceConnected(ComponentName name, IBinder service) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1067 IMediaContainerService imcs = 1068 IMediaContainerService.Stub.asInterface(service); 1069 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1070 } 1071 1072 public void onServiceDisconnected(ComponentName name) { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1074 } 1075 } 1076 1077 // Recordkeeping of restore-after-install operations that are currently in flight 1078 // between the Package Manager and the Backup Manager 1079 static class PostInstallData { 1080 public InstallArgs args; 1081 public PackageInstalledInfo res; 1082 1083 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1084 args = _a; 1085 res = _r; 1086 } 1087 } 1088 1089 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1090 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1091 1092 // XML tags for backup/restore of various bits of state 1093 private static final String TAG_PREFERRED_BACKUP = "pa"; 1094 private static final String TAG_DEFAULT_APPS = "da"; 1095 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1096 1097 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1098 private static final String TAG_ALL_GRANTS = "rt-grants"; 1099 private static final String TAG_GRANT = "grant"; 1100 private static final String ATTR_PACKAGE_NAME = "pkg"; 1101 1102 private static final String TAG_PERMISSION = "perm"; 1103 private static final String ATTR_PERMISSION_NAME = "name"; 1104 private static final String ATTR_IS_GRANTED = "g"; 1105 private static final String ATTR_USER_SET = "set"; 1106 private static final String ATTR_USER_FIXED = "fixed"; 1107 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1108 1109 // System/policy permission grants are not backed up 1110 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1111 FLAG_PERMISSION_POLICY_FIXED 1112 | FLAG_PERMISSION_SYSTEM_FIXED 1113 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1114 1115 // And we back up these user-adjusted states 1116 private static final int USER_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_USER_SET 1118 | FLAG_PERMISSION_USER_FIXED 1119 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1120 1121 final @Nullable String mRequiredVerifierPackage; 1122 final @NonNull String mRequiredInstallerPackage; 1123 final @Nullable String mSetupWizardPackage; 1124 final @NonNull String mServicesSystemSharedLibraryPackageName; 1125 final @NonNull String mSharedSystemSharedLibraryPackageName; 1126 1127 private final PackageUsage mPackageUsage = new PackageUsage(); 1128 1129 private class PackageUsage { 1130 private static final int WRITE_INTERVAL 1131 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1132 1133 private final Object mFileLock = new Object(); 1134 private final AtomicLong mLastWritten = new AtomicLong(0); 1135 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1136 1137 private boolean mIsHistoricalPackageUsageAvailable = true; 1138 1139 boolean isHistoricalPackageUsageAvailable() { 1140 return mIsHistoricalPackageUsageAvailable; 1141 } 1142 1143 void write(boolean force) { 1144 if (force) { 1145 writeInternal(); 1146 return; 1147 } 1148 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1149 && !DEBUG_DEXOPT) { 1150 return; 1151 } 1152 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1153 new Thread("PackageUsage_DiskWriter") { 1154 @Override 1155 public void run() { 1156 try { 1157 writeInternal(); 1158 } finally { 1159 mBackgroundWriteRunning.set(false); 1160 } 1161 } 1162 }.start(); 1163 } 1164 } 1165 1166 private void writeInternal() { 1167 synchronized (mPackages) { 1168 synchronized (mFileLock) { 1169 AtomicFile file = getFile(); 1170 FileOutputStream f = null; 1171 try { 1172 f = file.startWrite(); 1173 BufferedOutputStream out = new BufferedOutputStream(f); 1174 FileUtils.setPermissions(file.getBaseFile().getPath(), 1175 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1176 StringBuilder sb = new StringBuilder(); 1177 1178 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1179 sb.append('\n'); 1180 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1181 1182 for (PackageParser.Package pkg : mPackages.values()) { 1183 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1184 continue; 1185 } 1186 sb.setLength(0); 1187 sb.append(pkg.packageName); 1188 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1189 sb.append(' '); 1190 sb.append(usageTimeInMillis); 1191 } 1192 sb.append('\n'); 1193 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1194 } 1195 out.flush(); 1196 file.finishWrite(f); 1197 } catch (IOException e) { 1198 if (f != null) { 1199 file.failWrite(f); 1200 } 1201 Log.e(TAG, "Failed to write package usage times", e); 1202 } 1203 } 1204 } 1205 mLastWritten.set(SystemClock.elapsedRealtime()); 1206 } 1207 1208 void readLP() { 1209 synchronized (mFileLock) { 1210 AtomicFile file = getFile(); 1211 BufferedInputStream in = null; 1212 try { 1213 in = new BufferedInputStream(file.openRead()); 1214 StringBuffer sb = new StringBuffer(); 1215 1216 String firstLine = readLine(in, sb); 1217 if (firstLine == null) { 1218 // Empty file. Do nothing. 1219 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1220 readVersion1LP(in, sb); 1221 } else { 1222 readVersion0LP(in, sb, firstLine); 1223 } 1224 } catch (FileNotFoundException expected) { 1225 mIsHistoricalPackageUsageAvailable = false; 1226 } catch (IOException e) { 1227 Log.w(TAG, "Failed to read package usage times", e); 1228 } finally { 1229 IoUtils.closeQuietly(in); 1230 } 1231 } 1232 mLastWritten.set(SystemClock.elapsedRealtime()); 1233 } 1234 1235 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1236 throws IOException { 1237 // Initial version of the file had no version number and stored one 1238 // package-timestamp pair per line. 1239 // Note that the first line has already been read from the InputStream. 1240 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1241 String[] tokens = line.split(" "); 1242 if (tokens.length != 2) { 1243 throw new IOException("Failed to parse " + line + 1244 " as package-timestamp pair."); 1245 } 1246 1247 String packageName = tokens[0]; 1248 PackageParser.Package pkg = mPackages.get(packageName); 1249 if (pkg == null) { 1250 continue; 1251 } 1252 1253 long timestamp = parseAsLong(tokens[1]); 1254 for (int reason = 0; 1255 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1256 reason++) { 1257 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1258 } 1259 } 1260 } 1261 1262 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1263 // Version 1 of the file started with the corresponding version 1264 // number and then stored a package name and eight timestamps per line. 1265 String line; 1266 while ((line = readLine(in, sb)) != null) { 1267 String[] tokens = line.split(" "); 1268 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1269 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1270 } 1271 1272 String packageName = tokens[0]; 1273 PackageParser.Package pkg = mPackages.get(packageName); 1274 if (pkg == null) { 1275 continue; 1276 } 1277 1278 for (int reason = 0; 1279 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1280 reason++) { 1281 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1282 } 1283 } 1284 } 1285 1286 private long parseAsLong(String token) throws IOException { 1287 try { 1288 return Long.parseLong(token); 1289 } catch (NumberFormatException e) { 1290 throw new IOException("Failed to parse " + token + " as a long.", e); 1291 } 1292 } 1293 1294 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1295 return readToken(in, sb, '\n'); 1296 } 1297 1298 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1299 throws IOException { 1300 sb.setLength(0); 1301 while (true) { 1302 int ch = in.read(); 1303 if (ch == -1) { 1304 if (sb.length() == 0) { 1305 return null; 1306 } 1307 throw new IOException("Unexpected EOF"); 1308 } 1309 if (ch == endOfToken) { 1310 return sb.toString(); 1311 } 1312 sb.append((char)ch); 1313 } 1314 } 1315 1316 private AtomicFile getFile() { 1317 File dataDir = Environment.getDataDirectory(); 1318 File systemDir = new File(dataDir, "system"); 1319 File fname = new File(systemDir, "package-usage.list"); 1320 return new AtomicFile(fname); 1321 } 1322 1323 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1324 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1325 } 1326 1327 class PackageHandler extends Handler { 1328 private boolean mBound = false; 1329 final ArrayList<HandlerParams> mPendingInstalls = 1330 new ArrayList<HandlerParams>(); 1331 1332 private boolean connectToService() { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1334 " DefaultContainerService"); 1335 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1337 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1338 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 mBound = true; 1341 return true; 1342 } 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1344 return false; 1345 } 1346 1347 private void disconnectService() { 1348 mContainerService = null; 1349 mBound = false; 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1351 mContext.unbindService(mDefContainerConn); 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 } 1354 1355 PackageHandler(Looper looper) { 1356 super(looper); 1357 } 1358 1359 public void handleMessage(Message msg) { 1360 try { 1361 doHandleMessage(msg); 1362 } finally { 1363 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1364 } 1365 } 1366 1367 void doHandleMessage(Message msg) { 1368 switch (msg.what) { 1369 case INIT_COPY: { 1370 HandlerParams params = (HandlerParams) msg.obj; 1371 int idx = mPendingInstalls.size(); 1372 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1373 // If a bind was already initiated we dont really 1374 // need to do anything. The pending install 1375 // will be processed later on. 1376 if (!mBound) { 1377 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 // If this is the only one pending we might 1380 // have to bind to the service again. 1381 if (!connectToService()) { 1382 Slog.e(TAG, "Failed to bind to media container service"); 1383 params.serviceError(); 1384 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1385 System.identityHashCode(mHandler)); 1386 if (params.traceMethod != null) { 1387 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1388 params.traceCookie); 1389 } 1390 return; 1391 } else { 1392 // Once we bind to the service, the first 1393 // pending request will be processed. 1394 mPendingInstalls.add(idx, params); 1395 } 1396 } else { 1397 mPendingInstalls.add(idx, params); 1398 // Already bound to the service. Just make 1399 // sure we trigger off processing the first request. 1400 if (idx == 0) { 1401 mHandler.sendEmptyMessage(MCS_BOUND); 1402 } 1403 } 1404 break; 1405 } 1406 case MCS_BOUND: { 1407 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1408 if (msg.obj != null) { 1409 mContainerService = (IMediaContainerService) msg.obj; 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1411 System.identityHashCode(mHandler)); 1412 } 1413 if (mContainerService == null) { 1414 if (!mBound) { 1415 // Something seriously wrong since we are not bound and we are not 1416 // waiting for connection. Bail out. 1417 Slog.e(TAG, "Cannot bind to media container service"); 1418 for (HandlerParams params : mPendingInstalls) { 1419 // Indicate service bind error 1420 params.serviceError(); 1421 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1422 System.identityHashCode(params)); 1423 if (params.traceMethod != null) { 1424 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1425 params.traceMethod, params.traceCookie); 1426 } 1427 return; 1428 } 1429 mPendingInstalls.clear(); 1430 } else { 1431 Slog.w(TAG, "Waiting to connect to media container service"); 1432 } 1433 } else if (mPendingInstalls.size() > 0) { 1434 HandlerParams params = mPendingInstalls.get(0); 1435 if (params != null) { 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1439 if (params.startCopy()) { 1440 // We are done... look for more work or to 1441 // go idle. 1442 if (DEBUG_SD_INSTALL) Log.i(TAG, 1443 "Checking for more work or unbind..."); 1444 // Delete pending install 1445 if (mPendingInstalls.size() > 0) { 1446 mPendingInstalls.remove(0); 1447 } 1448 if (mPendingInstalls.size() == 0) { 1449 if (mBound) { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, 1451 "Posting delayed MCS_UNBIND"); 1452 removeMessages(MCS_UNBIND); 1453 Message ubmsg = obtainMessage(MCS_UNBIND); 1454 // Unbind after a little delay, to avoid 1455 // continual thrashing. 1456 sendMessageDelayed(ubmsg, 10000); 1457 } 1458 } else { 1459 // There are more pending requests in queue. 1460 // Just post MCS_BOUND message to trigger processing 1461 // of next pending install. 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, 1463 "Posting MCS_BOUND for next work"); 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1468 } 1469 } else { 1470 // Should never happen ideally. 1471 Slog.w(TAG, "Empty queue"); 1472 } 1473 break; 1474 } 1475 case MCS_RECONNECT: { 1476 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1477 if (mPendingInstalls.size() > 0) { 1478 if (mBound) { 1479 disconnectService(); 1480 } 1481 if (!connectToService()) { 1482 Slog.e(TAG, "Failed to bind to media container service"); 1483 for (HandlerParams params : mPendingInstalls) { 1484 // Indicate service bind error 1485 params.serviceError(); 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1487 System.identityHashCode(params)); 1488 } 1489 mPendingInstalls.clear(); 1490 } 1491 } 1492 break; 1493 } 1494 case MCS_UNBIND: { 1495 // If there is no actual work left, then time to unbind. 1496 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1497 1498 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1499 if (mBound) { 1500 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1501 1502 disconnectService(); 1503 } 1504 } else if (mPendingInstalls.size() > 0) { 1505 // There are more pending requests in queue. 1506 // Just post MCS_BOUND message to trigger processing 1507 // of next pending install. 1508 mHandler.sendEmptyMessage(MCS_BOUND); 1509 } 1510 1511 break; 1512 } 1513 case MCS_GIVE_UP: { 1514 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1515 HandlerParams params = mPendingInstalls.remove(0); 1516 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1517 System.identityHashCode(params)); 1518 break; 1519 } 1520 case SEND_PENDING_BROADCAST: { 1521 String packages[]; 1522 ArrayList<String> components[]; 1523 int size = 0; 1524 int uids[]; 1525 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1526 synchronized (mPackages) { 1527 if (mPendingBroadcasts == null) { 1528 return; 1529 } 1530 size = mPendingBroadcasts.size(); 1531 if (size <= 0) { 1532 // Nothing to be done. Just return 1533 return; 1534 } 1535 packages = new String[size]; 1536 components = new ArrayList[size]; 1537 uids = new int[size]; 1538 int i = 0; // filling out the above arrays 1539 1540 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1541 int packageUserId = mPendingBroadcasts.userIdAt(n); 1542 Iterator<Map.Entry<String, ArrayList<String>>> it 1543 = mPendingBroadcasts.packagesForUserId(packageUserId) 1544 .entrySet().iterator(); 1545 while (it.hasNext() && i < size) { 1546 Map.Entry<String, ArrayList<String>> ent = it.next(); 1547 packages[i] = ent.getKey(); 1548 components[i] = ent.getValue(); 1549 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1550 uids[i] = (ps != null) 1551 ? UserHandle.getUid(packageUserId, ps.appId) 1552 : -1; 1553 i++; 1554 } 1555 } 1556 size = i; 1557 mPendingBroadcasts.clear(); 1558 } 1559 // Send broadcasts 1560 for (int i = 0; i < size; i++) { 1561 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1562 } 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1564 break; 1565 } 1566 case START_CLEANING_PACKAGE: { 1567 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1568 final String packageName = (String)msg.obj; 1569 final int userId = msg.arg1; 1570 final boolean andCode = msg.arg2 != 0; 1571 synchronized (mPackages) { 1572 if (userId == UserHandle.USER_ALL) { 1573 int[] users = sUserManager.getUserIds(); 1574 for (int user : users) { 1575 mSettings.addPackageToCleanLPw( 1576 new PackageCleanItem(user, packageName, andCode)); 1577 } 1578 } else { 1579 mSettings.addPackageToCleanLPw( 1580 new PackageCleanItem(userId, packageName, andCode)); 1581 } 1582 } 1583 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1584 startCleaningPackages(); 1585 } break; 1586 case POST_INSTALL: { 1587 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1588 1589 PostInstallData data = mRunningInstalls.get(msg.arg1); 1590 final boolean didRestore = (msg.arg2 != 0); 1591 mRunningInstalls.delete(msg.arg1); 1592 1593 if (data != null) { 1594 InstallArgs args = data.args; 1595 PackageInstalledInfo parentRes = data.res; 1596 1597 final boolean grantPermissions = (args.installFlags 1598 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1599 final boolean killApp = (args.installFlags 1600 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1601 final String[] grantedPermissions = args.installGrantPermissions; 1602 1603 // Handle the parent package 1604 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1605 grantedPermissions, didRestore, args.installerPackageName, 1606 args.observer); 1607 1608 // Handle the child packages 1609 final int childCount = (parentRes.addedChildPackages != null) 1610 ? parentRes.addedChildPackages.size() : 0; 1611 for (int i = 0; i < childCount; i++) { 1612 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1613 handlePackagePostInstall(childRes, grantPermissions, killApp, 1614 grantedPermissions, false, args.installerPackageName, 1615 args.observer); 1616 } 1617 1618 // Log tracing if needed 1619 if (args.traceMethod != null) { 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1621 args.traceCookie); 1622 } 1623 } else { 1624 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1625 } 1626 1627 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1628 } break; 1629 case UPDATED_MEDIA_STATUS: { 1630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1631 boolean reportStatus = msg.arg1 == 1; 1632 boolean doGc = msg.arg2 == 1; 1633 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1634 if (doGc) { 1635 // Force a gc to clear up stale containers. 1636 Runtime.getRuntime().gc(); 1637 } 1638 if (msg.obj != null) { 1639 @SuppressWarnings("unchecked") 1640 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1642 // Unload containers 1643 unloadAllContainers(args); 1644 } 1645 if (reportStatus) { 1646 try { 1647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1648 PackageHelper.getMountService().finishMediaUpdate(); 1649 } catch (RemoteException e) { 1650 Log.e(TAG, "MountService not running?"); 1651 } 1652 } 1653 } break; 1654 case WRITE_SETTINGS: { 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1656 synchronized (mPackages) { 1657 removeMessages(WRITE_SETTINGS); 1658 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1659 mSettings.writeLPr(); 1660 mDirtyUsers.clear(); 1661 } 1662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1663 } break; 1664 case WRITE_PACKAGE_RESTRICTIONS: { 1665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1666 synchronized (mPackages) { 1667 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1668 for (int userId : mDirtyUsers) { 1669 mSettings.writePackageRestrictionsLPr(userId); 1670 } 1671 mDirtyUsers.clear(); 1672 } 1673 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1674 } break; 1675 case WRITE_PACKAGE_LIST: { 1676 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1677 synchronized (mPackages) { 1678 removeMessages(WRITE_PACKAGE_LIST); 1679 mSettings.writePackageListLPr(msg.arg1); 1680 } 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1682 } break; 1683 case CHECK_PENDING_VERIFICATION: { 1684 final int verificationId = msg.arg1; 1685 final PackageVerificationState state = mPendingVerification.get(verificationId); 1686 1687 if ((state != null) && !state.timeoutExtended()) { 1688 final InstallArgs args = state.getInstallArgs(); 1689 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1690 1691 Slog.i(TAG, "Verification timed out for " + originUri); 1692 mPendingVerification.remove(verificationId); 1693 1694 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1695 1696 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1697 Slog.i(TAG, "Continuing with installation of " + originUri); 1698 state.setVerifierResponse(Binder.getCallingUid(), 1699 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1700 broadcastPackageVerified(verificationId, originUri, 1701 PackageManager.VERIFICATION_ALLOW, 1702 state.getInstallArgs().getUser()); 1703 try { 1704 ret = args.copyApk(mContainerService, true); 1705 } catch (RemoteException e) { 1706 Slog.e(TAG, "Could not contact the ContainerService"); 1707 } 1708 } else { 1709 broadcastPackageVerified(verificationId, originUri, 1710 PackageManager.VERIFICATION_REJECT, 1711 state.getInstallArgs().getUser()); 1712 } 1713 1714 Trace.asyncTraceEnd( 1715 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1716 1717 processPendingInstall(args, ret); 1718 mHandler.sendEmptyMessage(MCS_UNBIND); 1719 } 1720 break; 1721 } 1722 case PACKAGE_VERIFIED: { 1723 final int verificationId = msg.arg1; 1724 1725 final PackageVerificationState state = mPendingVerification.get(verificationId); 1726 if (state == null) { 1727 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1728 break; 1729 } 1730 1731 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1732 1733 state.setVerifierResponse(response.callerUid, response.code); 1734 1735 if (state.isVerificationComplete()) { 1736 mPendingVerification.remove(verificationId); 1737 1738 final InstallArgs args = state.getInstallArgs(); 1739 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1740 1741 int ret; 1742 if (state.isInstallAllowed()) { 1743 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1744 broadcastPackageVerified(verificationId, originUri, 1745 response.code, state.getInstallArgs().getUser()); 1746 try { 1747 ret = args.copyApk(mContainerService, true); 1748 } catch (RemoteException e) { 1749 Slog.e(TAG, "Could not contact the ContainerService"); 1750 } 1751 } else { 1752 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1753 } 1754 1755 Trace.asyncTraceEnd( 1756 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1757 1758 processPendingInstall(args, ret); 1759 mHandler.sendEmptyMessage(MCS_UNBIND); 1760 } 1761 1762 break; 1763 } 1764 case START_INTENT_FILTER_VERIFICATIONS: { 1765 IFVerificationParams params = (IFVerificationParams) msg.obj; 1766 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1767 params.replacing, params.pkg); 1768 break; 1769 } 1770 case INTENT_FILTER_VERIFIED: { 1771 final int verificationId = msg.arg1; 1772 1773 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1774 verificationId); 1775 if (state == null) { 1776 Slog.w(TAG, "Invalid IntentFilter verification token " 1777 + verificationId + " received"); 1778 break; 1779 } 1780 1781 final int userId = state.getUserId(); 1782 1783 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1784 "Processing IntentFilter verification with token:" 1785 + verificationId + " and userId:" + userId); 1786 1787 final IntentFilterVerificationResponse response = 1788 (IntentFilterVerificationResponse) msg.obj; 1789 1790 state.setVerifierResponse(response.callerUid, response.code); 1791 1792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1793 "IntentFilter verification with token:" + verificationId 1794 + " and userId:" + userId 1795 + " is settings verifier response with response code:" 1796 + response.code); 1797 1798 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1799 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1800 + response.getFailedDomainsString()); 1801 } 1802 1803 if (state.isVerificationComplete()) { 1804 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1805 } else { 1806 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1807 "IntentFilter verification with token:" + verificationId 1808 + " was not said to be complete"); 1809 } 1810 1811 break; 1812 } 1813 } 1814 } 1815 } 1816 1817 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1818 boolean killApp, String[] grantedPermissions, 1819 boolean launchedForRestore, String installerPackage, 1820 IPackageInstallObserver2 installObserver) { 1821 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1822 // Send the removed broadcasts 1823 if (res.removedInfo != null) { 1824 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1825 } 1826 1827 // Now that we successfully installed the package, grant runtime 1828 // permissions if requested before broadcasting the install. 1829 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1830 >= Build.VERSION_CODES.M) { 1831 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1832 } 1833 1834 final boolean update = res.removedInfo != null 1835 && res.removedInfo.removedPackage != null; 1836 1837 // If this is the first time we have child packages for a disabled privileged 1838 // app that had no children, we grant requested runtime permissions to the new 1839 // children if the parent on the system image had them already granted. 1840 if (res.pkg.parentPackage != null) { 1841 synchronized (mPackages) { 1842 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1843 } 1844 } 1845 1846 synchronized (mPackages) { 1847 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1848 } 1849 1850 final String packageName = res.pkg.applicationInfo.packageName; 1851 Bundle extras = new Bundle(1); 1852 extras.putInt(Intent.EXTRA_UID, res.uid); 1853 1854 // Determine the set of users who are adding this package for 1855 // the first time vs. those who are seeing an update. 1856 int[] firstUsers = EMPTY_INT_ARRAY; 1857 int[] updateUsers = EMPTY_INT_ARRAY; 1858 if (res.origUsers == null || res.origUsers.length == 0) { 1859 firstUsers = res.newUsers; 1860 } else { 1861 for (int newUser : res.newUsers) { 1862 boolean isNew = true; 1863 for (int origUser : res.origUsers) { 1864 if (origUser == newUser) { 1865 isNew = false; 1866 break; 1867 } 1868 } 1869 if (isNew) { 1870 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1871 } else { 1872 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1873 } 1874 } 1875 } 1876 1877 // Send installed broadcasts if the install/update is not ephemeral 1878 if (!isEphemeral(res.pkg)) { 1879 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1880 1881 // Send added for users that see the package for the first time 1882 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1883 extras, 0 /*flags*/, null /*targetPackage*/, 1884 null /*finishedReceiver*/, firstUsers); 1885 1886 // Send added for users that don't see the package for the first time 1887 if (update) { 1888 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1889 } 1890 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1891 extras, 0 /*flags*/, null /*targetPackage*/, 1892 null /*finishedReceiver*/, updateUsers); 1893 1894 // Send replaced for users that don't see the package for the first time 1895 if (update) { 1896 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1897 packageName, extras, 0 /*flags*/, 1898 null /*targetPackage*/, null /*finishedReceiver*/, 1899 updateUsers); 1900 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1901 null /*package*/, null /*extras*/, 0 /*flags*/, 1902 packageName /*targetPackage*/, 1903 null /*finishedReceiver*/, updateUsers); 1904 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1905 // First-install and we did a restore, so we're responsible for the 1906 // first-launch broadcast. 1907 if (DEBUG_BACKUP) { 1908 Slog.i(TAG, "Post-restore of " + packageName 1909 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1910 } 1911 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1912 } 1913 1914 // Send broadcast package appeared if forward locked/external for all users 1915 // treat asec-hosted packages like removable media on upgrade 1916 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1917 if (DEBUG_INSTALL) { 1918 Slog.i(TAG, "upgrading pkg " + res.pkg 1919 + " is ASEC-hosted -> AVAILABLE"); 1920 } 1921 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1922 ArrayList<String> pkgList = new ArrayList<>(1); 1923 pkgList.add(packageName); 1924 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1925 } 1926 } 1927 1928 // Work that needs to happen on first install within each user 1929 if (firstUsers != null && firstUsers.length > 0) { 1930 synchronized (mPackages) { 1931 for (int userId : firstUsers) { 1932 // If this app is a browser and it's newly-installed for some 1933 // users, clear any default-browser state in those users. The 1934 // app's nature doesn't depend on the user, so we can just check 1935 // its browser nature in any user and generalize. 1936 if (packageIsBrowser(packageName, userId)) { 1937 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1938 } 1939 1940 // We may also need to apply pending (restored) runtime 1941 // permission grants within these users. 1942 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1943 } 1944 } 1945 } 1946 1947 // Log current value of "unknown sources" setting 1948 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1949 getUnknownSourcesSettings()); 1950 1951 // Force a gc to clear up things 1952 Runtime.getRuntime().gc(); 1953 1954 // Remove the replaced package's older resources safely now 1955 // We delete after a gc for applications on sdcard. 1956 if (res.removedInfo != null && res.removedInfo.args != null) { 1957 synchronized (mInstallLock) { 1958 res.removedInfo.args.doPostDeleteLI(true); 1959 } 1960 } 1961 } 1962 1963 // If someone is watching installs - notify them 1964 if (installObserver != null) { 1965 try { 1966 Bundle extras = extrasForInstallResult(res); 1967 installObserver.onPackageInstalled(res.name, res.returnCode, 1968 res.returnMsg, extras); 1969 } catch (RemoteException e) { 1970 Slog.i(TAG, "Observer no longer exists."); 1971 } 1972 } 1973 } 1974 1975 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1976 PackageParser.Package pkg) { 1977 if (pkg.parentPackage == null) { 1978 return; 1979 } 1980 if (pkg.requestedPermissions == null) { 1981 return; 1982 } 1983 final PackageSetting disabledSysParentPs = mSettings 1984 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1985 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1986 || !disabledSysParentPs.isPrivileged() 1987 || (disabledSysParentPs.childPackageNames != null 1988 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1989 return; 1990 } 1991 final int[] allUserIds = sUserManager.getUserIds(); 1992 final int permCount = pkg.requestedPermissions.size(); 1993 for (int i = 0; i < permCount; i++) { 1994 String permission = pkg.requestedPermissions.get(i); 1995 BasePermission bp = mSettings.mPermissions.get(permission); 1996 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1997 continue; 1998 } 1999 for (int userId : allUserIds) { 2000 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2001 permission, userId)) { 2002 grantRuntimePermission(pkg.packageName, permission, userId); 2003 } 2004 } 2005 } 2006 } 2007 2008 private StorageEventListener mStorageListener = new StorageEventListener() { 2009 @Override 2010 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2011 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2012 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2013 final String volumeUuid = vol.getFsUuid(); 2014 2015 // Clean up any users or apps that were removed or recreated 2016 // while this volume was missing 2017 reconcileUsers(volumeUuid); 2018 reconcileApps(volumeUuid); 2019 2020 // Clean up any install sessions that expired or were 2021 // cancelled while this volume was missing 2022 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2023 2024 loadPrivatePackages(vol); 2025 2026 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2027 unloadPrivatePackages(vol); 2028 } 2029 } 2030 2031 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2032 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2033 updateExternalMediaStatus(true, false); 2034 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2035 updateExternalMediaStatus(false, false); 2036 } 2037 } 2038 } 2039 2040 @Override 2041 public void onVolumeForgotten(String fsUuid) { 2042 if (TextUtils.isEmpty(fsUuid)) { 2043 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2044 return; 2045 } 2046 2047 // Remove any apps installed on the forgotten volume 2048 synchronized (mPackages) { 2049 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2050 for (PackageSetting ps : packages) { 2051 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2052 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2053 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2054 } 2055 2056 mSettings.onVolumeForgotten(fsUuid); 2057 mSettings.writeLPr(); 2058 } 2059 } 2060 }; 2061 2062 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2063 String[] grantedPermissions) { 2064 for (int userId : userIds) { 2065 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2066 } 2067 2068 // We could have touched GID membership, so flush out packages.list 2069 synchronized (mPackages) { 2070 mSettings.writePackageListLPr(); 2071 } 2072 } 2073 2074 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2075 String[] grantedPermissions) { 2076 SettingBase sb = (SettingBase) pkg.mExtras; 2077 if (sb == null) { 2078 return; 2079 } 2080 2081 PermissionsState permissionsState = sb.getPermissionsState(); 2082 2083 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2084 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2085 2086 for (String permission : pkg.requestedPermissions) { 2087 final BasePermission bp; 2088 synchronized (mPackages) { 2089 bp = mSettings.mPermissions.get(permission); 2090 } 2091 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2092 && (grantedPermissions == null 2093 || ArrayUtils.contains(grantedPermissions, permission))) { 2094 final int flags = permissionsState.getPermissionFlags(permission, userId); 2095 // Installer cannot change immutable permissions. 2096 if ((flags & immutableFlags) == 0) { 2097 grantRuntimePermission(pkg.packageName, permission, userId); 2098 } 2099 } 2100 } 2101 } 2102 2103 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2104 Bundle extras = null; 2105 switch (res.returnCode) { 2106 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2107 extras = new Bundle(); 2108 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2109 res.origPermission); 2110 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2111 res.origPackage); 2112 break; 2113 } 2114 case PackageManager.INSTALL_SUCCEEDED: { 2115 extras = new Bundle(); 2116 extras.putBoolean(Intent.EXTRA_REPLACING, 2117 res.removedInfo != null && res.removedInfo.removedPackage != null); 2118 break; 2119 } 2120 } 2121 return extras; 2122 } 2123 2124 void scheduleWriteSettingsLocked() { 2125 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2126 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2127 } 2128 } 2129 2130 void scheduleWritePackageListLocked(int userId) { 2131 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2132 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2133 msg.arg1 = userId; 2134 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2135 } 2136 } 2137 2138 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2139 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2140 scheduleWritePackageRestrictionsLocked(userId); 2141 } 2142 2143 void scheduleWritePackageRestrictionsLocked(int userId) { 2144 final int[] userIds = (userId == UserHandle.USER_ALL) 2145 ? sUserManager.getUserIds() : new int[]{userId}; 2146 for (int nextUserId : userIds) { 2147 if (!sUserManager.exists(nextUserId)) return; 2148 mDirtyUsers.add(nextUserId); 2149 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2150 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2151 } 2152 } 2153 } 2154 2155 public static PackageManagerService main(Context context, Installer installer, 2156 boolean factoryTest, boolean onlyCore) { 2157 // Self-check for initial settings. 2158 PackageManagerServiceCompilerMapping.checkProperties(); 2159 2160 PackageManagerService m = new PackageManagerService(context, installer, 2161 factoryTest, onlyCore); 2162 m.enableSystemUserPackages(); 2163 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2164 // disabled after already being started. 2165 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2166 UserHandle.USER_SYSTEM); 2167 ServiceManager.addService("package", m); 2168 return m; 2169 } 2170 2171 private void enableSystemUserPackages() { 2172 if (!UserManager.isSplitSystemUser()) { 2173 return; 2174 } 2175 // For system user, enable apps based on the following conditions: 2176 // - app is whitelisted or belong to one of these groups: 2177 // -- system app which has no launcher icons 2178 // -- system app which has INTERACT_ACROSS_USERS permission 2179 // -- system IME app 2180 // - app is not in the blacklist 2181 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2182 Set<String> enableApps = new ArraySet<>(); 2183 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2184 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2185 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2186 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2187 enableApps.addAll(wlApps); 2188 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2189 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2190 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2191 enableApps.removeAll(blApps); 2192 Log.i(TAG, "Applications installed for system user: " + enableApps); 2193 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2194 UserHandle.SYSTEM); 2195 final int allAppsSize = allAps.size(); 2196 synchronized (mPackages) { 2197 for (int i = 0; i < allAppsSize; i++) { 2198 String pName = allAps.get(i); 2199 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2200 // Should not happen, but we shouldn't be failing if it does 2201 if (pkgSetting == null) { 2202 continue; 2203 } 2204 boolean install = enableApps.contains(pName); 2205 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2206 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2207 + " for system user"); 2208 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2209 } 2210 } 2211 } 2212 } 2213 2214 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2215 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2216 Context.DISPLAY_SERVICE); 2217 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2218 } 2219 2220 public PackageManagerService(Context context, Installer installer, 2221 boolean factoryTest, boolean onlyCore) { 2222 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2223 SystemClock.uptimeMillis()); 2224 2225 if (mSdkVersion <= 0) { 2226 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2227 } 2228 2229 mContext = context; 2230 mFactoryTest = factoryTest; 2231 mOnlyCore = onlyCore; 2232 mMetrics = new DisplayMetrics(); 2233 mSettings = new Settings(mPackages); 2234 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2245 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2246 2247 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2248 if (separateProcesses != null && separateProcesses.length() > 0) { 2249 if ("*".equals(separateProcesses)) { 2250 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2251 mSeparateProcesses = null; 2252 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2253 } else { 2254 mDefParseFlags = 0; 2255 mSeparateProcesses = separateProcesses.split(","); 2256 Slog.w(TAG, "Running with debug.separate_processes: " 2257 + separateProcesses); 2258 } 2259 } else { 2260 mDefParseFlags = 0; 2261 mSeparateProcesses = null; 2262 } 2263 2264 mInstaller = installer; 2265 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2266 "*dexopt*"); 2267 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2268 2269 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2270 FgThread.get().getLooper()); 2271 2272 getDefaultDisplayMetrics(context, mMetrics); 2273 2274 SystemConfig systemConfig = SystemConfig.getInstance(); 2275 mGlobalGids = systemConfig.getGlobalGids(); 2276 mSystemPermissions = systemConfig.getSystemPermissions(); 2277 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2278 2279 synchronized (mInstallLock) { 2280 // writer 2281 synchronized (mPackages) { 2282 mHandlerThread = new ServiceThread(TAG, 2283 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2284 mHandlerThread.start(); 2285 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2286 mProcessLoggingHandler = new ProcessLoggingHandler(); 2287 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2288 2289 File dataDir = Environment.getDataDirectory(); 2290 mAppInstallDir = new File(dataDir, "app"); 2291 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2292 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2293 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2294 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2295 2296 sUserManager = new UserManagerService(context, this, mPackages); 2297 2298 // Propagate permission configuration in to package manager. 2299 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2300 = systemConfig.getPermissions(); 2301 for (int i=0; i<permConfig.size(); i++) { 2302 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2303 BasePermission bp = mSettings.mPermissions.get(perm.name); 2304 if (bp == null) { 2305 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2306 mSettings.mPermissions.put(perm.name, bp); 2307 } 2308 if (perm.gids != null) { 2309 bp.setGids(perm.gids, perm.perUser); 2310 } 2311 } 2312 2313 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2314 for (int i=0; i<libConfig.size(); i++) { 2315 mSharedLibraries.put(libConfig.keyAt(i), 2316 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2317 } 2318 2319 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2320 2321 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2322 2323 String customResolverActivity = Resources.getSystem().getString( 2324 R.string.config_customResolverActivity); 2325 if (TextUtils.isEmpty(customResolverActivity)) { 2326 customResolverActivity = null; 2327 } else { 2328 mCustomResolverComponentName = ComponentName.unflattenFromString( 2329 customResolverActivity); 2330 } 2331 2332 long startTime = SystemClock.uptimeMillis(); 2333 2334 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2335 startTime); 2336 2337 // Set flag to monitor and not change apk file paths when 2338 // scanning install directories. 2339 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2340 2341 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2342 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2343 2344 if (bootClassPath == null) { 2345 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2346 } 2347 2348 if (systemServerClassPath == null) { 2349 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2350 } 2351 2352 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2353 final String[] dexCodeInstructionSets = 2354 getDexCodeInstructionSets( 2355 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2356 2357 /** 2358 * Ensure all external libraries have had dexopt run on them. 2359 */ 2360 if (mSharedLibraries.size() > 0) { 2361 // NOTE: For now, we're compiling these system "shared libraries" 2362 // (and framework jars) into all available architectures. It's possible 2363 // to compile them only when we come across an app that uses them (there's 2364 // already logic for that in scanPackageLI) but that adds some complexity. 2365 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2366 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2367 final String lib = libEntry.path; 2368 if (lib == null) { 2369 continue; 2370 } 2371 2372 try { 2373 // Shared libraries do not have profiles so we perform a full 2374 // AOT compilation (if needed). 2375 int dexoptNeeded = DexFile.getDexOptNeeded( 2376 lib, dexCodeInstructionSet, 2377 getCompilerFilterForReason(REASON_SHARED_APK), 2378 false /* newProfile */); 2379 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2380 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2381 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2382 getCompilerFilterForReason(REASON_SHARED_APK), 2383 StorageManager.UUID_PRIVATE_INTERNAL, 2384 SKIP_SHARED_LIBRARY_CHECK); 2385 } 2386 } catch (FileNotFoundException e) { 2387 Slog.w(TAG, "Library not found: " + lib); 2388 } catch (IOException | InstallerException e) { 2389 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2390 + e.getMessage()); 2391 } 2392 } 2393 } 2394 } 2395 2396 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2397 2398 final VersionInfo ver = mSettings.getInternalVersion(); 2399 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2400 2401 // when upgrading from pre-M, promote system app permissions from install to runtime 2402 mPromoteSystemApps = 2403 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2404 2405 // When upgrading from pre-N, we need to handle package extraction like first boot, 2406 // as there is no profiling data available. 2407 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2408 2409 // save off the names of pre-existing system packages prior to scanning; we don't 2410 // want to automatically grant runtime permissions for new system apps 2411 if (mPromoteSystemApps) { 2412 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2413 while (pkgSettingIter.hasNext()) { 2414 PackageSetting ps = pkgSettingIter.next(); 2415 if (isSystemApp(ps)) { 2416 mExistingSystemPackages.add(ps.name); 2417 } 2418 } 2419 } 2420 2421 // Collect vendor overlay packages. 2422 // (Do this before scanning any apps.) 2423 // For security and version matching reason, only consider 2424 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2425 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2426 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR 2429 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2430 2431 // Find base frameworks (resource packages without code). 2432 scanDirTracedLI(frameworkDir, mDefParseFlags 2433 | PackageParser.PARSE_IS_SYSTEM 2434 | PackageParser.PARSE_IS_SYSTEM_DIR 2435 | PackageParser.PARSE_IS_PRIVILEGED, 2436 scanFlags | SCAN_NO_DEX, 0); 2437 2438 // Collected privileged system packages. 2439 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2440 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2441 | PackageParser.PARSE_IS_SYSTEM 2442 | PackageParser.PARSE_IS_SYSTEM_DIR 2443 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2444 2445 // Collect ordinary system packages. 2446 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2447 scanDirTracedLI(systemAppDir, mDefParseFlags 2448 | PackageParser.PARSE_IS_SYSTEM 2449 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2450 2451 // Collect all vendor packages. 2452 File vendorAppDir = new File("/vendor/app"); 2453 try { 2454 vendorAppDir = vendorAppDir.getCanonicalFile(); 2455 } catch (IOException e) { 2456 // failed to look up canonical path, continue with original one 2457 } 2458 scanDirTracedLI(vendorAppDir, mDefParseFlags 2459 | PackageParser.PARSE_IS_SYSTEM 2460 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2461 2462 // Collect all OEM packages. 2463 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2464 scanDirTracedLI(oemAppDir, mDefParseFlags 2465 | PackageParser.PARSE_IS_SYSTEM 2466 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2467 2468 // Prune any system packages that no longer exist. 2469 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2470 if (!mOnlyCore) { 2471 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2472 while (psit.hasNext()) { 2473 PackageSetting ps = psit.next(); 2474 2475 /* 2476 * If this is not a system app, it can't be a 2477 * disable system app. 2478 */ 2479 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2480 continue; 2481 } 2482 2483 /* 2484 * If the package is scanned, it's not erased. 2485 */ 2486 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2487 if (scannedPkg != null) { 2488 /* 2489 * If the system app is both scanned and in the 2490 * disabled packages list, then it must have been 2491 * added via OTA. Remove it from the currently 2492 * scanned package so the previously user-installed 2493 * application can be scanned. 2494 */ 2495 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2496 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2497 + ps.name + "; removing system app. Last known codePath=" 2498 + ps.codePathString + ", installStatus=" + ps.installStatus 2499 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2500 + scannedPkg.mVersionCode); 2501 removePackageLI(scannedPkg, true); 2502 mExpectingBetter.put(ps.name, ps.codePath); 2503 } 2504 2505 continue; 2506 } 2507 2508 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2509 psit.remove(); 2510 logCriticalInfo(Log.WARN, "System package " + ps.name 2511 + " no longer exists; it's data will be wiped"); 2512 // Actual deletion of code and data will be handled by later 2513 // reconciliation step 2514 } else { 2515 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2516 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2517 possiblyDeletedUpdatedSystemApps.add(ps.name); 2518 } 2519 } 2520 } 2521 } 2522 2523 //look for any incomplete package installations 2524 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2525 for (int i = 0; i < deletePkgsList.size(); i++) { 2526 // Actual deletion of code and data will be handled by later 2527 // reconciliation step 2528 final String packageName = deletePkgsList.get(i).name; 2529 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2530 synchronized (mPackages) { 2531 mSettings.removePackageLPw(packageName); 2532 } 2533 } 2534 2535 //delete tmp files 2536 deleteTempPackageFiles(); 2537 2538 // Remove any shared userIDs that have no associated packages 2539 mSettings.pruneSharedUsersLPw(); 2540 2541 if (!mOnlyCore) { 2542 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2543 SystemClock.uptimeMillis()); 2544 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2545 2546 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2547 | PackageParser.PARSE_FORWARD_LOCK, 2548 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2551 | PackageParser.PARSE_IS_EPHEMERAL, 2552 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2553 2554 /** 2555 * Remove disable package settings for any updated system 2556 * apps that were removed via an OTA. If they're not a 2557 * previously-updated app, remove them completely. 2558 * Otherwise, just revoke their system-level permissions. 2559 */ 2560 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2561 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2562 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2563 2564 String msg; 2565 if (deletedPkg == null) { 2566 msg = "Updated system package " + deletedAppName 2567 + " no longer exists; it's data will be wiped"; 2568 // Actual deletion of code and data will be handled by later 2569 // reconciliation step 2570 } else { 2571 msg = "Updated system app + " + deletedAppName 2572 + " no longer present; removing system privileges for " 2573 + deletedAppName; 2574 2575 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2576 2577 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2578 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2579 } 2580 logCriticalInfo(Log.WARN, msg); 2581 } 2582 2583 /** 2584 * Make sure all system apps that we expected to appear on 2585 * the userdata partition actually showed up. If they never 2586 * appeared, crawl back and revive the system version. 2587 */ 2588 for (int i = 0; i < mExpectingBetter.size(); i++) { 2589 final String packageName = mExpectingBetter.keyAt(i); 2590 if (!mPackages.containsKey(packageName)) { 2591 final File scanFile = mExpectingBetter.valueAt(i); 2592 2593 logCriticalInfo(Log.WARN, "Expected better " + packageName 2594 + " but never showed up; reverting to system"); 2595 2596 int reparseFlags = mDefParseFlags; 2597 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2598 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR 2600 | PackageParser.PARSE_IS_PRIVILEGED; 2601 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR; 2604 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2605 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2606 | PackageParser.PARSE_IS_SYSTEM_DIR; 2607 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2608 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2609 | PackageParser.PARSE_IS_SYSTEM_DIR; 2610 } else { 2611 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2612 continue; 2613 } 2614 2615 mSettings.enableSystemPackageLPw(packageName); 2616 2617 try { 2618 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2619 } catch (PackageManagerException e) { 2620 Slog.e(TAG, "Failed to parse original system package: " 2621 + e.getMessage()); 2622 } 2623 } 2624 } 2625 } 2626 mExpectingBetter.clear(); 2627 2628 // Resolve protected action filters. Only the setup wizard is allowed to 2629 // have a high priority filter for these actions. 2630 mSetupWizardPackage = getSetupWizardPackageName(); 2631 if (mProtectedFilters.size() > 0) { 2632 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2633 Slog.i(TAG, "No setup wizard;" 2634 + " All protected intents capped to priority 0"); 2635 } 2636 for (ActivityIntentInfo filter : mProtectedFilters) { 2637 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2638 if (DEBUG_FILTERS) { 2639 Slog.i(TAG, "Found setup wizard;" 2640 + " allow priority " + filter.getPriority() + ";" 2641 + " package: " + filter.activity.info.packageName 2642 + " activity: " + filter.activity.className 2643 + " priority: " + filter.getPriority()); 2644 } 2645 // skip setup wizard; allow it to keep the high priority filter 2646 continue; 2647 } 2648 Slog.w(TAG, "Protected action; cap priority to 0;" 2649 + " package: " + filter.activity.info.packageName 2650 + " activity: " + filter.activity.className 2651 + " origPrio: " + filter.getPriority()); 2652 filter.setPriority(0); 2653 } 2654 } 2655 mDeferProtectedFilters = false; 2656 mProtectedFilters.clear(); 2657 2658 // Now that we know all of the shared libraries, update all clients to have 2659 // the correct library paths. 2660 updateAllSharedLibrariesLPw(); 2661 2662 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2663 // NOTE: We ignore potential failures here during a system scan (like 2664 // the rest of the commands above) because there's precious little we 2665 // can do about it. A settings error is reported, though. 2666 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2667 false /* boot complete */); 2668 } 2669 2670 // Now that we know all the packages we are keeping, 2671 // read and update their last usage times. 2672 mPackageUsage.readLP(); 2673 2674 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2675 SystemClock.uptimeMillis()); 2676 Slog.i(TAG, "Time to scan packages: " 2677 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2678 + " seconds"); 2679 2680 // If the platform SDK has changed since the last time we booted, 2681 // we need to re-grant app permission to catch any new ones that 2682 // appear. This is really a hack, and means that apps can in some 2683 // cases get permissions that the user didn't initially explicitly 2684 // allow... it would be nice to have some better way to handle 2685 // this situation. 2686 int updateFlags = UPDATE_PERMISSIONS_ALL; 2687 if (ver.sdkVersion != mSdkVersion) { 2688 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2689 + mSdkVersion + "; regranting permissions for internal storage"); 2690 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2691 } 2692 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2693 ver.sdkVersion = mSdkVersion; 2694 2695 // If this is the first boot or an update from pre-M, and it is a normal 2696 // boot, then we need to initialize the default preferred apps across 2697 // all defined users. 2698 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2699 for (UserInfo user : sUserManager.getUsers(true)) { 2700 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2701 applyFactoryDefaultBrowserLPw(user.id); 2702 primeDomainVerificationsLPw(user.id); 2703 } 2704 } 2705 2706 // Prepare storage for system user really early during boot, 2707 // since core system apps like SettingsProvider and SystemUI 2708 // can't wait for user to start 2709 final int storageFlags; 2710 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2711 storageFlags = StorageManager.FLAG_STORAGE_DE; 2712 } else { 2713 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2714 } 2715 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2716 storageFlags); 2717 2718 // If this is first boot after an OTA, and a normal boot, then 2719 // we need to clear code cache directories. 2720 // Note that we do *not* clear the application profiles. These remain valid 2721 // across OTAs and are used to drive profile verification (post OTA) and 2722 // profile compilation (without waiting to collect a fresh set of profiles). 2723 if (mIsUpgrade && !onlyCore) { 2724 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2725 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2726 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2727 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2728 // No apps are running this early, so no need to freeze 2729 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2730 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2731 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2732 } 2733 } 2734 ver.fingerprint = Build.FINGERPRINT; 2735 } 2736 2737 checkDefaultBrowser(); 2738 2739 // clear only after permissions and other defaults have been updated 2740 mExistingSystemPackages.clear(); 2741 mPromoteSystemApps = false; 2742 2743 // All the changes are done during package scanning. 2744 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2745 2746 // can downgrade to reader 2747 mSettings.writeLPr(); 2748 2749 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2750 // early on (before the package manager declares itself as early) because other 2751 // components in the system server might ask for package contexts for these apps. 2752 // 2753 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2754 // (i.e, that the data partition is unavailable). 2755 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2756 long start = System.nanoTime(); 2757 List<PackageParser.Package> coreApps = new ArrayList<>(); 2758 for (PackageParser.Package pkg : mPackages.values()) { 2759 if (pkg.coreApp) { 2760 coreApps.add(pkg); 2761 } 2762 } 2763 2764 int[] stats = performDexOpt(coreApps, false, 2765 getCompilerFilterForReason(REASON_CORE_APP)); 2766 2767 final int elapsedTimeSeconds = 2768 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2769 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2770 2771 if (DEBUG_DEXOPT) { 2772 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2773 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2774 } 2775 2776 2777 // TODO: Should we log these stats to tron too ? 2778 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2779 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2780 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2781 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2782 } 2783 2784 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2785 SystemClock.uptimeMillis()); 2786 2787 if (!mOnlyCore) { 2788 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2789 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2790 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2791 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2792 mIntentFilterVerifierComponent); 2793 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2794 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2795 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2796 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2797 } else { 2798 mRequiredVerifierPackage = null; 2799 mRequiredInstallerPackage = null; 2800 mIntentFilterVerifierComponent = null; 2801 mIntentFilterVerifier = null; 2802 mServicesSystemSharedLibraryPackageName = null; 2803 mSharedSystemSharedLibraryPackageName = null; 2804 } 2805 2806 mInstallerService = new PackageInstallerService(context, this); 2807 2808 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2809 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2810 // both the installer and resolver must be present to enable ephemeral 2811 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2812 if (DEBUG_EPHEMERAL) { 2813 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2814 + " installer:" + ephemeralInstallerComponent); 2815 } 2816 mEphemeralResolverComponent = ephemeralResolverComponent; 2817 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2818 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2819 mEphemeralResolverConnection = 2820 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2821 } else { 2822 if (DEBUG_EPHEMERAL) { 2823 final String missingComponent = 2824 (ephemeralResolverComponent == null) 2825 ? (ephemeralInstallerComponent == null) 2826 ? "resolver and installer" 2827 : "resolver" 2828 : "installer"; 2829 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2830 } 2831 mEphemeralResolverComponent = null; 2832 mEphemeralInstallerComponent = null; 2833 mEphemeralResolverConnection = null; 2834 } 2835 2836 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2837 } // synchronized (mPackages) 2838 } // synchronized (mInstallLock) 2839 2840 // Now after opening every single application zip, make sure they 2841 // are all flushed. Not really needed, but keeps things nice and 2842 // tidy. 2843 Runtime.getRuntime().gc(); 2844 2845 // The initial scanning above does many calls into installd while 2846 // holding the mPackages lock, but we're mostly interested in yelling 2847 // once we have a booted system. 2848 mInstaller.setWarnIfHeld(mPackages); 2849 2850 // Expose private service for system components to use. 2851 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2852 } 2853 2854 @Override 2855 public boolean isFirstBoot() { 2856 return !mRestoredSettings; 2857 } 2858 2859 @Override 2860 public boolean isOnlyCoreApps() { 2861 return mOnlyCore; 2862 } 2863 2864 @Override 2865 public boolean isUpgrade() { 2866 return mIsUpgrade; 2867 } 2868 2869 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2870 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2871 2872 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2873 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2874 UserHandle.USER_SYSTEM); 2875 if (matches.size() == 1) { 2876 return matches.get(0).getComponentInfo().packageName; 2877 } else { 2878 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2879 return null; 2880 } 2881 } 2882 2883 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2884 synchronized (mPackages) { 2885 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2886 if (libraryEntry == null) { 2887 throw new IllegalStateException("Missing required shared library:" + libraryName); 2888 } 2889 return libraryEntry.apk; 2890 } 2891 } 2892 2893 private @NonNull String getRequiredInstallerLPr() { 2894 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2895 intent.addCategory(Intent.CATEGORY_DEFAULT); 2896 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2897 2898 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2899 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2900 UserHandle.USER_SYSTEM); 2901 if (matches.size() == 1) { 2902 ResolveInfo resolveInfo = matches.get(0); 2903 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2904 throw new RuntimeException("The installer must be a privileged app"); 2905 } 2906 return matches.get(0).getComponentInfo().packageName; 2907 } else { 2908 throw new RuntimeException("There must be exactly one installer; found " + matches); 2909 } 2910 } 2911 2912 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2913 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2914 2915 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2916 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2917 UserHandle.USER_SYSTEM); 2918 ResolveInfo best = null; 2919 final int N = matches.size(); 2920 for (int i = 0; i < N; i++) { 2921 final ResolveInfo cur = matches.get(i); 2922 final String packageName = cur.getComponentInfo().packageName; 2923 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2924 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2925 continue; 2926 } 2927 2928 if (best == null || cur.priority > best.priority) { 2929 best = cur; 2930 } 2931 } 2932 2933 if (best != null) { 2934 return best.getComponentInfo().getComponentName(); 2935 } else { 2936 throw new RuntimeException("There must be at least one intent filter verifier"); 2937 } 2938 } 2939 2940 private @Nullable ComponentName getEphemeralResolverLPr() { 2941 final String[] packageArray = 2942 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2943 if (packageArray.length == 0) { 2944 if (DEBUG_EPHEMERAL) { 2945 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2946 } 2947 return null; 2948 } 2949 2950 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2951 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2952 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2953 UserHandle.USER_SYSTEM); 2954 2955 final int N = resolvers.size(); 2956 if (N == 0) { 2957 if (DEBUG_EPHEMERAL) { 2958 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2959 } 2960 return null; 2961 } 2962 2963 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2964 for (int i = 0; i < N; i++) { 2965 final ResolveInfo info = resolvers.get(i); 2966 2967 if (info.serviceInfo == null) { 2968 continue; 2969 } 2970 2971 final String packageName = info.serviceInfo.packageName; 2972 if (!possiblePackages.contains(packageName)) { 2973 if (DEBUG_EPHEMERAL) { 2974 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2975 + " pkg: " + packageName + ", info:" + info); 2976 } 2977 continue; 2978 } 2979 2980 if (DEBUG_EPHEMERAL) { 2981 Slog.v(TAG, "Ephemeral resolver found;" 2982 + " pkg: " + packageName + ", info:" + info); 2983 } 2984 return new ComponentName(packageName, info.serviceInfo.name); 2985 } 2986 if (DEBUG_EPHEMERAL) { 2987 Slog.v(TAG, "Ephemeral resolver NOT found"); 2988 } 2989 return null; 2990 } 2991 2992 private @Nullable ComponentName getEphemeralInstallerLPr() { 2993 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2994 intent.addCategory(Intent.CATEGORY_DEFAULT); 2995 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2996 2997 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2998 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2999 UserHandle.USER_SYSTEM); 3000 if (matches.size() == 0) { 3001 return null; 3002 } else if (matches.size() == 1) { 3003 return matches.get(0).getComponentInfo().getComponentName(); 3004 } else { 3005 throw new RuntimeException( 3006 "There must be at most one ephemeral installer; found " + matches); 3007 } 3008 } 3009 3010 private void primeDomainVerificationsLPw(int userId) { 3011 if (DEBUG_DOMAIN_VERIFICATION) { 3012 Slog.d(TAG, "Priming domain verifications in user " + userId); 3013 } 3014 3015 SystemConfig systemConfig = SystemConfig.getInstance(); 3016 ArraySet<String> packages = systemConfig.getLinkedApps(); 3017 ArraySet<String> domains = new ArraySet<String>(); 3018 3019 for (String packageName : packages) { 3020 PackageParser.Package pkg = mPackages.get(packageName); 3021 if (pkg != null) { 3022 if (!pkg.isSystemApp()) { 3023 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3024 continue; 3025 } 3026 3027 domains.clear(); 3028 for (PackageParser.Activity a : pkg.activities) { 3029 for (ActivityIntentInfo filter : a.intents) { 3030 if (hasValidDomains(filter)) { 3031 domains.addAll(filter.getHostsList()); 3032 } 3033 } 3034 } 3035 3036 if (domains.size() > 0) { 3037 if (DEBUG_DOMAIN_VERIFICATION) { 3038 Slog.v(TAG, " + " + packageName); 3039 } 3040 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3041 // state w.r.t. the formal app-linkage "no verification attempted" state; 3042 // and then 'always' in the per-user state actually used for intent resolution. 3043 final IntentFilterVerificationInfo ivi; 3044 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3045 new ArrayList<String>(domains)); 3046 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3047 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3048 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3049 } else { 3050 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3051 + "' does not handle web links"); 3052 } 3053 } else { 3054 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3055 } 3056 } 3057 3058 scheduleWritePackageRestrictionsLocked(userId); 3059 scheduleWriteSettingsLocked(); 3060 } 3061 3062 private void applyFactoryDefaultBrowserLPw(int userId) { 3063 // The default browser app's package name is stored in a string resource, 3064 // with a product-specific overlay used for vendor customization. 3065 String browserPkg = mContext.getResources().getString( 3066 com.android.internal.R.string.default_browser); 3067 if (!TextUtils.isEmpty(browserPkg)) { 3068 // non-empty string => required to be a known package 3069 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3070 if (ps == null) { 3071 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3072 browserPkg = null; 3073 } else { 3074 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3075 } 3076 } 3077 3078 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3079 // default. If there's more than one, just leave everything alone. 3080 if (browserPkg == null) { 3081 calculateDefaultBrowserLPw(userId); 3082 } 3083 } 3084 3085 private void calculateDefaultBrowserLPw(int userId) { 3086 List<String> allBrowsers = resolveAllBrowserApps(userId); 3087 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3088 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3089 } 3090 3091 private List<String> resolveAllBrowserApps(int userId) { 3092 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3093 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3094 PackageManager.MATCH_ALL, userId); 3095 3096 final int count = list.size(); 3097 List<String> result = new ArrayList<String>(count); 3098 for (int i=0; i<count; i++) { 3099 ResolveInfo info = list.get(i); 3100 if (info.activityInfo == null 3101 || !info.handleAllWebDataURI 3102 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3103 || result.contains(info.activityInfo.packageName)) { 3104 continue; 3105 } 3106 result.add(info.activityInfo.packageName); 3107 } 3108 3109 return result; 3110 } 3111 3112 private boolean packageIsBrowser(String packageName, int userId) { 3113 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3114 PackageManager.MATCH_ALL, userId); 3115 final int N = list.size(); 3116 for (int i = 0; i < N; i++) { 3117 ResolveInfo info = list.get(i); 3118 if (packageName.equals(info.activityInfo.packageName)) { 3119 return true; 3120 } 3121 } 3122 return false; 3123 } 3124 3125 private void checkDefaultBrowser() { 3126 final int myUserId = UserHandle.myUserId(); 3127 final String packageName = getDefaultBrowserPackageName(myUserId); 3128 if (packageName != null) { 3129 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3130 if (info == null) { 3131 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3132 synchronized (mPackages) { 3133 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3134 } 3135 } 3136 } 3137 } 3138 3139 @Override 3140 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3141 throws RemoteException { 3142 try { 3143 return super.onTransact(code, data, reply, flags); 3144 } catch (RuntimeException e) { 3145 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3146 Slog.wtf(TAG, "Package Manager Crash", e); 3147 } 3148 throw e; 3149 } 3150 } 3151 3152 static int[] appendInts(int[] cur, int[] add) { 3153 if (add == null) return cur; 3154 if (cur == null) return add; 3155 final int N = add.length; 3156 for (int i=0; i<N; i++) { 3157 cur = appendInt(cur, add[i]); 3158 } 3159 return cur; 3160 } 3161 3162 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 if (ps == null) { 3165 return null; 3166 } 3167 final PackageParser.Package p = ps.pkg; 3168 if (p == null) { 3169 return null; 3170 } 3171 3172 final PermissionsState permissionsState = ps.getPermissionsState(); 3173 3174 final int[] gids = permissionsState.computeGids(userId); 3175 final Set<String> permissions = permissionsState.getPermissions(userId); 3176 final PackageUserState state = ps.readUserState(userId); 3177 3178 return PackageParser.generatePackageInfo(p, gids, flags, 3179 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3180 } 3181 3182 @Override 3183 public void checkPackageStartable(String packageName, int userId) { 3184 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3185 3186 synchronized (mPackages) { 3187 final PackageSetting ps = mSettings.mPackages.get(packageName); 3188 if (ps == null) { 3189 throw new SecurityException("Package " + packageName + " was not found!"); 3190 } 3191 3192 if (!ps.getInstalled(userId)) { 3193 throw new SecurityException( 3194 "Package " + packageName + " was not installed for user " + userId + "!"); 3195 } 3196 3197 if (mSafeMode && !ps.isSystem()) { 3198 throw new SecurityException("Package " + packageName + " not a system app!"); 3199 } 3200 3201 if (mFrozenPackages.contains(packageName)) { 3202 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3203 } 3204 3205 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3206 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3207 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3208 } 3209 } 3210 } 3211 3212 @Override 3213 public boolean isPackageAvailable(String packageName, int userId) { 3214 if (!sUserManager.exists(userId)) return false; 3215 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3216 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3217 synchronized (mPackages) { 3218 PackageParser.Package p = mPackages.get(packageName); 3219 if (p != null) { 3220 final PackageSetting ps = (PackageSetting) p.mExtras; 3221 if (ps != null) { 3222 final PackageUserState state = ps.readUserState(userId); 3223 if (state != null) { 3224 return PackageParser.isAvailable(state); 3225 } 3226 } 3227 } 3228 } 3229 return false; 3230 } 3231 3232 @Override 3233 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3234 if (!sUserManager.exists(userId)) return null; 3235 flags = updateFlagsForPackage(flags, userId, packageName); 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3237 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3238 // reader 3239 synchronized (mPackages) { 3240 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3241 PackageParser.Package p = null; 3242 if (matchFactoryOnly) { 3243 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3244 if (ps != null) { 3245 return generatePackageInfo(ps, flags, userId); 3246 } 3247 } 3248 if (p == null) { 3249 p = mPackages.get(packageName); 3250 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3251 return null; 3252 } 3253 } 3254 if (DEBUG_PACKAGE_INFO) 3255 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3256 if (p != null) { 3257 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3258 } 3259 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3260 final PackageSetting ps = mSettings.mPackages.get(packageName); 3261 return generatePackageInfo(ps, flags, userId); 3262 } 3263 } 3264 return null; 3265 } 3266 3267 @Override 3268 public String[] currentToCanonicalPackageNames(String[] names) { 3269 String[] out = new String[names.length]; 3270 // reader 3271 synchronized (mPackages) { 3272 for (int i=names.length-1; i>=0; i--) { 3273 PackageSetting ps = mSettings.mPackages.get(names[i]); 3274 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3275 } 3276 } 3277 return out; 3278 } 3279 3280 @Override 3281 public String[] canonicalToCurrentPackageNames(String[] names) { 3282 String[] out = new String[names.length]; 3283 // reader 3284 synchronized (mPackages) { 3285 for (int i=names.length-1; i>=0; i--) { 3286 String cur = mSettings.mRenamedPackages.get(names[i]); 3287 out[i] = cur != null ? cur : names[i]; 3288 } 3289 } 3290 return out; 3291 } 3292 3293 @Override 3294 public int getPackageUid(String packageName, int flags, int userId) { 3295 if (!sUserManager.exists(userId)) return -1; 3296 flags = updateFlagsForPackage(flags, userId, packageName); 3297 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3298 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3299 3300 // reader 3301 synchronized (mPackages) { 3302 final PackageParser.Package p = mPackages.get(packageName); 3303 if (p != null && p.isMatch(flags)) { 3304 return UserHandle.getUid(userId, p.applicationInfo.uid); 3305 } 3306 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3307 final PackageSetting ps = mSettings.mPackages.get(packageName); 3308 if (ps != null && ps.isMatch(flags)) { 3309 return UserHandle.getUid(userId, ps.appId); 3310 } 3311 } 3312 } 3313 3314 return -1; 3315 } 3316 3317 @Override 3318 public int[] getPackageGids(String packageName, int flags, int userId) { 3319 if (!sUserManager.exists(userId)) return null; 3320 flags = updateFlagsForPackage(flags, userId, packageName); 3321 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3322 false /* requireFullPermission */, false /* checkShell */, 3323 "getPackageGids"); 3324 3325 // reader 3326 synchronized (mPackages) { 3327 final PackageParser.Package p = mPackages.get(packageName); 3328 if (p != null && p.isMatch(flags)) { 3329 PackageSetting ps = (PackageSetting) p.mExtras; 3330 return ps.getPermissionsState().computeGids(userId); 3331 } 3332 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3333 final PackageSetting ps = mSettings.mPackages.get(packageName); 3334 if (ps != null && ps.isMatch(flags)) { 3335 return ps.getPermissionsState().computeGids(userId); 3336 } 3337 } 3338 } 3339 3340 return null; 3341 } 3342 3343 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3344 if (bp.perm != null) { 3345 return PackageParser.generatePermissionInfo(bp.perm, flags); 3346 } 3347 PermissionInfo pi = new PermissionInfo(); 3348 pi.name = bp.name; 3349 pi.packageName = bp.sourcePackage; 3350 pi.nonLocalizedLabel = bp.name; 3351 pi.protectionLevel = bp.protectionLevel; 3352 return pi; 3353 } 3354 3355 @Override 3356 public PermissionInfo getPermissionInfo(String name, int flags) { 3357 // reader 3358 synchronized (mPackages) { 3359 final BasePermission p = mSettings.mPermissions.get(name); 3360 if (p != null) { 3361 return generatePermissionInfo(p, flags); 3362 } 3363 return null; 3364 } 3365 } 3366 3367 @Override 3368 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3369 int flags) { 3370 // reader 3371 synchronized (mPackages) { 3372 if (group != null && !mPermissionGroups.containsKey(group)) { 3373 // This is thrown as NameNotFoundException 3374 return null; 3375 } 3376 3377 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3378 for (BasePermission p : mSettings.mPermissions.values()) { 3379 if (group == null) { 3380 if (p.perm == null || p.perm.info.group == null) { 3381 out.add(generatePermissionInfo(p, flags)); 3382 } 3383 } else { 3384 if (p.perm != null && group.equals(p.perm.info.group)) { 3385 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3386 } 3387 } 3388 } 3389 return new ParceledListSlice<>(out); 3390 } 3391 } 3392 3393 @Override 3394 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3395 // reader 3396 synchronized (mPackages) { 3397 return PackageParser.generatePermissionGroupInfo( 3398 mPermissionGroups.get(name), flags); 3399 } 3400 } 3401 3402 @Override 3403 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3404 // reader 3405 synchronized (mPackages) { 3406 final int N = mPermissionGroups.size(); 3407 ArrayList<PermissionGroupInfo> out 3408 = new ArrayList<PermissionGroupInfo>(N); 3409 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3410 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3411 } 3412 return new ParceledListSlice<>(out); 3413 } 3414 } 3415 3416 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3417 int userId) { 3418 if (!sUserManager.exists(userId)) return null; 3419 PackageSetting ps = mSettings.mPackages.get(packageName); 3420 if (ps != null) { 3421 if (ps.pkg == null) { 3422 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3423 if (pInfo != null) { 3424 return pInfo.applicationInfo; 3425 } 3426 return null; 3427 } 3428 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3429 ps.readUserState(userId), userId); 3430 } 3431 return null; 3432 } 3433 3434 @Override 3435 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3436 if (!sUserManager.exists(userId)) return null; 3437 flags = updateFlagsForApplication(flags, userId, packageName); 3438 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3439 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3440 // writer 3441 synchronized (mPackages) { 3442 PackageParser.Package p = mPackages.get(packageName); 3443 if (DEBUG_PACKAGE_INFO) Log.v( 3444 TAG, "getApplicationInfo " + packageName 3445 + ": " + p); 3446 if (p != null) { 3447 PackageSetting ps = mSettings.mPackages.get(packageName); 3448 if (ps == null) return null; 3449 // Note: isEnabledLP() does not apply here - always return info 3450 return PackageParser.generateApplicationInfo( 3451 p, flags, ps.readUserState(userId), userId); 3452 } 3453 if ("android".equals(packageName)||"system".equals(packageName)) { 3454 return mAndroidApplication; 3455 } 3456 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3457 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3458 } 3459 } 3460 return null; 3461 } 3462 3463 @Override 3464 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3465 final IPackageDataObserver observer) { 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.CLEAR_APP_CACHE, null); 3468 // Queue up an async operation since clearing cache may take a little while. 3469 mHandler.post(new Runnable() { 3470 public void run() { 3471 mHandler.removeCallbacks(this); 3472 boolean success = true; 3473 synchronized (mInstallLock) { 3474 try { 3475 mInstaller.freeCache(volumeUuid, freeStorageSize); 3476 } catch (InstallerException e) { 3477 Slog.w(TAG, "Couldn't clear application caches: " + e); 3478 success = false; 3479 } 3480 } 3481 if (observer != null) { 3482 try { 3483 observer.onRemoveCompleted(null, success); 3484 } catch (RemoteException e) { 3485 Slog.w(TAG, "RemoveException when invoking call back"); 3486 } 3487 } 3488 } 3489 }); 3490 } 3491 3492 @Override 3493 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3494 final IntentSender pi) { 3495 mContext.enforceCallingOrSelfPermission( 3496 android.Manifest.permission.CLEAR_APP_CACHE, null); 3497 // Queue up an async operation since clearing cache may take a little while. 3498 mHandler.post(new Runnable() { 3499 public void run() { 3500 mHandler.removeCallbacks(this); 3501 boolean success = true; 3502 synchronized (mInstallLock) { 3503 try { 3504 mInstaller.freeCache(volumeUuid, freeStorageSize); 3505 } catch (InstallerException e) { 3506 Slog.w(TAG, "Couldn't clear application caches: " + e); 3507 success = false; 3508 } 3509 } 3510 if(pi != null) { 3511 try { 3512 // Callback via pending intent 3513 int code = success ? 1 : 0; 3514 pi.sendIntent(null, code, null, 3515 null, null); 3516 } catch (SendIntentException e1) { 3517 Slog.i(TAG, "Failed to send pending intent"); 3518 } 3519 } 3520 } 3521 }); 3522 } 3523 3524 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3525 synchronized (mInstallLock) { 3526 try { 3527 mInstaller.freeCache(volumeUuid, freeStorageSize); 3528 } catch (InstallerException e) { 3529 throw new IOException("Failed to free enough space", e); 3530 } 3531 } 3532 } 3533 3534 /** 3535 * Update given flags based on encryption status of current user. 3536 */ 3537 private int updateFlags(int flags, int userId) { 3538 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3539 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3540 // Caller expressed an explicit opinion about what encryption 3541 // aware/unaware components they want to see, so fall through and 3542 // give them what they want 3543 } else { 3544 // Caller expressed no opinion, so match based on user state 3545 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3546 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3547 } else { 3548 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3549 } 3550 } 3551 return flags; 3552 } 3553 3554 private UserManagerInternal getUserManagerInternal() { 3555 if (mUserManagerInternal == null) { 3556 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3557 } 3558 return mUserManagerInternal; 3559 } 3560 3561 /** 3562 * Update given flags when being used to request {@link PackageInfo}. 3563 */ 3564 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3565 boolean triaged = true; 3566 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3567 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3568 // Caller is asking for component details, so they'd better be 3569 // asking for specific encryption matching behavior, or be triaged 3570 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3571 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3572 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3573 triaged = false; 3574 } 3575 } 3576 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3577 | PackageManager.MATCH_SYSTEM_ONLY 3578 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3579 triaged = false; 3580 } 3581 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3582 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3583 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3584 } 3585 return updateFlags(flags, userId); 3586 } 3587 3588 /** 3589 * Update given flags when being used to request {@link ApplicationInfo}. 3590 */ 3591 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3592 return updateFlagsForPackage(flags, userId, cookie); 3593 } 3594 3595 /** 3596 * Update given flags when being used to request {@link ComponentInfo}. 3597 */ 3598 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3599 if (cookie instanceof Intent) { 3600 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3601 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3602 } 3603 } 3604 3605 boolean triaged = true; 3606 // Caller is asking for component details, so they'd better be 3607 // asking for specific encryption matching behavior, or be triaged 3608 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3609 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3610 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3611 triaged = false; 3612 } 3613 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3614 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3615 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3616 } 3617 3618 return updateFlags(flags, userId); 3619 } 3620 3621 /** 3622 * Update given flags when being used to request {@link ResolveInfo}. 3623 */ 3624 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3625 // Safe mode means we shouldn't match any third-party components 3626 if (mSafeMode) { 3627 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3628 } 3629 3630 return updateFlagsForComponent(flags, userId, cookie); 3631 } 3632 3633 @Override 3634 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3635 if (!sUserManager.exists(userId)) return null; 3636 flags = updateFlagsForComponent(flags, userId, component); 3637 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3638 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3639 synchronized (mPackages) { 3640 PackageParser.Activity a = mActivities.mActivities.get(component); 3641 3642 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3643 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3644 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3645 if (ps == null) return null; 3646 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3647 userId); 3648 } 3649 if (mResolveComponentName.equals(component)) { 3650 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3651 new PackageUserState(), userId); 3652 } 3653 } 3654 return null; 3655 } 3656 3657 @Override 3658 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3659 String resolvedType) { 3660 synchronized (mPackages) { 3661 if (component.equals(mResolveComponentName)) { 3662 // The resolver supports EVERYTHING! 3663 return true; 3664 } 3665 PackageParser.Activity a = mActivities.mActivities.get(component); 3666 if (a == null) { 3667 return false; 3668 } 3669 for (int i=0; i<a.intents.size(); i++) { 3670 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3671 intent.getData(), intent.getCategories(), TAG) >= 0) { 3672 return true; 3673 } 3674 } 3675 return false; 3676 } 3677 } 3678 3679 @Override 3680 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3681 if (!sUserManager.exists(userId)) return null; 3682 flags = updateFlagsForComponent(flags, userId, component); 3683 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3684 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3685 synchronized (mPackages) { 3686 PackageParser.Activity a = mReceivers.mActivities.get(component); 3687 if (DEBUG_PACKAGE_INFO) Log.v( 3688 TAG, "getReceiverInfo " + component + ": " + a); 3689 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3690 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3691 if (ps == null) return null; 3692 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3693 userId); 3694 } 3695 } 3696 return null; 3697 } 3698 3699 @Override 3700 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3701 if (!sUserManager.exists(userId)) return null; 3702 flags = updateFlagsForComponent(flags, userId, component); 3703 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3704 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3705 synchronized (mPackages) { 3706 PackageParser.Service s = mServices.mServices.get(component); 3707 if (DEBUG_PACKAGE_INFO) Log.v( 3708 TAG, "getServiceInfo " + component + ": " + s); 3709 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3710 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3711 if (ps == null) return null; 3712 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3713 userId); 3714 } 3715 } 3716 return null; 3717 } 3718 3719 @Override 3720 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3721 if (!sUserManager.exists(userId)) return null; 3722 flags = updateFlagsForComponent(flags, userId, component); 3723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3724 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3725 synchronized (mPackages) { 3726 PackageParser.Provider p = mProviders.mProviders.get(component); 3727 if (DEBUG_PACKAGE_INFO) Log.v( 3728 TAG, "getProviderInfo " + component + ": " + p); 3729 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3730 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3731 if (ps == null) return null; 3732 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3733 userId); 3734 } 3735 } 3736 return null; 3737 } 3738 3739 @Override 3740 public String[] getSystemSharedLibraryNames() { 3741 Set<String> libSet; 3742 synchronized (mPackages) { 3743 libSet = mSharedLibraries.keySet(); 3744 int size = libSet.size(); 3745 if (size > 0) { 3746 String[] libs = new String[size]; 3747 libSet.toArray(libs); 3748 return libs; 3749 } 3750 } 3751 return null; 3752 } 3753 3754 @Override 3755 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3756 synchronized (mPackages) { 3757 return mServicesSystemSharedLibraryPackageName; 3758 } 3759 } 3760 3761 @Override 3762 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3763 synchronized (mPackages) { 3764 return mSharedSystemSharedLibraryPackageName; 3765 } 3766 } 3767 3768 @Override 3769 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3770 synchronized (mPackages) { 3771 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3772 3773 final FeatureInfo fi = new FeatureInfo(); 3774 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3775 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3776 res.add(fi); 3777 3778 return new ParceledListSlice<>(res); 3779 } 3780 } 3781 3782 @Override 3783 public boolean hasSystemFeature(String name, int version) { 3784 synchronized (mPackages) { 3785 final FeatureInfo feat = mAvailableFeatures.get(name); 3786 if (feat == null) { 3787 return false; 3788 } else { 3789 return feat.version >= version; 3790 } 3791 } 3792 } 3793 3794 @Override 3795 public int checkPermission(String permName, String pkgName, int userId) { 3796 if (!sUserManager.exists(userId)) { 3797 return PackageManager.PERMISSION_DENIED; 3798 } 3799 3800 synchronized (mPackages) { 3801 final PackageParser.Package p = mPackages.get(pkgName); 3802 if (p != null && p.mExtras != null) { 3803 final PackageSetting ps = (PackageSetting) p.mExtras; 3804 final PermissionsState permissionsState = ps.getPermissionsState(); 3805 if (permissionsState.hasPermission(permName, userId)) { 3806 return PackageManager.PERMISSION_GRANTED; 3807 } 3808 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3809 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3810 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3811 return PackageManager.PERMISSION_GRANTED; 3812 } 3813 } 3814 } 3815 3816 return PackageManager.PERMISSION_DENIED; 3817 } 3818 3819 @Override 3820 public int checkUidPermission(String permName, int uid) { 3821 final int userId = UserHandle.getUserId(uid); 3822 3823 if (!sUserManager.exists(userId)) { 3824 return PackageManager.PERMISSION_DENIED; 3825 } 3826 3827 synchronized (mPackages) { 3828 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3829 if (obj != null) { 3830 final SettingBase ps = (SettingBase) obj; 3831 final PermissionsState permissionsState = ps.getPermissionsState(); 3832 if (permissionsState.hasPermission(permName, userId)) { 3833 return PackageManager.PERMISSION_GRANTED; 3834 } 3835 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3836 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3837 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3838 return PackageManager.PERMISSION_GRANTED; 3839 } 3840 } else { 3841 ArraySet<String> perms = mSystemPermissions.get(uid); 3842 if (perms != null) { 3843 if (perms.contains(permName)) { 3844 return PackageManager.PERMISSION_GRANTED; 3845 } 3846 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3847 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3848 return PackageManager.PERMISSION_GRANTED; 3849 } 3850 } 3851 } 3852 } 3853 3854 return PackageManager.PERMISSION_DENIED; 3855 } 3856 3857 @Override 3858 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3859 if (UserHandle.getCallingUserId() != userId) { 3860 mContext.enforceCallingPermission( 3861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3862 "isPermissionRevokedByPolicy for user " + userId); 3863 } 3864 3865 if (checkPermission(permission, packageName, userId) 3866 == PackageManager.PERMISSION_GRANTED) { 3867 return false; 3868 } 3869 3870 final long identity = Binder.clearCallingIdentity(); 3871 try { 3872 final int flags = getPermissionFlags(permission, packageName, userId); 3873 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3874 } finally { 3875 Binder.restoreCallingIdentity(identity); 3876 } 3877 } 3878 3879 @Override 3880 public String getPermissionControllerPackageName() { 3881 synchronized (mPackages) { 3882 return mRequiredInstallerPackage; 3883 } 3884 } 3885 3886 /** 3887 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3888 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3889 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3890 * @param message the message to log on security exception 3891 */ 3892 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3893 boolean checkShell, String message) { 3894 if (userId < 0) { 3895 throw new IllegalArgumentException("Invalid userId " + userId); 3896 } 3897 if (checkShell) { 3898 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3899 } 3900 if (userId == UserHandle.getUserId(callingUid)) return; 3901 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3902 if (requireFullPermission) { 3903 mContext.enforceCallingOrSelfPermission( 3904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3905 } else { 3906 try { 3907 mContext.enforceCallingOrSelfPermission( 3908 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3909 } catch (SecurityException se) { 3910 mContext.enforceCallingOrSelfPermission( 3911 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3912 } 3913 } 3914 } 3915 } 3916 3917 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3918 if (callingUid == Process.SHELL_UID) { 3919 if (userHandle >= 0 3920 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3921 throw new SecurityException("Shell does not have permission to access user " 3922 + userHandle); 3923 } else if (userHandle < 0) { 3924 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3925 + Debug.getCallers(3)); 3926 } 3927 } 3928 } 3929 3930 private BasePermission findPermissionTreeLP(String permName) { 3931 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3932 if (permName.startsWith(bp.name) && 3933 permName.length() > bp.name.length() && 3934 permName.charAt(bp.name.length()) == '.') { 3935 return bp; 3936 } 3937 } 3938 return null; 3939 } 3940 3941 private BasePermission checkPermissionTreeLP(String permName) { 3942 if (permName != null) { 3943 BasePermission bp = findPermissionTreeLP(permName); 3944 if (bp != null) { 3945 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3946 return bp; 3947 } 3948 throw new SecurityException("Calling uid " 3949 + Binder.getCallingUid() 3950 + " is not allowed to add to permission tree " 3951 + bp.name + " owned by uid " + bp.uid); 3952 } 3953 } 3954 throw new SecurityException("No permission tree found for " + permName); 3955 } 3956 3957 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3958 if (s1 == null) { 3959 return s2 == null; 3960 } 3961 if (s2 == null) { 3962 return false; 3963 } 3964 if (s1.getClass() != s2.getClass()) { 3965 return false; 3966 } 3967 return s1.equals(s2); 3968 } 3969 3970 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3971 if (pi1.icon != pi2.icon) return false; 3972 if (pi1.logo != pi2.logo) return false; 3973 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3974 if (!compareStrings(pi1.name, pi2.name)) return false; 3975 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3976 // We'll take care of setting this one. 3977 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3978 // These are not currently stored in settings. 3979 //if (!compareStrings(pi1.group, pi2.group)) return false; 3980 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3981 //if (pi1.labelRes != pi2.labelRes) return false; 3982 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3983 return true; 3984 } 3985 3986 int permissionInfoFootprint(PermissionInfo info) { 3987 int size = info.name.length(); 3988 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3989 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3990 return size; 3991 } 3992 3993 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3994 int size = 0; 3995 for (BasePermission perm : mSettings.mPermissions.values()) { 3996 if (perm.uid == tree.uid) { 3997 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3998 } 3999 } 4000 return size; 4001 } 4002 4003 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4004 // We calculate the max size of permissions defined by this uid and throw 4005 // if that plus the size of 'info' would exceed our stated maximum. 4006 if (tree.uid != Process.SYSTEM_UID) { 4007 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4008 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4009 throw new SecurityException("Permission tree size cap exceeded"); 4010 } 4011 } 4012 } 4013 4014 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4015 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4016 throw new SecurityException("Label must be specified in permission"); 4017 } 4018 BasePermission tree = checkPermissionTreeLP(info.name); 4019 BasePermission bp = mSettings.mPermissions.get(info.name); 4020 boolean added = bp == null; 4021 boolean changed = true; 4022 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4023 if (added) { 4024 enforcePermissionCapLocked(info, tree); 4025 bp = new BasePermission(info.name, tree.sourcePackage, 4026 BasePermission.TYPE_DYNAMIC); 4027 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4028 throw new SecurityException( 4029 "Not allowed to modify non-dynamic permission " 4030 + info.name); 4031 } else { 4032 if (bp.protectionLevel == fixedLevel 4033 && bp.perm.owner.equals(tree.perm.owner) 4034 && bp.uid == tree.uid 4035 && comparePermissionInfos(bp.perm.info, info)) { 4036 changed = false; 4037 } 4038 } 4039 bp.protectionLevel = fixedLevel; 4040 info = new PermissionInfo(info); 4041 info.protectionLevel = fixedLevel; 4042 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4043 bp.perm.info.packageName = tree.perm.info.packageName; 4044 bp.uid = tree.uid; 4045 if (added) { 4046 mSettings.mPermissions.put(info.name, bp); 4047 } 4048 if (changed) { 4049 if (!async) { 4050 mSettings.writeLPr(); 4051 } else { 4052 scheduleWriteSettingsLocked(); 4053 } 4054 } 4055 return added; 4056 } 4057 4058 @Override 4059 public boolean addPermission(PermissionInfo info) { 4060 synchronized (mPackages) { 4061 return addPermissionLocked(info, false); 4062 } 4063 } 4064 4065 @Override 4066 public boolean addPermissionAsync(PermissionInfo info) { 4067 synchronized (mPackages) { 4068 return addPermissionLocked(info, true); 4069 } 4070 } 4071 4072 @Override 4073 public void removePermission(String name) { 4074 synchronized (mPackages) { 4075 checkPermissionTreeLP(name); 4076 BasePermission bp = mSettings.mPermissions.get(name); 4077 if (bp != null) { 4078 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4079 throw new SecurityException( 4080 "Not allowed to modify non-dynamic permission " 4081 + name); 4082 } 4083 mSettings.mPermissions.remove(name); 4084 mSettings.writeLPr(); 4085 } 4086 } 4087 } 4088 4089 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4090 BasePermission bp) { 4091 int index = pkg.requestedPermissions.indexOf(bp.name); 4092 if (index == -1) { 4093 throw new SecurityException("Package " + pkg.packageName 4094 + " has not requested permission " + bp.name); 4095 } 4096 if (!bp.isRuntime() && !bp.isDevelopment()) { 4097 throw new SecurityException("Permission " + bp.name 4098 + " is not a changeable permission type"); 4099 } 4100 } 4101 4102 @Override 4103 public void grantRuntimePermission(String packageName, String name, final int userId) { 4104 if (!sUserManager.exists(userId)) { 4105 Log.e(TAG, "No such user:" + userId); 4106 return; 4107 } 4108 4109 mContext.enforceCallingOrSelfPermission( 4110 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4111 "grantRuntimePermission"); 4112 4113 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4114 true /* requireFullPermission */, true /* checkShell */, 4115 "grantRuntimePermission"); 4116 4117 final int uid; 4118 final SettingBase sb; 4119 4120 synchronized (mPackages) { 4121 final PackageParser.Package pkg = mPackages.get(packageName); 4122 if (pkg == null) { 4123 throw new IllegalArgumentException("Unknown package: " + packageName); 4124 } 4125 4126 final BasePermission bp = mSettings.mPermissions.get(name); 4127 if (bp == null) { 4128 throw new IllegalArgumentException("Unknown permission: " + name); 4129 } 4130 4131 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4132 4133 // If a permission review is required for legacy apps we represent 4134 // their permissions as always granted runtime ones since we need 4135 // to keep the review required permission flag per user while an 4136 // install permission's state is shared across all users. 4137 if (Build.PERMISSIONS_REVIEW_REQUIRED 4138 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4139 && bp.isRuntime()) { 4140 return; 4141 } 4142 4143 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4144 sb = (SettingBase) pkg.mExtras; 4145 if (sb == null) { 4146 throw new IllegalArgumentException("Unknown package: " + packageName); 4147 } 4148 4149 final PermissionsState permissionsState = sb.getPermissionsState(); 4150 4151 final int flags = permissionsState.getPermissionFlags(name, userId); 4152 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4153 throw new SecurityException("Cannot grant system fixed permission " 4154 + name + " for package " + packageName); 4155 } 4156 4157 if (bp.isDevelopment()) { 4158 // Development permissions must be handled specially, since they are not 4159 // normal runtime permissions. For now they apply to all users. 4160 if (permissionsState.grantInstallPermission(bp) != 4161 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4162 scheduleWriteSettingsLocked(); 4163 } 4164 return; 4165 } 4166 4167 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4168 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4169 return; 4170 } 4171 4172 final int result = permissionsState.grantRuntimePermission(bp, userId); 4173 switch (result) { 4174 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4175 return; 4176 } 4177 4178 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4179 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4180 mHandler.post(new Runnable() { 4181 @Override 4182 public void run() { 4183 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4184 } 4185 }); 4186 } 4187 break; 4188 } 4189 4190 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4191 4192 // Not critical if that is lost - app has to request again. 4193 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4194 } 4195 4196 // Only need to do this if user is initialized. Otherwise it's a new user 4197 // and there are no processes running as the user yet and there's no need 4198 // to make an expensive call to remount processes for the changed permissions. 4199 if (READ_EXTERNAL_STORAGE.equals(name) 4200 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4201 final long token = Binder.clearCallingIdentity(); 4202 try { 4203 if (sUserManager.isInitialized(userId)) { 4204 MountServiceInternal mountServiceInternal = LocalServices.getService( 4205 MountServiceInternal.class); 4206 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4207 } 4208 } finally { 4209 Binder.restoreCallingIdentity(token); 4210 } 4211 } 4212 } 4213 4214 @Override 4215 public void revokeRuntimePermission(String packageName, String name, int userId) { 4216 if (!sUserManager.exists(userId)) { 4217 Log.e(TAG, "No such user:" + userId); 4218 return; 4219 } 4220 4221 mContext.enforceCallingOrSelfPermission( 4222 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4223 "revokeRuntimePermission"); 4224 4225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4226 true /* requireFullPermission */, true /* checkShell */, 4227 "revokeRuntimePermission"); 4228 4229 final int appId; 4230 4231 synchronized (mPackages) { 4232 final PackageParser.Package pkg = mPackages.get(packageName); 4233 if (pkg == null) { 4234 throw new IllegalArgumentException("Unknown package: " + packageName); 4235 } 4236 4237 final BasePermission bp = mSettings.mPermissions.get(name); 4238 if (bp == null) { 4239 throw new IllegalArgumentException("Unknown permission: " + name); 4240 } 4241 4242 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4243 4244 // If a permission review is required for legacy apps we represent 4245 // their permissions as always granted runtime ones since we need 4246 // to keep the review required permission flag per user while an 4247 // install permission's state is shared across all users. 4248 if (Build.PERMISSIONS_REVIEW_REQUIRED 4249 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4250 && bp.isRuntime()) { 4251 return; 4252 } 4253 4254 SettingBase sb = (SettingBase) pkg.mExtras; 4255 if (sb == null) { 4256 throw new IllegalArgumentException("Unknown package: " + packageName); 4257 } 4258 4259 final PermissionsState permissionsState = sb.getPermissionsState(); 4260 4261 final int flags = permissionsState.getPermissionFlags(name, userId); 4262 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4263 throw new SecurityException("Cannot revoke system fixed permission " 4264 + name + " for package " + packageName); 4265 } 4266 4267 if (bp.isDevelopment()) { 4268 // Development permissions must be handled specially, since they are not 4269 // normal runtime permissions. For now they apply to all users. 4270 if (permissionsState.revokeInstallPermission(bp) != 4271 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4272 scheduleWriteSettingsLocked(); 4273 } 4274 return; 4275 } 4276 4277 if (permissionsState.revokeRuntimePermission(bp, userId) == 4278 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4279 return; 4280 } 4281 4282 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4283 4284 // Critical, after this call app should never have the permission. 4285 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4286 4287 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4288 } 4289 4290 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4291 } 4292 4293 @Override 4294 public void resetRuntimePermissions() { 4295 mContext.enforceCallingOrSelfPermission( 4296 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4297 "revokeRuntimePermission"); 4298 4299 int callingUid = Binder.getCallingUid(); 4300 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4301 mContext.enforceCallingOrSelfPermission( 4302 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4303 "resetRuntimePermissions"); 4304 } 4305 4306 synchronized (mPackages) { 4307 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4308 for (int userId : UserManagerService.getInstance().getUserIds()) { 4309 final int packageCount = mPackages.size(); 4310 for (int i = 0; i < packageCount; i++) { 4311 PackageParser.Package pkg = mPackages.valueAt(i); 4312 if (!(pkg.mExtras instanceof PackageSetting)) { 4313 continue; 4314 } 4315 PackageSetting ps = (PackageSetting) pkg.mExtras; 4316 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4317 } 4318 } 4319 } 4320 } 4321 4322 @Override 4323 public int getPermissionFlags(String name, String packageName, int userId) { 4324 if (!sUserManager.exists(userId)) { 4325 return 0; 4326 } 4327 4328 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4329 4330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4331 true /* requireFullPermission */, false /* checkShell */, 4332 "getPermissionFlags"); 4333 4334 synchronized (mPackages) { 4335 final PackageParser.Package pkg = mPackages.get(packageName); 4336 if (pkg == null) { 4337 return 0; 4338 } 4339 4340 final BasePermission bp = mSettings.mPermissions.get(name); 4341 if (bp == null) { 4342 return 0; 4343 } 4344 4345 SettingBase sb = (SettingBase) pkg.mExtras; 4346 if (sb == null) { 4347 return 0; 4348 } 4349 4350 PermissionsState permissionsState = sb.getPermissionsState(); 4351 return permissionsState.getPermissionFlags(name, userId); 4352 } 4353 } 4354 4355 @Override 4356 public void updatePermissionFlags(String name, String packageName, int flagMask, 4357 int flagValues, int userId) { 4358 if (!sUserManager.exists(userId)) { 4359 return; 4360 } 4361 4362 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4363 4364 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4365 true /* requireFullPermission */, true /* checkShell */, 4366 "updatePermissionFlags"); 4367 4368 // Only the system can change these flags and nothing else. 4369 if (getCallingUid() != Process.SYSTEM_UID) { 4370 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4372 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4373 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4374 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4375 } 4376 4377 synchronized (mPackages) { 4378 final PackageParser.Package pkg = mPackages.get(packageName); 4379 if (pkg == null) { 4380 throw new IllegalArgumentException("Unknown package: " + packageName); 4381 } 4382 4383 final BasePermission bp = mSettings.mPermissions.get(name); 4384 if (bp == null) { 4385 throw new IllegalArgumentException("Unknown permission: " + name); 4386 } 4387 4388 SettingBase sb = (SettingBase) pkg.mExtras; 4389 if (sb == null) { 4390 throw new IllegalArgumentException("Unknown package: " + packageName); 4391 } 4392 4393 PermissionsState permissionsState = sb.getPermissionsState(); 4394 4395 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4396 4397 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4398 // Install and runtime permissions are stored in different places, 4399 // so figure out what permission changed and persist the change. 4400 if (permissionsState.getInstallPermissionState(name) != null) { 4401 scheduleWriteSettingsLocked(); 4402 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4403 || hadState) { 4404 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4405 } 4406 } 4407 } 4408 } 4409 4410 /** 4411 * Update the permission flags for all packages and runtime permissions of a user in order 4412 * to allow device or profile owner to remove POLICY_FIXED. 4413 */ 4414 @Override 4415 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4416 if (!sUserManager.exists(userId)) { 4417 return; 4418 } 4419 4420 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4421 4422 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4423 true /* requireFullPermission */, true /* checkShell */, 4424 "updatePermissionFlagsForAllApps"); 4425 4426 // Only the system can change system fixed flags. 4427 if (getCallingUid() != Process.SYSTEM_UID) { 4428 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4429 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4430 } 4431 4432 synchronized (mPackages) { 4433 boolean changed = false; 4434 final int packageCount = mPackages.size(); 4435 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4436 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4437 SettingBase sb = (SettingBase) pkg.mExtras; 4438 if (sb == null) { 4439 continue; 4440 } 4441 PermissionsState permissionsState = sb.getPermissionsState(); 4442 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4443 userId, flagMask, flagValues); 4444 } 4445 if (changed) { 4446 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4447 } 4448 } 4449 } 4450 4451 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4452 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4453 != PackageManager.PERMISSION_GRANTED 4454 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4455 != PackageManager.PERMISSION_GRANTED) { 4456 throw new SecurityException(message + " requires " 4457 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4458 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4459 } 4460 } 4461 4462 @Override 4463 public boolean shouldShowRequestPermissionRationale(String permissionName, 4464 String packageName, int userId) { 4465 if (UserHandle.getCallingUserId() != userId) { 4466 mContext.enforceCallingPermission( 4467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4468 "canShowRequestPermissionRationale for user " + userId); 4469 } 4470 4471 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4472 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4473 return false; 4474 } 4475 4476 if (checkPermission(permissionName, packageName, userId) 4477 == PackageManager.PERMISSION_GRANTED) { 4478 return false; 4479 } 4480 4481 final int flags; 4482 4483 final long identity = Binder.clearCallingIdentity(); 4484 try { 4485 flags = getPermissionFlags(permissionName, 4486 packageName, userId); 4487 } finally { 4488 Binder.restoreCallingIdentity(identity); 4489 } 4490 4491 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4492 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4493 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4494 4495 if ((flags & fixedFlags) != 0) { 4496 return false; 4497 } 4498 4499 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4500 } 4501 4502 @Override 4503 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4504 mContext.enforceCallingOrSelfPermission( 4505 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4506 "addOnPermissionsChangeListener"); 4507 4508 synchronized (mPackages) { 4509 mOnPermissionChangeListeners.addListenerLocked(listener); 4510 } 4511 } 4512 4513 @Override 4514 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4515 synchronized (mPackages) { 4516 mOnPermissionChangeListeners.removeListenerLocked(listener); 4517 } 4518 } 4519 4520 @Override 4521 public boolean isProtectedBroadcast(String actionName) { 4522 synchronized (mPackages) { 4523 if (mProtectedBroadcasts.contains(actionName)) { 4524 return true; 4525 } else if (actionName != null) { 4526 // TODO: remove these terrible hacks 4527 if (actionName.startsWith("android.net.netmon.lingerExpired") 4528 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4529 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4530 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4531 return true; 4532 } 4533 } 4534 } 4535 return false; 4536 } 4537 4538 @Override 4539 public int checkSignatures(String pkg1, String pkg2) { 4540 synchronized (mPackages) { 4541 final PackageParser.Package p1 = mPackages.get(pkg1); 4542 final PackageParser.Package p2 = mPackages.get(pkg2); 4543 if (p1 == null || p1.mExtras == null 4544 || p2 == null || p2.mExtras == null) { 4545 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4546 } 4547 return compareSignatures(p1.mSignatures, p2.mSignatures); 4548 } 4549 } 4550 4551 @Override 4552 public int checkUidSignatures(int uid1, int uid2) { 4553 // Map to base uids. 4554 uid1 = UserHandle.getAppId(uid1); 4555 uid2 = UserHandle.getAppId(uid2); 4556 // reader 4557 synchronized (mPackages) { 4558 Signature[] s1; 4559 Signature[] s2; 4560 Object obj = mSettings.getUserIdLPr(uid1); 4561 if (obj != null) { 4562 if (obj instanceof SharedUserSetting) { 4563 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4564 } else if (obj instanceof PackageSetting) { 4565 s1 = ((PackageSetting)obj).signatures.mSignatures; 4566 } else { 4567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4568 } 4569 } else { 4570 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4571 } 4572 obj = mSettings.getUserIdLPr(uid2); 4573 if (obj != null) { 4574 if (obj instanceof SharedUserSetting) { 4575 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4576 } else if (obj instanceof PackageSetting) { 4577 s2 = ((PackageSetting)obj).signatures.mSignatures; 4578 } else { 4579 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4580 } 4581 } else { 4582 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4583 } 4584 return compareSignatures(s1, s2); 4585 } 4586 } 4587 4588 /** 4589 * This method should typically only be used when granting or revoking 4590 * permissions, since the app may immediately restart after this call. 4591 * <p> 4592 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4593 * guard your work against the app being relaunched. 4594 */ 4595 private void killUid(int appId, int userId, String reason) { 4596 final long identity = Binder.clearCallingIdentity(); 4597 try { 4598 IActivityManager am = ActivityManagerNative.getDefault(); 4599 if (am != null) { 4600 try { 4601 am.killUid(appId, userId, reason); 4602 } catch (RemoteException e) { 4603 /* ignore - same process */ 4604 } 4605 } 4606 } finally { 4607 Binder.restoreCallingIdentity(identity); 4608 } 4609 } 4610 4611 /** 4612 * Compares two sets of signatures. Returns: 4613 * <br /> 4614 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4615 * <br /> 4616 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4617 * <br /> 4618 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4619 * <br /> 4620 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4621 * <br /> 4622 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4623 */ 4624 static int compareSignatures(Signature[] s1, Signature[] s2) { 4625 if (s1 == null) { 4626 return s2 == null 4627 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4628 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4629 } 4630 4631 if (s2 == null) { 4632 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4633 } 4634 4635 if (s1.length != s2.length) { 4636 return PackageManager.SIGNATURE_NO_MATCH; 4637 } 4638 4639 // Since both signature sets are of size 1, we can compare without HashSets. 4640 if (s1.length == 1) { 4641 return s1[0].equals(s2[0]) ? 4642 PackageManager.SIGNATURE_MATCH : 4643 PackageManager.SIGNATURE_NO_MATCH; 4644 } 4645 4646 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4647 for (Signature sig : s1) { 4648 set1.add(sig); 4649 } 4650 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4651 for (Signature sig : s2) { 4652 set2.add(sig); 4653 } 4654 // Make sure s2 contains all signatures in s1. 4655 if (set1.equals(set2)) { 4656 return PackageManager.SIGNATURE_MATCH; 4657 } 4658 return PackageManager.SIGNATURE_NO_MATCH; 4659 } 4660 4661 /** 4662 * If the database version for this type of package (internal storage or 4663 * external storage) is less than the version where package signatures 4664 * were updated, return true. 4665 */ 4666 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4667 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4668 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4669 } 4670 4671 /** 4672 * Used for backward compatibility to make sure any packages with 4673 * certificate chains get upgraded to the new style. {@code existingSigs} 4674 * will be in the old format (since they were stored on disk from before the 4675 * system upgrade) and {@code scannedSigs} will be in the newer format. 4676 */ 4677 private int compareSignaturesCompat(PackageSignatures existingSigs, 4678 PackageParser.Package scannedPkg) { 4679 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4680 return PackageManager.SIGNATURE_NO_MATCH; 4681 } 4682 4683 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4684 for (Signature sig : existingSigs.mSignatures) { 4685 existingSet.add(sig); 4686 } 4687 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4688 for (Signature sig : scannedPkg.mSignatures) { 4689 try { 4690 Signature[] chainSignatures = sig.getChainSignatures(); 4691 for (Signature chainSig : chainSignatures) { 4692 scannedCompatSet.add(chainSig); 4693 } 4694 } catch (CertificateEncodingException e) { 4695 scannedCompatSet.add(sig); 4696 } 4697 } 4698 /* 4699 * Make sure the expanded scanned set contains all signatures in the 4700 * existing one. 4701 */ 4702 if (scannedCompatSet.equals(existingSet)) { 4703 // Migrate the old signatures to the new scheme. 4704 existingSigs.assignSignatures(scannedPkg.mSignatures); 4705 // The new KeySets will be re-added later in the scanning process. 4706 synchronized (mPackages) { 4707 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4708 } 4709 return PackageManager.SIGNATURE_MATCH; 4710 } 4711 return PackageManager.SIGNATURE_NO_MATCH; 4712 } 4713 4714 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4715 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4716 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4717 } 4718 4719 private int compareSignaturesRecover(PackageSignatures existingSigs, 4720 PackageParser.Package scannedPkg) { 4721 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4722 return PackageManager.SIGNATURE_NO_MATCH; 4723 } 4724 4725 String msg = null; 4726 try { 4727 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4728 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4729 + scannedPkg.packageName); 4730 return PackageManager.SIGNATURE_MATCH; 4731 } 4732 } catch (CertificateException e) { 4733 msg = e.getMessage(); 4734 } 4735 4736 logCriticalInfo(Log.INFO, 4737 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4738 return PackageManager.SIGNATURE_NO_MATCH; 4739 } 4740 4741 @Override 4742 public List<String> getAllPackages() { 4743 synchronized (mPackages) { 4744 return new ArrayList<String>(mPackages.keySet()); 4745 } 4746 } 4747 4748 @Override 4749 public String[] getPackagesForUid(int uid) { 4750 uid = UserHandle.getAppId(uid); 4751 // reader 4752 synchronized (mPackages) { 4753 Object obj = mSettings.getUserIdLPr(uid); 4754 if (obj instanceof SharedUserSetting) { 4755 final SharedUserSetting sus = (SharedUserSetting) obj; 4756 final int N = sus.packages.size(); 4757 final String[] res = new String[N]; 4758 for (int i = 0; i < N; i++) { 4759 res[i] = sus.packages.valueAt(i).name; 4760 } 4761 return res; 4762 } else if (obj instanceof PackageSetting) { 4763 final PackageSetting ps = (PackageSetting) obj; 4764 return new String[] { ps.name }; 4765 } 4766 } 4767 return null; 4768 } 4769 4770 @Override 4771 public String getNameForUid(int uid) { 4772 // reader 4773 synchronized (mPackages) { 4774 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4775 if (obj instanceof SharedUserSetting) { 4776 final SharedUserSetting sus = (SharedUserSetting) obj; 4777 return sus.name + ":" + sus.userId; 4778 } else if (obj instanceof PackageSetting) { 4779 final PackageSetting ps = (PackageSetting) obj; 4780 return ps.name; 4781 } 4782 } 4783 return null; 4784 } 4785 4786 @Override 4787 public int getUidForSharedUser(String sharedUserName) { 4788 if(sharedUserName == null) { 4789 return -1; 4790 } 4791 // reader 4792 synchronized (mPackages) { 4793 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4794 if (suid == null) { 4795 return -1; 4796 } 4797 return suid.userId; 4798 } 4799 } 4800 4801 @Override 4802 public int getFlagsForUid(int uid) { 4803 synchronized (mPackages) { 4804 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4805 if (obj instanceof SharedUserSetting) { 4806 final SharedUserSetting sus = (SharedUserSetting) obj; 4807 return sus.pkgFlags; 4808 } else if (obj instanceof PackageSetting) { 4809 final PackageSetting ps = (PackageSetting) obj; 4810 return ps.pkgFlags; 4811 } 4812 } 4813 return 0; 4814 } 4815 4816 @Override 4817 public int getPrivateFlagsForUid(int uid) { 4818 synchronized (mPackages) { 4819 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4820 if (obj instanceof SharedUserSetting) { 4821 final SharedUserSetting sus = (SharedUserSetting) obj; 4822 return sus.pkgPrivateFlags; 4823 } else if (obj instanceof PackageSetting) { 4824 final PackageSetting ps = (PackageSetting) obj; 4825 return ps.pkgPrivateFlags; 4826 } 4827 } 4828 return 0; 4829 } 4830 4831 @Override 4832 public boolean isUidPrivileged(int uid) { 4833 uid = UserHandle.getAppId(uid); 4834 // reader 4835 synchronized (mPackages) { 4836 Object obj = mSettings.getUserIdLPr(uid); 4837 if (obj instanceof SharedUserSetting) { 4838 final SharedUserSetting sus = (SharedUserSetting) obj; 4839 final Iterator<PackageSetting> it = sus.packages.iterator(); 4840 while (it.hasNext()) { 4841 if (it.next().isPrivileged()) { 4842 return true; 4843 } 4844 } 4845 } else if (obj instanceof PackageSetting) { 4846 final PackageSetting ps = (PackageSetting) obj; 4847 return ps.isPrivileged(); 4848 } 4849 } 4850 return false; 4851 } 4852 4853 @Override 4854 public String[] getAppOpPermissionPackages(String permissionName) { 4855 synchronized (mPackages) { 4856 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4857 if (pkgs == null) { 4858 return null; 4859 } 4860 return pkgs.toArray(new String[pkgs.size()]); 4861 } 4862 } 4863 4864 @Override 4865 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4866 int flags, int userId) { 4867 try { 4868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4869 4870 if (!sUserManager.exists(userId)) return null; 4871 flags = updateFlagsForResolve(flags, userId, intent); 4872 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4873 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4874 4875 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4876 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4877 flags, userId); 4878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4879 4880 final ResolveInfo bestChoice = 4881 chooseBestActivity(intent, resolvedType, flags, query, userId); 4882 4883 if (isEphemeralAllowed(intent, query, userId)) { 4884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4885 final EphemeralResolveInfo ai = 4886 getEphemeralResolveInfo(intent, resolvedType, userId); 4887 if (ai != null) { 4888 if (DEBUG_EPHEMERAL) { 4889 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4890 } 4891 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4892 bestChoice.ephemeralResolveInfo = ai; 4893 } 4894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4895 } 4896 return bestChoice; 4897 } finally { 4898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4899 } 4900 } 4901 4902 @Override 4903 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4904 IntentFilter filter, int match, ComponentName activity) { 4905 final int userId = UserHandle.getCallingUserId(); 4906 if (DEBUG_PREFERRED) { 4907 Log.v(TAG, "setLastChosenActivity intent=" + intent 4908 + " resolvedType=" + resolvedType 4909 + " flags=" + flags 4910 + " filter=" + filter 4911 + " match=" + match 4912 + " activity=" + activity); 4913 filter.dump(new PrintStreamPrinter(System.out), " "); 4914 } 4915 intent.setComponent(null); 4916 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4917 userId); 4918 // Find any earlier preferred or last chosen entries and nuke them 4919 findPreferredActivity(intent, resolvedType, 4920 flags, query, 0, false, true, false, userId); 4921 // Add the new activity as the last chosen for this filter 4922 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4923 "Setting last chosen"); 4924 } 4925 4926 @Override 4927 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4928 final int userId = UserHandle.getCallingUserId(); 4929 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4930 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4931 userId); 4932 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4933 false, false, false, userId); 4934 } 4935 4936 4937 private boolean isEphemeralAllowed( 4938 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4939 // Short circuit and return early if possible. 4940 if (DISABLE_EPHEMERAL_APPS) { 4941 return false; 4942 } 4943 final int callingUser = UserHandle.getCallingUserId(); 4944 if (callingUser != UserHandle.USER_SYSTEM) { 4945 return false; 4946 } 4947 if (mEphemeralResolverConnection == null) { 4948 return false; 4949 } 4950 if (intent.getComponent() != null) { 4951 return false; 4952 } 4953 if (intent.getPackage() != null) { 4954 return false; 4955 } 4956 final boolean isWebUri = hasWebURI(intent); 4957 if (!isWebUri) { 4958 return false; 4959 } 4960 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4961 synchronized (mPackages) { 4962 final int count = resolvedActivites.size(); 4963 for (int n = 0; n < count; n++) { 4964 ResolveInfo info = resolvedActivites.get(n); 4965 String packageName = info.activityInfo.packageName; 4966 PackageSetting ps = mSettings.mPackages.get(packageName); 4967 if (ps != null) { 4968 // Try to get the status from User settings first 4969 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4970 int status = (int) (packedStatus >> 32); 4971 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4972 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4973 if (DEBUG_EPHEMERAL) { 4974 Slog.v(TAG, "DENY ephemeral apps;" 4975 + " pkg: " + packageName + ", status: " + status); 4976 } 4977 return false; 4978 } 4979 } 4980 } 4981 } 4982 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4983 return true; 4984 } 4985 4986 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4987 int userId) { 4988 MessageDigest digest = null; 4989 try { 4990 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4991 } catch (NoSuchAlgorithmException e) { 4992 // If we can't create a digest, ignore ephemeral apps. 4993 return null; 4994 } 4995 4996 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4997 final byte[] digestBytes = digest.digest(hostBytes); 4998 int shaPrefix = 4999 digestBytes[0] << 24 5000 | digestBytes[1] << 16 5001 | digestBytes[2] << 8 5002 | digestBytes[3] << 0; 5003 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5004 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 5005 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5006 // No hash prefix match; there are no ephemeral apps for this domain. 5007 return null; 5008 } 5009 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 5010 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 5011 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 5012 continue; 5013 } 5014 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5015 // No filters; this should never happen. 5016 if (filters.isEmpty()) { 5017 continue; 5018 } 5019 // We have a domain match; resolve the filters to see if anything matches. 5020 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5021 for (int j = filters.size() - 1; j >= 0; --j) { 5022 final EphemeralResolveIntentInfo intentInfo = 5023 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5024 ephemeralResolver.addFilter(intentInfo); 5025 } 5026 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5027 intent, resolvedType, false /*defaultOnly*/, userId); 5028 if (!matchedResolveInfoList.isEmpty()) { 5029 return matchedResolveInfoList.get(0); 5030 } 5031 } 5032 // Hash or filter mis-match; no ephemeral apps for this domain. 5033 return null; 5034 } 5035 5036 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5037 int flags, List<ResolveInfo> query, int userId) { 5038 if (query != null) { 5039 final int N = query.size(); 5040 if (N == 1) { 5041 return query.get(0); 5042 } else if (N > 1) { 5043 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5044 // If there is more than one activity with the same priority, 5045 // then let the user decide between them. 5046 ResolveInfo r0 = query.get(0); 5047 ResolveInfo r1 = query.get(1); 5048 if (DEBUG_INTENT_MATCHING || debug) { 5049 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5050 + r1.activityInfo.name + "=" + r1.priority); 5051 } 5052 // If the first activity has a higher priority, or a different 5053 // default, then it is always desirable to pick it. 5054 if (r0.priority != r1.priority 5055 || r0.preferredOrder != r1.preferredOrder 5056 || r0.isDefault != r1.isDefault) { 5057 return query.get(0); 5058 } 5059 // If we have saved a preference for a preferred activity for 5060 // this Intent, use that. 5061 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5062 flags, query, r0.priority, true, false, debug, userId); 5063 if (ri != null) { 5064 return ri; 5065 } 5066 ri = new ResolveInfo(mResolveInfo); 5067 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5068 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5069 // If all of the options come from the same package, show the application's 5070 // label and icon instead of the generic resolver's. 5071 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5072 // and then throw away the ResolveInfo itself, meaning that the caller loses 5073 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5074 // a fallback for this case; we only set the target package's resources on 5075 // the ResolveInfo, not the ActivityInfo. 5076 final String intentPackage = intent.getPackage(); 5077 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5078 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5079 ri.resolvePackageName = intentPackage; 5080 if (userNeedsBadging(userId)) { 5081 ri.noResourceId = true; 5082 } else { 5083 ri.icon = appi.icon; 5084 } 5085 ri.iconResourceId = appi.icon; 5086 ri.labelRes = appi.labelRes; 5087 } 5088 ri.activityInfo.applicationInfo = new ApplicationInfo( 5089 ri.activityInfo.applicationInfo); 5090 if (userId != 0) { 5091 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5092 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5093 } 5094 // Make sure that the resolver is displayable in car mode 5095 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5096 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5097 return ri; 5098 } 5099 } 5100 return null; 5101 } 5102 5103 /** 5104 * Return true if the given list is not empty and all of its contents have 5105 * an activityInfo with the given package name. 5106 */ 5107 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5108 if (ArrayUtils.isEmpty(list)) { 5109 return false; 5110 } 5111 for (int i = 0, N = list.size(); i < N; i++) { 5112 final ResolveInfo ri = list.get(i); 5113 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5114 if (ai == null || !packageName.equals(ai.packageName)) { 5115 return false; 5116 } 5117 } 5118 return true; 5119 } 5120 5121 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5122 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5123 final int N = query.size(); 5124 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5125 .get(userId); 5126 // Get the list of persistent preferred activities that handle the intent 5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5128 List<PersistentPreferredActivity> pprefs = ppir != null 5129 ? ppir.queryIntent(intent, resolvedType, 5130 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5131 : null; 5132 if (pprefs != null && pprefs.size() > 0) { 5133 final int M = pprefs.size(); 5134 for (int i=0; i<M; i++) { 5135 final PersistentPreferredActivity ppa = pprefs.get(i); 5136 if (DEBUG_PREFERRED || debug) { 5137 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5138 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5139 + "\n component=" + ppa.mComponent); 5140 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5141 } 5142 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5143 flags | MATCH_DISABLED_COMPONENTS, userId); 5144 if (DEBUG_PREFERRED || debug) { 5145 Slog.v(TAG, "Found persistent preferred activity:"); 5146 if (ai != null) { 5147 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5148 } else { 5149 Slog.v(TAG, " null"); 5150 } 5151 } 5152 if (ai == null) { 5153 // This previously registered persistent preferred activity 5154 // component is no longer known. Ignore it and do NOT remove it. 5155 continue; 5156 } 5157 for (int j=0; j<N; j++) { 5158 final ResolveInfo ri = query.get(j); 5159 if (!ri.activityInfo.applicationInfo.packageName 5160 .equals(ai.applicationInfo.packageName)) { 5161 continue; 5162 } 5163 if (!ri.activityInfo.name.equals(ai.name)) { 5164 continue; 5165 } 5166 // Found a persistent preference that can handle the intent. 5167 if (DEBUG_PREFERRED || debug) { 5168 Slog.v(TAG, "Returning persistent preferred activity: " + 5169 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5170 } 5171 return ri; 5172 } 5173 } 5174 } 5175 return null; 5176 } 5177 5178 // TODO: handle preferred activities missing while user has amnesia 5179 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5180 List<ResolveInfo> query, int priority, boolean always, 5181 boolean removeMatches, boolean debug, int userId) { 5182 if (!sUserManager.exists(userId)) return null; 5183 flags = updateFlagsForResolve(flags, userId, intent); 5184 // writer 5185 synchronized (mPackages) { 5186 if (intent.getSelector() != null) { 5187 intent = intent.getSelector(); 5188 } 5189 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5190 5191 // Try to find a matching persistent preferred activity. 5192 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5193 debug, userId); 5194 5195 // If a persistent preferred activity matched, use it. 5196 if (pri != null) { 5197 return pri; 5198 } 5199 5200 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5201 // Get the list of preferred activities that handle the intent 5202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5203 List<PreferredActivity> prefs = pir != null 5204 ? pir.queryIntent(intent, resolvedType, 5205 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5206 : null; 5207 if (prefs != null && prefs.size() > 0) { 5208 boolean changed = false; 5209 try { 5210 // First figure out how good the original match set is. 5211 // We will only allow preferred activities that came 5212 // from the same match quality. 5213 int match = 0; 5214 5215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5216 5217 final int N = query.size(); 5218 for (int j=0; j<N; j++) { 5219 final ResolveInfo ri = query.get(j); 5220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5221 + ": 0x" + Integer.toHexString(match)); 5222 if (ri.match > match) { 5223 match = ri.match; 5224 } 5225 } 5226 5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5228 + Integer.toHexString(match)); 5229 5230 match &= IntentFilter.MATCH_CATEGORY_MASK; 5231 final int M = prefs.size(); 5232 for (int i=0; i<M; i++) { 5233 final PreferredActivity pa = prefs.get(i); 5234 if (DEBUG_PREFERRED || debug) { 5235 Slog.v(TAG, "Checking PreferredActivity ds=" 5236 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5237 + "\n component=" + pa.mPref.mComponent); 5238 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5239 } 5240 if (pa.mPref.mMatch != match) { 5241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5242 + Integer.toHexString(pa.mPref.mMatch)); 5243 continue; 5244 } 5245 // If it's not an "always" type preferred activity and that's what we're 5246 // looking for, skip it. 5247 if (always && !pa.mPref.mAlways) { 5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5249 continue; 5250 } 5251 final ActivityInfo ai = getActivityInfo( 5252 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5253 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5254 userId); 5255 if (DEBUG_PREFERRED || debug) { 5256 Slog.v(TAG, "Found preferred activity:"); 5257 if (ai != null) { 5258 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5259 } else { 5260 Slog.v(TAG, " null"); 5261 } 5262 } 5263 if (ai == null) { 5264 // This previously registered preferred activity 5265 // component is no longer known. Most likely an update 5266 // to the app was installed and in the new version this 5267 // component no longer exists. Clean it up by removing 5268 // it from the preferred activities list, and skip it. 5269 Slog.w(TAG, "Removing dangling preferred activity: " 5270 + pa.mPref.mComponent); 5271 pir.removeFilter(pa); 5272 changed = true; 5273 continue; 5274 } 5275 for (int j=0; j<N; j++) { 5276 final ResolveInfo ri = query.get(j); 5277 if (!ri.activityInfo.applicationInfo.packageName 5278 .equals(ai.applicationInfo.packageName)) { 5279 continue; 5280 } 5281 if (!ri.activityInfo.name.equals(ai.name)) { 5282 continue; 5283 } 5284 5285 if (removeMatches) { 5286 pir.removeFilter(pa); 5287 changed = true; 5288 if (DEBUG_PREFERRED) { 5289 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5290 } 5291 break; 5292 } 5293 5294 // Okay we found a previously set preferred or last chosen app. 5295 // If the result set is different from when this 5296 // was created, we need to clear it and re-ask the 5297 // user their preference, if we're looking for an "always" type entry. 5298 if (always && !pa.mPref.sameSet(query)) { 5299 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5300 + intent + " type " + resolvedType); 5301 if (DEBUG_PREFERRED) { 5302 Slog.v(TAG, "Removing preferred activity since set changed " 5303 + pa.mPref.mComponent); 5304 } 5305 pir.removeFilter(pa); 5306 // Re-add the filter as a "last chosen" entry (!always) 5307 PreferredActivity lastChosen = new PreferredActivity( 5308 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5309 pir.addFilter(lastChosen); 5310 changed = true; 5311 return null; 5312 } 5313 5314 // Yay! Either the set matched or we're looking for the last chosen 5315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5316 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5317 return ri; 5318 } 5319 } 5320 } finally { 5321 if (changed) { 5322 if (DEBUG_PREFERRED) { 5323 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5324 } 5325 scheduleWritePackageRestrictionsLocked(userId); 5326 } 5327 } 5328 } 5329 } 5330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5331 return null; 5332 } 5333 5334 /* 5335 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5336 */ 5337 @Override 5338 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5339 int targetUserId) { 5340 mContext.enforceCallingOrSelfPermission( 5341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5342 List<CrossProfileIntentFilter> matches = 5343 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5344 if (matches != null) { 5345 int size = matches.size(); 5346 for (int i = 0; i < size; i++) { 5347 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5348 } 5349 } 5350 if (hasWebURI(intent)) { 5351 // cross-profile app linking works only towards the parent. 5352 final UserInfo parent = getProfileParent(sourceUserId); 5353 synchronized(mPackages) { 5354 int flags = updateFlagsForResolve(0, parent.id, intent); 5355 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5356 intent, resolvedType, flags, sourceUserId, parent.id); 5357 return xpDomainInfo != null; 5358 } 5359 } 5360 return false; 5361 } 5362 5363 private UserInfo getProfileParent(int userId) { 5364 final long identity = Binder.clearCallingIdentity(); 5365 try { 5366 return sUserManager.getProfileParent(userId); 5367 } finally { 5368 Binder.restoreCallingIdentity(identity); 5369 } 5370 } 5371 5372 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5373 String resolvedType, int userId) { 5374 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5375 if (resolver != null) { 5376 return resolver.queryIntent(intent, resolvedType, false, userId); 5377 } 5378 return null; 5379 } 5380 5381 @Override 5382 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5383 String resolvedType, int flags, int userId) { 5384 try { 5385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5386 5387 return new ParceledListSlice<>( 5388 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5389 } finally { 5390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5391 } 5392 } 5393 5394 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5395 String resolvedType, int flags, int userId) { 5396 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5397 flags = updateFlagsForResolve(flags, userId, intent); 5398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5399 false /* requireFullPermission */, false /* checkShell */, 5400 "query intent activities"); 5401 ComponentName comp = intent.getComponent(); 5402 if (comp == null) { 5403 if (intent.getSelector() != null) { 5404 intent = intent.getSelector(); 5405 comp = intent.getComponent(); 5406 } 5407 } 5408 5409 if (comp != null) { 5410 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5411 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5412 if (ai != null) { 5413 final ResolveInfo ri = new ResolveInfo(); 5414 ri.activityInfo = ai; 5415 list.add(ri); 5416 } 5417 return list; 5418 } 5419 5420 // reader 5421 synchronized (mPackages) { 5422 final String pkgName = intent.getPackage(); 5423 if (pkgName == null) { 5424 List<CrossProfileIntentFilter> matchingFilters = 5425 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5426 // Check for results that need to skip the current profile. 5427 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5428 resolvedType, flags, userId); 5429 if (xpResolveInfo != null) { 5430 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5431 result.add(xpResolveInfo); 5432 return filterIfNotSystemUser(result, userId); 5433 } 5434 5435 // Check for results in the current profile. 5436 List<ResolveInfo> result = mActivities.queryIntent( 5437 intent, resolvedType, flags, userId); 5438 result = filterIfNotSystemUser(result, userId); 5439 5440 // Check for cross profile results. 5441 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5442 xpResolveInfo = queryCrossProfileIntents( 5443 matchingFilters, intent, resolvedType, flags, userId, 5444 hasNonNegativePriorityResult); 5445 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5446 boolean isVisibleToUser = filterIfNotSystemUser( 5447 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5448 if (isVisibleToUser) { 5449 result.add(xpResolveInfo); 5450 Collections.sort(result, mResolvePrioritySorter); 5451 } 5452 } 5453 if (hasWebURI(intent)) { 5454 CrossProfileDomainInfo xpDomainInfo = null; 5455 final UserInfo parent = getProfileParent(userId); 5456 if (parent != null) { 5457 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5458 flags, userId, parent.id); 5459 } 5460 if (xpDomainInfo != null) { 5461 if (xpResolveInfo != null) { 5462 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5463 // in the result. 5464 result.remove(xpResolveInfo); 5465 } 5466 if (result.size() == 0) { 5467 result.add(xpDomainInfo.resolveInfo); 5468 return result; 5469 } 5470 } else if (result.size() <= 1) { 5471 return result; 5472 } 5473 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5474 xpDomainInfo, userId); 5475 Collections.sort(result, mResolvePrioritySorter); 5476 } 5477 return result; 5478 } 5479 final PackageParser.Package pkg = mPackages.get(pkgName); 5480 if (pkg != null) { 5481 return filterIfNotSystemUser( 5482 mActivities.queryIntentForPackage( 5483 intent, resolvedType, flags, pkg.activities, userId), 5484 userId); 5485 } 5486 return new ArrayList<ResolveInfo>(); 5487 } 5488 } 5489 5490 private static class CrossProfileDomainInfo { 5491 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5492 ResolveInfo resolveInfo; 5493 /* Best domain verification status of the activities found in the other profile */ 5494 int bestDomainVerificationStatus; 5495 } 5496 5497 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5498 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5499 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5500 sourceUserId)) { 5501 return null; 5502 } 5503 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5504 resolvedType, flags, parentUserId); 5505 5506 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5507 return null; 5508 } 5509 CrossProfileDomainInfo result = null; 5510 int size = resultTargetUser.size(); 5511 for (int i = 0; i < size; i++) { 5512 ResolveInfo riTargetUser = resultTargetUser.get(i); 5513 // Intent filter verification is only for filters that specify a host. So don't return 5514 // those that handle all web uris. 5515 if (riTargetUser.handleAllWebDataURI) { 5516 continue; 5517 } 5518 String packageName = riTargetUser.activityInfo.packageName; 5519 PackageSetting ps = mSettings.mPackages.get(packageName); 5520 if (ps == null) { 5521 continue; 5522 } 5523 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5524 int status = (int)(verificationState >> 32); 5525 if (result == null) { 5526 result = new CrossProfileDomainInfo(); 5527 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5528 sourceUserId, parentUserId); 5529 result.bestDomainVerificationStatus = status; 5530 } else { 5531 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5532 result.bestDomainVerificationStatus); 5533 } 5534 } 5535 // Don't consider matches with status NEVER across profiles. 5536 if (result != null && result.bestDomainVerificationStatus 5537 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5538 return null; 5539 } 5540 return result; 5541 } 5542 5543 /** 5544 * Verification statuses are ordered from the worse to the best, except for 5545 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5546 */ 5547 private int bestDomainVerificationStatus(int status1, int status2) { 5548 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5549 return status2; 5550 } 5551 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5552 return status1; 5553 } 5554 return (int) MathUtils.max(status1, status2); 5555 } 5556 5557 private boolean isUserEnabled(int userId) { 5558 long callingId = Binder.clearCallingIdentity(); 5559 try { 5560 UserInfo userInfo = sUserManager.getUserInfo(userId); 5561 return userInfo != null && userInfo.isEnabled(); 5562 } finally { 5563 Binder.restoreCallingIdentity(callingId); 5564 } 5565 } 5566 5567 /** 5568 * Filter out activities with systemUserOnly flag set, when current user is not System. 5569 * 5570 * @return filtered list 5571 */ 5572 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5573 if (userId == UserHandle.USER_SYSTEM) { 5574 return resolveInfos; 5575 } 5576 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5577 ResolveInfo info = resolveInfos.get(i); 5578 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5579 resolveInfos.remove(i); 5580 } 5581 } 5582 return resolveInfos; 5583 } 5584 5585 /** 5586 * @param resolveInfos list of resolve infos in descending priority order 5587 * @return if the list contains a resolve info with non-negative priority 5588 */ 5589 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5590 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5591 } 5592 5593 private static boolean hasWebURI(Intent intent) { 5594 if (intent.getData() == null) { 5595 return false; 5596 } 5597 final String scheme = intent.getScheme(); 5598 if (TextUtils.isEmpty(scheme)) { 5599 return false; 5600 } 5601 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5602 } 5603 5604 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5605 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5606 int userId) { 5607 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5608 5609 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5610 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5611 candidates.size()); 5612 } 5613 5614 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5615 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5616 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5617 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5618 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5619 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5620 5621 synchronized (mPackages) { 5622 final int count = candidates.size(); 5623 // First, try to use linked apps. Partition the candidates into four lists: 5624 // one for the final results, one for the "do not use ever", one for "undefined status" 5625 // and finally one for "browser app type". 5626 for (int n=0; n<count; n++) { 5627 ResolveInfo info = candidates.get(n); 5628 String packageName = info.activityInfo.packageName; 5629 PackageSetting ps = mSettings.mPackages.get(packageName); 5630 if (ps != null) { 5631 // Add to the special match all list (Browser use case) 5632 if (info.handleAllWebDataURI) { 5633 matchAllList.add(info); 5634 continue; 5635 } 5636 // Try to get the status from User settings first 5637 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5638 int status = (int)(packedStatus >> 32); 5639 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5640 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5641 if (DEBUG_DOMAIN_VERIFICATION) { 5642 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5643 + " : linkgen=" + linkGeneration); 5644 } 5645 // Use link-enabled generation as preferredOrder, i.e. 5646 // prefer newly-enabled over earlier-enabled. 5647 info.preferredOrder = linkGeneration; 5648 alwaysList.add(info); 5649 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5650 if (DEBUG_DOMAIN_VERIFICATION) { 5651 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5652 } 5653 neverList.add(info); 5654 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5655 if (DEBUG_DOMAIN_VERIFICATION) { 5656 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5657 } 5658 alwaysAskList.add(info); 5659 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5660 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5661 if (DEBUG_DOMAIN_VERIFICATION) { 5662 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5663 } 5664 undefinedList.add(info); 5665 } 5666 } 5667 } 5668 5669 // We'll want to include browser possibilities in a few cases 5670 boolean includeBrowser = false; 5671 5672 // First try to add the "always" resolution(s) for the current user, if any 5673 if (alwaysList.size() > 0) { 5674 result.addAll(alwaysList); 5675 } else { 5676 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5677 result.addAll(undefinedList); 5678 // Maybe add one for the other profile. 5679 if (xpDomainInfo != null && ( 5680 xpDomainInfo.bestDomainVerificationStatus 5681 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5682 result.add(xpDomainInfo.resolveInfo); 5683 } 5684 includeBrowser = true; 5685 } 5686 5687 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5688 // If there were 'always' entries their preferred order has been set, so we also 5689 // back that off to make the alternatives equivalent 5690 if (alwaysAskList.size() > 0) { 5691 for (ResolveInfo i : result) { 5692 i.preferredOrder = 0; 5693 } 5694 result.addAll(alwaysAskList); 5695 includeBrowser = true; 5696 } 5697 5698 if (includeBrowser) { 5699 // Also add browsers (all of them or only the default one) 5700 if (DEBUG_DOMAIN_VERIFICATION) { 5701 Slog.v(TAG, " ...including browsers in candidate set"); 5702 } 5703 if ((matchFlags & MATCH_ALL) != 0) { 5704 result.addAll(matchAllList); 5705 } else { 5706 // Browser/generic handling case. If there's a default browser, go straight 5707 // to that (but only if there is no other higher-priority match). 5708 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5709 int maxMatchPrio = 0; 5710 ResolveInfo defaultBrowserMatch = null; 5711 final int numCandidates = matchAllList.size(); 5712 for (int n = 0; n < numCandidates; n++) { 5713 ResolveInfo info = matchAllList.get(n); 5714 // track the highest overall match priority... 5715 if (info.priority > maxMatchPrio) { 5716 maxMatchPrio = info.priority; 5717 } 5718 // ...and the highest-priority default browser match 5719 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5720 if (defaultBrowserMatch == null 5721 || (defaultBrowserMatch.priority < info.priority)) { 5722 if (debug) { 5723 Slog.v(TAG, "Considering default browser match " + info); 5724 } 5725 defaultBrowserMatch = info; 5726 } 5727 } 5728 } 5729 if (defaultBrowserMatch != null 5730 && defaultBrowserMatch.priority >= maxMatchPrio 5731 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5732 { 5733 if (debug) { 5734 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5735 } 5736 result.add(defaultBrowserMatch); 5737 } else { 5738 result.addAll(matchAllList); 5739 } 5740 } 5741 5742 // If there is nothing selected, add all candidates and remove the ones that the user 5743 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5744 if (result.size() == 0) { 5745 result.addAll(candidates); 5746 result.removeAll(neverList); 5747 } 5748 } 5749 } 5750 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5751 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5752 result.size()); 5753 for (ResolveInfo info : result) { 5754 Slog.v(TAG, " + " + info.activityInfo); 5755 } 5756 } 5757 return result; 5758 } 5759 5760 // Returns a packed value as a long: 5761 // 5762 // high 'int'-sized word: link status: undefined/ask/never/always. 5763 // low 'int'-sized word: relative priority among 'always' results. 5764 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5765 long result = ps.getDomainVerificationStatusForUser(userId); 5766 // if none available, get the master status 5767 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5768 if (ps.getIntentFilterVerificationInfo() != null) { 5769 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5770 } 5771 } 5772 return result; 5773 } 5774 5775 private ResolveInfo querySkipCurrentProfileIntents( 5776 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5777 int flags, int sourceUserId) { 5778 if (matchingFilters != null) { 5779 int size = matchingFilters.size(); 5780 for (int i = 0; i < size; i ++) { 5781 CrossProfileIntentFilter filter = matchingFilters.get(i); 5782 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5783 // Checking if there are activities in the target user that can handle the 5784 // intent. 5785 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5786 resolvedType, flags, sourceUserId); 5787 if (resolveInfo != null) { 5788 return resolveInfo; 5789 } 5790 } 5791 } 5792 } 5793 return null; 5794 } 5795 5796 // Return matching ResolveInfo in target user if any. 5797 private ResolveInfo queryCrossProfileIntents( 5798 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5799 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5800 if (matchingFilters != null) { 5801 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5802 // match the same intent. For performance reasons, it is better not to 5803 // run queryIntent twice for the same userId 5804 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5805 int size = matchingFilters.size(); 5806 for (int i = 0; i < size; i++) { 5807 CrossProfileIntentFilter filter = matchingFilters.get(i); 5808 int targetUserId = filter.getTargetUserId(); 5809 boolean skipCurrentProfile = 5810 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5811 boolean skipCurrentProfileIfNoMatchFound = 5812 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5813 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5814 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5815 // Checking if there are activities in the target user that can handle the 5816 // intent. 5817 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5818 resolvedType, flags, sourceUserId); 5819 if (resolveInfo != null) return resolveInfo; 5820 alreadyTriedUserIds.put(targetUserId, true); 5821 } 5822 } 5823 } 5824 return null; 5825 } 5826 5827 /** 5828 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5829 * will forward the intent to the filter's target user. 5830 * Otherwise, returns null. 5831 */ 5832 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5833 String resolvedType, int flags, int sourceUserId) { 5834 int targetUserId = filter.getTargetUserId(); 5835 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5836 resolvedType, flags, targetUserId); 5837 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5838 // If all the matches in the target profile are suspended, return null. 5839 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5840 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5841 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5842 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5843 targetUserId); 5844 } 5845 } 5846 } 5847 return null; 5848 } 5849 5850 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5851 int sourceUserId, int targetUserId) { 5852 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5853 long ident = Binder.clearCallingIdentity(); 5854 boolean targetIsProfile; 5855 try { 5856 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5857 } finally { 5858 Binder.restoreCallingIdentity(ident); 5859 } 5860 String className; 5861 if (targetIsProfile) { 5862 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5863 } else { 5864 className = FORWARD_INTENT_TO_PARENT; 5865 } 5866 ComponentName forwardingActivityComponentName = new ComponentName( 5867 mAndroidApplication.packageName, className); 5868 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5869 sourceUserId); 5870 if (!targetIsProfile) { 5871 forwardingActivityInfo.showUserIcon = targetUserId; 5872 forwardingResolveInfo.noResourceId = true; 5873 } 5874 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5875 forwardingResolveInfo.priority = 0; 5876 forwardingResolveInfo.preferredOrder = 0; 5877 forwardingResolveInfo.match = 0; 5878 forwardingResolveInfo.isDefault = true; 5879 forwardingResolveInfo.filter = filter; 5880 forwardingResolveInfo.targetUserId = targetUserId; 5881 return forwardingResolveInfo; 5882 } 5883 5884 @Override 5885 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5886 Intent[] specifics, String[] specificTypes, Intent intent, 5887 String resolvedType, int flags, int userId) { 5888 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5889 specificTypes, intent, resolvedType, flags, userId)); 5890 } 5891 5892 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5893 Intent[] specifics, String[] specificTypes, Intent intent, 5894 String resolvedType, int flags, int userId) { 5895 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5896 flags = updateFlagsForResolve(flags, userId, intent); 5897 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5898 false /* requireFullPermission */, false /* checkShell */, 5899 "query intent activity options"); 5900 final String resultsAction = intent.getAction(); 5901 5902 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5903 | PackageManager.GET_RESOLVED_FILTER, userId); 5904 5905 if (DEBUG_INTENT_MATCHING) { 5906 Log.v(TAG, "Query " + intent + ": " + results); 5907 } 5908 5909 int specificsPos = 0; 5910 int N; 5911 5912 // todo: note that the algorithm used here is O(N^2). This 5913 // isn't a problem in our current environment, but if we start running 5914 // into situations where we have more than 5 or 10 matches then this 5915 // should probably be changed to something smarter... 5916 5917 // First we go through and resolve each of the specific items 5918 // that were supplied, taking care of removing any corresponding 5919 // duplicate items in the generic resolve list. 5920 if (specifics != null) { 5921 for (int i=0; i<specifics.length; i++) { 5922 final Intent sintent = specifics[i]; 5923 if (sintent == null) { 5924 continue; 5925 } 5926 5927 if (DEBUG_INTENT_MATCHING) { 5928 Log.v(TAG, "Specific #" + i + ": " + sintent); 5929 } 5930 5931 String action = sintent.getAction(); 5932 if (resultsAction != null && resultsAction.equals(action)) { 5933 // If this action was explicitly requested, then don't 5934 // remove things that have it. 5935 action = null; 5936 } 5937 5938 ResolveInfo ri = null; 5939 ActivityInfo ai = null; 5940 5941 ComponentName comp = sintent.getComponent(); 5942 if (comp == null) { 5943 ri = resolveIntent( 5944 sintent, 5945 specificTypes != null ? specificTypes[i] : null, 5946 flags, userId); 5947 if (ri == null) { 5948 continue; 5949 } 5950 if (ri == mResolveInfo) { 5951 // ACK! Must do something better with this. 5952 } 5953 ai = ri.activityInfo; 5954 comp = new ComponentName(ai.applicationInfo.packageName, 5955 ai.name); 5956 } else { 5957 ai = getActivityInfo(comp, flags, userId); 5958 if (ai == null) { 5959 continue; 5960 } 5961 } 5962 5963 // Look for any generic query activities that are duplicates 5964 // of this specific one, and remove them from the results. 5965 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5966 N = results.size(); 5967 int j; 5968 for (j=specificsPos; j<N; j++) { 5969 ResolveInfo sri = results.get(j); 5970 if ((sri.activityInfo.name.equals(comp.getClassName()) 5971 && sri.activityInfo.applicationInfo.packageName.equals( 5972 comp.getPackageName())) 5973 || (action != null && sri.filter.matchAction(action))) { 5974 results.remove(j); 5975 if (DEBUG_INTENT_MATCHING) Log.v( 5976 TAG, "Removing duplicate item from " + j 5977 + " due to specific " + specificsPos); 5978 if (ri == null) { 5979 ri = sri; 5980 } 5981 j--; 5982 N--; 5983 } 5984 } 5985 5986 // Add this specific item to its proper place. 5987 if (ri == null) { 5988 ri = new ResolveInfo(); 5989 ri.activityInfo = ai; 5990 } 5991 results.add(specificsPos, ri); 5992 ri.specificIndex = i; 5993 specificsPos++; 5994 } 5995 } 5996 5997 // Now we go through the remaining generic results and remove any 5998 // duplicate actions that are found here. 5999 N = results.size(); 6000 for (int i=specificsPos; i<N-1; i++) { 6001 final ResolveInfo rii = results.get(i); 6002 if (rii.filter == null) { 6003 continue; 6004 } 6005 6006 // Iterate over all of the actions of this result's intent 6007 // filter... typically this should be just one. 6008 final Iterator<String> it = rii.filter.actionsIterator(); 6009 if (it == null) { 6010 continue; 6011 } 6012 while (it.hasNext()) { 6013 final String action = it.next(); 6014 if (resultsAction != null && resultsAction.equals(action)) { 6015 // If this action was explicitly requested, then don't 6016 // remove things that have it. 6017 continue; 6018 } 6019 for (int j=i+1; j<N; j++) { 6020 final ResolveInfo rij = results.get(j); 6021 if (rij.filter != null && rij.filter.hasAction(action)) { 6022 results.remove(j); 6023 if (DEBUG_INTENT_MATCHING) Log.v( 6024 TAG, "Removing duplicate item from " + j 6025 + " due to action " + action + " at " + i); 6026 j--; 6027 N--; 6028 } 6029 } 6030 } 6031 6032 // If the caller didn't request filter information, drop it now 6033 // so we don't have to marshall/unmarshall it. 6034 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6035 rii.filter = null; 6036 } 6037 } 6038 6039 // Filter out the caller activity if so requested. 6040 if (caller != null) { 6041 N = results.size(); 6042 for (int i=0; i<N; i++) { 6043 ActivityInfo ainfo = results.get(i).activityInfo; 6044 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6045 && caller.getClassName().equals(ainfo.name)) { 6046 results.remove(i); 6047 break; 6048 } 6049 } 6050 } 6051 6052 // If the caller didn't request filter information, 6053 // drop them now so we don't have to 6054 // marshall/unmarshall it. 6055 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6056 N = results.size(); 6057 for (int i=0; i<N; i++) { 6058 results.get(i).filter = null; 6059 } 6060 } 6061 6062 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6063 return results; 6064 } 6065 6066 @Override 6067 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6068 String resolvedType, int flags, int userId) { 6069 return new ParceledListSlice<>( 6070 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6071 } 6072 6073 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6074 String resolvedType, int flags, int userId) { 6075 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6076 flags = updateFlagsForResolve(flags, userId, intent); 6077 ComponentName comp = intent.getComponent(); 6078 if (comp == null) { 6079 if (intent.getSelector() != null) { 6080 intent = intent.getSelector(); 6081 comp = intent.getComponent(); 6082 } 6083 } 6084 if (comp != null) { 6085 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6086 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6087 if (ai != null) { 6088 ResolveInfo ri = new ResolveInfo(); 6089 ri.activityInfo = ai; 6090 list.add(ri); 6091 } 6092 return list; 6093 } 6094 6095 // reader 6096 synchronized (mPackages) { 6097 String pkgName = intent.getPackage(); 6098 if (pkgName == null) { 6099 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6100 } 6101 final PackageParser.Package pkg = mPackages.get(pkgName); 6102 if (pkg != null) { 6103 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6104 userId); 6105 } 6106 return Collections.emptyList(); 6107 } 6108 } 6109 6110 @Override 6111 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6112 if (!sUserManager.exists(userId)) return null; 6113 flags = updateFlagsForResolve(flags, userId, intent); 6114 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6115 if (query != null) { 6116 if (query.size() >= 1) { 6117 // If there is more than one service with the same priority, 6118 // just arbitrarily pick the first one. 6119 return query.get(0); 6120 } 6121 } 6122 return null; 6123 } 6124 6125 @Override 6126 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6127 String resolvedType, int flags, int userId) { 6128 return new ParceledListSlice<>( 6129 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6130 } 6131 6132 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6133 String resolvedType, int flags, int userId) { 6134 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6135 flags = updateFlagsForResolve(flags, userId, intent); 6136 ComponentName comp = intent.getComponent(); 6137 if (comp == null) { 6138 if (intent.getSelector() != null) { 6139 intent = intent.getSelector(); 6140 comp = intent.getComponent(); 6141 } 6142 } 6143 if (comp != null) { 6144 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6145 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6146 if (si != null) { 6147 final ResolveInfo ri = new ResolveInfo(); 6148 ri.serviceInfo = si; 6149 list.add(ri); 6150 } 6151 return list; 6152 } 6153 6154 // reader 6155 synchronized (mPackages) { 6156 String pkgName = intent.getPackage(); 6157 if (pkgName == null) { 6158 return mServices.queryIntent(intent, resolvedType, flags, userId); 6159 } 6160 final PackageParser.Package pkg = mPackages.get(pkgName); 6161 if (pkg != null) { 6162 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6163 userId); 6164 } 6165 return Collections.emptyList(); 6166 } 6167 } 6168 6169 @Override 6170 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6171 String resolvedType, int flags, int userId) { 6172 return new ParceledListSlice<>( 6173 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6174 } 6175 6176 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6177 Intent intent, String resolvedType, int flags, int userId) { 6178 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6179 flags = updateFlagsForResolve(flags, userId, intent); 6180 ComponentName comp = intent.getComponent(); 6181 if (comp == null) { 6182 if (intent.getSelector() != null) { 6183 intent = intent.getSelector(); 6184 comp = intent.getComponent(); 6185 } 6186 } 6187 if (comp != null) { 6188 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6189 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6190 if (pi != null) { 6191 final ResolveInfo ri = new ResolveInfo(); 6192 ri.providerInfo = pi; 6193 list.add(ri); 6194 } 6195 return list; 6196 } 6197 6198 // reader 6199 synchronized (mPackages) { 6200 String pkgName = intent.getPackage(); 6201 if (pkgName == null) { 6202 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6203 } 6204 final PackageParser.Package pkg = mPackages.get(pkgName); 6205 if (pkg != null) { 6206 return mProviders.queryIntentForPackage( 6207 intent, resolvedType, flags, pkg.providers, userId); 6208 } 6209 return Collections.emptyList(); 6210 } 6211 } 6212 6213 @Override 6214 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6215 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6216 flags = updateFlagsForPackage(flags, userId, null); 6217 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6219 true /* requireFullPermission */, false /* checkShell */, 6220 "get installed packages"); 6221 6222 // writer 6223 synchronized (mPackages) { 6224 ArrayList<PackageInfo> list; 6225 if (listUninstalled) { 6226 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6227 for (PackageSetting ps : mSettings.mPackages.values()) { 6228 final PackageInfo pi; 6229 if (ps.pkg != null) { 6230 pi = generatePackageInfo(ps, flags, userId); 6231 } else { 6232 pi = generatePackageInfo(ps, flags, userId); 6233 } 6234 if (pi != null) { 6235 list.add(pi); 6236 } 6237 } 6238 } else { 6239 list = new ArrayList<PackageInfo>(mPackages.size()); 6240 for (PackageParser.Package p : mPackages.values()) { 6241 final PackageInfo pi = 6242 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6243 if (pi != null) { 6244 list.add(pi); 6245 } 6246 } 6247 } 6248 6249 return new ParceledListSlice<PackageInfo>(list); 6250 } 6251 } 6252 6253 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6254 String[] permissions, boolean[] tmp, int flags, int userId) { 6255 int numMatch = 0; 6256 final PermissionsState permissionsState = ps.getPermissionsState(); 6257 for (int i=0; i<permissions.length; i++) { 6258 final String permission = permissions[i]; 6259 if (permissionsState.hasPermission(permission, userId)) { 6260 tmp[i] = true; 6261 numMatch++; 6262 } else { 6263 tmp[i] = false; 6264 } 6265 } 6266 if (numMatch == 0) { 6267 return; 6268 } 6269 final PackageInfo pi; 6270 if (ps.pkg != null) { 6271 pi = generatePackageInfo(ps, flags, userId); 6272 } else { 6273 pi = generatePackageInfo(ps, flags, userId); 6274 } 6275 // The above might return null in cases of uninstalled apps or install-state 6276 // skew across users/profiles. 6277 if (pi != null) { 6278 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6279 if (numMatch == permissions.length) { 6280 pi.requestedPermissions = permissions; 6281 } else { 6282 pi.requestedPermissions = new String[numMatch]; 6283 numMatch = 0; 6284 for (int i=0; i<permissions.length; i++) { 6285 if (tmp[i]) { 6286 pi.requestedPermissions[numMatch] = permissions[i]; 6287 numMatch++; 6288 } 6289 } 6290 } 6291 } 6292 list.add(pi); 6293 } 6294 } 6295 6296 @Override 6297 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6298 String[] permissions, int flags, int userId) { 6299 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6300 flags = updateFlagsForPackage(flags, userId, permissions); 6301 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6302 6303 // writer 6304 synchronized (mPackages) { 6305 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6306 boolean[] tmpBools = new boolean[permissions.length]; 6307 if (listUninstalled) { 6308 for (PackageSetting ps : mSettings.mPackages.values()) { 6309 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6310 } 6311 } else { 6312 for (PackageParser.Package pkg : mPackages.values()) { 6313 PackageSetting ps = (PackageSetting)pkg.mExtras; 6314 if (ps != null) { 6315 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6316 userId); 6317 } 6318 } 6319 } 6320 6321 return new ParceledListSlice<PackageInfo>(list); 6322 } 6323 } 6324 6325 @Override 6326 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6327 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6328 flags = updateFlagsForApplication(flags, userId, null); 6329 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6330 6331 // writer 6332 synchronized (mPackages) { 6333 ArrayList<ApplicationInfo> list; 6334 if (listUninstalled) { 6335 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6336 for (PackageSetting ps : mSettings.mPackages.values()) { 6337 ApplicationInfo ai; 6338 if (ps.pkg != null) { 6339 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6340 ps.readUserState(userId), userId); 6341 } else { 6342 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6343 } 6344 if (ai != null) { 6345 list.add(ai); 6346 } 6347 } 6348 } else { 6349 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6350 for (PackageParser.Package p : mPackages.values()) { 6351 if (p.mExtras != null) { 6352 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6353 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6354 if (ai != null) { 6355 list.add(ai); 6356 } 6357 } 6358 } 6359 } 6360 6361 return new ParceledListSlice<ApplicationInfo>(list); 6362 } 6363 } 6364 6365 @Override 6366 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6367 if (DISABLE_EPHEMERAL_APPS) { 6368 return null; 6369 } 6370 6371 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6372 "getEphemeralApplications"); 6373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6374 true /* requireFullPermission */, false /* checkShell */, 6375 "getEphemeralApplications"); 6376 synchronized (mPackages) { 6377 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6378 .getEphemeralApplicationsLPw(userId); 6379 if (ephemeralApps != null) { 6380 return new ParceledListSlice<>(ephemeralApps); 6381 } 6382 } 6383 return null; 6384 } 6385 6386 @Override 6387 public boolean isEphemeralApplication(String packageName, int userId) { 6388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6389 true /* requireFullPermission */, false /* checkShell */, 6390 "isEphemeral"); 6391 if (DISABLE_EPHEMERAL_APPS) { 6392 return false; 6393 } 6394 6395 if (!isCallerSameApp(packageName)) { 6396 return false; 6397 } 6398 synchronized (mPackages) { 6399 PackageParser.Package pkg = mPackages.get(packageName); 6400 if (pkg != null) { 6401 return pkg.applicationInfo.isEphemeralApp(); 6402 } 6403 } 6404 return false; 6405 } 6406 6407 @Override 6408 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6409 if (DISABLE_EPHEMERAL_APPS) { 6410 return null; 6411 } 6412 6413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6414 true /* requireFullPermission */, false /* checkShell */, 6415 "getCookie"); 6416 if (!isCallerSameApp(packageName)) { 6417 return null; 6418 } 6419 synchronized (mPackages) { 6420 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6421 packageName, userId); 6422 } 6423 } 6424 6425 @Override 6426 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6427 if (DISABLE_EPHEMERAL_APPS) { 6428 return true; 6429 } 6430 6431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6432 true /* requireFullPermission */, true /* checkShell */, 6433 "setCookie"); 6434 if (!isCallerSameApp(packageName)) { 6435 return false; 6436 } 6437 synchronized (mPackages) { 6438 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6439 packageName, cookie, userId); 6440 } 6441 } 6442 6443 @Override 6444 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6445 if (DISABLE_EPHEMERAL_APPS) { 6446 return null; 6447 } 6448 6449 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6450 "getEphemeralApplicationIcon"); 6451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6452 true /* requireFullPermission */, false /* checkShell */, 6453 "getEphemeralApplicationIcon"); 6454 synchronized (mPackages) { 6455 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6456 packageName, userId); 6457 } 6458 } 6459 6460 private boolean isCallerSameApp(String packageName) { 6461 PackageParser.Package pkg = mPackages.get(packageName); 6462 return pkg != null 6463 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6464 } 6465 6466 @Override 6467 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6468 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6469 } 6470 6471 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6472 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6473 6474 // reader 6475 synchronized (mPackages) { 6476 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6477 final int userId = UserHandle.getCallingUserId(); 6478 while (i.hasNext()) { 6479 final PackageParser.Package p = i.next(); 6480 if (p.applicationInfo == null) continue; 6481 6482 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6483 && !p.applicationInfo.isDirectBootAware(); 6484 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6485 && p.applicationInfo.isDirectBootAware(); 6486 6487 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6488 && (!mSafeMode || isSystemApp(p)) 6489 && (matchesUnaware || matchesAware)) { 6490 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6491 if (ps != null) { 6492 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6493 ps.readUserState(userId), userId); 6494 if (ai != null) { 6495 finalList.add(ai); 6496 } 6497 } 6498 } 6499 } 6500 } 6501 6502 return finalList; 6503 } 6504 6505 @Override 6506 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6507 if (!sUserManager.exists(userId)) return null; 6508 flags = updateFlagsForComponent(flags, userId, name); 6509 // reader 6510 synchronized (mPackages) { 6511 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6512 PackageSetting ps = provider != null 6513 ? mSettings.mPackages.get(provider.owner.packageName) 6514 : null; 6515 return ps != null 6516 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6517 ? PackageParser.generateProviderInfo(provider, flags, 6518 ps.readUserState(userId), userId) 6519 : null; 6520 } 6521 } 6522 6523 /** 6524 * @deprecated 6525 */ 6526 @Deprecated 6527 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6528 // reader 6529 synchronized (mPackages) { 6530 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6531 .entrySet().iterator(); 6532 final int userId = UserHandle.getCallingUserId(); 6533 while (i.hasNext()) { 6534 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6535 PackageParser.Provider p = entry.getValue(); 6536 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6537 6538 if (ps != null && p.syncable 6539 && (!mSafeMode || (p.info.applicationInfo.flags 6540 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6541 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6542 ps.readUserState(userId), userId); 6543 if (info != null) { 6544 outNames.add(entry.getKey()); 6545 outInfo.add(info); 6546 } 6547 } 6548 } 6549 } 6550 } 6551 6552 @Override 6553 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6554 int uid, int flags) { 6555 final int userId = processName != null ? UserHandle.getUserId(uid) 6556 : UserHandle.getCallingUserId(); 6557 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6558 flags = updateFlagsForComponent(flags, userId, processName); 6559 6560 ArrayList<ProviderInfo> finalList = null; 6561 // reader 6562 synchronized (mPackages) { 6563 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6564 while (i.hasNext()) { 6565 final PackageParser.Provider p = i.next(); 6566 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6567 if (ps != null && p.info.authority != null 6568 && (processName == null 6569 || (p.info.processName.equals(processName) 6570 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6571 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6572 if (finalList == null) { 6573 finalList = new ArrayList<ProviderInfo>(3); 6574 } 6575 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6576 ps.readUserState(userId), userId); 6577 if (info != null) { 6578 finalList.add(info); 6579 } 6580 } 6581 } 6582 } 6583 6584 if (finalList != null) { 6585 Collections.sort(finalList, mProviderInitOrderSorter); 6586 return new ParceledListSlice<ProviderInfo>(finalList); 6587 } 6588 6589 return ParceledListSlice.emptyList(); 6590 } 6591 6592 @Override 6593 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6594 // reader 6595 synchronized (mPackages) { 6596 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6597 return PackageParser.generateInstrumentationInfo(i, flags); 6598 } 6599 } 6600 6601 @Override 6602 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6603 String targetPackage, int flags) { 6604 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6605 } 6606 6607 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6608 int flags) { 6609 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6610 6611 // reader 6612 synchronized (mPackages) { 6613 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6614 while (i.hasNext()) { 6615 final PackageParser.Instrumentation p = i.next(); 6616 if (targetPackage == null 6617 || targetPackage.equals(p.info.targetPackage)) { 6618 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6619 flags); 6620 if (ii != null) { 6621 finalList.add(ii); 6622 } 6623 } 6624 } 6625 } 6626 6627 return finalList; 6628 } 6629 6630 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6631 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6632 if (overlays == null) { 6633 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6634 return; 6635 } 6636 for (PackageParser.Package opkg : overlays.values()) { 6637 // Not much to do if idmap fails: we already logged the error 6638 // and we certainly don't want to abort installation of pkg simply 6639 // because an overlay didn't fit properly. For these reasons, 6640 // ignore the return value of createIdmapForPackagePairLI. 6641 createIdmapForPackagePairLI(pkg, opkg); 6642 } 6643 } 6644 6645 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6646 PackageParser.Package opkg) { 6647 if (!opkg.mTrustedOverlay) { 6648 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6649 opkg.baseCodePath + ": overlay not trusted"); 6650 return false; 6651 } 6652 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6653 if (overlaySet == null) { 6654 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6655 opkg.baseCodePath + " but target package has no known overlays"); 6656 return false; 6657 } 6658 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6659 // TODO: generate idmap for split APKs 6660 try { 6661 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6662 } catch (InstallerException e) { 6663 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6664 + opkg.baseCodePath); 6665 return false; 6666 } 6667 PackageParser.Package[] overlayArray = 6668 overlaySet.values().toArray(new PackageParser.Package[0]); 6669 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6670 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6671 return p1.mOverlayPriority - p2.mOverlayPriority; 6672 } 6673 }; 6674 Arrays.sort(overlayArray, cmp); 6675 6676 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6677 int i = 0; 6678 for (PackageParser.Package p : overlayArray) { 6679 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6680 } 6681 return true; 6682 } 6683 6684 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6686 try { 6687 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6688 } finally { 6689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6690 } 6691 } 6692 6693 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6694 final File[] files = dir.listFiles(); 6695 if (ArrayUtils.isEmpty(files)) { 6696 Log.d(TAG, "No files in app dir " + dir); 6697 return; 6698 } 6699 6700 if (DEBUG_PACKAGE_SCANNING) { 6701 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6702 + " flags=0x" + Integer.toHexString(parseFlags)); 6703 } 6704 6705 for (File file : files) { 6706 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6707 && !PackageInstallerService.isStageName(file.getName()); 6708 if (!isPackage) { 6709 // Ignore entries which are not packages 6710 continue; 6711 } 6712 try { 6713 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6714 scanFlags, currentTime, null); 6715 } catch (PackageManagerException e) { 6716 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6717 6718 // Delete invalid userdata apps 6719 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6720 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6721 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6722 removeCodePathLI(file); 6723 } 6724 } 6725 } 6726 } 6727 6728 private static File getSettingsProblemFile() { 6729 File dataDir = Environment.getDataDirectory(); 6730 File systemDir = new File(dataDir, "system"); 6731 File fname = new File(systemDir, "uiderrors.txt"); 6732 return fname; 6733 } 6734 6735 static void reportSettingsProblem(int priority, String msg) { 6736 logCriticalInfo(priority, msg); 6737 } 6738 6739 static void logCriticalInfo(int priority, String msg) { 6740 Slog.println(priority, TAG, msg); 6741 EventLogTags.writePmCriticalInfo(msg); 6742 try { 6743 File fname = getSettingsProblemFile(); 6744 FileOutputStream out = new FileOutputStream(fname, true); 6745 PrintWriter pw = new FastPrintWriter(out); 6746 SimpleDateFormat formatter = new SimpleDateFormat(); 6747 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6748 pw.println(dateString + ": " + msg); 6749 pw.close(); 6750 FileUtils.setPermissions( 6751 fname.toString(), 6752 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6753 -1, -1); 6754 } catch (java.io.IOException e) { 6755 } 6756 } 6757 6758 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6759 final int policyFlags) throws PackageManagerException { 6760 if (ps != null 6761 && ps.codePath.equals(srcFile) 6762 && ps.timeStamp == srcFile.lastModified() 6763 && !isCompatSignatureUpdateNeeded(pkg) 6764 && !isRecoverSignatureUpdateNeeded(pkg)) { 6765 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6766 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6767 ArraySet<PublicKey> signingKs; 6768 synchronized (mPackages) { 6769 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6770 } 6771 if (ps.signatures.mSignatures != null 6772 && ps.signatures.mSignatures.length != 0 6773 && signingKs != null) { 6774 // Optimization: reuse the existing cached certificates 6775 // if the package appears to be unchanged. 6776 pkg.mSignatures = ps.signatures.mSignatures; 6777 pkg.mSigningKeys = signingKs; 6778 return; 6779 } 6780 6781 Slog.w(TAG, "PackageSetting for " + ps.name 6782 + " is missing signatures. Collecting certs again to recover them."); 6783 } else { 6784 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6785 } 6786 6787 try { 6788 PackageParser.collectCertificates(pkg, policyFlags); 6789 } catch (PackageParserException e) { 6790 throw PackageManagerException.from(e); 6791 } 6792 } 6793 6794 /** 6795 * Traces a package scan. 6796 * @see #scanPackageLI(File, int, int, long, UserHandle) 6797 */ 6798 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6799 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6801 try { 6802 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6803 } finally { 6804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6805 } 6806 } 6807 6808 /** 6809 * Scans a package and returns the newly parsed package. 6810 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6811 */ 6812 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6813 long currentTime, UserHandle user) throws PackageManagerException { 6814 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6815 PackageParser pp = new PackageParser(); 6816 pp.setSeparateProcesses(mSeparateProcesses); 6817 pp.setOnlyCoreApps(mOnlyCore); 6818 pp.setDisplayMetrics(mMetrics); 6819 6820 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6821 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6822 } 6823 6824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6825 final PackageParser.Package pkg; 6826 try { 6827 pkg = pp.parsePackage(scanFile, parseFlags); 6828 } catch (PackageParserException e) { 6829 throw PackageManagerException.from(e); 6830 } finally { 6831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6832 } 6833 6834 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6835 } 6836 6837 /** 6838 * Scans a package and returns the newly parsed package. 6839 * @throws PackageManagerException on a parse error. 6840 */ 6841 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6842 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6843 throws PackageManagerException { 6844 // If the package has children and this is the first dive in the function 6845 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6846 // packages (parent and children) would be successfully scanned before the 6847 // actual scan since scanning mutates internal state and we want to atomically 6848 // install the package and its children. 6849 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6850 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6851 scanFlags |= SCAN_CHECK_ONLY; 6852 } 6853 } else { 6854 scanFlags &= ~SCAN_CHECK_ONLY; 6855 } 6856 6857 // Scan the parent 6858 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6859 scanFlags, currentTime, user); 6860 6861 // Scan the children 6862 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6863 for (int i = 0; i < childCount; i++) { 6864 PackageParser.Package childPackage = pkg.childPackages.get(i); 6865 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6866 currentTime, user); 6867 } 6868 6869 6870 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6871 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6872 } 6873 6874 return scannedPkg; 6875 } 6876 6877 /** 6878 * Scans a package and returns the newly parsed package. 6879 * @throws PackageManagerException on a parse error. 6880 */ 6881 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6882 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6883 throws PackageManagerException { 6884 PackageSetting ps = null; 6885 PackageSetting updatedPkg; 6886 // reader 6887 synchronized (mPackages) { 6888 // Look to see if we already know about this package. 6889 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6890 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6891 // This package has been renamed to its original name. Let's 6892 // use that. 6893 ps = mSettings.peekPackageLPr(oldName); 6894 } 6895 // If there was no original package, see one for the real package name. 6896 if (ps == null) { 6897 ps = mSettings.peekPackageLPr(pkg.packageName); 6898 } 6899 // Check to see if this package could be hiding/updating a system 6900 // package. Must look for it either under the original or real 6901 // package name depending on our state. 6902 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6903 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6904 6905 // If this is a package we don't know about on the system partition, we 6906 // may need to remove disabled child packages on the system partition 6907 // or may need to not add child packages if the parent apk is updated 6908 // on the data partition and no longer defines this child package. 6909 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6910 // If this is a parent package for an updated system app and this system 6911 // app got an OTA update which no longer defines some of the child packages 6912 // we have to prune them from the disabled system packages. 6913 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6914 if (disabledPs != null) { 6915 final int scannedChildCount = (pkg.childPackages != null) 6916 ? pkg.childPackages.size() : 0; 6917 final int disabledChildCount = disabledPs.childPackageNames != null 6918 ? disabledPs.childPackageNames.size() : 0; 6919 for (int i = 0; i < disabledChildCount; i++) { 6920 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6921 boolean disabledPackageAvailable = false; 6922 for (int j = 0; j < scannedChildCount; j++) { 6923 PackageParser.Package childPkg = pkg.childPackages.get(j); 6924 if (childPkg.packageName.equals(disabledChildPackageName)) { 6925 disabledPackageAvailable = true; 6926 break; 6927 } 6928 } 6929 if (!disabledPackageAvailable) { 6930 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6931 } 6932 } 6933 } 6934 } 6935 } 6936 6937 boolean updatedPkgBetter = false; 6938 // First check if this is a system package that may involve an update 6939 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6940 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6941 // it needs to drop FLAG_PRIVILEGED. 6942 if (locationIsPrivileged(scanFile)) { 6943 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6944 } else { 6945 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6946 } 6947 6948 if (ps != null && !ps.codePath.equals(scanFile)) { 6949 // The path has changed from what was last scanned... check the 6950 // version of the new path against what we have stored to determine 6951 // what to do. 6952 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6953 if (pkg.mVersionCode <= ps.versionCode) { 6954 // The system package has been updated and the code path does not match 6955 // Ignore entry. Skip it. 6956 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6957 + " ignored: updated version " + ps.versionCode 6958 + " better than this " + pkg.mVersionCode); 6959 if (!updatedPkg.codePath.equals(scanFile)) { 6960 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6961 + ps.name + " changing from " + updatedPkg.codePathString 6962 + " to " + scanFile); 6963 updatedPkg.codePath = scanFile; 6964 updatedPkg.codePathString = scanFile.toString(); 6965 updatedPkg.resourcePath = scanFile; 6966 updatedPkg.resourcePathString = scanFile.toString(); 6967 } 6968 updatedPkg.pkg = pkg; 6969 updatedPkg.versionCode = pkg.mVersionCode; 6970 6971 // Update the disabled system child packages to point to the package too. 6972 final int childCount = updatedPkg.childPackageNames != null 6973 ? updatedPkg.childPackageNames.size() : 0; 6974 for (int i = 0; i < childCount; i++) { 6975 String childPackageName = updatedPkg.childPackageNames.get(i); 6976 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6977 childPackageName); 6978 if (updatedChildPkg != null) { 6979 updatedChildPkg.pkg = pkg; 6980 updatedChildPkg.versionCode = pkg.mVersionCode; 6981 } 6982 } 6983 6984 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6985 + scanFile + " ignored: updated version " + ps.versionCode 6986 + " better than this " + pkg.mVersionCode); 6987 } else { 6988 // The current app on the system partition is better than 6989 // what we have updated to on the data partition; switch 6990 // back to the system partition version. 6991 // At this point, its safely assumed that package installation for 6992 // apps in system partition will go through. If not there won't be a working 6993 // version of the app 6994 // writer 6995 synchronized (mPackages) { 6996 // Just remove the loaded entries from package lists. 6997 mPackages.remove(ps.name); 6998 } 6999 7000 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7001 + " reverting from " + ps.codePathString 7002 + ": new version " + pkg.mVersionCode 7003 + " better than installed " + ps.versionCode); 7004 7005 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7006 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7007 synchronized (mInstallLock) { 7008 args.cleanUpResourcesLI(); 7009 } 7010 synchronized (mPackages) { 7011 mSettings.enableSystemPackageLPw(ps.name); 7012 } 7013 updatedPkgBetter = true; 7014 } 7015 } 7016 } 7017 7018 if (updatedPkg != null) { 7019 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7020 // initially 7021 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7022 7023 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7024 // flag set initially 7025 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7026 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7027 } 7028 } 7029 7030 // Verify certificates against what was last scanned 7031 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7032 7033 /* 7034 * A new system app appeared, but we already had a non-system one of the 7035 * same name installed earlier. 7036 */ 7037 boolean shouldHideSystemApp = false; 7038 if (updatedPkg == null && ps != null 7039 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7040 /* 7041 * Check to make sure the signatures match first. If they don't, 7042 * wipe the installed application and its data. 7043 */ 7044 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7045 != PackageManager.SIGNATURE_MATCH) { 7046 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7047 + " signatures don't match existing userdata copy; removing"); 7048 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7049 "scanPackageInternalLI")) { 7050 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7051 } 7052 ps = null; 7053 } else { 7054 /* 7055 * If the newly-added system app is an older version than the 7056 * already installed version, hide it. It will be scanned later 7057 * and re-added like an update. 7058 */ 7059 if (pkg.mVersionCode <= ps.versionCode) { 7060 shouldHideSystemApp = true; 7061 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7062 + " but new version " + pkg.mVersionCode + " better than installed " 7063 + ps.versionCode + "; hiding system"); 7064 } else { 7065 /* 7066 * The newly found system app is a newer version that the 7067 * one previously installed. Simply remove the 7068 * already-installed application and replace it with our own 7069 * while keeping the application data. 7070 */ 7071 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7072 + " reverting from " + ps.codePathString + ": new version " 7073 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7074 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7075 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7076 synchronized (mInstallLock) { 7077 args.cleanUpResourcesLI(); 7078 } 7079 } 7080 } 7081 } 7082 7083 // The apk is forward locked (not public) if its code and resources 7084 // are kept in different files. (except for app in either system or 7085 // vendor path). 7086 // TODO grab this value from PackageSettings 7087 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7088 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7089 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7090 } 7091 } 7092 7093 // TODO: extend to support forward-locked splits 7094 String resourcePath = null; 7095 String baseResourcePath = null; 7096 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7097 if (ps != null && ps.resourcePathString != null) { 7098 resourcePath = ps.resourcePathString; 7099 baseResourcePath = ps.resourcePathString; 7100 } else { 7101 // Should not happen at all. Just log an error. 7102 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7103 } 7104 } else { 7105 resourcePath = pkg.codePath; 7106 baseResourcePath = pkg.baseCodePath; 7107 } 7108 7109 // Set application objects path explicitly. 7110 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7111 pkg.setApplicationInfoCodePath(pkg.codePath); 7112 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7113 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7114 pkg.setApplicationInfoResourcePath(resourcePath); 7115 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7116 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7117 7118 // Note that we invoke the following method only if we are about to unpack an application 7119 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7120 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7121 7122 /* 7123 * If the system app should be overridden by a previously installed 7124 * data, hide the system app now and let the /data/app scan pick it up 7125 * again. 7126 */ 7127 if (shouldHideSystemApp) { 7128 synchronized (mPackages) { 7129 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7130 } 7131 } 7132 7133 return scannedPkg; 7134 } 7135 7136 private static String fixProcessName(String defProcessName, 7137 String processName, int uid) { 7138 if (processName == null) { 7139 return defProcessName; 7140 } 7141 return processName; 7142 } 7143 7144 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7145 throws PackageManagerException { 7146 if (pkgSetting.signatures.mSignatures != null) { 7147 // Already existing package. Make sure signatures match 7148 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7149 == PackageManager.SIGNATURE_MATCH; 7150 if (!match) { 7151 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7152 == PackageManager.SIGNATURE_MATCH; 7153 } 7154 if (!match) { 7155 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7156 == PackageManager.SIGNATURE_MATCH; 7157 } 7158 if (!match) { 7159 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7160 + pkg.packageName + " signatures do not match the " 7161 + "previously installed version; ignoring!"); 7162 } 7163 } 7164 7165 // Check for shared user signatures 7166 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7167 // Already existing package. Make sure signatures match 7168 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7169 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7170 if (!match) { 7171 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7172 == PackageManager.SIGNATURE_MATCH; 7173 } 7174 if (!match) { 7175 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7176 == PackageManager.SIGNATURE_MATCH; 7177 } 7178 if (!match) { 7179 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7180 "Package " + pkg.packageName 7181 + " has no signatures that match those in shared user " 7182 + pkgSetting.sharedUser.name + "; ignoring!"); 7183 } 7184 } 7185 } 7186 7187 /** 7188 * Enforces that only the system UID or root's UID can call a method exposed 7189 * via Binder. 7190 * 7191 * @param message used as message if SecurityException is thrown 7192 * @throws SecurityException if the caller is not system or root 7193 */ 7194 private static final void enforceSystemOrRoot(String message) { 7195 final int uid = Binder.getCallingUid(); 7196 if (uid != Process.SYSTEM_UID && uid != 0) { 7197 throw new SecurityException(message); 7198 } 7199 } 7200 7201 @Override 7202 public void performFstrimIfNeeded() { 7203 enforceSystemOrRoot("Only the system can request fstrim"); 7204 7205 // Before everything else, see whether we need to fstrim. 7206 try { 7207 IMountService ms = PackageHelper.getMountService(); 7208 if (ms != null) { 7209 final boolean isUpgrade = isUpgrade(); 7210 boolean doTrim = isUpgrade; 7211 if (doTrim) { 7212 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7213 } else { 7214 final long interval = android.provider.Settings.Global.getLong( 7215 mContext.getContentResolver(), 7216 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7217 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7218 if (interval > 0) { 7219 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7220 if (timeSinceLast > interval) { 7221 doTrim = true; 7222 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7223 + "; running immediately"); 7224 } 7225 } 7226 } 7227 if (doTrim) { 7228 if (!isFirstBoot()) { 7229 try { 7230 ActivityManagerNative.getDefault().showBootMessage( 7231 mContext.getResources().getString( 7232 R.string.android_upgrading_fstrim), true); 7233 } catch (RemoteException e) { 7234 } 7235 } 7236 ms.runMaintenance(); 7237 } 7238 } else { 7239 Slog.e(TAG, "Mount service unavailable!"); 7240 } 7241 } catch (RemoteException e) { 7242 // Can't happen; MountService is local 7243 } 7244 } 7245 7246 @Override 7247 public void updatePackagesIfNeeded() { 7248 enforceSystemOrRoot("Only the system can request package update"); 7249 7250 // We need to re-extract after an OTA. 7251 boolean causeUpgrade = isUpgrade(); 7252 7253 // First boot or factory reset. 7254 // Note: we also handle devices that are upgrading to N right now as if it is their 7255 // first boot, as they do not have profile data. 7256 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7257 7258 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7259 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7260 7261 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7262 return; 7263 } 7264 7265 List<PackageParser.Package> pkgs; 7266 synchronized (mPackages) { 7267 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7268 } 7269 7270 final long startTime = System.nanoTime(); 7271 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7272 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7273 7274 final int elapsedTimeSeconds = 7275 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7276 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7279 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7280 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7281 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7282 } 7283 7284 /** 7285 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7286 * containing statistics about the invocation. The array consists of three elements, 7287 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7288 * and {@code numberOfPackagesFailed}. 7289 */ 7290 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7291 String compilerFilter) { 7292 7293 int numberOfPackagesVisited = 0; 7294 int numberOfPackagesOptimized = 0; 7295 int numberOfPackagesSkipped = 0; 7296 int numberOfPackagesFailed = 0; 7297 final int numberOfPackagesToDexopt = pkgs.size(); 7298 7299 for (PackageParser.Package pkg : pkgs) { 7300 numberOfPackagesVisited++; 7301 7302 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7303 if (DEBUG_DEXOPT) { 7304 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7305 } 7306 numberOfPackagesSkipped++; 7307 continue; 7308 } 7309 7310 if (DEBUG_DEXOPT) { 7311 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7312 numberOfPackagesToDexopt + ": " + pkg.packageName); 7313 } 7314 7315 if (showDialog) { 7316 try { 7317 ActivityManagerNative.getDefault().showBootMessage( 7318 mContext.getResources().getString(R.string.android_upgrading_apk, 7319 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7320 } catch (RemoteException e) { 7321 } 7322 } 7323 7324 // checkProfiles is false to avoid merging profiles during boot which 7325 // might interfere with background compilation (b/28612421). 7326 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7327 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7328 // trade-off worth doing to save boot time work. 7329 int dexOptStatus = performDexOptTraced(pkg.packageName, 7330 false /* checkProfiles */, 7331 compilerFilter, 7332 false /* force */); 7333 switch (dexOptStatus) { 7334 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7335 numberOfPackagesOptimized++; 7336 break; 7337 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7338 numberOfPackagesSkipped++; 7339 break; 7340 case PackageDexOptimizer.DEX_OPT_FAILED: 7341 numberOfPackagesFailed++; 7342 break; 7343 default: 7344 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7345 break; 7346 } 7347 } 7348 7349 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7350 numberOfPackagesFailed }; 7351 } 7352 7353 @Override 7354 public void notifyPackageUse(String packageName, int reason) { 7355 synchronized (mPackages) { 7356 PackageParser.Package p = mPackages.get(packageName); 7357 if (p == null) { 7358 return; 7359 } 7360 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7361 } 7362 } 7363 7364 // TODO: this is not used nor needed. Delete it. 7365 @Override 7366 public boolean performDexOptIfNeeded(String packageName) { 7367 int dexOptStatus = performDexOptTraced(packageName, 7368 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7369 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7370 } 7371 7372 @Override 7373 public boolean performDexOpt(String packageName, 7374 boolean checkProfiles, int compileReason, boolean force) { 7375 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7376 getCompilerFilterForReason(compileReason), force); 7377 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7378 } 7379 7380 @Override 7381 public boolean performDexOptMode(String packageName, 7382 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7383 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7384 targetCompilerFilter, force); 7385 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7386 } 7387 7388 private int performDexOptTraced(String packageName, 7389 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7391 try { 7392 return performDexOptInternal(packageName, checkProfiles, 7393 targetCompilerFilter, force); 7394 } finally { 7395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7396 } 7397 } 7398 7399 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7400 // if the package can now be considered up to date for the given filter. 7401 private int performDexOptInternal(String packageName, 7402 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7403 PackageParser.Package p; 7404 synchronized (mPackages) { 7405 p = mPackages.get(packageName); 7406 if (p == null) { 7407 // Package could not be found. Report failure. 7408 return PackageDexOptimizer.DEX_OPT_FAILED; 7409 } 7410 mPackageUsage.write(false); 7411 } 7412 long callingId = Binder.clearCallingIdentity(); 7413 try { 7414 synchronized (mInstallLock) { 7415 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7416 targetCompilerFilter, force); 7417 } 7418 } finally { 7419 Binder.restoreCallingIdentity(callingId); 7420 } 7421 } 7422 7423 public ArraySet<String> getOptimizablePackages() { 7424 ArraySet<String> pkgs = new ArraySet<String>(); 7425 synchronized (mPackages) { 7426 for (PackageParser.Package p : mPackages.values()) { 7427 if (PackageDexOptimizer.canOptimizePackage(p)) { 7428 pkgs.add(p.packageName); 7429 } 7430 } 7431 } 7432 return pkgs; 7433 } 7434 7435 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7436 boolean checkProfiles, String targetCompilerFilter, 7437 boolean force) { 7438 // Select the dex optimizer based on the force parameter. 7439 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7440 // allocate an object here. 7441 PackageDexOptimizer pdo = force 7442 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7443 : mPackageDexOptimizer; 7444 7445 // Optimize all dependencies first. Note: we ignore the return value and march on 7446 // on errors. 7447 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7448 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7449 if (!deps.isEmpty()) { 7450 for (PackageParser.Package depPackage : deps) { 7451 // TODO: Analyze and investigate if we (should) profile libraries. 7452 // Currently this will do a full compilation of the library by default. 7453 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7454 false /* checkProfiles */, 7455 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7456 } 7457 } 7458 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7459 targetCompilerFilter); 7460 } 7461 7462 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7463 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7464 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7465 Set<String> collectedNames = new HashSet<>(); 7466 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7467 7468 retValue.remove(p); 7469 7470 return retValue; 7471 } else { 7472 return Collections.emptyList(); 7473 } 7474 } 7475 7476 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7477 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7478 if (!collectedNames.contains(p.packageName)) { 7479 collectedNames.add(p.packageName); 7480 collected.add(p); 7481 7482 if (p.usesLibraries != null) { 7483 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7484 } 7485 if (p.usesOptionalLibraries != null) { 7486 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7487 collectedNames); 7488 } 7489 } 7490 } 7491 7492 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7493 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7494 for (String libName : libs) { 7495 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7496 if (libPkg != null) { 7497 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7498 } 7499 } 7500 } 7501 7502 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7503 synchronized (mPackages) { 7504 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7505 if (lib != null && lib.apk != null) { 7506 return mPackages.get(lib.apk); 7507 } 7508 } 7509 return null; 7510 } 7511 7512 public void shutdown() { 7513 mPackageUsage.write(true); 7514 } 7515 7516 @Override 7517 public void dumpProfiles(String packageName) { 7518 PackageParser.Package pkg; 7519 synchronized (mPackages) { 7520 pkg = mPackages.get(packageName); 7521 if (pkg == null) { 7522 throw new IllegalArgumentException("Unknown package: " + packageName); 7523 } 7524 } 7525 /* Only the shell, root, or the app user should be able to dump profiles. */ 7526 int callingUid = Binder.getCallingUid(); 7527 if (callingUid != Process.SHELL_UID && 7528 callingUid != Process.ROOT_UID && 7529 callingUid != pkg.applicationInfo.uid) { 7530 throw new SecurityException("dumpProfiles"); 7531 } 7532 7533 synchronized (mInstallLock) { 7534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7535 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7536 try { 7537 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7538 String gid = Integer.toString(sharedGid); 7539 String codePaths = TextUtils.join(";", allCodePaths); 7540 mInstaller.dumpProfiles(gid, packageName, codePaths); 7541 } catch (InstallerException e) { 7542 Slog.w(TAG, "Failed to dump profiles", e); 7543 } 7544 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7545 } 7546 } 7547 7548 @Override 7549 public void forceDexOpt(String packageName) { 7550 enforceSystemOrRoot("forceDexOpt"); 7551 7552 PackageParser.Package pkg; 7553 synchronized (mPackages) { 7554 pkg = mPackages.get(packageName); 7555 if (pkg == null) { 7556 throw new IllegalArgumentException("Unknown package: " + packageName); 7557 } 7558 } 7559 7560 synchronized (mInstallLock) { 7561 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7562 7563 // Whoever is calling forceDexOpt wants a fully compiled package. 7564 // Don't use profiles since that may cause compilation to be skipped. 7565 final int res = performDexOptInternalWithDependenciesLI(pkg, 7566 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7567 true /* force */); 7568 7569 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7570 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7571 throw new IllegalStateException("Failed to dexopt: " + res); 7572 } 7573 } 7574 } 7575 7576 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7577 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7578 Slog.w(TAG, "Unable to update from " + oldPkg.name 7579 + " to " + newPkg.packageName 7580 + ": old package not in system partition"); 7581 return false; 7582 } else if (mPackages.get(oldPkg.name) != null) { 7583 Slog.w(TAG, "Unable to update from " + oldPkg.name 7584 + " to " + newPkg.packageName 7585 + ": old package still exists"); 7586 return false; 7587 } 7588 return true; 7589 } 7590 7591 void removeCodePathLI(File codePath) { 7592 if (codePath.isDirectory()) { 7593 try { 7594 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7595 } catch (InstallerException e) { 7596 Slog.w(TAG, "Failed to remove code path", e); 7597 } 7598 } else { 7599 codePath.delete(); 7600 } 7601 } 7602 7603 private int[] resolveUserIds(int userId) { 7604 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7605 } 7606 7607 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7608 if (pkg == null) { 7609 Slog.wtf(TAG, "Package was null!", new Throwable()); 7610 return; 7611 } 7612 clearAppDataLeafLIF(pkg, userId, flags); 7613 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7614 for (int i = 0; i < childCount; i++) { 7615 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7616 } 7617 } 7618 7619 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7620 final PackageSetting ps; 7621 synchronized (mPackages) { 7622 ps = mSettings.mPackages.get(pkg.packageName); 7623 } 7624 for (int realUserId : resolveUserIds(userId)) { 7625 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7626 try { 7627 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7628 ceDataInode); 7629 } catch (InstallerException e) { 7630 Slog.w(TAG, String.valueOf(e)); 7631 } 7632 } 7633 } 7634 7635 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7636 if (pkg == null) { 7637 Slog.wtf(TAG, "Package was null!", new Throwable()); 7638 return; 7639 } 7640 destroyAppDataLeafLIF(pkg, userId, flags); 7641 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7642 for (int i = 0; i < childCount; i++) { 7643 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7644 } 7645 } 7646 7647 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7648 final PackageSetting ps; 7649 synchronized (mPackages) { 7650 ps = mSettings.mPackages.get(pkg.packageName); 7651 } 7652 for (int realUserId : resolveUserIds(userId)) { 7653 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7654 try { 7655 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7656 ceDataInode); 7657 } catch (InstallerException e) { 7658 Slog.w(TAG, String.valueOf(e)); 7659 } 7660 } 7661 } 7662 7663 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7664 if (pkg == null) { 7665 Slog.wtf(TAG, "Package was null!", new Throwable()); 7666 return; 7667 } 7668 destroyAppProfilesLeafLIF(pkg); 7669 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7670 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7671 for (int i = 0; i < childCount; i++) { 7672 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7673 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7674 true /* removeBaseMarker */); 7675 } 7676 } 7677 7678 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7679 boolean removeBaseMarker) { 7680 if (pkg.isForwardLocked()) { 7681 return; 7682 } 7683 7684 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7685 try { 7686 path = PackageManagerServiceUtils.realpath(new File(path)); 7687 } catch (IOException e) { 7688 // TODO: Should we return early here ? 7689 Slog.w(TAG, "Failed to get canonical path", e); 7690 continue; 7691 } 7692 7693 final String useMarker = path.replace('/', '@'); 7694 for (int realUserId : resolveUserIds(userId)) { 7695 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7696 if (removeBaseMarker) { 7697 File foreignUseMark = new File(profileDir, useMarker); 7698 if (foreignUseMark.exists()) { 7699 if (!foreignUseMark.delete()) { 7700 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7701 + pkg.packageName); 7702 } 7703 } 7704 } 7705 7706 File[] markers = profileDir.listFiles(); 7707 if (markers != null) { 7708 final String searchString = "@" + pkg.packageName + "@"; 7709 // We also delete all markers that contain the package name we're 7710 // uninstalling. These are associated with secondary dex-files belonging 7711 // to the package. Reconstructing the path of these dex files is messy 7712 // in general. 7713 for (File marker : markers) { 7714 if (marker.getName().indexOf(searchString) > 0) { 7715 if (!marker.delete()) { 7716 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7717 + pkg.packageName); 7718 } 7719 } 7720 } 7721 } 7722 } 7723 } 7724 } 7725 7726 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7727 try { 7728 mInstaller.destroyAppProfiles(pkg.packageName); 7729 } catch (InstallerException e) { 7730 Slog.w(TAG, String.valueOf(e)); 7731 } 7732 } 7733 7734 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7735 if (pkg == null) { 7736 Slog.wtf(TAG, "Package was null!", new Throwable()); 7737 return; 7738 } 7739 clearAppProfilesLeafLIF(pkg); 7740 // We don't remove the base foreign use marker when clearing profiles because 7741 // we will rename it when the app is updated. Unlike the actual profile contents, 7742 // the foreign use marker is good across installs. 7743 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7744 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7745 for (int i = 0; i < childCount; i++) { 7746 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7747 } 7748 } 7749 7750 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7751 try { 7752 mInstaller.clearAppProfiles(pkg.packageName); 7753 } catch (InstallerException e) { 7754 Slog.w(TAG, String.valueOf(e)); 7755 } 7756 } 7757 7758 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7759 long lastUpdateTime) { 7760 // Set parent install/update time 7761 PackageSetting ps = (PackageSetting) pkg.mExtras; 7762 if (ps != null) { 7763 ps.firstInstallTime = firstInstallTime; 7764 ps.lastUpdateTime = lastUpdateTime; 7765 } 7766 // Set children install/update time 7767 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7768 for (int i = 0; i < childCount; i++) { 7769 PackageParser.Package childPkg = pkg.childPackages.get(i); 7770 ps = (PackageSetting) childPkg.mExtras; 7771 if (ps != null) { 7772 ps.firstInstallTime = firstInstallTime; 7773 ps.lastUpdateTime = lastUpdateTime; 7774 } 7775 } 7776 } 7777 7778 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7779 PackageParser.Package changingLib) { 7780 if (file.path != null) { 7781 usesLibraryFiles.add(file.path); 7782 return; 7783 } 7784 PackageParser.Package p = mPackages.get(file.apk); 7785 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7786 // If we are doing this while in the middle of updating a library apk, 7787 // then we need to make sure to use that new apk for determining the 7788 // dependencies here. (We haven't yet finished committing the new apk 7789 // to the package manager state.) 7790 if (p == null || p.packageName.equals(changingLib.packageName)) { 7791 p = changingLib; 7792 } 7793 } 7794 if (p != null) { 7795 usesLibraryFiles.addAll(p.getAllCodePaths()); 7796 } 7797 } 7798 7799 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7800 PackageParser.Package changingLib) throws PackageManagerException { 7801 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7802 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7803 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7804 for (int i=0; i<N; i++) { 7805 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7806 if (file == null) { 7807 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7808 "Package " + pkg.packageName + " requires unavailable shared library " 7809 + pkg.usesLibraries.get(i) + "; failing!"); 7810 } 7811 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7812 } 7813 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7814 for (int i=0; i<N; i++) { 7815 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7816 if (file == null) { 7817 Slog.w(TAG, "Package " + pkg.packageName 7818 + " desires unavailable shared library " 7819 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7820 } else { 7821 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7822 } 7823 } 7824 N = usesLibraryFiles.size(); 7825 if (N > 0) { 7826 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7827 } else { 7828 pkg.usesLibraryFiles = null; 7829 } 7830 } 7831 } 7832 7833 private static boolean hasString(List<String> list, List<String> which) { 7834 if (list == null) { 7835 return false; 7836 } 7837 for (int i=list.size()-1; i>=0; i--) { 7838 for (int j=which.size()-1; j>=0; j--) { 7839 if (which.get(j).equals(list.get(i))) { 7840 return true; 7841 } 7842 } 7843 } 7844 return false; 7845 } 7846 7847 private void updateAllSharedLibrariesLPw() { 7848 for (PackageParser.Package pkg : mPackages.values()) { 7849 try { 7850 updateSharedLibrariesLPw(pkg, null); 7851 } catch (PackageManagerException e) { 7852 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7853 } 7854 } 7855 } 7856 7857 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7858 PackageParser.Package changingPkg) { 7859 ArrayList<PackageParser.Package> res = null; 7860 for (PackageParser.Package pkg : mPackages.values()) { 7861 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7862 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7863 if (res == null) { 7864 res = new ArrayList<PackageParser.Package>(); 7865 } 7866 res.add(pkg); 7867 try { 7868 updateSharedLibrariesLPw(pkg, changingPkg); 7869 } catch (PackageManagerException e) { 7870 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7871 } 7872 } 7873 } 7874 return res; 7875 } 7876 7877 /** 7878 * Derive the value of the {@code cpuAbiOverride} based on the provided 7879 * value and an optional stored value from the package settings. 7880 */ 7881 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7882 String cpuAbiOverride = null; 7883 7884 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7885 cpuAbiOverride = null; 7886 } else if (abiOverride != null) { 7887 cpuAbiOverride = abiOverride; 7888 } else if (settings != null) { 7889 cpuAbiOverride = settings.cpuAbiOverrideString; 7890 } 7891 7892 return cpuAbiOverride; 7893 } 7894 7895 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7896 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7897 throws PackageManagerException { 7898 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7899 // If the package has children and this is the first dive in the function 7900 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7901 // whether all packages (parent and children) would be successfully scanned 7902 // before the actual scan since scanning mutates internal state and we want 7903 // to atomically install the package and its children. 7904 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7905 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7906 scanFlags |= SCAN_CHECK_ONLY; 7907 } 7908 } else { 7909 scanFlags &= ~SCAN_CHECK_ONLY; 7910 } 7911 7912 final PackageParser.Package scannedPkg; 7913 try { 7914 // Scan the parent 7915 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7916 // Scan the children 7917 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7918 for (int i = 0; i < childCount; i++) { 7919 PackageParser.Package childPkg = pkg.childPackages.get(i); 7920 scanPackageLI(childPkg, policyFlags, 7921 scanFlags, currentTime, user); 7922 } 7923 } finally { 7924 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7925 } 7926 7927 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7928 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7929 } 7930 7931 return scannedPkg; 7932 } 7933 7934 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7935 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7936 boolean success = false; 7937 try { 7938 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7939 currentTime, user); 7940 success = true; 7941 return res; 7942 } finally { 7943 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7944 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7945 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7946 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7947 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7948 } 7949 } 7950 } 7951 7952 /** 7953 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7954 */ 7955 private static boolean apkHasCode(String fileName) { 7956 StrictJarFile jarFile = null; 7957 try { 7958 jarFile = new StrictJarFile(fileName, 7959 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7960 return jarFile.findEntry("classes.dex") != null; 7961 } catch (IOException ignore) { 7962 } finally { 7963 try { 7964 jarFile.close(); 7965 } catch (IOException ignore) {} 7966 } 7967 return false; 7968 } 7969 7970 /** 7971 * Enforces code policy for the package. This ensures that if an APK has 7972 * declared hasCode="true" in its manifest that the APK actually contains 7973 * code. 7974 * 7975 * @throws PackageManagerException If bytecode could not be found when it should exist 7976 */ 7977 private static void enforceCodePolicy(PackageParser.Package pkg) 7978 throws PackageManagerException { 7979 final boolean shouldHaveCode = 7980 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7981 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7982 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7983 "Package " + pkg.baseCodePath + " code is missing"); 7984 } 7985 7986 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7987 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7988 final boolean splitShouldHaveCode = 7989 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7990 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7991 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7992 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7993 } 7994 } 7995 } 7996 } 7997 7998 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7999 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8000 throws PackageManagerException { 8001 final File scanFile = new File(pkg.codePath); 8002 if (pkg.applicationInfo.getCodePath() == null || 8003 pkg.applicationInfo.getResourcePath() == null) { 8004 // Bail out. The resource and code paths haven't been set. 8005 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8006 "Code and resource paths haven't been set correctly"); 8007 } 8008 8009 // Apply policy 8010 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8011 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8012 if (pkg.applicationInfo.isDirectBootAware()) { 8013 // we're direct boot aware; set for all components 8014 for (PackageParser.Service s : pkg.services) { 8015 s.info.encryptionAware = s.info.directBootAware = true; 8016 } 8017 for (PackageParser.Provider p : pkg.providers) { 8018 p.info.encryptionAware = p.info.directBootAware = true; 8019 } 8020 for (PackageParser.Activity a : pkg.activities) { 8021 a.info.encryptionAware = a.info.directBootAware = true; 8022 } 8023 for (PackageParser.Activity r : pkg.receivers) { 8024 r.info.encryptionAware = r.info.directBootAware = true; 8025 } 8026 } 8027 } else { 8028 // Only allow system apps to be flagged as core apps. 8029 pkg.coreApp = false; 8030 // clear flags not applicable to regular apps 8031 pkg.applicationInfo.privateFlags &= 8032 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8033 pkg.applicationInfo.privateFlags &= 8034 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8035 } 8036 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8037 8038 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8039 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8040 } 8041 8042 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8043 enforceCodePolicy(pkg); 8044 } 8045 8046 if (mCustomResolverComponentName != null && 8047 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8048 setUpCustomResolverActivity(pkg); 8049 } 8050 8051 if (pkg.packageName.equals("android")) { 8052 synchronized (mPackages) { 8053 if (mAndroidApplication != null) { 8054 Slog.w(TAG, "*************************************************"); 8055 Slog.w(TAG, "Core android package being redefined. Skipping."); 8056 Slog.w(TAG, " file=" + scanFile); 8057 Slog.w(TAG, "*************************************************"); 8058 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8059 "Core android package being redefined. Skipping."); 8060 } 8061 8062 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8063 // Set up information for our fall-back user intent resolution activity. 8064 mPlatformPackage = pkg; 8065 pkg.mVersionCode = mSdkVersion; 8066 mAndroidApplication = pkg.applicationInfo; 8067 8068 if (!mResolverReplaced) { 8069 mResolveActivity.applicationInfo = mAndroidApplication; 8070 mResolveActivity.name = ResolverActivity.class.getName(); 8071 mResolveActivity.packageName = mAndroidApplication.packageName; 8072 mResolveActivity.processName = "system:ui"; 8073 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8074 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8075 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8076 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8077 mResolveActivity.exported = true; 8078 mResolveActivity.enabled = true; 8079 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8080 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8081 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8082 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8083 | ActivityInfo.CONFIG_ORIENTATION 8084 | ActivityInfo.CONFIG_KEYBOARD 8085 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8086 mResolveInfo.activityInfo = mResolveActivity; 8087 mResolveInfo.priority = 0; 8088 mResolveInfo.preferredOrder = 0; 8089 mResolveInfo.match = 0; 8090 mResolveComponentName = new ComponentName( 8091 mAndroidApplication.packageName, mResolveActivity.name); 8092 } 8093 } 8094 } 8095 } 8096 8097 if (DEBUG_PACKAGE_SCANNING) { 8098 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8099 Log.d(TAG, "Scanning package " + pkg.packageName); 8100 } 8101 8102 synchronized (mPackages) { 8103 if (mPackages.containsKey(pkg.packageName) 8104 || mSharedLibraries.containsKey(pkg.packageName)) { 8105 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8106 "Application package " + pkg.packageName 8107 + " already installed. Skipping duplicate."); 8108 } 8109 8110 // If we're only installing presumed-existing packages, require that the 8111 // scanned APK is both already known and at the path previously established 8112 // for it. Previously unknown packages we pick up normally, but if we have an 8113 // a priori expectation about this package's install presence, enforce it. 8114 // With a singular exception for new system packages. When an OTA contains 8115 // a new system package, we allow the codepath to change from a system location 8116 // to the user-installed location. If we don't allow this change, any newer, 8117 // user-installed version of the application will be ignored. 8118 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8119 if (mExpectingBetter.containsKey(pkg.packageName)) { 8120 logCriticalInfo(Log.WARN, 8121 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8122 } else { 8123 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8124 if (known != null) { 8125 if (DEBUG_PACKAGE_SCANNING) { 8126 Log.d(TAG, "Examining " + pkg.codePath 8127 + " and requiring known paths " + known.codePathString 8128 + " & " + known.resourcePathString); 8129 } 8130 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8131 || !pkg.applicationInfo.getResourcePath().equals( 8132 known.resourcePathString)) { 8133 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8134 "Application package " + pkg.packageName 8135 + " found at " + pkg.applicationInfo.getCodePath() 8136 + " but expected at " + known.codePathString 8137 + "; ignoring."); 8138 } 8139 } 8140 } 8141 } 8142 } 8143 8144 // Initialize package source and resource directories 8145 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8146 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8147 8148 SharedUserSetting suid = null; 8149 PackageSetting pkgSetting = null; 8150 8151 if (!isSystemApp(pkg)) { 8152 // Only system apps can use these features. 8153 pkg.mOriginalPackages = null; 8154 pkg.mRealPackage = null; 8155 pkg.mAdoptPermissions = null; 8156 } 8157 8158 // Getting the package setting may have a side-effect, so if we 8159 // are only checking if scan would succeed, stash a copy of the 8160 // old setting to restore at the end. 8161 PackageSetting nonMutatedPs = null; 8162 8163 // writer 8164 synchronized (mPackages) { 8165 if (pkg.mSharedUserId != null) { 8166 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8167 if (suid == null) { 8168 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8169 "Creating application package " + pkg.packageName 8170 + " for shared user failed"); 8171 } 8172 if (DEBUG_PACKAGE_SCANNING) { 8173 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8174 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8175 + "): packages=" + suid.packages); 8176 } 8177 } 8178 8179 // Check if we are renaming from an original package name. 8180 PackageSetting origPackage = null; 8181 String realName = null; 8182 if (pkg.mOriginalPackages != null) { 8183 // This package may need to be renamed to a previously 8184 // installed name. Let's check on that... 8185 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8186 if (pkg.mOriginalPackages.contains(renamed)) { 8187 // This package had originally been installed as the 8188 // original name, and we have already taken care of 8189 // transitioning to the new one. Just update the new 8190 // one to continue using the old name. 8191 realName = pkg.mRealPackage; 8192 if (!pkg.packageName.equals(renamed)) { 8193 // Callers into this function may have already taken 8194 // care of renaming the package; only do it here if 8195 // it is not already done. 8196 pkg.setPackageName(renamed); 8197 } 8198 8199 } else { 8200 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8201 if ((origPackage = mSettings.peekPackageLPr( 8202 pkg.mOriginalPackages.get(i))) != null) { 8203 // We do have the package already installed under its 8204 // original name... should we use it? 8205 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8206 // New package is not compatible with original. 8207 origPackage = null; 8208 continue; 8209 } else if (origPackage.sharedUser != null) { 8210 // Make sure uid is compatible between packages. 8211 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8212 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8213 + " to " + pkg.packageName + ": old uid " 8214 + origPackage.sharedUser.name 8215 + " differs from " + pkg.mSharedUserId); 8216 origPackage = null; 8217 continue; 8218 } 8219 // TODO: Add case when shared user id is added [b/28144775] 8220 } else { 8221 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8222 + pkg.packageName + " to old name " + origPackage.name); 8223 } 8224 break; 8225 } 8226 } 8227 } 8228 } 8229 8230 if (mTransferedPackages.contains(pkg.packageName)) { 8231 Slog.w(TAG, "Package " + pkg.packageName 8232 + " was transferred to another, but its .apk remains"); 8233 } 8234 8235 // See comments in nonMutatedPs declaration 8236 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8237 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8238 if (foundPs != null) { 8239 nonMutatedPs = new PackageSetting(foundPs); 8240 } 8241 } 8242 8243 // Just create the setting, don't add it yet. For already existing packages 8244 // the PkgSetting exists already and doesn't have to be created. 8245 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8246 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8247 pkg.applicationInfo.primaryCpuAbi, 8248 pkg.applicationInfo.secondaryCpuAbi, 8249 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8250 user, false); 8251 if (pkgSetting == null) { 8252 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8253 "Creating application package " + pkg.packageName + " failed"); 8254 } 8255 8256 if (pkgSetting.origPackage != null) { 8257 // If we are first transitioning from an original package, 8258 // fix up the new package's name now. We need to do this after 8259 // looking up the package under its new name, so getPackageLP 8260 // can take care of fiddling things correctly. 8261 pkg.setPackageName(origPackage.name); 8262 8263 // File a report about this. 8264 String msg = "New package " + pkgSetting.realName 8265 + " renamed to replace old package " + pkgSetting.name; 8266 reportSettingsProblem(Log.WARN, msg); 8267 8268 // Make a note of it. 8269 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8270 mTransferedPackages.add(origPackage.name); 8271 } 8272 8273 // No longer need to retain this. 8274 pkgSetting.origPackage = null; 8275 } 8276 8277 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8278 // Make a note of it. 8279 mTransferedPackages.add(pkg.packageName); 8280 } 8281 8282 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8283 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8284 } 8285 8286 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8287 // Check all shared libraries and map to their actual file path. 8288 // We only do this here for apps not on a system dir, because those 8289 // are the only ones that can fail an install due to this. We 8290 // will take care of the system apps by updating all of their 8291 // library paths after the scan is done. 8292 updateSharedLibrariesLPw(pkg, null); 8293 } 8294 8295 if (mFoundPolicyFile) { 8296 SELinuxMMAC.assignSeinfoValue(pkg); 8297 } 8298 8299 pkg.applicationInfo.uid = pkgSetting.appId; 8300 pkg.mExtras = pkgSetting; 8301 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8302 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8303 // We just determined the app is signed correctly, so bring 8304 // over the latest parsed certs. 8305 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8306 } else { 8307 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8308 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8309 "Package " + pkg.packageName + " upgrade keys do not match the " 8310 + "previously installed version"); 8311 } else { 8312 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8313 String msg = "System package " + pkg.packageName 8314 + " signature changed; retaining data."; 8315 reportSettingsProblem(Log.WARN, msg); 8316 } 8317 } 8318 } else { 8319 try { 8320 verifySignaturesLP(pkgSetting, pkg); 8321 // We just determined the app is signed correctly, so bring 8322 // over the latest parsed certs. 8323 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8324 } catch (PackageManagerException e) { 8325 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8326 throw e; 8327 } 8328 // The signature has changed, but this package is in the system 8329 // image... let's recover! 8330 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8331 // However... if this package is part of a shared user, but it 8332 // doesn't match the signature of the shared user, let's fail. 8333 // What this means is that you can't change the signatures 8334 // associated with an overall shared user, which doesn't seem all 8335 // that unreasonable. 8336 if (pkgSetting.sharedUser != null) { 8337 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8338 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8339 throw new PackageManagerException( 8340 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8341 "Signature mismatch for shared user: " 8342 + pkgSetting.sharedUser); 8343 } 8344 } 8345 // File a report about this. 8346 String msg = "System package " + pkg.packageName 8347 + " signature changed; retaining data."; 8348 reportSettingsProblem(Log.WARN, msg); 8349 } 8350 } 8351 // Verify that this new package doesn't have any content providers 8352 // that conflict with existing packages. Only do this if the 8353 // package isn't already installed, since we don't want to break 8354 // things that are installed. 8355 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8356 final int N = pkg.providers.size(); 8357 int i; 8358 for (i=0; i<N; i++) { 8359 PackageParser.Provider p = pkg.providers.get(i); 8360 if (p.info.authority != null) { 8361 String names[] = p.info.authority.split(";"); 8362 for (int j = 0; j < names.length; j++) { 8363 if (mProvidersByAuthority.containsKey(names[j])) { 8364 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8365 final String otherPackageName = 8366 ((other != null && other.getComponentName() != null) ? 8367 other.getComponentName().getPackageName() : "?"); 8368 throw new PackageManagerException( 8369 INSTALL_FAILED_CONFLICTING_PROVIDER, 8370 "Can't install because provider name " + names[j] 8371 + " (in package " + pkg.applicationInfo.packageName 8372 + ") is already used by " + otherPackageName); 8373 } 8374 } 8375 } 8376 } 8377 } 8378 8379 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8380 // This package wants to adopt ownership of permissions from 8381 // another package. 8382 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8383 final String origName = pkg.mAdoptPermissions.get(i); 8384 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8385 if (orig != null) { 8386 if (verifyPackageUpdateLPr(orig, pkg)) { 8387 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8388 + pkg.packageName); 8389 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8390 } 8391 } 8392 } 8393 } 8394 } 8395 8396 final String pkgName = pkg.packageName; 8397 8398 final long scanFileTime = scanFile.lastModified(); 8399 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8400 pkg.applicationInfo.processName = fixProcessName( 8401 pkg.applicationInfo.packageName, 8402 pkg.applicationInfo.processName, 8403 pkg.applicationInfo.uid); 8404 8405 if (pkg != mPlatformPackage) { 8406 // Get all of our default paths setup 8407 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8408 } 8409 8410 final String path = scanFile.getPath(); 8411 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8412 8413 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8414 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8415 8416 // Some system apps still use directory structure for native libraries 8417 // in which case we might end up not detecting abi solely based on apk 8418 // structure. Try to detect abi based on directory structure. 8419 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8420 pkg.applicationInfo.primaryCpuAbi == null) { 8421 setBundledAppAbisAndRoots(pkg, pkgSetting); 8422 setNativeLibraryPaths(pkg); 8423 } 8424 8425 } else { 8426 if ((scanFlags & SCAN_MOVE) != 0) { 8427 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8428 // but we already have this packages package info in the PackageSetting. We just 8429 // use that and derive the native library path based on the new codepath. 8430 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8431 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8432 } 8433 8434 // Set native library paths again. For moves, the path will be updated based on the 8435 // ABIs we've determined above. For non-moves, the path will be updated based on the 8436 // ABIs we determined during compilation, but the path will depend on the final 8437 // package path (after the rename away from the stage path). 8438 setNativeLibraryPaths(pkg); 8439 } 8440 8441 // This is a special case for the "system" package, where the ABI is 8442 // dictated by the zygote configuration (and init.rc). We should keep track 8443 // of this ABI so that we can deal with "normal" applications that run under 8444 // the same UID correctly. 8445 if (mPlatformPackage == pkg) { 8446 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8447 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8448 } 8449 8450 // If there's a mismatch between the abi-override in the package setting 8451 // and the abiOverride specified for the install. Warn about this because we 8452 // would've already compiled the app without taking the package setting into 8453 // account. 8454 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8455 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8456 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8457 " for package " + pkg.packageName); 8458 } 8459 } 8460 8461 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8462 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8463 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8464 8465 // Copy the derived override back to the parsed package, so that we can 8466 // update the package settings accordingly. 8467 pkg.cpuAbiOverride = cpuAbiOverride; 8468 8469 if (DEBUG_ABI_SELECTION) { 8470 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8471 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8472 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8473 } 8474 8475 // Push the derived path down into PackageSettings so we know what to 8476 // clean up at uninstall time. 8477 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8478 8479 if (DEBUG_ABI_SELECTION) { 8480 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8481 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8482 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8483 } 8484 8485 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8486 // We don't do this here during boot because we can do it all 8487 // at once after scanning all existing packages. 8488 // 8489 // We also do this *before* we perform dexopt on this package, so that 8490 // we can avoid redundant dexopts, and also to make sure we've got the 8491 // code and package path correct. 8492 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8493 pkg, true /* boot complete */); 8494 } 8495 8496 if (mFactoryTest && pkg.requestedPermissions.contains( 8497 android.Manifest.permission.FACTORY_TEST)) { 8498 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8499 } 8500 8501 ArrayList<PackageParser.Package> clientLibPkgs = null; 8502 8503 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8504 if (nonMutatedPs != null) { 8505 synchronized (mPackages) { 8506 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8507 } 8508 } 8509 return pkg; 8510 } 8511 8512 // Only privileged apps and updated privileged apps can add child packages. 8513 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8514 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8515 throw new PackageManagerException("Only privileged apps and updated " 8516 + "privileged apps can add child packages. Ignoring package " 8517 + pkg.packageName); 8518 } 8519 final int childCount = pkg.childPackages.size(); 8520 for (int i = 0; i < childCount; i++) { 8521 PackageParser.Package childPkg = pkg.childPackages.get(i); 8522 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8523 childPkg.packageName)) { 8524 throw new PackageManagerException("Cannot override a child package of " 8525 + "another disabled system app. Ignoring package " + pkg.packageName); 8526 } 8527 } 8528 } 8529 8530 // writer 8531 synchronized (mPackages) { 8532 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8533 // Only system apps can add new shared libraries. 8534 if (pkg.libraryNames != null) { 8535 for (int i=0; i<pkg.libraryNames.size(); i++) { 8536 String name = pkg.libraryNames.get(i); 8537 boolean allowed = false; 8538 if (pkg.isUpdatedSystemApp()) { 8539 // New library entries can only be added through the 8540 // system image. This is important to get rid of a lot 8541 // of nasty edge cases: for example if we allowed a non- 8542 // system update of the app to add a library, then uninstalling 8543 // the update would make the library go away, and assumptions 8544 // we made such as through app install filtering would now 8545 // have allowed apps on the device which aren't compatible 8546 // with it. Better to just have the restriction here, be 8547 // conservative, and create many fewer cases that can negatively 8548 // impact the user experience. 8549 final PackageSetting sysPs = mSettings 8550 .getDisabledSystemPkgLPr(pkg.packageName); 8551 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8552 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8553 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8554 allowed = true; 8555 break; 8556 } 8557 } 8558 } 8559 } else { 8560 allowed = true; 8561 } 8562 if (allowed) { 8563 if (!mSharedLibraries.containsKey(name)) { 8564 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8565 } else if (!name.equals(pkg.packageName)) { 8566 Slog.w(TAG, "Package " + pkg.packageName + " library " 8567 + name + " already exists; skipping"); 8568 } 8569 } else { 8570 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8571 + name + " that is not declared on system image; skipping"); 8572 } 8573 } 8574 if ((scanFlags & SCAN_BOOTING) == 0) { 8575 // If we are not booting, we need to update any applications 8576 // that are clients of our shared library. If we are booting, 8577 // this will all be done once the scan is complete. 8578 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8579 } 8580 } 8581 } 8582 } 8583 8584 if ((scanFlags & SCAN_BOOTING) != 0) { 8585 // No apps can run during boot scan, so they don't need to be frozen 8586 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8587 // Caller asked to not kill app, so it's probably not frozen 8588 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8589 // Caller asked us to ignore frozen check for some reason; they 8590 // probably didn't know the package name 8591 } else { 8592 // We're doing major surgery on this package, so it better be frozen 8593 // right now to keep it from launching 8594 checkPackageFrozen(pkgName); 8595 } 8596 8597 // Also need to kill any apps that are dependent on the library. 8598 if (clientLibPkgs != null) { 8599 for (int i=0; i<clientLibPkgs.size(); i++) { 8600 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8601 killApplication(clientPkg.applicationInfo.packageName, 8602 clientPkg.applicationInfo.uid, "update lib"); 8603 } 8604 } 8605 8606 // Make sure we're not adding any bogus keyset info 8607 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8608 ksms.assertScannedPackageValid(pkg); 8609 8610 // writer 8611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8612 8613 boolean createIdmapFailed = false; 8614 synchronized (mPackages) { 8615 // We don't expect installation to fail beyond this point 8616 8617 if (pkgSetting.pkg != null) { 8618 // Note that |user| might be null during the initial boot scan. If a codePath 8619 // for an app has changed during a boot scan, it's due to an app update that's 8620 // part of the system partition and marker changes must be applied to all users. 8621 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8622 (user != null) ? user : UserHandle.ALL); 8623 } 8624 8625 // Add the new setting to mSettings 8626 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8627 // Add the new setting to mPackages 8628 mPackages.put(pkg.applicationInfo.packageName, pkg); 8629 // Make sure we don't accidentally delete its data. 8630 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8631 while (iter.hasNext()) { 8632 PackageCleanItem item = iter.next(); 8633 if (pkgName.equals(item.packageName)) { 8634 iter.remove(); 8635 } 8636 } 8637 8638 // Take care of first install / last update times. 8639 if (currentTime != 0) { 8640 if (pkgSetting.firstInstallTime == 0) { 8641 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8642 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8643 pkgSetting.lastUpdateTime = currentTime; 8644 } 8645 } else if (pkgSetting.firstInstallTime == 0) { 8646 // We need *something*. Take time time stamp of the file. 8647 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8648 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8649 if (scanFileTime != pkgSetting.timeStamp) { 8650 // A package on the system image has changed; consider this 8651 // to be an update. 8652 pkgSetting.lastUpdateTime = scanFileTime; 8653 } 8654 } 8655 8656 // Add the package's KeySets to the global KeySetManagerService 8657 ksms.addScannedPackageLPw(pkg); 8658 8659 int N = pkg.providers.size(); 8660 StringBuilder r = null; 8661 int i; 8662 for (i=0; i<N; i++) { 8663 PackageParser.Provider p = pkg.providers.get(i); 8664 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8665 p.info.processName, pkg.applicationInfo.uid); 8666 mProviders.addProvider(p); 8667 p.syncable = p.info.isSyncable; 8668 if (p.info.authority != null) { 8669 String names[] = p.info.authority.split(";"); 8670 p.info.authority = null; 8671 for (int j = 0; j < names.length; j++) { 8672 if (j == 1 && p.syncable) { 8673 // We only want the first authority for a provider to possibly be 8674 // syncable, so if we already added this provider using a different 8675 // authority clear the syncable flag. We copy the provider before 8676 // changing it because the mProviders object contains a reference 8677 // to a provider that we don't want to change. 8678 // Only do this for the second authority since the resulting provider 8679 // object can be the same for all future authorities for this provider. 8680 p = new PackageParser.Provider(p); 8681 p.syncable = false; 8682 } 8683 if (!mProvidersByAuthority.containsKey(names[j])) { 8684 mProvidersByAuthority.put(names[j], p); 8685 if (p.info.authority == null) { 8686 p.info.authority = names[j]; 8687 } else { 8688 p.info.authority = p.info.authority + ";" + names[j]; 8689 } 8690 if (DEBUG_PACKAGE_SCANNING) { 8691 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8692 Log.d(TAG, "Registered content provider: " + names[j] 8693 + ", className = " + p.info.name + ", isSyncable = " 8694 + p.info.isSyncable); 8695 } 8696 } else { 8697 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8698 Slog.w(TAG, "Skipping provider name " + names[j] + 8699 " (in package " + pkg.applicationInfo.packageName + 8700 "): name already used by " 8701 + ((other != null && other.getComponentName() != null) 8702 ? other.getComponentName().getPackageName() : "?")); 8703 } 8704 } 8705 } 8706 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8707 if (r == null) { 8708 r = new StringBuilder(256); 8709 } else { 8710 r.append(' '); 8711 } 8712 r.append(p.info.name); 8713 } 8714 } 8715 if (r != null) { 8716 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8717 } 8718 8719 N = pkg.services.size(); 8720 r = null; 8721 for (i=0; i<N; i++) { 8722 PackageParser.Service s = pkg.services.get(i); 8723 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8724 s.info.processName, pkg.applicationInfo.uid); 8725 mServices.addService(s); 8726 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8727 if (r == null) { 8728 r = new StringBuilder(256); 8729 } else { 8730 r.append(' '); 8731 } 8732 r.append(s.info.name); 8733 } 8734 } 8735 if (r != null) { 8736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8737 } 8738 8739 N = pkg.receivers.size(); 8740 r = null; 8741 for (i=0; i<N; i++) { 8742 PackageParser.Activity a = pkg.receivers.get(i); 8743 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8744 a.info.processName, pkg.applicationInfo.uid); 8745 mReceivers.addActivity(a, "receiver"); 8746 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8747 if (r == null) { 8748 r = new StringBuilder(256); 8749 } else { 8750 r.append(' '); 8751 } 8752 r.append(a.info.name); 8753 } 8754 } 8755 if (r != null) { 8756 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8757 } 8758 8759 N = pkg.activities.size(); 8760 r = null; 8761 for (i=0; i<N; i++) { 8762 PackageParser.Activity a = pkg.activities.get(i); 8763 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8764 a.info.processName, pkg.applicationInfo.uid); 8765 mActivities.addActivity(a, "activity"); 8766 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8767 if (r == null) { 8768 r = new StringBuilder(256); 8769 } else { 8770 r.append(' '); 8771 } 8772 r.append(a.info.name); 8773 } 8774 } 8775 if (r != null) { 8776 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8777 } 8778 8779 N = pkg.permissionGroups.size(); 8780 r = null; 8781 for (i=0; i<N; i++) { 8782 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8783 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8784 if (cur == null) { 8785 mPermissionGroups.put(pg.info.name, pg); 8786 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8787 if (r == null) { 8788 r = new StringBuilder(256); 8789 } else { 8790 r.append(' '); 8791 } 8792 r.append(pg.info.name); 8793 } 8794 } else { 8795 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8796 + pg.info.packageName + " ignored: original from " 8797 + cur.info.packageName); 8798 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8799 if (r == null) { 8800 r = new StringBuilder(256); 8801 } else { 8802 r.append(' '); 8803 } 8804 r.append("DUP:"); 8805 r.append(pg.info.name); 8806 } 8807 } 8808 } 8809 if (r != null) { 8810 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8811 } 8812 8813 N = pkg.permissions.size(); 8814 r = null; 8815 for (i=0; i<N; i++) { 8816 PackageParser.Permission p = pkg.permissions.get(i); 8817 8818 // Assume by default that we did not install this permission into the system. 8819 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8820 8821 // Now that permission groups have a special meaning, we ignore permission 8822 // groups for legacy apps to prevent unexpected behavior. In particular, 8823 // permissions for one app being granted to someone just becase they happen 8824 // to be in a group defined by another app (before this had no implications). 8825 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8826 p.group = mPermissionGroups.get(p.info.group); 8827 // Warn for a permission in an unknown group. 8828 if (p.info.group != null && p.group == null) { 8829 Slog.w(TAG, "Permission " + p.info.name + " from package " 8830 + p.info.packageName + " in an unknown group " + p.info.group); 8831 } 8832 } 8833 8834 ArrayMap<String, BasePermission> permissionMap = 8835 p.tree ? mSettings.mPermissionTrees 8836 : mSettings.mPermissions; 8837 BasePermission bp = permissionMap.get(p.info.name); 8838 8839 // Allow system apps to redefine non-system permissions 8840 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8841 final boolean currentOwnerIsSystem = (bp.perm != null 8842 && isSystemApp(bp.perm.owner)); 8843 if (isSystemApp(p.owner)) { 8844 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8845 // It's a built-in permission and no owner, take ownership now 8846 bp.packageSetting = pkgSetting; 8847 bp.perm = p; 8848 bp.uid = pkg.applicationInfo.uid; 8849 bp.sourcePackage = p.info.packageName; 8850 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8851 } else if (!currentOwnerIsSystem) { 8852 String msg = "New decl " + p.owner + " of permission " 8853 + p.info.name + " is system; overriding " + bp.sourcePackage; 8854 reportSettingsProblem(Log.WARN, msg); 8855 bp = null; 8856 } 8857 } 8858 } 8859 8860 if (bp == null) { 8861 bp = new BasePermission(p.info.name, p.info.packageName, 8862 BasePermission.TYPE_NORMAL); 8863 permissionMap.put(p.info.name, bp); 8864 } 8865 8866 if (bp.perm == null) { 8867 if (bp.sourcePackage == null 8868 || bp.sourcePackage.equals(p.info.packageName)) { 8869 BasePermission tree = findPermissionTreeLP(p.info.name); 8870 if (tree == null 8871 || tree.sourcePackage.equals(p.info.packageName)) { 8872 bp.packageSetting = pkgSetting; 8873 bp.perm = p; 8874 bp.uid = pkg.applicationInfo.uid; 8875 bp.sourcePackage = p.info.packageName; 8876 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8877 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8878 if (r == null) { 8879 r = new StringBuilder(256); 8880 } else { 8881 r.append(' '); 8882 } 8883 r.append(p.info.name); 8884 } 8885 } else { 8886 Slog.w(TAG, "Permission " + p.info.name + " from package " 8887 + p.info.packageName + " ignored: base tree " 8888 + tree.name + " is from package " 8889 + tree.sourcePackage); 8890 } 8891 } else { 8892 Slog.w(TAG, "Permission " + p.info.name + " from package " 8893 + p.info.packageName + " ignored: original from " 8894 + bp.sourcePackage); 8895 } 8896 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8897 if (r == null) { 8898 r = new StringBuilder(256); 8899 } else { 8900 r.append(' '); 8901 } 8902 r.append("DUP:"); 8903 r.append(p.info.name); 8904 } 8905 if (bp.perm == p) { 8906 bp.protectionLevel = p.info.protectionLevel; 8907 } 8908 } 8909 8910 if (r != null) { 8911 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8912 } 8913 8914 N = pkg.instrumentation.size(); 8915 r = null; 8916 for (i=0; i<N; i++) { 8917 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8918 a.info.packageName = pkg.applicationInfo.packageName; 8919 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8920 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8921 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8922 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8923 a.info.dataDir = pkg.applicationInfo.dataDir; 8924 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8925 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8926 8927 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8928 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8929 mInstrumentation.put(a.getComponentName(), a); 8930 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8931 if (r == null) { 8932 r = new StringBuilder(256); 8933 } else { 8934 r.append(' '); 8935 } 8936 r.append(a.info.name); 8937 } 8938 } 8939 if (r != null) { 8940 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8941 } 8942 8943 if (pkg.protectedBroadcasts != null) { 8944 N = pkg.protectedBroadcasts.size(); 8945 for (i=0; i<N; i++) { 8946 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8947 } 8948 } 8949 8950 pkgSetting.setTimeStamp(scanFileTime); 8951 8952 // Create idmap files for pairs of (packages, overlay packages). 8953 // Note: "android", ie framework-res.apk, is handled by native layers. 8954 if (pkg.mOverlayTarget != null) { 8955 // This is an overlay package. 8956 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8957 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8958 mOverlays.put(pkg.mOverlayTarget, 8959 new ArrayMap<String, PackageParser.Package>()); 8960 } 8961 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8962 map.put(pkg.packageName, pkg); 8963 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8964 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8965 createIdmapFailed = true; 8966 } 8967 } 8968 } else if (mOverlays.containsKey(pkg.packageName) && 8969 !pkg.packageName.equals("android")) { 8970 // This is a regular package, with one or more known overlay packages. 8971 createIdmapsForPackageLI(pkg); 8972 } 8973 } 8974 8975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8976 8977 if (createIdmapFailed) { 8978 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8979 "scanPackageLI failed to createIdmap"); 8980 } 8981 return pkg; 8982 } 8983 8984 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8985 PackageParser.Package update, UserHandle user) { 8986 if (existing.applicationInfo == null || update.applicationInfo == null) { 8987 // This isn't due to an app installation. 8988 return; 8989 } 8990 8991 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8992 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8993 8994 // The codePath hasn't changed, so there's nothing for us to do. 8995 if (Objects.equals(oldCodePath, newCodePath)) { 8996 return; 8997 } 8998 8999 File canonicalNewCodePath; 9000 try { 9001 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9002 } catch (IOException e) { 9003 Slog.w(TAG, "Failed to get canonical path.", e); 9004 return; 9005 } 9006 9007 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9008 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9009 // that the last component of the path (i.e, the name) doesn't need canonicalization 9010 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9011 // but may change in the future. Hopefully this function won't exist at that point. 9012 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9013 oldCodePath.getName()); 9014 9015 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9016 // with "@". 9017 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9018 if (!oldMarkerPrefix.endsWith("@")) { 9019 oldMarkerPrefix += "@"; 9020 } 9021 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9022 if (!newMarkerPrefix.endsWith("@")) { 9023 newMarkerPrefix += "@"; 9024 } 9025 9026 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9027 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9028 for (String updatedPath : updatedPaths) { 9029 String updatedPathName = new File(updatedPath).getName(); 9030 markerSuffixes.add(updatedPathName.replace('/', '@')); 9031 } 9032 9033 for (int userId : resolveUserIds(user.getIdentifier())) { 9034 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9035 9036 for (String markerSuffix : markerSuffixes) { 9037 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9038 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9039 if (oldForeignUseMark.exists()) { 9040 try { 9041 Os.rename(oldForeignUseMark.getAbsolutePath(), 9042 newForeignUseMark.getAbsolutePath()); 9043 } catch (ErrnoException e) { 9044 Slog.w(TAG, "Failed to rename foreign use marker", e); 9045 oldForeignUseMark.delete(); 9046 } 9047 } 9048 } 9049 } 9050 } 9051 9052 /** 9053 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9054 * is derived purely on the basis of the contents of {@code scanFile} and 9055 * {@code cpuAbiOverride}. 9056 * 9057 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9058 */ 9059 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9060 String cpuAbiOverride, boolean extractLibs) 9061 throws PackageManagerException { 9062 // TODO: We can probably be smarter about this stuff. For installed apps, 9063 // we can calculate this information at install time once and for all. For 9064 // system apps, we can probably assume that this information doesn't change 9065 // after the first boot scan. As things stand, we do lots of unnecessary work. 9066 9067 // Give ourselves some initial paths; we'll come back for another 9068 // pass once we've determined ABI below. 9069 setNativeLibraryPaths(pkg); 9070 9071 // We would never need to extract libs for forward-locked and external packages, 9072 // since the container service will do it for us. We shouldn't attempt to 9073 // extract libs from system app when it was not updated. 9074 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9075 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9076 extractLibs = false; 9077 } 9078 9079 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9080 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9081 9082 NativeLibraryHelper.Handle handle = null; 9083 try { 9084 handle = NativeLibraryHelper.Handle.create(pkg); 9085 // TODO(multiArch): This can be null for apps that didn't go through the 9086 // usual installation process. We can calculate it again, like we 9087 // do during install time. 9088 // 9089 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9090 // unnecessary. 9091 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9092 9093 // Null out the abis so that they can be recalculated. 9094 pkg.applicationInfo.primaryCpuAbi = null; 9095 pkg.applicationInfo.secondaryCpuAbi = null; 9096 if (isMultiArch(pkg.applicationInfo)) { 9097 // Warn if we've set an abiOverride for multi-lib packages.. 9098 // By definition, we need to copy both 32 and 64 bit libraries for 9099 // such packages. 9100 if (pkg.cpuAbiOverride != null 9101 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9102 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9103 } 9104 9105 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9106 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9107 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9108 if (extractLibs) { 9109 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9110 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9111 useIsaSpecificSubdirs); 9112 } else { 9113 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9114 } 9115 } 9116 9117 maybeThrowExceptionForMultiArchCopy( 9118 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9119 9120 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9121 if (extractLibs) { 9122 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9123 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9124 useIsaSpecificSubdirs); 9125 } else { 9126 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9127 } 9128 } 9129 9130 maybeThrowExceptionForMultiArchCopy( 9131 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9132 9133 if (abi64 >= 0) { 9134 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9135 } 9136 9137 if (abi32 >= 0) { 9138 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9139 if (abi64 >= 0) { 9140 if (pkg.use32bitAbi) { 9141 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9142 pkg.applicationInfo.primaryCpuAbi = abi; 9143 } else { 9144 pkg.applicationInfo.secondaryCpuAbi = abi; 9145 } 9146 } else { 9147 pkg.applicationInfo.primaryCpuAbi = abi; 9148 } 9149 } 9150 9151 } else { 9152 String[] abiList = (cpuAbiOverride != null) ? 9153 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9154 9155 // Enable gross and lame hacks for apps that are built with old 9156 // SDK tools. We must scan their APKs for renderscript bitcode and 9157 // not launch them if it's present. Don't bother checking on devices 9158 // that don't have 64 bit support. 9159 boolean needsRenderScriptOverride = false; 9160 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9161 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9162 abiList = Build.SUPPORTED_32_BIT_ABIS; 9163 needsRenderScriptOverride = true; 9164 } 9165 9166 final int copyRet; 9167 if (extractLibs) { 9168 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9169 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9170 } else { 9171 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9172 } 9173 9174 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9175 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9176 "Error unpackaging native libs for app, errorCode=" + copyRet); 9177 } 9178 9179 if (copyRet >= 0) { 9180 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9181 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9182 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9183 } else if (needsRenderScriptOverride) { 9184 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9185 } 9186 } 9187 } catch (IOException ioe) { 9188 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9189 } finally { 9190 IoUtils.closeQuietly(handle); 9191 } 9192 9193 // Now that we've calculated the ABIs and determined if it's an internal app, 9194 // we will go ahead and populate the nativeLibraryPath. 9195 setNativeLibraryPaths(pkg); 9196 } 9197 9198 /** 9199 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9200 * i.e, so that all packages can be run inside a single process if required. 9201 * 9202 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9203 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9204 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9205 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9206 * updating a package that belongs to a shared user. 9207 * 9208 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9209 * adds unnecessary complexity. 9210 */ 9211 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9212 PackageParser.Package scannedPackage, boolean bootComplete) { 9213 String requiredInstructionSet = null; 9214 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9215 requiredInstructionSet = VMRuntime.getInstructionSet( 9216 scannedPackage.applicationInfo.primaryCpuAbi); 9217 } 9218 9219 PackageSetting requirer = null; 9220 for (PackageSetting ps : packagesForUser) { 9221 // If packagesForUser contains scannedPackage, we skip it. This will happen 9222 // when scannedPackage is an update of an existing package. Without this check, 9223 // we will never be able to change the ABI of any package belonging to a shared 9224 // user, even if it's compatible with other packages. 9225 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9226 if (ps.primaryCpuAbiString == null) { 9227 continue; 9228 } 9229 9230 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9231 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9232 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9233 // this but there's not much we can do. 9234 String errorMessage = "Instruction set mismatch, " 9235 + ((requirer == null) ? "[caller]" : requirer) 9236 + " requires " + requiredInstructionSet + " whereas " + ps 9237 + " requires " + instructionSet; 9238 Slog.w(TAG, errorMessage); 9239 } 9240 9241 if (requiredInstructionSet == null) { 9242 requiredInstructionSet = instructionSet; 9243 requirer = ps; 9244 } 9245 } 9246 } 9247 9248 if (requiredInstructionSet != null) { 9249 String adjustedAbi; 9250 if (requirer != null) { 9251 // requirer != null implies that either scannedPackage was null or that scannedPackage 9252 // did not require an ABI, in which case we have to adjust scannedPackage to match 9253 // the ABI of the set (which is the same as requirer's ABI) 9254 adjustedAbi = requirer.primaryCpuAbiString; 9255 if (scannedPackage != null) { 9256 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9257 } 9258 } else { 9259 // requirer == null implies that we're updating all ABIs in the set to 9260 // match scannedPackage. 9261 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9262 } 9263 9264 for (PackageSetting ps : packagesForUser) { 9265 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9266 if (ps.primaryCpuAbiString != null) { 9267 continue; 9268 } 9269 9270 ps.primaryCpuAbiString = adjustedAbi; 9271 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9272 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9273 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9274 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9275 + " (requirer=" 9276 + (requirer == null ? "null" : requirer.pkg.packageName) 9277 + ", scannedPackage=" 9278 + (scannedPackage != null ? scannedPackage.packageName : "null") 9279 + ")"); 9280 try { 9281 mInstaller.rmdex(ps.codePathString, 9282 getDexCodeInstructionSet(getPreferredInstructionSet())); 9283 } catch (InstallerException ignored) { 9284 } 9285 } 9286 } 9287 } 9288 } 9289 } 9290 9291 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9292 synchronized (mPackages) { 9293 mResolverReplaced = true; 9294 // Set up information for custom user intent resolution activity. 9295 mResolveActivity.applicationInfo = pkg.applicationInfo; 9296 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9297 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9298 mResolveActivity.processName = pkg.applicationInfo.packageName; 9299 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9300 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9301 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9302 mResolveActivity.theme = 0; 9303 mResolveActivity.exported = true; 9304 mResolveActivity.enabled = true; 9305 mResolveInfo.activityInfo = mResolveActivity; 9306 mResolveInfo.priority = 0; 9307 mResolveInfo.preferredOrder = 0; 9308 mResolveInfo.match = 0; 9309 mResolveComponentName = mCustomResolverComponentName; 9310 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9311 mResolveComponentName); 9312 } 9313 } 9314 9315 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9316 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9317 9318 // Set up information for ephemeral installer activity 9319 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9320 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9321 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9322 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9323 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9324 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9325 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9326 mEphemeralInstallerActivity.theme = 0; 9327 mEphemeralInstallerActivity.exported = true; 9328 mEphemeralInstallerActivity.enabled = true; 9329 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9330 mEphemeralInstallerInfo.priority = 0; 9331 mEphemeralInstallerInfo.preferredOrder = 0; 9332 mEphemeralInstallerInfo.match = 0; 9333 9334 if (DEBUG_EPHEMERAL) { 9335 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9336 } 9337 } 9338 9339 private static String calculateBundledApkRoot(final String codePathString) { 9340 final File codePath = new File(codePathString); 9341 final File codeRoot; 9342 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9343 codeRoot = Environment.getRootDirectory(); 9344 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9345 codeRoot = Environment.getOemDirectory(); 9346 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9347 codeRoot = Environment.getVendorDirectory(); 9348 } else { 9349 // Unrecognized code path; take its top real segment as the apk root: 9350 // e.g. /something/app/blah.apk => /something 9351 try { 9352 File f = codePath.getCanonicalFile(); 9353 File parent = f.getParentFile(); // non-null because codePath is a file 9354 File tmp; 9355 while ((tmp = parent.getParentFile()) != null) { 9356 f = parent; 9357 parent = tmp; 9358 } 9359 codeRoot = f; 9360 Slog.w(TAG, "Unrecognized code path " 9361 + codePath + " - using " + codeRoot); 9362 } catch (IOException e) { 9363 // Can't canonicalize the code path -- shenanigans? 9364 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9365 return Environment.getRootDirectory().getPath(); 9366 } 9367 } 9368 return codeRoot.getPath(); 9369 } 9370 9371 /** 9372 * Derive and set the location of native libraries for the given package, 9373 * which varies depending on where and how the package was installed. 9374 */ 9375 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9376 final ApplicationInfo info = pkg.applicationInfo; 9377 final String codePath = pkg.codePath; 9378 final File codeFile = new File(codePath); 9379 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9380 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9381 9382 info.nativeLibraryRootDir = null; 9383 info.nativeLibraryRootRequiresIsa = false; 9384 info.nativeLibraryDir = null; 9385 info.secondaryNativeLibraryDir = null; 9386 9387 if (isApkFile(codeFile)) { 9388 // Monolithic install 9389 if (bundledApp) { 9390 // If "/system/lib64/apkname" exists, assume that is the per-package 9391 // native library directory to use; otherwise use "/system/lib/apkname". 9392 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9393 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9394 getPrimaryInstructionSet(info)); 9395 9396 // This is a bundled system app so choose the path based on the ABI. 9397 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9398 // is just the default path. 9399 final String apkName = deriveCodePathName(codePath); 9400 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9401 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9402 apkName).getAbsolutePath(); 9403 9404 if (info.secondaryCpuAbi != null) { 9405 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9406 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9407 secondaryLibDir, apkName).getAbsolutePath(); 9408 } 9409 } else if (asecApp) { 9410 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9411 .getAbsolutePath(); 9412 } else { 9413 final String apkName = deriveCodePathName(codePath); 9414 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9415 .getAbsolutePath(); 9416 } 9417 9418 info.nativeLibraryRootRequiresIsa = false; 9419 info.nativeLibraryDir = info.nativeLibraryRootDir; 9420 } else { 9421 // Cluster install 9422 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9423 info.nativeLibraryRootRequiresIsa = true; 9424 9425 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9426 getPrimaryInstructionSet(info)).getAbsolutePath(); 9427 9428 if (info.secondaryCpuAbi != null) { 9429 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9430 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9431 } 9432 } 9433 } 9434 9435 /** 9436 * Calculate the abis and roots for a bundled app. These can uniquely 9437 * be determined from the contents of the system partition, i.e whether 9438 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9439 * of this information, and instead assume that the system was built 9440 * sensibly. 9441 */ 9442 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9443 PackageSetting pkgSetting) { 9444 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9445 9446 // If "/system/lib64/apkname" exists, assume that is the per-package 9447 // native library directory to use; otherwise use "/system/lib/apkname". 9448 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9449 setBundledAppAbi(pkg, apkRoot, apkName); 9450 // pkgSetting might be null during rescan following uninstall of updates 9451 // to a bundled app, so accommodate that possibility. The settings in 9452 // that case will be established later from the parsed package. 9453 // 9454 // If the settings aren't null, sync them up with what we've just derived. 9455 // note that apkRoot isn't stored in the package settings. 9456 if (pkgSetting != null) { 9457 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9458 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9459 } 9460 } 9461 9462 /** 9463 * Deduces the ABI of a bundled app and sets the relevant fields on the 9464 * parsed pkg object. 9465 * 9466 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9467 * under which system libraries are installed. 9468 * @param apkName the name of the installed package. 9469 */ 9470 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9471 final File codeFile = new File(pkg.codePath); 9472 9473 final boolean has64BitLibs; 9474 final boolean has32BitLibs; 9475 if (isApkFile(codeFile)) { 9476 // Monolithic install 9477 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9478 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9479 } else { 9480 // Cluster install 9481 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9482 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9483 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9484 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9485 has64BitLibs = (new File(rootDir, isa)).exists(); 9486 } else { 9487 has64BitLibs = false; 9488 } 9489 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9490 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9491 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9492 has32BitLibs = (new File(rootDir, isa)).exists(); 9493 } else { 9494 has32BitLibs = false; 9495 } 9496 } 9497 9498 if (has64BitLibs && !has32BitLibs) { 9499 // The package has 64 bit libs, but not 32 bit libs. Its primary 9500 // ABI should be 64 bit. We can safely assume here that the bundled 9501 // native libraries correspond to the most preferred ABI in the list. 9502 9503 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9504 pkg.applicationInfo.secondaryCpuAbi = null; 9505 } else if (has32BitLibs && !has64BitLibs) { 9506 // The package has 32 bit libs but not 64 bit libs. Its primary 9507 // ABI should be 32 bit. 9508 9509 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9510 pkg.applicationInfo.secondaryCpuAbi = null; 9511 } else if (has32BitLibs && has64BitLibs) { 9512 // The application has both 64 and 32 bit bundled libraries. We check 9513 // here that the app declares multiArch support, and warn if it doesn't. 9514 // 9515 // We will be lenient here and record both ABIs. The primary will be the 9516 // ABI that's higher on the list, i.e, a device that's configured to prefer 9517 // 64 bit apps will see a 64 bit primary ABI, 9518 9519 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9520 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9521 } 9522 9523 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9524 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9525 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9526 } else { 9527 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9528 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9529 } 9530 } else { 9531 pkg.applicationInfo.primaryCpuAbi = null; 9532 pkg.applicationInfo.secondaryCpuAbi = null; 9533 } 9534 } 9535 9536 private void killApplication(String pkgName, int appId, String reason) { 9537 // Request the ActivityManager to kill the process(only for existing packages) 9538 // so that we do not end up in a confused state while the user is still using the older 9539 // version of the application while the new one gets installed. 9540 final long token = Binder.clearCallingIdentity(); 9541 try { 9542 IActivityManager am = ActivityManagerNative.getDefault(); 9543 if (am != null) { 9544 try { 9545 am.killApplicationWithAppId(pkgName, appId, reason); 9546 } catch (RemoteException e) { 9547 } 9548 } 9549 } finally { 9550 Binder.restoreCallingIdentity(token); 9551 } 9552 } 9553 9554 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9555 // Remove the parent package setting 9556 PackageSetting ps = (PackageSetting) pkg.mExtras; 9557 if (ps != null) { 9558 removePackageLI(ps, chatty); 9559 } 9560 // Remove the child package setting 9561 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9562 for (int i = 0; i < childCount; i++) { 9563 PackageParser.Package childPkg = pkg.childPackages.get(i); 9564 ps = (PackageSetting) childPkg.mExtras; 9565 if (ps != null) { 9566 removePackageLI(ps, chatty); 9567 } 9568 } 9569 } 9570 9571 void removePackageLI(PackageSetting ps, boolean chatty) { 9572 if (DEBUG_INSTALL) { 9573 if (chatty) 9574 Log.d(TAG, "Removing package " + ps.name); 9575 } 9576 9577 // writer 9578 synchronized (mPackages) { 9579 mPackages.remove(ps.name); 9580 final PackageParser.Package pkg = ps.pkg; 9581 if (pkg != null) { 9582 cleanPackageDataStructuresLILPw(pkg, chatty); 9583 } 9584 } 9585 } 9586 9587 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9588 if (DEBUG_INSTALL) { 9589 if (chatty) 9590 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9591 } 9592 9593 // writer 9594 synchronized (mPackages) { 9595 // Remove the parent package 9596 mPackages.remove(pkg.applicationInfo.packageName); 9597 cleanPackageDataStructuresLILPw(pkg, chatty); 9598 9599 // Remove the child packages 9600 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9601 for (int i = 0; i < childCount; i++) { 9602 PackageParser.Package childPkg = pkg.childPackages.get(i); 9603 mPackages.remove(childPkg.applicationInfo.packageName); 9604 cleanPackageDataStructuresLILPw(childPkg, chatty); 9605 } 9606 } 9607 } 9608 9609 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9610 int N = pkg.providers.size(); 9611 StringBuilder r = null; 9612 int i; 9613 for (i=0; i<N; i++) { 9614 PackageParser.Provider p = pkg.providers.get(i); 9615 mProviders.removeProvider(p); 9616 if (p.info.authority == null) { 9617 9618 /* There was another ContentProvider with this authority when 9619 * this app was installed so this authority is null, 9620 * Ignore it as we don't have to unregister the provider. 9621 */ 9622 continue; 9623 } 9624 String names[] = p.info.authority.split(";"); 9625 for (int j = 0; j < names.length; j++) { 9626 if (mProvidersByAuthority.get(names[j]) == p) { 9627 mProvidersByAuthority.remove(names[j]); 9628 if (DEBUG_REMOVE) { 9629 if (chatty) 9630 Log.d(TAG, "Unregistered content provider: " + names[j] 9631 + ", className = " + p.info.name + ", isSyncable = " 9632 + p.info.isSyncable); 9633 } 9634 } 9635 } 9636 if (DEBUG_REMOVE && chatty) { 9637 if (r == null) { 9638 r = new StringBuilder(256); 9639 } else { 9640 r.append(' '); 9641 } 9642 r.append(p.info.name); 9643 } 9644 } 9645 if (r != null) { 9646 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9647 } 9648 9649 N = pkg.services.size(); 9650 r = null; 9651 for (i=0; i<N; i++) { 9652 PackageParser.Service s = pkg.services.get(i); 9653 mServices.removeService(s); 9654 if (chatty) { 9655 if (r == null) { 9656 r = new StringBuilder(256); 9657 } else { 9658 r.append(' '); 9659 } 9660 r.append(s.info.name); 9661 } 9662 } 9663 if (r != null) { 9664 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9665 } 9666 9667 N = pkg.receivers.size(); 9668 r = null; 9669 for (i=0; i<N; i++) { 9670 PackageParser.Activity a = pkg.receivers.get(i); 9671 mReceivers.removeActivity(a, "receiver"); 9672 if (DEBUG_REMOVE && chatty) { 9673 if (r == null) { 9674 r = new StringBuilder(256); 9675 } else { 9676 r.append(' '); 9677 } 9678 r.append(a.info.name); 9679 } 9680 } 9681 if (r != null) { 9682 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9683 } 9684 9685 N = pkg.activities.size(); 9686 r = null; 9687 for (i=0; i<N; i++) { 9688 PackageParser.Activity a = pkg.activities.get(i); 9689 mActivities.removeActivity(a, "activity"); 9690 if (DEBUG_REMOVE && chatty) { 9691 if (r == null) { 9692 r = new StringBuilder(256); 9693 } else { 9694 r.append(' '); 9695 } 9696 r.append(a.info.name); 9697 } 9698 } 9699 if (r != null) { 9700 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9701 } 9702 9703 N = pkg.permissions.size(); 9704 r = null; 9705 for (i=0; i<N; i++) { 9706 PackageParser.Permission p = pkg.permissions.get(i); 9707 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9708 if (bp == null) { 9709 bp = mSettings.mPermissionTrees.get(p.info.name); 9710 } 9711 if (bp != null && bp.perm == p) { 9712 bp.perm = null; 9713 if (DEBUG_REMOVE && chatty) { 9714 if (r == null) { 9715 r = new StringBuilder(256); 9716 } else { 9717 r.append(' '); 9718 } 9719 r.append(p.info.name); 9720 } 9721 } 9722 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9723 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9724 if (appOpPkgs != null) { 9725 appOpPkgs.remove(pkg.packageName); 9726 } 9727 } 9728 } 9729 if (r != null) { 9730 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9731 } 9732 9733 N = pkg.requestedPermissions.size(); 9734 r = null; 9735 for (i=0; i<N; i++) { 9736 String perm = pkg.requestedPermissions.get(i); 9737 BasePermission bp = mSettings.mPermissions.get(perm); 9738 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9739 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9740 if (appOpPkgs != null) { 9741 appOpPkgs.remove(pkg.packageName); 9742 if (appOpPkgs.isEmpty()) { 9743 mAppOpPermissionPackages.remove(perm); 9744 } 9745 } 9746 } 9747 } 9748 if (r != null) { 9749 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9750 } 9751 9752 N = pkg.instrumentation.size(); 9753 r = null; 9754 for (i=0; i<N; i++) { 9755 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9756 mInstrumentation.remove(a.getComponentName()); 9757 if (DEBUG_REMOVE && chatty) { 9758 if (r == null) { 9759 r = new StringBuilder(256); 9760 } else { 9761 r.append(' '); 9762 } 9763 r.append(a.info.name); 9764 } 9765 } 9766 if (r != null) { 9767 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9768 } 9769 9770 r = null; 9771 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9772 // Only system apps can hold shared libraries. 9773 if (pkg.libraryNames != null) { 9774 for (i=0; i<pkg.libraryNames.size(); i++) { 9775 String name = pkg.libraryNames.get(i); 9776 SharedLibraryEntry cur = mSharedLibraries.get(name); 9777 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9778 mSharedLibraries.remove(name); 9779 if (DEBUG_REMOVE && chatty) { 9780 if (r == null) { 9781 r = new StringBuilder(256); 9782 } else { 9783 r.append(' '); 9784 } 9785 r.append(name); 9786 } 9787 } 9788 } 9789 } 9790 } 9791 if (r != null) { 9792 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9793 } 9794 } 9795 9796 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9797 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9798 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9799 return true; 9800 } 9801 } 9802 return false; 9803 } 9804 9805 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9806 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9807 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9808 9809 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9810 // Update the parent permissions 9811 updatePermissionsLPw(pkg.packageName, pkg, flags); 9812 // Update the child permissions 9813 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9814 for (int i = 0; i < childCount; i++) { 9815 PackageParser.Package childPkg = pkg.childPackages.get(i); 9816 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9817 } 9818 } 9819 9820 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9821 int flags) { 9822 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9823 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9824 } 9825 9826 private void updatePermissionsLPw(String changingPkg, 9827 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9828 // Make sure there are no dangling permission trees. 9829 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9830 while (it.hasNext()) { 9831 final BasePermission bp = it.next(); 9832 if (bp.packageSetting == null) { 9833 // We may not yet have parsed the package, so just see if 9834 // we still know about its settings. 9835 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9836 } 9837 if (bp.packageSetting == null) { 9838 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9839 + " from package " + bp.sourcePackage); 9840 it.remove(); 9841 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9842 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9843 Slog.i(TAG, "Removing old permission tree: " + bp.name 9844 + " from package " + bp.sourcePackage); 9845 flags |= UPDATE_PERMISSIONS_ALL; 9846 it.remove(); 9847 } 9848 } 9849 } 9850 9851 // Make sure all dynamic permissions have been assigned to a package, 9852 // and make sure there are no dangling permissions. 9853 it = mSettings.mPermissions.values().iterator(); 9854 while (it.hasNext()) { 9855 final BasePermission bp = it.next(); 9856 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9857 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9858 + bp.name + " pkg=" + bp.sourcePackage 9859 + " info=" + bp.pendingInfo); 9860 if (bp.packageSetting == null && bp.pendingInfo != null) { 9861 final BasePermission tree = findPermissionTreeLP(bp.name); 9862 if (tree != null && tree.perm != null) { 9863 bp.packageSetting = tree.packageSetting; 9864 bp.perm = new PackageParser.Permission(tree.perm.owner, 9865 new PermissionInfo(bp.pendingInfo)); 9866 bp.perm.info.packageName = tree.perm.info.packageName; 9867 bp.perm.info.name = bp.name; 9868 bp.uid = tree.uid; 9869 } 9870 } 9871 } 9872 if (bp.packageSetting == null) { 9873 // We may not yet have parsed the package, so just see if 9874 // we still know about its settings. 9875 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9876 } 9877 if (bp.packageSetting == null) { 9878 Slog.w(TAG, "Removing dangling permission: " + bp.name 9879 + " from package " + bp.sourcePackage); 9880 it.remove(); 9881 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9882 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9883 Slog.i(TAG, "Removing old permission: " + bp.name 9884 + " from package " + bp.sourcePackage); 9885 flags |= UPDATE_PERMISSIONS_ALL; 9886 it.remove(); 9887 } 9888 } 9889 } 9890 9891 // Now update the permissions for all packages, in particular 9892 // replace the granted permissions of the system packages. 9893 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9894 for (PackageParser.Package pkg : mPackages.values()) { 9895 if (pkg != pkgInfo) { 9896 // Only replace for packages on requested volume 9897 final String volumeUuid = getVolumeUuidForPackage(pkg); 9898 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9899 && Objects.equals(replaceVolumeUuid, volumeUuid); 9900 grantPermissionsLPw(pkg, replace, changingPkg); 9901 } 9902 } 9903 } 9904 9905 if (pkgInfo != null) { 9906 // Only replace for packages on requested volume 9907 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9908 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9909 && Objects.equals(replaceVolumeUuid, volumeUuid); 9910 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9911 } 9912 } 9913 9914 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9915 String packageOfInterest) { 9916 // IMPORTANT: There are two types of permissions: install and runtime. 9917 // Install time permissions are granted when the app is installed to 9918 // all device users and users added in the future. Runtime permissions 9919 // are granted at runtime explicitly to specific users. Normal and signature 9920 // protected permissions are install time permissions. Dangerous permissions 9921 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9922 // otherwise they are runtime permissions. This function does not manage 9923 // runtime permissions except for the case an app targeting Lollipop MR1 9924 // being upgraded to target a newer SDK, in which case dangerous permissions 9925 // are transformed from install time to runtime ones. 9926 9927 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9928 if (ps == null) { 9929 return; 9930 } 9931 9932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9933 9934 PermissionsState permissionsState = ps.getPermissionsState(); 9935 PermissionsState origPermissions = permissionsState; 9936 9937 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9938 9939 boolean runtimePermissionsRevoked = false; 9940 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9941 9942 boolean changedInstallPermission = false; 9943 9944 if (replace) { 9945 ps.installPermissionsFixed = false; 9946 if (!ps.isSharedUser()) { 9947 origPermissions = new PermissionsState(permissionsState); 9948 permissionsState.reset(); 9949 } else { 9950 // We need to know only about runtime permission changes since the 9951 // calling code always writes the install permissions state but 9952 // the runtime ones are written only if changed. The only cases of 9953 // changed runtime permissions here are promotion of an install to 9954 // runtime and revocation of a runtime from a shared user. 9955 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9956 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9957 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9958 runtimePermissionsRevoked = true; 9959 } 9960 } 9961 } 9962 9963 permissionsState.setGlobalGids(mGlobalGids); 9964 9965 final int N = pkg.requestedPermissions.size(); 9966 for (int i=0; i<N; i++) { 9967 final String name = pkg.requestedPermissions.get(i); 9968 final BasePermission bp = mSettings.mPermissions.get(name); 9969 9970 if (DEBUG_INSTALL) { 9971 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9972 } 9973 9974 if (bp == null || bp.packageSetting == null) { 9975 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9976 Slog.w(TAG, "Unknown permission " + name 9977 + " in package " + pkg.packageName); 9978 } 9979 continue; 9980 } 9981 9982 final String perm = bp.name; 9983 boolean allowedSig = false; 9984 int grant = GRANT_DENIED; 9985 9986 // Keep track of app op permissions. 9987 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9988 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9989 if (pkgs == null) { 9990 pkgs = new ArraySet<>(); 9991 mAppOpPermissionPackages.put(bp.name, pkgs); 9992 } 9993 pkgs.add(pkg.packageName); 9994 } 9995 9996 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9997 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9998 >= Build.VERSION_CODES.M; 9999 switch (level) { 10000 case PermissionInfo.PROTECTION_NORMAL: { 10001 // For all apps normal permissions are install time ones. 10002 grant = GRANT_INSTALL; 10003 } break; 10004 10005 case PermissionInfo.PROTECTION_DANGEROUS: { 10006 // If a permission review is required for legacy apps we represent 10007 // their permissions as always granted runtime ones since we need 10008 // to keep the review required permission flag per user while an 10009 // install permission's state is shared across all users. 10010 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10011 // For legacy apps dangerous permissions are install time ones. 10012 grant = GRANT_INSTALL; 10013 } else if (origPermissions.hasInstallPermission(bp.name)) { 10014 // For legacy apps that became modern, install becomes runtime. 10015 grant = GRANT_UPGRADE; 10016 } else if (mPromoteSystemApps 10017 && isSystemApp(ps) 10018 && mExistingSystemPackages.contains(ps.name)) { 10019 // For legacy system apps, install becomes runtime. 10020 // We cannot check hasInstallPermission() for system apps since those 10021 // permissions were granted implicitly and not persisted pre-M. 10022 grant = GRANT_UPGRADE; 10023 } else { 10024 // For modern apps keep runtime permissions unchanged. 10025 grant = GRANT_RUNTIME; 10026 } 10027 } break; 10028 10029 case PermissionInfo.PROTECTION_SIGNATURE: { 10030 // For all apps signature permissions are install time ones. 10031 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10032 if (allowedSig) { 10033 grant = GRANT_INSTALL; 10034 } 10035 } break; 10036 } 10037 10038 if (DEBUG_INSTALL) { 10039 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10040 } 10041 10042 if (grant != GRANT_DENIED) { 10043 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10044 // If this is an existing, non-system package, then 10045 // we can't add any new permissions to it. 10046 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10047 // Except... if this is a permission that was added 10048 // to the platform (note: need to only do this when 10049 // updating the platform). 10050 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10051 grant = GRANT_DENIED; 10052 } 10053 } 10054 } 10055 10056 switch (grant) { 10057 case GRANT_INSTALL: { 10058 // Revoke this as runtime permission to handle the case of 10059 // a runtime permission being downgraded to an install one. 10060 // Also in permission review mode we keep dangerous permissions 10061 // for legacy apps 10062 for (int userId : UserManagerService.getInstance().getUserIds()) { 10063 if (origPermissions.getRuntimePermissionState( 10064 bp.name, userId) != null) { 10065 // Revoke the runtime permission and clear the flags. 10066 origPermissions.revokeRuntimePermission(bp, userId); 10067 origPermissions.updatePermissionFlags(bp, userId, 10068 PackageManager.MASK_PERMISSION_FLAGS, 0); 10069 // If we revoked a permission permission, we have to write. 10070 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10071 changedRuntimePermissionUserIds, userId); 10072 } 10073 } 10074 // Grant an install permission. 10075 if (permissionsState.grantInstallPermission(bp) != 10076 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10077 changedInstallPermission = true; 10078 } 10079 } break; 10080 10081 case GRANT_RUNTIME: { 10082 // Grant previously granted runtime permissions. 10083 for (int userId : UserManagerService.getInstance().getUserIds()) { 10084 PermissionState permissionState = origPermissions 10085 .getRuntimePermissionState(bp.name, userId); 10086 int flags = permissionState != null 10087 ? permissionState.getFlags() : 0; 10088 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10089 if (permissionsState.grantRuntimePermission(bp, userId) == 10090 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10091 // If we cannot put the permission as it was, we have to write. 10092 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10093 changedRuntimePermissionUserIds, userId); 10094 } 10095 // If the app supports runtime permissions no need for a review. 10096 if (Build.PERMISSIONS_REVIEW_REQUIRED 10097 && appSupportsRuntimePermissions 10098 && (flags & PackageManager 10099 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10100 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10101 // Since we changed the flags, we have to write. 10102 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10103 changedRuntimePermissionUserIds, userId); 10104 } 10105 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10106 && !appSupportsRuntimePermissions) { 10107 // For legacy apps that need a permission review, every new 10108 // runtime permission is granted but it is pending a review. 10109 // We also need to review only platform defined runtime 10110 // permissions as these are the only ones the platform knows 10111 // how to disable the API to simulate revocation as legacy 10112 // apps don't expect to run with revoked permissions. 10113 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10114 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10115 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10116 // We changed the flags, hence have to write. 10117 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10118 changedRuntimePermissionUserIds, userId); 10119 } 10120 } 10121 if (permissionsState.grantRuntimePermission(bp, userId) 10122 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10123 // We changed the permission, hence have to write. 10124 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10125 changedRuntimePermissionUserIds, userId); 10126 } 10127 } 10128 // Propagate the permission flags. 10129 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10130 } 10131 } break; 10132 10133 case GRANT_UPGRADE: { 10134 // Grant runtime permissions for a previously held install permission. 10135 PermissionState permissionState = origPermissions 10136 .getInstallPermissionState(bp.name); 10137 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10138 10139 if (origPermissions.revokeInstallPermission(bp) 10140 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10141 // We will be transferring the permission flags, so clear them. 10142 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10143 PackageManager.MASK_PERMISSION_FLAGS, 0); 10144 changedInstallPermission = true; 10145 } 10146 10147 // If the permission is not to be promoted to runtime we ignore it and 10148 // also its other flags as they are not applicable to install permissions. 10149 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10150 for (int userId : currentUserIds) { 10151 if (permissionsState.grantRuntimePermission(bp, userId) != 10152 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10153 // Transfer the permission flags. 10154 permissionsState.updatePermissionFlags(bp, userId, 10155 flags, flags); 10156 // If we granted the permission, we have to write. 10157 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10158 changedRuntimePermissionUserIds, userId); 10159 } 10160 } 10161 } 10162 } break; 10163 10164 default: { 10165 if (packageOfInterest == null 10166 || packageOfInterest.equals(pkg.packageName)) { 10167 Slog.w(TAG, "Not granting permission " + perm 10168 + " to package " + pkg.packageName 10169 + " because it was previously installed without"); 10170 } 10171 } break; 10172 } 10173 } else { 10174 if (permissionsState.revokeInstallPermission(bp) != 10175 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10176 // Also drop the permission flags. 10177 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10178 PackageManager.MASK_PERMISSION_FLAGS, 0); 10179 changedInstallPermission = true; 10180 Slog.i(TAG, "Un-granting permission " + perm 10181 + " from package " + pkg.packageName 10182 + " (protectionLevel=" + bp.protectionLevel 10183 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10184 + ")"); 10185 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10186 // Don't print warning for app op permissions, since it is fine for them 10187 // not to be granted, there is a UI for the user to decide. 10188 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10189 Slog.w(TAG, "Not granting permission " + perm 10190 + " to package " + pkg.packageName 10191 + " (protectionLevel=" + bp.protectionLevel 10192 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10193 + ")"); 10194 } 10195 } 10196 } 10197 } 10198 10199 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10200 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10201 // This is the first that we have heard about this package, so the 10202 // permissions we have now selected are fixed until explicitly 10203 // changed. 10204 ps.installPermissionsFixed = true; 10205 } 10206 10207 // Persist the runtime permissions state for users with changes. If permissions 10208 // were revoked because no app in the shared user declares them we have to 10209 // write synchronously to avoid losing runtime permissions state. 10210 for (int userId : changedRuntimePermissionUserIds) { 10211 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10212 } 10213 10214 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10215 } 10216 10217 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10218 boolean allowed = false; 10219 final int NP = PackageParser.NEW_PERMISSIONS.length; 10220 for (int ip=0; ip<NP; ip++) { 10221 final PackageParser.NewPermissionInfo npi 10222 = PackageParser.NEW_PERMISSIONS[ip]; 10223 if (npi.name.equals(perm) 10224 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10225 allowed = true; 10226 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10227 + pkg.packageName); 10228 break; 10229 } 10230 } 10231 return allowed; 10232 } 10233 10234 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10235 BasePermission bp, PermissionsState origPermissions) { 10236 boolean allowed; 10237 allowed = (compareSignatures( 10238 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10239 == PackageManager.SIGNATURE_MATCH) 10240 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10241 == PackageManager.SIGNATURE_MATCH); 10242 if (!allowed && (bp.protectionLevel 10243 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10244 if (isSystemApp(pkg)) { 10245 // For updated system applications, a system permission 10246 // is granted only if it had been defined by the original application. 10247 if (pkg.isUpdatedSystemApp()) { 10248 final PackageSetting sysPs = mSettings 10249 .getDisabledSystemPkgLPr(pkg.packageName); 10250 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10251 // If the original was granted this permission, we take 10252 // that grant decision as read and propagate it to the 10253 // update. 10254 if (sysPs.isPrivileged()) { 10255 allowed = true; 10256 } 10257 } else { 10258 // The system apk may have been updated with an older 10259 // version of the one on the data partition, but which 10260 // granted a new system permission that it didn't have 10261 // before. In this case we do want to allow the app to 10262 // now get the new permission if the ancestral apk is 10263 // privileged to get it. 10264 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10265 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10266 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10267 allowed = true; 10268 break; 10269 } 10270 } 10271 } 10272 // Also if a privileged parent package on the system image or any of 10273 // its children requested a privileged permission, the updated child 10274 // packages can also get the permission. 10275 if (pkg.parentPackage != null) { 10276 final PackageSetting disabledSysParentPs = mSettings 10277 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10278 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10279 && disabledSysParentPs.isPrivileged()) { 10280 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10281 allowed = true; 10282 } else if (disabledSysParentPs.pkg.childPackages != null) { 10283 final int count = disabledSysParentPs.pkg.childPackages.size(); 10284 for (int i = 0; i < count; i++) { 10285 PackageParser.Package disabledSysChildPkg = 10286 disabledSysParentPs.pkg.childPackages.get(i); 10287 if (isPackageRequestingPermission(disabledSysChildPkg, 10288 perm)) { 10289 allowed = true; 10290 break; 10291 } 10292 } 10293 } 10294 } 10295 } 10296 } 10297 } else { 10298 allowed = isPrivilegedApp(pkg); 10299 } 10300 } 10301 } 10302 if (!allowed) { 10303 if (!allowed && (bp.protectionLevel 10304 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10305 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10306 // If this was a previously normal/dangerous permission that got moved 10307 // to a system permission as part of the runtime permission redesign, then 10308 // we still want to blindly grant it to old apps. 10309 allowed = true; 10310 } 10311 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10312 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10313 // If this permission is to be granted to the system installer and 10314 // this app is an installer, then it gets the permission. 10315 allowed = true; 10316 } 10317 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10318 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10319 // If this permission is to be granted to the system verifier and 10320 // this app is a verifier, then it gets the permission. 10321 allowed = true; 10322 } 10323 if (!allowed && (bp.protectionLevel 10324 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10325 && isSystemApp(pkg)) { 10326 // Any pre-installed system app is allowed to get this permission. 10327 allowed = true; 10328 } 10329 if (!allowed && (bp.protectionLevel 10330 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10331 // For development permissions, a development permission 10332 // is granted only if it was already granted. 10333 allowed = origPermissions.hasInstallPermission(perm); 10334 } 10335 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10336 && pkg.packageName.equals(mSetupWizardPackage)) { 10337 // If this permission is to be granted to the system setup wizard and 10338 // this app is a setup wizard, then it gets the permission. 10339 allowed = true; 10340 } 10341 } 10342 return allowed; 10343 } 10344 10345 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10346 final int permCount = pkg.requestedPermissions.size(); 10347 for (int j = 0; j < permCount; j++) { 10348 String requestedPermission = pkg.requestedPermissions.get(j); 10349 if (permission.equals(requestedPermission)) { 10350 return true; 10351 } 10352 } 10353 return false; 10354 } 10355 10356 final class ActivityIntentResolver 10357 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10358 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10359 boolean defaultOnly, int userId) { 10360 if (!sUserManager.exists(userId)) return null; 10361 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10362 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10363 } 10364 10365 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10366 int userId) { 10367 if (!sUserManager.exists(userId)) return null; 10368 mFlags = flags; 10369 return super.queryIntent(intent, resolvedType, 10370 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10371 } 10372 10373 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10374 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10375 if (!sUserManager.exists(userId)) return null; 10376 if (packageActivities == null) { 10377 return null; 10378 } 10379 mFlags = flags; 10380 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10381 final int N = packageActivities.size(); 10382 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10383 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10384 10385 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10386 for (int i = 0; i < N; ++i) { 10387 intentFilters = packageActivities.get(i).intents; 10388 if (intentFilters != null && intentFilters.size() > 0) { 10389 PackageParser.ActivityIntentInfo[] array = 10390 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10391 intentFilters.toArray(array); 10392 listCut.add(array); 10393 } 10394 } 10395 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10396 } 10397 10398 /** 10399 * Finds a privileged activity that matches the specified activity names. 10400 */ 10401 private PackageParser.Activity findMatchingActivity( 10402 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10403 for (PackageParser.Activity sysActivity : activityList) { 10404 if (sysActivity.info.name.equals(activityInfo.name)) { 10405 return sysActivity; 10406 } 10407 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10408 return sysActivity; 10409 } 10410 if (sysActivity.info.targetActivity != null) { 10411 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10412 return sysActivity; 10413 } 10414 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10415 return sysActivity; 10416 } 10417 } 10418 } 10419 return null; 10420 } 10421 10422 public class IterGenerator<E> { 10423 public Iterator<E> generate(ActivityIntentInfo info) { 10424 return null; 10425 } 10426 } 10427 10428 public class ActionIterGenerator extends IterGenerator<String> { 10429 @Override 10430 public Iterator<String> generate(ActivityIntentInfo info) { 10431 return info.actionsIterator(); 10432 } 10433 } 10434 10435 public class CategoriesIterGenerator extends IterGenerator<String> { 10436 @Override 10437 public Iterator<String> generate(ActivityIntentInfo info) { 10438 return info.categoriesIterator(); 10439 } 10440 } 10441 10442 public class SchemesIterGenerator extends IterGenerator<String> { 10443 @Override 10444 public Iterator<String> generate(ActivityIntentInfo info) { 10445 return info.schemesIterator(); 10446 } 10447 } 10448 10449 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10450 @Override 10451 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10452 return info.authoritiesIterator(); 10453 } 10454 } 10455 10456 /** 10457 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10458 * MODIFIED. Do not pass in a list that should not be changed. 10459 */ 10460 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10461 IterGenerator<T> generator, Iterator<T> searchIterator) { 10462 // loop through the set of actions; every one must be found in the intent filter 10463 while (searchIterator.hasNext()) { 10464 // we must have at least one filter in the list to consider a match 10465 if (intentList.size() == 0) { 10466 break; 10467 } 10468 10469 final T searchAction = searchIterator.next(); 10470 10471 // loop through the set of intent filters 10472 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10473 while (intentIter.hasNext()) { 10474 final ActivityIntentInfo intentInfo = intentIter.next(); 10475 boolean selectionFound = false; 10476 10477 // loop through the intent filter's selection criteria; at least one 10478 // of them must match the searched criteria 10479 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10480 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10481 final T intentSelection = intentSelectionIter.next(); 10482 if (intentSelection != null && intentSelection.equals(searchAction)) { 10483 selectionFound = true; 10484 break; 10485 } 10486 } 10487 10488 // the selection criteria wasn't found in this filter's set; this filter 10489 // is not a potential match 10490 if (!selectionFound) { 10491 intentIter.remove(); 10492 } 10493 } 10494 } 10495 } 10496 10497 private boolean isProtectedAction(ActivityIntentInfo filter) { 10498 final Iterator<String> actionsIter = filter.actionsIterator(); 10499 while (actionsIter != null && actionsIter.hasNext()) { 10500 final String filterAction = actionsIter.next(); 10501 if (PROTECTED_ACTIONS.contains(filterAction)) { 10502 return true; 10503 } 10504 } 10505 return false; 10506 } 10507 10508 /** 10509 * Adjusts the priority of the given intent filter according to policy. 10510 * <p> 10511 * <ul> 10512 * <li>The priority for non privileged applications is capped to '0'</li> 10513 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10514 * <li>The priority for unbundled updates to privileged applications is capped to the 10515 * priority defined on the system partition</li> 10516 * </ul> 10517 * <p> 10518 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10519 * allowed to obtain any priority on any action. 10520 */ 10521 private void adjustPriority( 10522 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10523 // nothing to do; priority is fine as-is 10524 if (intent.getPriority() <= 0) { 10525 return; 10526 } 10527 10528 final ActivityInfo activityInfo = intent.activity.info; 10529 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10530 10531 final boolean privilegedApp = 10532 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10533 if (!privilegedApp) { 10534 // non-privileged applications can never define a priority >0 10535 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10536 + " package: " + applicationInfo.packageName 10537 + " activity: " + intent.activity.className 10538 + " origPrio: " + intent.getPriority()); 10539 intent.setPriority(0); 10540 return; 10541 } 10542 10543 if (systemActivities == null) { 10544 // the system package is not disabled; we're parsing the system partition 10545 if (isProtectedAction(intent)) { 10546 if (mDeferProtectedFilters) { 10547 // We can't deal with these just yet. No component should ever obtain a 10548 // >0 priority for a protected actions, with ONE exception -- the setup 10549 // wizard. The setup wizard, however, cannot be known until we're able to 10550 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10551 // until all intent filters have been processed. Chicken, meet egg. 10552 // Let the filter temporarily have a high priority and rectify the 10553 // priorities after all system packages have been scanned. 10554 mProtectedFilters.add(intent); 10555 if (DEBUG_FILTERS) { 10556 Slog.i(TAG, "Protected action; save for later;" 10557 + " package: " + applicationInfo.packageName 10558 + " activity: " + intent.activity.className 10559 + " origPrio: " + intent.getPriority()); 10560 } 10561 return; 10562 } else { 10563 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10564 Slog.i(TAG, "No setup wizard;" 10565 + " All protected intents capped to priority 0"); 10566 } 10567 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10568 if (DEBUG_FILTERS) { 10569 Slog.i(TAG, "Found setup wizard;" 10570 + " allow priority " + intent.getPriority() + ";" 10571 + " package: " + intent.activity.info.packageName 10572 + " activity: " + intent.activity.className 10573 + " priority: " + intent.getPriority()); 10574 } 10575 // setup wizard gets whatever it wants 10576 return; 10577 } 10578 Slog.w(TAG, "Protected action; cap priority to 0;" 10579 + " package: " + intent.activity.info.packageName 10580 + " activity: " + intent.activity.className 10581 + " origPrio: " + intent.getPriority()); 10582 intent.setPriority(0); 10583 return; 10584 } 10585 } 10586 // privileged apps on the system image get whatever priority they request 10587 return; 10588 } 10589 10590 // privileged app unbundled update ... try to find the same activity 10591 final PackageParser.Activity foundActivity = 10592 findMatchingActivity(systemActivities, activityInfo); 10593 if (foundActivity == null) { 10594 // this is a new activity; it cannot obtain >0 priority 10595 if (DEBUG_FILTERS) { 10596 Slog.i(TAG, "New activity; cap priority to 0;" 10597 + " package: " + applicationInfo.packageName 10598 + " activity: " + intent.activity.className 10599 + " origPrio: " + intent.getPriority()); 10600 } 10601 intent.setPriority(0); 10602 return; 10603 } 10604 10605 // found activity, now check for filter equivalence 10606 10607 // a shallow copy is enough; we modify the list, not its contents 10608 final List<ActivityIntentInfo> intentListCopy = 10609 new ArrayList<>(foundActivity.intents); 10610 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10611 10612 // find matching action subsets 10613 final Iterator<String> actionsIterator = intent.actionsIterator(); 10614 if (actionsIterator != null) { 10615 getIntentListSubset( 10616 intentListCopy, new ActionIterGenerator(), actionsIterator); 10617 if (intentListCopy.size() == 0) { 10618 // no more intents to match; we're not equivalent 10619 if (DEBUG_FILTERS) { 10620 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10621 + " package: " + applicationInfo.packageName 10622 + " activity: " + intent.activity.className 10623 + " origPrio: " + intent.getPriority()); 10624 } 10625 intent.setPriority(0); 10626 return; 10627 } 10628 } 10629 10630 // find matching category subsets 10631 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10632 if (categoriesIterator != null) { 10633 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10634 categoriesIterator); 10635 if (intentListCopy.size() == 0) { 10636 // no more intents to match; we're not equivalent 10637 if (DEBUG_FILTERS) { 10638 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10639 + " package: " + applicationInfo.packageName 10640 + " activity: " + intent.activity.className 10641 + " origPrio: " + intent.getPriority()); 10642 } 10643 intent.setPriority(0); 10644 return; 10645 } 10646 } 10647 10648 // find matching schemes subsets 10649 final Iterator<String> schemesIterator = intent.schemesIterator(); 10650 if (schemesIterator != null) { 10651 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10652 schemesIterator); 10653 if (intentListCopy.size() == 0) { 10654 // no more intents to match; we're not equivalent 10655 if (DEBUG_FILTERS) { 10656 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10657 + " package: " + applicationInfo.packageName 10658 + " activity: " + intent.activity.className 10659 + " origPrio: " + intent.getPriority()); 10660 } 10661 intent.setPriority(0); 10662 return; 10663 } 10664 } 10665 10666 // find matching authorities subsets 10667 final Iterator<IntentFilter.AuthorityEntry> 10668 authoritiesIterator = intent.authoritiesIterator(); 10669 if (authoritiesIterator != null) { 10670 getIntentListSubset(intentListCopy, 10671 new AuthoritiesIterGenerator(), 10672 authoritiesIterator); 10673 if (intentListCopy.size() == 0) { 10674 // no more intents to match; we're not equivalent 10675 if (DEBUG_FILTERS) { 10676 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10677 + " package: " + applicationInfo.packageName 10678 + " activity: " + intent.activity.className 10679 + " origPrio: " + intent.getPriority()); 10680 } 10681 intent.setPriority(0); 10682 return; 10683 } 10684 } 10685 10686 // we found matching filter(s); app gets the max priority of all intents 10687 int cappedPriority = 0; 10688 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10689 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10690 } 10691 if (intent.getPriority() > cappedPriority) { 10692 if (DEBUG_FILTERS) { 10693 Slog.i(TAG, "Found matching filter(s);" 10694 + " cap priority to " + cappedPriority + ";" 10695 + " package: " + applicationInfo.packageName 10696 + " activity: " + intent.activity.className 10697 + " origPrio: " + intent.getPriority()); 10698 } 10699 intent.setPriority(cappedPriority); 10700 return; 10701 } 10702 // all this for nothing; the requested priority was <= what was on the system 10703 } 10704 10705 public final void addActivity(PackageParser.Activity a, String type) { 10706 mActivities.put(a.getComponentName(), a); 10707 if (DEBUG_SHOW_INFO) 10708 Log.v( 10709 TAG, " " + type + " " + 10710 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10711 if (DEBUG_SHOW_INFO) 10712 Log.v(TAG, " Class=" + a.info.name); 10713 final int NI = a.intents.size(); 10714 for (int j=0; j<NI; j++) { 10715 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10716 if ("activity".equals(type)) { 10717 final PackageSetting ps = 10718 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10719 final List<PackageParser.Activity> systemActivities = 10720 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10721 adjustPriority(systemActivities, intent); 10722 } 10723 if (DEBUG_SHOW_INFO) { 10724 Log.v(TAG, " IntentFilter:"); 10725 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10726 } 10727 if (!intent.debugCheck()) { 10728 Log.w(TAG, "==> For Activity " + a.info.name); 10729 } 10730 addFilter(intent); 10731 } 10732 } 10733 10734 public final void removeActivity(PackageParser.Activity a, String type) { 10735 mActivities.remove(a.getComponentName()); 10736 if (DEBUG_SHOW_INFO) { 10737 Log.v(TAG, " " + type + " " 10738 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10739 : a.info.name) + ":"); 10740 Log.v(TAG, " Class=" + a.info.name); 10741 } 10742 final int NI = a.intents.size(); 10743 for (int j=0; j<NI; j++) { 10744 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10745 if (DEBUG_SHOW_INFO) { 10746 Log.v(TAG, " IntentFilter:"); 10747 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10748 } 10749 removeFilter(intent); 10750 } 10751 } 10752 10753 @Override 10754 protected boolean allowFilterResult( 10755 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10756 ActivityInfo filterAi = filter.activity.info; 10757 for (int i=dest.size()-1; i>=0; i--) { 10758 ActivityInfo destAi = dest.get(i).activityInfo; 10759 if (destAi.name == filterAi.name 10760 && destAi.packageName == filterAi.packageName) { 10761 return false; 10762 } 10763 } 10764 return true; 10765 } 10766 10767 @Override 10768 protected ActivityIntentInfo[] newArray(int size) { 10769 return new ActivityIntentInfo[size]; 10770 } 10771 10772 @Override 10773 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10774 if (!sUserManager.exists(userId)) return true; 10775 PackageParser.Package p = filter.activity.owner; 10776 if (p != null) { 10777 PackageSetting ps = (PackageSetting)p.mExtras; 10778 if (ps != null) { 10779 // System apps are never considered stopped for purposes of 10780 // filtering, because there may be no way for the user to 10781 // actually re-launch them. 10782 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10783 && ps.getStopped(userId); 10784 } 10785 } 10786 return false; 10787 } 10788 10789 @Override 10790 protected boolean isPackageForFilter(String packageName, 10791 PackageParser.ActivityIntentInfo info) { 10792 return packageName.equals(info.activity.owner.packageName); 10793 } 10794 10795 @Override 10796 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10797 int match, int userId) { 10798 if (!sUserManager.exists(userId)) return null; 10799 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10800 return null; 10801 } 10802 final PackageParser.Activity activity = info.activity; 10803 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10804 if (ps == null) { 10805 return null; 10806 } 10807 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10808 ps.readUserState(userId), userId); 10809 if (ai == null) { 10810 return null; 10811 } 10812 final ResolveInfo res = new ResolveInfo(); 10813 res.activityInfo = ai; 10814 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10815 res.filter = info; 10816 } 10817 if (info != null) { 10818 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10819 } 10820 res.priority = info.getPriority(); 10821 res.preferredOrder = activity.owner.mPreferredOrder; 10822 //System.out.println("Result: " + res.activityInfo.className + 10823 // " = " + res.priority); 10824 res.match = match; 10825 res.isDefault = info.hasDefault; 10826 res.labelRes = info.labelRes; 10827 res.nonLocalizedLabel = info.nonLocalizedLabel; 10828 if (userNeedsBadging(userId)) { 10829 res.noResourceId = true; 10830 } else { 10831 res.icon = info.icon; 10832 } 10833 res.iconResourceId = info.icon; 10834 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10835 return res; 10836 } 10837 10838 @Override 10839 protected void sortResults(List<ResolveInfo> results) { 10840 Collections.sort(results, mResolvePrioritySorter); 10841 } 10842 10843 @Override 10844 protected void dumpFilter(PrintWriter out, String prefix, 10845 PackageParser.ActivityIntentInfo filter) { 10846 out.print(prefix); out.print( 10847 Integer.toHexString(System.identityHashCode(filter.activity))); 10848 out.print(' '); 10849 filter.activity.printComponentShortName(out); 10850 out.print(" filter "); 10851 out.println(Integer.toHexString(System.identityHashCode(filter))); 10852 } 10853 10854 @Override 10855 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10856 return filter.activity; 10857 } 10858 10859 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10860 PackageParser.Activity activity = (PackageParser.Activity)label; 10861 out.print(prefix); out.print( 10862 Integer.toHexString(System.identityHashCode(activity))); 10863 out.print(' '); 10864 activity.printComponentShortName(out); 10865 if (count > 1) { 10866 out.print(" ("); out.print(count); out.print(" filters)"); 10867 } 10868 out.println(); 10869 } 10870 10871 // Keys are String (activity class name), values are Activity. 10872 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10873 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10874 private int mFlags; 10875 } 10876 10877 private final class ServiceIntentResolver 10878 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10879 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10880 boolean defaultOnly, int userId) { 10881 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10882 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10883 } 10884 10885 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10886 int userId) { 10887 if (!sUserManager.exists(userId)) return null; 10888 mFlags = flags; 10889 return super.queryIntent(intent, resolvedType, 10890 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10891 } 10892 10893 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10894 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10895 if (!sUserManager.exists(userId)) return null; 10896 if (packageServices == null) { 10897 return null; 10898 } 10899 mFlags = flags; 10900 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10901 final int N = packageServices.size(); 10902 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10903 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10904 10905 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10906 for (int i = 0; i < N; ++i) { 10907 intentFilters = packageServices.get(i).intents; 10908 if (intentFilters != null && intentFilters.size() > 0) { 10909 PackageParser.ServiceIntentInfo[] array = 10910 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10911 intentFilters.toArray(array); 10912 listCut.add(array); 10913 } 10914 } 10915 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10916 } 10917 10918 public final void addService(PackageParser.Service s) { 10919 mServices.put(s.getComponentName(), s); 10920 if (DEBUG_SHOW_INFO) { 10921 Log.v(TAG, " " 10922 + (s.info.nonLocalizedLabel != null 10923 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10924 Log.v(TAG, " Class=" + s.info.name); 10925 } 10926 final int NI = s.intents.size(); 10927 int j; 10928 for (j=0; j<NI; j++) { 10929 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10930 if (DEBUG_SHOW_INFO) { 10931 Log.v(TAG, " IntentFilter:"); 10932 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10933 } 10934 if (!intent.debugCheck()) { 10935 Log.w(TAG, "==> For Service " + s.info.name); 10936 } 10937 addFilter(intent); 10938 } 10939 } 10940 10941 public final void removeService(PackageParser.Service s) { 10942 mServices.remove(s.getComponentName()); 10943 if (DEBUG_SHOW_INFO) { 10944 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10945 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10946 Log.v(TAG, " Class=" + s.info.name); 10947 } 10948 final int NI = s.intents.size(); 10949 int j; 10950 for (j=0; j<NI; j++) { 10951 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10952 if (DEBUG_SHOW_INFO) { 10953 Log.v(TAG, " IntentFilter:"); 10954 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10955 } 10956 removeFilter(intent); 10957 } 10958 } 10959 10960 @Override 10961 protected boolean allowFilterResult( 10962 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10963 ServiceInfo filterSi = filter.service.info; 10964 for (int i=dest.size()-1; i>=0; i--) { 10965 ServiceInfo destAi = dest.get(i).serviceInfo; 10966 if (destAi.name == filterSi.name 10967 && destAi.packageName == filterSi.packageName) { 10968 return false; 10969 } 10970 } 10971 return true; 10972 } 10973 10974 @Override 10975 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10976 return new PackageParser.ServiceIntentInfo[size]; 10977 } 10978 10979 @Override 10980 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10981 if (!sUserManager.exists(userId)) return true; 10982 PackageParser.Package p = filter.service.owner; 10983 if (p != null) { 10984 PackageSetting ps = (PackageSetting)p.mExtras; 10985 if (ps != null) { 10986 // System apps are never considered stopped for purposes of 10987 // filtering, because there may be no way for the user to 10988 // actually re-launch them. 10989 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10990 && ps.getStopped(userId); 10991 } 10992 } 10993 return false; 10994 } 10995 10996 @Override 10997 protected boolean isPackageForFilter(String packageName, 10998 PackageParser.ServiceIntentInfo info) { 10999 return packageName.equals(info.service.owner.packageName); 11000 } 11001 11002 @Override 11003 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11004 int match, int userId) { 11005 if (!sUserManager.exists(userId)) return null; 11006 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11007 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11008 return null; 11009 } 11010 final PackageParser.Service service = info.service; 11011 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11012 if (ps == null) { 11013 return null; 11014 } 11015 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11016 ps.readUserState(userId), userId); 11017 if (si == null) { 11018 return null; 11019 } 11020 final ResolveInfo res = new ResolveInfo(); 11021 res.serviceInfo = si; 11022 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11023 res.filter = filter; 11024 } 11025 res.priority = info.getPriority(); 11026 res.preferredOrder = service.owner.mPreferredOrder; 11027 res.match = match; 11028 res.isDefault = info.hasDefault; 11029 res.labelRes = info.labelRes; 11030 res.nonLocalizedLabel = info.nonLocalizedLabel; 11031 res.icon = info.icon; 11032 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11033 return res; 11034 } 11035 11036 @Override 11037 protected void sortResults(List<ResolveInfo> results) { 11038 Collections.sort(results, mResolvePrioritySorter); 11039 } 11040 11041 @Override 11042 protected void dumpFilter(PrintWriter out, String prefix, 11043 PackageParser.ServiceIntentInfo filter) { 11044 out.print(prefix); out.print( 11045 Integer.toHexString(System.identityHashCode(filter.service))); 11046 out.print(' '); 11047 filter.service.printComponentShortName(out); 11048 out.print(" filter "); 11049 out.println(Integer.toHexString(System.identityHashCode(filter))); 11050 } 11051 11052 @Override 11053 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11054 return filter.service; 11055 } 11056 11057 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11058 PackageParser.Service service = (PackageParser.Service)label; 11059 out.print(prefix); out.print( 11060 Integer.toHexString(System.identityHashCode(service))); 11061 out.print(' '); 11062 service.printComponentShortName(out); 11063 if (count > 1) { 11064 out.print(" ("); out.print(count); out.print(" filters)"); 11065 } 11066 out.println(); 11067 } 11068 11069// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11070// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11071// final List<ResolveInfo> retList = Lists.newArrayList(); 11072// while (i.hasNext()) { 11073// final ResolveInfo resolveInfo = (ResolveInfo) i; 11074// if (isEnabledLP(resolveInfo.serviceInfo)) { 11075// retList.add(resolveInfo); 11076// } 11077// } 11078// return retList; 11079// } 11080 11081 // Keys are String (activity class name), values are Activity. 11082 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11083 = new ArrayMap<ComponentName, PackageParser.Service>(); 11084 private int mFlags; 11085 }; 11086 11087 private final class ProviderIntentResolver 11088 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11090 boolean defaultOnly, int userId) { 11091 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11092 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11093 } 11094 11095 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11096 int userId) { 11097 if (!sUserManager.exists(userId)) 11098 return null; 11099 mFlags = flags; 11100 return super.queryIntent(intent, resolvedType, 11101 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11102 } 11103 11104 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11105 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11106 if (!sUserManager.exists(userId)) 11107 return null; 11108 if (packageProviders == null) { 11109 return null; 11110 } 11111 mFlags = flags; 11112 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11113 final int N = packageProviders.size(); 11114 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11115 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11116 11117 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11118 for (int i = 0; i < N; ++i) { 11119 intentFilters = packageProviders.get(i).intents; 11120 if (intentFilters != null && intentFilters.size() > 0) { 11121 PackageParser.ProviderIntentInfo[] array = 11122 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11123 intentFilters.toArray(array); 11124 listCut.add(array); 11125 } 11126 } 11127 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11128 } 11129 11130 public final void addProvider(PackageParser.Provider p) { 11131 if (mProviders.containsKey(p.getComponentName())) { 11132 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11133 return; 11134 } 11135 11136 mProviders.put(p.getComponentName(), p); 11137 if (DEBUG_SHOW_INFO) { 11138 Log.v(TAG, " " 11139 + (p.info.nonLocalizedLabel != null 11140 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11141 Log.v(TAG, " Class=" + p.info.name); 11142 } 11143 final int NI = p.intents.size(); 11144 int j; 11145 for (j = 0; j < NI; j++) { 11146 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11147 if (DEBUG_SHOW_INFO) { 11148 Log.v(TAG, " IntentFilter:"); 11149 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11150 } 11151 if (!intent.debugCheck()) { 11152 Log.w(TAG, "==> For Provider " + p.info.name); 11153 } 11154 addFilter(intent); 11155 } 11156 } 11157 11158 public final void removeProvider(PackageParser.Provider p) { 11159 mProviders.remove(p.getComponentName()); 11160 if (DEBUG_SHOW_INFO) { 11161 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11162 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11163 Log.v(TAG, " Class=" + p.info.name); 11164 } 11165 final int NI = p.intents.size(); 11166 int j; 11167 for (j = 0; j < NI; j++) { 11168 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11169 if (DEBUG_SHOW_INFO) { 11170 Log.v(TAG, " IntentFilter:"); 11171 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11172 } 11173 removeFilter(intent); 11174 } 11175 } 11176 11177 @Override 11178 protected boolean allowFilterResult( 11179 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11180 ProviderInfo filterPi = filter.provider.info; 11181 for (int i = dest.size() - 1; i >= 0; i--) { 11182 ProviderInfo destPi = dest.get(i).providerInfo; 11183 if (destPi.name == filterPi.name 11184 && destPi.packageName == filterPi.packageName) { 11185 return false; 11186 } 11187 } 11188 return true; 11189 } 11190 11191 @Override 11192 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11193 return new PackageParser.ProviderIntentInfo[size]; 11194 } 11195 11196 @Override 11197 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11198 if (!sUserManager.exists(userId)) 11199 return true; 11200 PackageParser.Package p = filter.provider.owner; 11201 if (p != null) { 11202 PackageSetting ps = (PackageSetting) p.mExtras; 11203 if (ps != null) { 11204 // System apps are never considered stopped for purposes of 11205 // filtering, because there may be no way for the user to 11206 // actually re-launch them. 11207 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11208 && ps.getStopped(userId); 11209 } 11210 } 11211 return false; 11212 } 11213 11214 @Override 11215 protected boolean isPackageForFilter(String packageName, 11216 PackageParser.ProviderIntentInfo info) { 11217 return packageName.equals(info.provider.owner.packageName); 11218 } 11219 11220 @Override 11221 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11222 int match, int userId) { 11223 if (!sUserManager.exists(userId)) 11224 return null; 11225 final PackageParser.ProviderIntentInfo info = filter; 11226 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11227 return null; 11228 } 11229 final PackageParser.Provider provider = info.provider; 11230 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11231 if (ps == null) { 11232 return null; 11233 } 11234 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11235 ps.readUserState(userId), userId); 11236 if (pi == null) { 11237 return null; 11238 } 11239 final ResolveInfo res = new ResolveInfo(); 11240 res.providerInfo = pi; 11241 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11242 res.filter = filter; 11243 } 11244 res.priority = info.getPriority(); 11245 res.preferredOrder = provider.owner.mPreferredOrder; 11246 res.match = match; 11247 res.isDefault = info.hasDefault; 11248 res.labelRes = info.labelRes; 11249 res.nonLocalizedLabel = info.nonLocalizedLabel; 11250 res.icon = info.icon; 11251 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11252 return res; 11253 } 11254 11255 @Override 11256 protected void sortResults(List<ResolveInfo> results) { 11257 Collections.sort(results, mResolvePrioritySorter); 11258 } 11259 11260 @Override 11261 protected void dumpFilter(PrintWriter out, String prefix, 11262 PackageParser.ProviderIntentInfo filter) { 11263 out.print(prefix); 11264 out.print( 11265 Integer.toHexString(System.identityHashCode(filter.provider))); 11266 out.print(' '); 11267 filter.provider.printComponentShortName(out); 11268 out.print(" filter "); 11269 out.println(Integer.toHexString(System.identityHashCode(filter))); 11270 } 11271 11272 @Override 11273 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11274 return filter.provider; 11275 } 11276 11277 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11278 PackageParser.Provider provider = (PackageParser.Provider)label; 11279 out.print(prefix); out.print( 11280 Integer.toHexString(System.identityHashCode(provider))); 11281 out.print(' '); 11282 provider.printComponentShortName(out); 11283 if (count > 1) { 11284 out.print(" ("); out.print(count); out.print(" filters)"); 11285 } 11286 out.println(); 11287 } 11288 11289 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11290 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11291 private int mFlags; 11292 } 11293 11294 private static final class EphemeralIntentResolver 11295 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11296 @Override 11297 protected EphemeralResolveIntentInfo[] newArray(int size) { 11298 return new EphemeralResolveIntentInfo[size]; 11299 } 11300 11301 @Override 11302 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11303 return true; 11304 } 11305 11306 @Override 11307 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11308 int userId) { 11309 if (!sUserManager.exists(userId)) { 11310 return null; 11311 } 11312 return info.getEphemeralResolveInfo(); 11313 } 11314 } 11315 11316 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11317 new Comparator<ResolveInfo>() { 11318 public int compare(ResolveInfo r1, ResolveInfo r2) { 11319 int v1 = r1.priority; 11320 int v2 = r2.priority; 11321 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11322 if (v1 != v2) { 11323 return (v1 > v2) ? -1 : 1; 11324 } 11325 v1 = r1.preferredOrder; 11326 v2 = r2.preferredOrder; 11327 if (v1 != v2) { 11328 return (v1 > v2) ? -1 : 1; 11329 } 11330 if (r1.isDefault != r2.isDefault) { 11331 return r1.isDefault ? -1 : 1; 11332 } 11333 v1 = r1.match; 11334 v2 = r2.match; 11335 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11336 if (v1 != v2) { 11337 return (v1 > v2) ? -1 : 1; 11338 } 11339 if (r1.system != r2.system) { 11340 return r1.system ? -1 : 1; 11341 } 11342 if (r1.activityInfo != null) { 11343 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11344 } 11345 if (r1.serviceInfo != null) { 11346 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11347 } 11348 if (r1.providerInfo != null) { 11349 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11350 } 11351 return 0; 11352 } 11353 }; 11354 11355 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11356 new Comparator<ProviderInfo>() { 11357 public int compare(ProviderInfo p1, ProviderInfo p2) { 11358 final int v1 = p1.initOrder; 11359 final int v2 = p2.initOrder; 11360 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11361 } 11362 }; 11363 11364 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11365 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11366 final int[] userIds) { 11367 mHandler.post(new Runnable() { 11368 @Override 11369 public void run() { 11370 try { 11371 final IActivityManager am = ActivityManagerNative.getDefault(); 11372 if (am == null) return; 11373 final int[] resolvedUserIds; 11374 if (userIds == null) { 11375 resolvedUserIds = am.getRunningUserIds(); 11376 } else { 11377 resolvedUserIds = userIds; 11378 } 11379 for (int id : resolvedUserIds) { 11380 final Intent intent = new Intent(action, 11381 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11382 if (extras != null) { 11383 intent.putExtras(extras); 11384 } 11385 if (targetPkg != null) { 11386 intent.setPackage(targetPkg); 11387 } 11388 // Modify the UID when posting to other users 11389 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11390 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11391 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11392 intent.putExtra(Intent.EXTRA_UID, uid); 11393 } 11394 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11395 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11396 if (DEBUG_BROADCASTS) { 11397 RuntimeException here = new RuntimeException("here"); 11398 here.fillInStackTrace(); 11399 Slog.d(TAG, "Sending to user " + id + ": " 11400 + intent.toShortString(false, true, false, false) 11401 + " " + intent.getExtras(), here); 11402 } 11403 am.broadcastIntent(null, intent, null, finishedReceiver, 11404 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11405 null, finishedReceiver != null, false, id); 11406 } 11407 } catch (RemoteException ex) { 11408 } 11409 } 11410 }); 11411 } 11412 11413 /** 11414 * Check if the external storage media is available. This is true if there 11415 * is a mounted external storage medium or if the external storage is 11416 * emulated. 11417 */ 11418 private boolean isExternalMediaAvailable() { 11419 return mMediaMounted || Environment.isExternalStorageEmulated(); 11420 } 11421 11422 @Override 11423 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11424 // writer 11425 synchronized (mPackages) { 11426 if (!isExternalMediaAvailable()) { 11427 // If the external storage is no longer mounted at this point, 11428 // the caller may not have been able to delete all of this 11429 // packages files and can not delete any more. Bail. 11430 return null; 11431 } 11432 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11433 if (lastPackage != null) { 11434 pkgs.remove(lastPackage); 11435 } 11436 if (pkgs.size() > 0) { 11437 return pkgs.get(0); 11438 } 11439 } 11440 return null; 11441 } 11442 11443 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11444 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11445 userId, andCode ? 1 : 0, packageName); 11446 if (mSystemReady) { 11447 msg.sendToTarget(); 11448 } else { 11449 if (mPostSystemReadyMessages == null) { 11450 mPostSystemReadyMessages = new ArrayList<>(); 11451 } 11452 mPostSystemReadyMessages.add(msg); 11453 } 11454 } 11455 11456 void startCleaningPackages() { 11457 // reader 11458 if (!isExternalMediaAvailable()) { 11459 return; 11460 } 11461 synchronized (mPackages) { 11462 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11463 return; 11464 } 11465 } 11466 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11467 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11468 IActivityManager am = ActivityManagerNative.getDefault(); 11469 if (am != null) { 11470 try { 11471 am.startService(null, intent, null, mContext.getOpPackageName(), 11472 UserHandle.USER_SYSTEM); 11473 } catch (RemoteException e) { 11474 } 11475 } 11476 } 11477 11478 @Override 11479 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11480 int installFlags, String installerPackageName, int userId) { 11481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11482 11483 final int callingUid = Binder.getCallingUid(); 11484 enforceCrossUserPermission(callingUid, userId, 11485 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11486 11487 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11488 try { 11489 if (observer != null) { 11490 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11491 } 11492 } catch (RemoteException re) { 11493 } 11494 return; 11495 } 11496 11497 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11498 installFlags |= PackageManager.INSTALL_FROM_ADB; 11499 11500 } else { 11501 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11502 // about installerPackageName. 11503 11504 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11505 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11506 } 11507 11508 UserHandle user; 11509 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11510 user = UserHandle.ALL; 11511 } else { 11512 user = new UserHandle(userId); 11513 } 11514 11515 // Only system components can circumvent runtime permissions when installing. 11516 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11517 && mContext.checkCallingOrSelfPermission(Manifest.permission 11518 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11519 throw new SecurityException("You need the " 11520 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11521 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11522 } 11523 11524 final File originFile = new File(originPath); 11525 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11526 11527 final Message msg = mHandler.obtainMessage(INIT_COPY); 11528 final VerificationInfo verificationInfo = new VerificationInfo( 11529 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11530 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11531 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11532 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11533 null /*certificates*/); 11534 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11535 msg.obj = params; 11536 11537 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11538 System.identityHashCode(msg.obj)); 11539 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11540 System.identityHashCode(msg.obj)); 11541 11542 mHandler.sendMessage(msg); 11543 } 11544 11545 void installStage(String packageName, File stagedDir, String stagedCid, 11546 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11547 String installerPackageName, int installerUid, UserHandle user, 11548 Certificate[][] certificates) { 11549 if (DEBUG_EPHEMERAL) { 11550 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11551 Slog.d(TAG, "Ephemeral install of " + packageName); 11552 } 11553 } 11554 final VerificationInfo verificationInfo = new VerificationInfo( 11555 sessionParams.originatingUri, sessionParams.referrerUri, 11556 sessionParams.originatingUid, installerUid); 11557 11558 final OriginInfo origin; 11559 if (stagedDir != null) { 11560 origin = OriginInfo.fromStagedFile(stagedDir); 11561 } else { 11562 origin = OriginInfo.fromStagedContainer(stagedCid); 11563 } 11564 11565 final Message msg = mHandler.obtainMessage(INIT_COPY); 11566 final InstallParams params = new InstallParams(origin, null, observer, 11567 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11568 verificationInfo, user, sessionParams.abiOverride, 11569 sessionParams.grantedRuntimePermissions, certificates); 11570 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11571 msg.obj = params; 11572 11573 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11574 System.identityHashCode(msg.obj)); 11575 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11576 System.identityHashCode(msg.obj)); 11577 11578 mHandler.sendMessage(msg); 11579 } 11580 11581 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11582 int userId) { 11583 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11584 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11585 } 11586 11587 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11588 int appId, int userId) { 11589 Bundle extras = new Bundle(1); 11590 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11591 11592 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11593 packageName, extras, 0, null, null, new int[] {userId}); 11594 try { 11595 IActivityManager am = ActivityManagerNative.getDefault(); 11596 if (isSystem && am.isUserRunning(userId, 0)) { 11597 // The just-installed/enabled app is bundled on the system, so presumed 11598 // to be able to run automatically without needing an explicit launch. 11599 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11600 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11601 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11602 .setPackage(packageName); 11603 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11604 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11605 } 11606 } catch (RemoteException e) { 11607 // shouldn't happen 11608 Slog.w(TAG, "Unable to bootstrap installed package", e); 11609 } 11610 } 11611 11612 @Override 11613 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11614 int userId) { 11615 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11616 PackageSetting pkgSetting; 11617 final int uid = Binder.getCallingUid(); 11618 enforceCrossUserPermission(uid, userId, 11619 true /* requireFullPermission */, true /* checkShell */, 11620 "setApplicationHiddenSetting for user " + userId); 11621 11622 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11623 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11624 return false; 11625 } 11626 11627 long callingId = Binder.clearCallingIdentity(); 11628 try { 11629 boolean sendAdded = false; 11630 boolean sendRemoved = false; 11631 // writer 11632 synchronized (mPackages) { 11633 pkgSetting = mSettings.mPackages.get(packageName); 11634 if (pkgSetting == null) { 11635 return false; 11636 } 11637 if (pkgSetting.getHidden(userId) != hidden) { 11638 pkgSetting.setHidden(hidden, userId); 11639 mSettings.writePackageRestrictionsLPr(userId); 11640 if (hidden) { 11641 sendRemoved = true; 11642 } else { 11643 sendAdded = true; 11644 } 11645 } 11646 } 11647 if (sendAdded) { 11648 sendPackageAddedForUser(packageName, pkgSetting, userId); 11649 return true; 11650 } 11651 if (sendRemoved) { 11652 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11653 "hiding pkg"); 11654 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11655 return true; 11656 } 11657 } finally { 11658 Binder.restoreCallingIdentity(callingId); 11659 } 11660 return false; 11661 } 11662 11663 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11664 int userId) { 11665 final PackageRemovedInfo info = new PackageRemovedInfo(); 11666 info.removedPackage = packageName; 11667 info.removedUsers = new int[] {userId}; 11668 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11669 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11670 } 11671 11672 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11673 if (pkgList.length > 0) { 11674 Bundle extras = new Bundle(1); 11675 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11676 11677 sendPackageBroadcast( 11678 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11679 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11680 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11681 new int[] {userId}); 11682 } 11683 } 11684 11685 /** 11686 * Returns true if application is not found or there was an error. Otherwise it returns 11687 * the hidden state of the package for the given user. 11688 */ 11689 @Override 11690 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11692 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11693 true /* requireFullPermission */, false /* checkShell */, 11694 "getApplicationHidden for user " + userId); 11695 PackageSetting pkgSetting; 11696 long callingId = Binder.clearCallingIdentity(); 11697 try { 11698 // writer 11699 synchronized (mPackages) { 11700 pkgSetting = mSettings.mPackages.get(packageName); 11701 if (pkgSetting == null) { 11702 return true; 11703 } 11704 return pkgSetting.getHidden(userId); 11705 } 11706 } finally { 11707 Binder.restoreCallingIdentity(callingId); 11708 } 11709 } 11710 11711 /** 11712 * @hide 11713 */ 11714 @Override 11715 public int installExistingPackageAsUser(String packageName, int userId) { 11716 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11717 null); 11718 PackageSetting pkgSetting; 11719 final int uid = Binder.getCallingUid(); 11720 enforceCrossUserPermission(uid, userId, 11721 true /* requireFullPermission */, true /* checkShell */, 11722 "installExistingPackage for user " + userId); 11723 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11724 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11725 } 11726 11727 long callingId = Binder.clearCallingIdentity(); 11728 try { 11729 boolean installed = false; 11730 11731 // writer 11732 synchronized (mPackages) { 11733 pkgSetting = mSettings.mPackages.get(packageName); 11734 if (pkgSetting == null) { 11735 return PackageManager.INSTALL_FAILED_INVALID_URI; 11736 } 11737 if (!pkgSetting.getInstalled(userId)) { 11738 pkgSetting.setInstalled(true, userId); 11739 pkgSetting.setHidden(false, userId); 11740 mSettings.writePackageRestrictionsLPr(userId); 11741 installed = true; 11742 } 11743 } 11744 11745 if (installed) { 11746 if (pkgSetting.pkg != null) { 11747 synchronized (mInstallLock) { 11748 // We don't need to freeze for a brand new install 11749 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11750 } 11751 } 11752 sendPackageAddedForUser(packageName, pkgSetting, userId); 11753 } 11754 } finally { 11755 Binder.restoreCallingIdentity(callingId); 11756 } 11757 11758 return PackageManager.INSTALL_SUCCEEDED; 11759 } 11760 11761 boolean isUserRestricted(int userId, String restrictionKey) { 11762 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11763 if (restrictions.getBoolean(restrictionKey, false)) { 11764 Log.w(TAG, "User is restricted: " + restrictionKey); 11765 return true; 11766 } 11767 return false; 11768 } 11769 11770 @Override 11771 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11772 int userId) { 11773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11774 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11775 true /* requireFullPermission */, true /* checkShell */, 11776 "setPackagesSuspended for user " + userId); 11777 11778 if (ArrayUtils.isEmpty(packageNames)) { 11779 return packageNames; 11780 } 11781 11782 // List of package names for whom the suspended state has changed. 11783 List<String> changedPackages = new ArrayList<>(packageNames.length); 11784 // List of package names for whom the suspended state is not set as requested in this 11785 // method. 11786 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11787 long callingId = Binder.clearCallingIdentity(); 11788 try { 11789 for (int i = 0; i < packageNames.length; i++) { 11790 String packageName = packageNames[i]; 11791 boolean changed = false; 11792 final int appId; 11793 synchronized (mPackages) { 11794 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11795 if (pkgSetting == null) { 11796 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11797 + "\". Skipping suspending/un-suspending."); 11798 unactionedPackages.add(packageName); 11799 continue; 11800 } 11801 appId = pkgSetting.appId; 11802 if (pkgSetting.getSuspended(userId) != suspended) { 11803 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11804 unactionedPackages.add(packageName); 11805 continue; 11806 } 11807 pkgSetting.setSuspended(suspended, userId); 11808 mSettings.writePackageRestrictionsLPr(userId); 11809 changed = true; 11810 changedPackages.add(packageName); 11811 } 11812 } 11813 11814 if (changed && suspended) { 11815 killApplication(packageName, UserHandle.getUid(userId, appId), 11816 "suspending package"); 11817 } 11818 } 11819 } finally { 11820 Binder.restoreCallingIdentity(callingId); 11821 } 11822 11823 if (!changedPackages.isEmpty()) { 11824 sendPackagesSuspendedForUser(changedPackages.toArray( 11825 new String[changedPackages.size()]), userId, suspended); 11826 } 11827 11828 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11829 } 11830 11831 @Override 11832 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11833 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11834 true /* requireFullPermission */, false /* checkShell */, 11835 "isPackageSuspendedForUser for user " + userId); 11836 synchronized (mPackages) { 11837 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11838 if (pkgSetting == null) { 11839 throw new IllegalArgumentException("Unknown target package: " + packageName); 11840 } 11841 return pkgSetting.getSuspended(userId); 11842 } 11843 } 11844 11845 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11846 if (isPackageDeviceAdmin(packageName, userId)) { 11847 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11848 + "\": has an active device admin"); 11849 return false; 11850 } 11851 11852 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11853 if (packageName.equals(activeLauncherPackageName)) { 11854 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11855 + "\": contains the active launcher"); 11856 return false; 11857 } 11858 11859 if (packageName.equals(mRequiredInstallerPackage)) { 11860 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11861 + "\": required for package installation"); 11862 return false; 11863 } 11864 11865 if (packageName.equals(mRequiredVerifierPackage)) { 11866 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11867 + "\": required for package verification"); 11868 return false; 11869 } 11870 11871 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11872 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11873 + "\": is the default dialer"); 11874 return false; 11875 } 11876 11877 return true; 11878 } 11879 11880 private String getActiveLauncherPackageName(int userId) { 11881 Intent intent = new Intent(Intent.ACTION_MAIN); 11882 intent.addCategory(Intent.CATEGORY_HOME); 11883 ResolveInfo resolveInfo = resolveIntent( 11884 intent, 11885 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11886 PackageManager.MATCH_DEFAULT_ONLY, 11887 userId); 11888 11889 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11890 } 11891 11892 private String getDefaultDialerPackageName(int userId) { 11893 synchronized (mPackages) { 11894 return mSettings.getDefaultDialerPackageNameLPw(userId); 11895 } 11896 } 11897 11898 @Override 11899 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11900 mContext.enforceCallingOrSelfPermission( 11901 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11902 "Only package verification agents can verify applications"); 11903 11904 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11905 final PackageVerificationResponse response = new PackageVerificationResponse( 11906 verificationCode, Binder.getCallingUid()); 11907 msg.arg1 = id; 11908 msg.obj = response; 11909 mHandler.sendMessage(msg); 11910 } 11911 11912 @Override 11913 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11914 long millisecondsToDelay) { 11915 mContext.enforceCallingOrSelfPermission( 11916 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11917 "Only package verification agents can extend verification timeouts"); 11918 11919 final PackageVerificationState state = mPendingVerification.get(id); 11920 final PackageVerificationResponse response = new PackageVerificationResponse( 11921 verificationCodeAtTimeout, Binder.getCallingUid()); 11922 11923 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11924 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11925 } 11926 if (millisecondsToDelay < 0) { 11927 millisecondsToDelay = 0; 11928 } 11929 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11930 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11931 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11932 } 11933 11934 if ((state != null) && !state.timeoutExtended()) { 11935 state.extendTimeout(); 11936 11937 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11938 msg.arg1 = id; 11939 msg.obj = response; 11940 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11941 } 11942 } 11943 11944 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11945 int verificationCode, UserHandle user) { 11946 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11947 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11948 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11949 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11950 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11951 11952 mContext.sendBroadcastAsUser(intent, user, 11953 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11954 } 11955 11956 private ComponentName matchComponentForVerifier(String packageName, 11957 List<ResolveInfo> receivers) { 11958 ActivityInfo targetReceiver = null; 11959 11960 final int NR = receivers.size(); 11961 for (int i = 0; i < NR; i++) { 11962 final ResolveInfo info = receivers.get(i); 11963 if (info.activityInfo == null) { 11964 continue; 11965 } 11966 11967 if (packageName.equals(info.activityInfo.packageName)) { 11968 targetReceiver = info.activityInfo; 11969 break; 11970 } 11971 } 11972 11973 if (targetReceiver == null) { 11974 return null; 11975 } 11976 11977 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11978 } 11979 11980 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11981 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11982 if (pkgInfo.verifiers.length == 0) { 11983 return null; 11984 } 11985 11986 final int N = pkgInfo.verifiers.length; 11987 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11988 for (int i = 0; i < N; i++) { 11989 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11990 11991 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11992 receivers); 11993 if (comp == null) { 11994 continue; 11995 } 11996 11997 final int verifierUid = getUidForVerifier(verifierInfo); 11998 if (verifierUid == -1) { 11999 continue; 12000 } 12001 12002 if (DEBUG_VERIFY) { 12003 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12004 + " with the correct signature"); 12005 } 12006 sufficientVerifiers.add(comp); 12007 verificationState.addSufficientVerifier(verifierUid); 12008 } 12009 12010 return sufficientVerifiers; 12011 } 12012 12013 private int getUidForVerifier(VerifierInfo verifierInfo) { 12014 synchronized (mPackages) { 12015 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12016 if (pkg == null) { 12017 return -1; 12018 } else if (pkg.mSignatures.length != 1) { 12019 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12020 + " has more than one signature; ignoring"); 12021 return -1; 12022 } 12023 12024 /* 12025 * If the public key of the package's signature does not match 12026 * our expected public key, then this is a different package and 12027 * we should skip. 12028 */ 12029 12030 final byte[] expectedPublicKey; 12031 try { 12032 final Signature verifierSig = pkg.mSignatures[0]; 12033 final PublicKey publicKey = verifierSig.getPublicKey(); 12034 expectedPublicKey = publicKey.getEncoded(); 12035 } catch (CertificateException e) { 12036 return -1; 12037 } 12038 12039 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12040 12041 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12042 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12043 + " does not have the expected public key; ignoring"); 12044 return -1; 12045 } 12046 12047 return pkg.applicationInfo.uid; 12048 } 12049 } 12050 12051 @Override 12052 public void finishPackageInstall(int token, boolean didLaunch) { 12053 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12054 12055 if (DEBUG_INSTALL) { 12056 Slog.v(TAG, "BM finishing package install for " + token); 12057 } 12058 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12059 12060 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12061 mHandler.sendMessage(msg); 12062 } 12063 12064 /** 12065 * Get the verification agent timeout. 12066 * 12067 * @return verification timeout in milliseconds 12068 */ 12069 private long getVerificationTimeout() { 12070 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12071 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12072 DEFAULT_VERIFICATION_TIMEOUT); 12073 } 12074 12075 /** 12076 * Get the default verification agent response code. 12077 * 12078 * @return default verification response code 12079 */ 12080 private int getDefaultVerificationResponse() { 12081 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12082 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12083 DEFAULT_VERIFICATION_RESPONSE); 12084 } 12085 12086 /** 12087 * Check whether or not package verification has been enabled. 12088 * 12089 * @return true if verification should be performed 12090 */ 12091 private boolean isVerificationEnabled(int userId, int installFlags) { 12092 if (!DEFAULT_VERIFY_ENABLE) { 12093 return false; 12094 } 12095 // Ephemeral apps don't get the full verification treatment 12096 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12097 if (DEBUG_EPHEMERAL) { 12098 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12099 } 12100 return false; 12101 } 12102 12103 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12104 12105 // Check if installing from ADB 12106 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12107 // Do not run verification in a test harness environment 12108 if (ActivityManager.isRunningInTestHarness()) { 12109 return false; 12110 } 12111 if (ensureVerifyAppsEnabled) { 12112 return true; 12113 } 12114 // Check if the developer does not want package verification for ADB installs 12115 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12116 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12117 return false; 12118 } 12119 } 12120 12121 if (ensureVerifyAppsEnabled) { 12122 return true; 12123 } 12124 12125 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12126 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12127 } 12128 12129 @Override 12130 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12131 throws RemoteException { 12132 mContext.enforceCallingOrSelfPermission( 12133 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12134 "Only intentfilter verification agents can verify applications"); 12135 12136 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12137 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12138 Binder.getCallingUid(), verificationCode, failedDomains); 12139 msg.arg1 = id; 12140 msg.obj = response; 12141 mHandler.sendMessage(msg); 12142 } 12143 12144 @Override 12145 public int getIntentVerificationStatus(String packageName, int userId) { 12146 synchronized (mPackages) { 12147 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12148 } 12149 } 12150 12151 @Override 12152 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12153 mContext.enforceCallingOrSelfPermission( 12154 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12155 12156 boolean result = false; 12157 synchronized (mPackages) { 12158 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12159 } 12160 if (result) { 12161 scheduleWritePackageRestrictionsLocked(userId); 12162 } 12163 return result; 12164 } 12165 12166 @Override 12167 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12168 String packageName) { 12169 synchronized (mPackages) { 12170 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12171 } 12172 } 12173 12174 @Override 12175 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12176 if (TextUtils.isEmpty(packageName)) { 12177 return ParceledListSlice.emptyList(); 12178 } 12179 synchronized (mPackages) { 12180 PackageParser.Package pkg = mPackages.get(packageName); 12181 if (pkg == null || pkg.activities == null) { 12182 return ParceledListSlice.emptyList(); 12183 } 12184 final int count = pkg.activities.size(); 12185 ArrayList<IntentFilter> result = new ArrayList<>(); 12186 for (int n=0; n<count; n++) { 12187 PackageParser.Activity activity = pkg.activities.get(n); 12188 if (activity.intents != null && activity.intents.size() > 0) { 12189 result.addAll(activity.intents); 12190 } 12191 } 12192 return new ParceledListSlice<>(result); 12193 } 12194 } 12195 12196 @Override 12197 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12198 mContext.enforceCallingOrSelfPermission( 12199 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12200 12201 synchronized (mPackages) { 12202 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12203 if (packageName != null) { 12204 result |= updateIntentVerificationStatus(packageName, 12205 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12206 userId); 12207 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12208 packageName, userId); 12209 } 12210 return result; 12211 } 12212 } 12213 12214 @Override 12215 public String getDefaultBrowserPackageName(int userId) { 12216 synchronized (mPackages) { 12217 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12218 } 12219 } 12220 12221 /** 12222 * Get the "allow unknown sources" setting. 12223 * 12224 * @return the current "allow unknown sources" setting 12225 */ 12226 private int getUnknownSourcesSettings() { 12227 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12228 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12229 -1); 12230 } 12231 12232 @Override 12233 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12234 final int uid = Binder.getCallingUid(); 12235 // writer 12236 synchronized (mPackages) { 12237 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12238 if (targetPackageSetting == null) { 12239 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12240 } 12241 12242 PackageSetting installerPackageSetting; 12243 if (installerPackageName != null) { 12244 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12245 if (installerPackageSetting == null) { 12246 throw new IllegalArgumentException("Unknown installer package: " 12247 + installerPackageName); 12248 } 12249 } else { 12250 installerPackageSetting = null; 12251 } 12252 12253 Signature[] callerSignature; 12254 Object obj = mSettings.getUserIdLPr(uid); 12255 if (obj != null) { 12256 if (obj instanceof SharedUserSetting) { 12257 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12258 } else if (obj instanceof PackageSetting) { 12259 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12260 } else { 12261 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12262 } 12263 } else { 12264 throw new SecurityException("Unknown calling UID: " + uid); 12265 } 12266 12267 // Verify: can't set installerPackageName to a package that is 12268 // not signed with the same cert as the caller. 12269 if (installerPackageSetting != null) { 12270 if (compareSignatures(callerSignature, 12271 installerPackageSetting.signatures.mSignatures) 12272 != PackageManager.SIGNATURE_MATCH) { 12273 throw new SecurityException( 12274 "Caller does not have same cert as new installer package " 12275 + installerPackageName); 12276 } 12277 } 12278 12279 // Verify: if target already has an installer package, it must 12280 // be signed with the same cert as the caller. 12281 if (targetPackageSetting.installerPackageName != null) { 12282 PackageSetting setting = mSettings.mPackages.get( 12283 targetPackageSetting.installerPackageName); 12284 // If the currently set package isn't valid, then it's always 12285 // okay to change it. 12286 if (setting != null) { 12287 if (compareSignatures(callerSignature, 12288 setting.signatures.mSignatures) 12289 != PackageManager.SIGNATURE_MATCH) { 12290 throw new SecurityException( 12291 "Caller does not have same cert as old installer package " 12292 + targetPackageSetting.installerPackageName); 12293 } 12294 } 12295 } 12296 12297 // Okay! 12298 targetPackageSetting.installerPackageName = installerPackageName; 12299 if (installerPackageName != null) { 12300 mSettings.mInstallerPackages.add(installerPackageName); 12301 } 12302 scheduleWriteSettingsLocked(); 12303 } 12304 } 12305 12306 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12307 // Queue up an async operation since the package installation may take a little while. 12308 mHandler.post(new Runnable() { 12309 public void run() { 12310 mHandler.removeCallbacks(this); 12311 // Result object to be returned 12312 PackageInstalledInfo res = new PackageInstalledInfo(); 12313 res.setReturnCode(currentStatus); 12314 res.uid = -1; 12315 res.pkg = null; 12316 res.removedInfo = null; 12317 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12318 args.doPreInstall(res.returnCode); 12319 synchronized (mInstallLock) { 12320 installPackageTracedLI(args, res); 12321 } 12322 args.doPostInstall(res.returnCode, res.uid); 12323 } 12324 12325 // A restore should be performed at this point if (a) the install 12326 // succeeded, (b) the operation is not an update, and (c) the new 12327 // package has not opted out of backup participation. 12328 final boolean update = res.removedInfo != null 12329 && res.removedInfo.removedPackage != null; 12330 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12331 boolean doRestore = !update 12332 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12333 12334 // Set up the post-install work request bookkeeping. This will be used 12335 // and cleaned up by the post-install event handling regardless of whether 12336 // there's a restore pass performed. Token values are >= 1. 12337 int token; 12338 if (mNextInstallToken < 0) mNextInstallToken = 1; 12339 token = mNextInstallToken++; 12340 12341 PostInstallData data = new PostInstallData(args, res); 12342 mRunningInstalls.put(token, data); 12343 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12344 12345 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12346 // Pass responsibility to the Backup Manager. It will perform a 12347 // restore if appropriate, then pass responsibility back to the 12348 // Package Manager to run the post-install observer callbacks 12349 // and broadcasts. 12350 IBackupManager bm = IBackupManager.Stub.asInterface( 12351 ServiceManager.getService(Context.BACKUP_SERVICE)); 12352 if (bm != null) { 12353 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12354 + " to BM for possible restore"); 12355 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12356 try { 12357 // TODO: http://b/22388012 12358 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12359 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12360 } else { 12361 doRestore = false; 12362 } 12363 } catch (RemoteException e) { 12364 // can't happen; the backup manager is local 12365 } catch (Exception e) { 12366 Slog.e(TAG, "Exception trying to enqueue restore", e); 12367 doRestore = false; 12368 } 12369 } else { 12370 Slog.e(TAG, "Backup Manager not found!"); 12371 doRestore = false; 12372 } 12373 } 12374 12375 if (!doRestore) { 12376 // No restore possible, or the Backup Manager was mysteriously not 12377 // available -- just fire the post-install work request directly. 12378 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12379 12380 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12381 12382 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12383 mHandler.sendMessage(msg); 12384 } 12385 } 12386 }); 12387 } 12388 12389 /** 12390 * Callback from PackageSettings whenever an app is first transitioned out of the 12391 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12392 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12393 * here whether the app is the target of an ongoing install, and only send the 12394 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12395 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12396 * handling. 12397 */ 12398 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12399 // Serialize this with the rest of the install-process message chain. In the 12400 // restore-at-install case, this Runnable will necessarily run before the 12401 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12402 // are coherent. In the non-restore case, the app has already completed install 12403 // and been launched through some other means, so it is not in a problematic 12404 // state for observers to see the FIRST_LAUNCH signal. 12405 mHandler.post(new Runnable() { 12406 @Override 12407 public void run() { 12408 for (int i = 0; i < mRunningInstalls.size(); i++) { 12409 final PostInstallData data = mRunningInstalls.valueAt(i); 12410 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12411 // right package; but is it for the right user? 12412 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12413 if (userId == data.res.newUsers[uIndex]) { 12414 if (DEBUG_BACKUP) { 12415 Slog.i(TAG, "Package " + pkgName 12416 + " being restored so deferring FIRST_LAUNCH"); 12417 } 12418 return; 12419 } 12420 } 12421 } 12422 } 12423 // didn't find it, so not being restored 12424 if (DEBUG_BACKUP) { 12425 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12426 } 12427 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12428 } 12429 }); 12430 } 12431 12432 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12433 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12434 installerPkg, null, userIds); 12435 } 12436 12437 private abstract class HandlerParams { 12438 private static final int MAX_RETRIES = 4; 12439 12440 /** 12441 * Number of times startCopy() has been attempted and had a non-fatal 12442 * error. 12443 */ 12444 private int mRetries = 0; 12445 12446 /** User handle for the user requesting the information or installation. */ 12447 private final UserHandle mUser; 12448 String traceMethod; 12449 int traceCookie; 12450 12451 HandlerParams(UserHandle user) { 12452 mUser = user; 12453 } 12454 12455 UserHandle getUser() { 12456 return mUser; 12457 } 12458 12459 HandlerParams setTraceMethod(String traceMethod) { 12460 this.traceMethod = traceMethod; 12461 return this; 12462 } 12463 12464 HandlerParams setTraceCookie(int traceCookie) { 12465 this.traceCookie = traceCookie; 12466 return this; 12467 } 12468 12469 final boolean startCopy() { 12470 boolean res; 12471 try { 12472 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12473 12474 if (++mRetries > MAX_RETRIES) { 12475 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12476 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12477 handleServiceError(); 12478 return false; 12479 } else { 12480 handleStartCopy(); 12481 res = true; 12482 } 12483 } catch (RemoteException e) { 12484 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12485 mHandler.sendEmptyMessage(MCS_RECONNECT); 12486 res = false; 12487 } 12488 handleReturnCode(); 12489 return res; 12490 } 12491 12492 final void serviceError() { 12493 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12494 handleServiceError(); 12495 handleReturnCode(); 12496 } 12497 12498 abstract void handleStartCopy() throws RemoteException; 12499 abstract void handleServiceError(); 12500 abstract void handleReturnCode(); 12501 } 12502 12503 class MeasureParams extends HandlerParams { 12504 private final PackageStats mStats; 12505 private boolean mSuccess; 12506 12507 private final IPackageStatsObserver mObserver; 12508 12509 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12510 super(new UserHandle(stats.userHandle)); 12511 mObserver = observer; 12512 mStats = stats; 12513 } 12514 12515 @Override 12516 public String toString() { 12517 return "MeasureParams{" 12518 + Integer.toHexString(System.identityHashCode(this)) 12519 + " " + mStats.packageName + "}"; 12520 } 12521 12522 @Override 12523 void handleStartCopy() throws RemoteException { 12524 synchronized (mInstallLock) { 12525 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12526 } 12527 12528 if (mSuccess) { 12529 boolean mounted = false; 12530 try { 12531 final String status = Environment.getExternalStorageState(); 12532 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12533 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12534 } catch (Exception e) { 12535 } 12536 12537 if (mounted) { 12538 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12539 12540 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12541 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12542 12543 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12544 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12545 12546 // Always subtract cache size, since it's a subdirectory 12547 mStats.externalDataSize -= mStats.externalCacheSize; 12548 12549 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12550 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12551 12552 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12553 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12554 } 12555 } 12556 } 12557 12558 @Override 12559 void handleReturnCode() { 12560 if (mObserver != null) { 12561 try { 12562 mObserver.onGetStatsCompleted(mStats, mSuccess); 12563 } catch (RemoteException e) { 12564 Slog.i(TAG, "Observer no longer exists."); 12565 } 12566 } 12567 } 12568 12569 @Override 12570 void handleServiceError() { 12571 Slog.e(TAG, "Could not measure application " + mStats.packageName 12572 + " external storage"); 12573 } 12574 } 12575 12576 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12577 throws RemoteException { 12578 long result = 0; 12579 for (File path : paths) { 12580 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12581 } 12582 return result; 12583 } 12584 12585 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12586 for (File path : paths) { 12587 try { 12588 mcs.clearDirectory(path.getAbsolutePath()); 12589 } catch (RemoteException e) { 12590 } 12591 } 12592 } 12593 12594 static class OriginInfo { 12595 /** 12596 * Location where install is coming from, before it has been 12597 * copied/renamed into place. This could be a single monolithic APK 12598 * file, or a cluster directory. This location may be untrusted. 12599 */ 12600 final File file; 12601 final String cid; 12602 12603 /** 12604 * Flag indicating that {@link #file} or {@link #cid} has already been 12605 * staged, meaning downstream users don't need to defensively copy the 12606 * contents. 12607 */ 12608 final boolean staged; 12609 12610 /** 12611 * Flag indicating that {@link #file} or {@link #cid} is an already 12612 * installed app that is being moved. 12613 */ 12614 final boolean existing; 12615 12616 final String resolvedPath; 12617 final File resolvedFile; 12618 12619 static OriginInfo fromNothing() { 12620 return new OriginInfo(null, null, false, false); 12621 } 12622 12623 static OriginInfo fromUntrustedFile(File file) { 12624 return new OriginInfo(file, null, false, false); 12625 } 12626 12627 static OriginInfo fromExistingFile(File file) { 12628 return new OriginInfo(file, null, false, true); 12629 } 12630 12631 static OriginInfo fromStagedFile(File file) { 12632 return new OriginInfo(file, null, true, false); 12633 } 12634 12635 static OriginInfo fromStagedContainer(String cid) { 12636 return new OriginInfo(null, cid, true, false); 12637 } 12638 12639 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12640 this.file = file; 12641 this.cid = cid; 12642 this.staged = staged; 12643 this.existing = existing; 12644 12645 if (cid != null) { 12646 resolvedPath = PackageHelper.getSdDir(cid); 12647 resolvedFile = new File(resolvedPath); 12648 } else if (file != null) { 12649 resolvedPath = file.getAbsolutePath(); 12650 resolvedFile = file; 12651 } else { 12652 resolvedPath = null; 12653 resolvedFile = null; 12654 } 12655 } 12656 } 12657 12658 static class MoveInfo { 12659 final int moveId; 12660 final String fromUuid; 12661 final String toUuid; 12662 final String packageName; 12663 final String dataAppName; 12664 final int appId; 12665 final String seinfo; 12666 final int targetSdkVersion; 12667 12668 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12669 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12670 this.moveId = moveId; 12671 this.fromUuid = fromUuid; 12672 this.toUuid = toUuid; 12673 this.packageName = packageName; 12674 this.dataAppName = dataAppName; 12675 this.appId = appId; 12676 this.seinfo = seinfo; 12677 this.targetSdkVersion = targetSdkVersion; 12678 } 12679 } 12680 12681 static class VerificationInfo { 12682 /** A constant used to indicate that a uid value is not present. */ 12683 public static final int NO_UID = -1; 12684 12685 /** URI referencing where the package was downloaded from. */ 12686 final Uri originatingUri; 12687 12688 /** HTTP referrer URI associated with the originatingURI. */ 12689 final Uri referrer; 12690 12691 /** UID of the application that the install request originated from. */ 12692 final int originatingUid; 12693 12694 /** UID of application requesting the install */ 12695 final int installerUid; 12696 12697 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12698 this.originatingUri = originatingUri; 12699 this.referrer = referrer; 12700 this.originatingUid = originatingUid; 12701 this.installerUid = installerUid; 12702 } 12703 } 12704 12705 class InstallParams extends HandlerParams { 12706 final OriginInfo origin; 12707 final MoveInfo move; 12708 final IPackageInstallObserver2 observer; 12709 int installFlags; 12710 final String installerPackageName; 12711 final String volumeUuid; 12712 private InstallArgs mArgs; 12713 private int mRet; 12714 final String packageAbiOverride; 12715 final String[] grantedRuntimePermissions; 12716 final VerificationInfo verificationInfo; 12717 final Certificate[][] certificates; 12718 12719 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12720 int installFlags, String installerPackageName, String volumeUuid, 12721 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12722 String[] grantedPermissions, Certificate[][] certificates) { 12723 super(user); 12724 this.origin = origin; 12725 this.move = move; 12726 this.observer = observer; 12727 this.installFlags = installFlags; 12728 this.installerPackageName = installerPackageName; 12729 this.volumeUuid = volumeUuid; 12730 this.verificationInfo = verificationInfo; 12731 this.packageAbiOverride = packageAbiOverride; 12732 this.grantedRuntimePermissions = grantedPermissions; 12733 this.certificates = certificates; 12734 } 12735 12736 @Override 12737 public String toString() { 12738 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12739 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12740 } 12741 12742 private int installLocationPolicy(PackageInfoLite pkgLite) { 12743 String packageName = pkgLite.packageName; 12744 int installLocation = pkgLite.installLocation; 12745 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12746 // reader 12747 synchronized (mPackages) { 12748 // Currently installed package which the new package is attempting to replace or 12749 // null if no such package is installed. 12750 PackageParser.Package installedPkg = mPackages.get(packageName); 12751 // Package which currently owns the data which the new package will own if installed. 12752 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12753 // will be null whereas dataOwnerPkg will contain information about the package 12754 // which was uninstalled while keeping its data. 12755 PackageParser.Package dataOwnerPkg = installedPkg; 12756 if (dataOwnerPkg == null) { 12757 PackageSetting ps = mSettings.mPackages.get(packageName); 12758 if (ps != null) { 12759 dataOwnerPkg = ps.pkg; 12760 } 12761 } 12762 12763 if (dataOwnerPkg != null) { 12764 // If installed, the package will get access to data left on the device by its 12765 // predecessor. As a security measure, this is permited only if this is not a 12766 // version downgrade or if the predecessor package is marked as debuggable and 12767 // a downgrade is explicitly requested. 12768 // 12769 // On debuggable platform builds, downgrades are permitted even for 12770 // non-debuggable packages to make testing easier. Debuggable platform builds do 12771 // not offer security guarantees and thus it's OK to disable some security 12772 // mechanisms to make debugging/testing easier on those builds. However, even on 12773 // debuggable builds downgrades of packages are permitted only if requested via 12774 // installFlags. This is because we aim to keep the behavior of debuggable 12775 // platform builds as close as possible to the behavior of non-debuggable 12776 // platform builds. 12777 final boolean downgradeRequested = 12778 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12779 final boolean packageDebuggable = 12780 (dataOwnerPkg.applicationInfo.flags 12781 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12782 final boolean downgradePermitted = 12783 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12784 if (!downgradePermitted) { 12785 try { 12786 checkDowngrade(dataOwnerPkg, pkgLite); 12787 } catch (PackageManagerException e) { 12788 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12789 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12790 } 12791 } 12792 } 12793 12794 if (installedPkg != null) { 12795 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12796 // Check for updated system application. 12797 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12798 if (onSd) { 12799 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12800 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12801 } 12802 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12803 } else { 12804 if (onSd) { 12805 // Install flag overrides everything. 12806 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12807 } 12808 // If current upgrade specifies particular preference 12809 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12810 // Application explicitly specified internal. 12811 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12812 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12813 // App explictly prefers external. Let policy decide 12814 } else { 12815 // Prefer previous location 12816 if (isExternal(installedPkg)) { 12817 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12818 } 12819 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12820 } 12821 } 12822 } else { 12823 // Invalid install. Return error code 12824 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12825 } 12826 } 12827 } 12828 // All the special cases have been taken care of. 12829 // Return result based on recommended install location. 12830 if (onSd) { 12831 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12832 } 12833 return pkgLite.recommendedInstallLocation; 12834 } 12835 12836 /* 12837 * Invoke remote method to get package information and install 12838 * location values. Override install location based on default 12839 * policy if needed and then create install arguments based 12840 * on the install location. 12841 */ 12842 public void handleStartCopy() throws RemoteException { 12843 int ret = PackageManager.INSTALL_SUCCEEDED; 12844 12845 // If we're already staged, we've firmly committed to an install location 12846 if (origin.staged) { 12847 if (origin.file != null) { 12848 installFlags |= PackageManager.INSTALL_INTERNAL; 12849 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12850 } else if (origin.cid != null) { 12851 installFlags |= PackageManager.INSTALL_EXTERNAL; 12852 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12853 } else { 12854 throw new IllegalStateException("Invalid stage location"); 12855 } 12856 } 12857 12858 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12859 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12860 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12861 PackageInfoLite pkgLite = null; 12862 12863 if (onInt && onSd) { 12864 // Check if both bits are set. 12865 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12866 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12867 } else if (onSd && ephemeral) { 12868 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12869 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12870 } else { 12871 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12872 packageAbiOverride); 12873 12874 if (DEBUG_EPHEMERAL && ephemeral) { 12875 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12876 } 12877 12878 /* 12879 * If we have too little free space, try to free cache 12880 * before giving up. 12881 */ 12882 if (!origin.staged && pkgLite.recommendedInstallLocation 12883 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12884 // TODO: focus freeing disk space on the target device 12885 final StorageManager storage = StorageManager.from(mContext); 12886 final long lowThreshold = storage.getStorageLowBytes( 12887 Environment.getDataDirectory()); 12888 12889 final long sizeBytes = mContainerService.calculateInstalledSize( 12890 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12891 12892 try { 12893 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12894 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12895 installFlags, packageAbiOverride); 12896 } catch (InstallerException e) { 12897 Slog.w(TAG, "Failed to free cache", e); 12898 } 12899 12900 /* 12901 * The cache free must have deleted the file we 12902 * downloaded to install. 12903 * 12904 * TODO: fix the "freeCache" call to not delete 12905 * the file we care about. 12906 */ 12907 if (pkgLite.recommendedInstallLocation 12908 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12909 pkgLite.recommendedInstallLocation 12910 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12911 } 12912 } 12913 } 12914 12915 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12916 int loc = pkgLite.recommendedInstallLocation; 12917 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12918 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12919 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12920 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12921 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12922 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12923 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12924 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12925 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12926 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12927 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12928 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12929 } else { 12930 // Override with defaults if needed. 12931 loc = installLocationPolicy(pkgLite); 12932 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12933 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12934 } else if (!onSd && !onInt) { 12935 // Override install location with flags 12936 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12937 // Set the flag to install on external media. 12938 installFlags |= PackageManager.INSTALL_EXTERNAL; 12939 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12940 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12941 if (DEBUG_EPHEMERAL) { 12942 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12943 } 12944 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12945 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12946 |PackageManager.INSTALL_INTERNAL); 12947 } else { 12948 // Make sure the flag for installing on external 12949 // media is unset 12950 installFlags |= PackageManager.INSTALL_INTERNAL; 12951 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12952 } 12953 } 12954 } 12955 } 12956 12957 final InstallArgs args = createInstallArgs(this); 12958 mArgs = args; 12959 12960 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12961 // TODO: http://b/22976637 12962 // Apps installed for "all" users use the device owner to verify the app 12963 UserHandle verifierUser = getUser(); 12964 if (verifierUser == UserHandle.ALL) { 12965 verifierUser = UserHandle.SYSTEM; 12966 } 12967 12968 /* 12969 * Determine if we have any installed package verifiers. If we 12970 * do, then we'll defer to them to verify the packages. 12971 */ 12972 final int requiredUid = mRequiredVerifierPackage == null ? -1 12973 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12974 verifierUser.getIdentifier()); 12975 if (!origin.existing && requiredUid != -1 12976 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12977 final Intent verification = new Intent( 12978 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12979 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12980 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12981 PACKAGE_MIME_TYPE); 12982 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12983 12984 // Query all live verifiers based on current user state 12985 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12986 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12987 12988 if (DEBUG_VERIFY) { 12989 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12990 + verification.toString() + " with " + pkgLite.verifiers.length 12991 + " optional verifiers"); 12992 } 12993 12994 final int verificationId = mPendingVerificationToken++; 12995 12996 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12997 12998 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12999 installerPackageName); 13000 13001 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13002 installFlags); 13003 13004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13005 pkgLite.packageName); 13006 13007 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13008 pkgLite.versionCode); 13009 13010 if (verificationInfo != null) { 13011 if (verificationInfo.originatingUri != null) { 13012 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13013 verificationInfo.originatingUri); 13014 } 13015 if (verificationInfo.referrer != null) { 13016 verification.putExtra(Intent.EXTRA_REFERRER, 13017 verificationInfo.referrer); 13018 } 13019 if (verificationInfo.originatingUid >= 0) { 13020 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13021 verificationInfo.originatingUid); 13022 } 13023 if (verificationInfo.installerUid >= 0) { 13024 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13025 verificationInfo.installerUid); 13026 } 13027 } 13028 13029 final PackageVerificationState verificationState = new PackageVerificationState( 13030 requiredUid, args); 13031 13032 mPendingVerification.append(verificationId, verificationState); 13033 13034 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13035 receivers, verificationState); 13036 13037 /* 13038 * If any sufficient verifiers were listed in the package 13039 * manifest, attempt to ask them. 13040 */ 13041 if (sufficientVerifiers != null) { 13042 final int N = sufficientVerifiers.size(); 13043 if (N == 0) { 13044 Slog.i(TAG, "Additional verifiers required, but none installed."); 13045 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13046 } else { 13047 for (int i = 0; i < N; i++) { 13048 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13049 13050 final Intent sufficientIntent = new Intent(verification); 13051 sufficientIntent.setComponent(verifierComponent); 13052 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13053 } 13054 } 13055 } 13056 13057 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13058 mRequiredVerifierPackage, receivers); 13059 if (ret == PackageManager.INSTALL_SUCCEEDED 13060 && mRequiredVerifierPackage != null) { 13061 Trace.asyncTraceBegin( 13062 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13063 /* 13064 * Send the intent to the required verification agent, 13065 * but only start the verification timeout after the 13066 * target BroadcastReceivers have run. 13067 */ 13068 verification.setComponent(requiredVerifierComponent); 13069 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13070 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13071 new BroadcastReceiver() { 13072 @Override 13073 public void onReceive(Context context, Intent intent) { 13074 final Message msg = mHandler 13075 .obtainMessage(CHECK_PENDING_VERIFICATION); 13076 msg.arg1 = verificationId; 13077 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13078 } 13079 }, null, 0, null, null); 13080 13081 /* 13082 * We don't want the copy to proceed until verification 13083 * succeeds, so null out this field. 13084 */ 13085 mArgs = null; 13086 } 13087 } else { 13088 /* 13089 * No package verification is enabled, so immediately start 13090 * the remote call to initiate copy using temporary file. 13091 */ 13092 ret = args.copyApk(mContainerService, true); 13093 } 13094 } 13095 13096 mRet = ret; 13097 } 13098 13099 @Override 13100 void handleReturnCode() { 13101 // If mArgs is null, then MCS couldn't be reached. When it 13102 // reconnects, it will try again to install. At that point, this 13103 // will succeed. 13104 if (mArgs != null) { 13105 processPendingInstall(mArgs, mRet); 13106 } 13107 } 13108 13109 @Override 13110 void handleServiceError() { 13111 mArgs = createInstallArgs(this); 13112 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13113 } 13114 13115 public boolean isForwardLocked() { 13116 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13117 } 13118 } 13119 13120 /** 13121 * Used during creation of InstallArgs 13122 * 13123 * @param installFlags package installation flags 13124 * @return true if should be installed on external storage 13125 */ 13126 private static boolean installOnExternalAsec(int installFlags) { 13127 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13128 return false; 13129 } 13130 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13131 return true; 13132 } 13133 return false; 13134 } 13135 13136 /** 13137 * Used during creation of InstallArgs 13138 * 13139 * @param installFlags package installation flags 13140 * @return true if should be installed as forward locked 13141 */ 13142 private static boolean installForwardLocked(int installFlags) { 13143 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13144 } 13145 13146 private InstallArgs createInstallArgs(InstallParams params) { 13147 if (params.move != null) { 13148 return new MoveInstallArgs(params); 13149 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13150 return new AsecInstallArgs(params); 13151 } else { 13152 return new FileInstallArgs(params); 13153 } 13154 } 13155 13156 /** 13157 * Create args that describe an existing installed package. Typically used 13158 * when cleaning up old installs, or used as a move source. 13159 */ 13160 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13161 String resourcePath, String[] instructionSets) { 13162 final boolean isInAsec; 13163 if (installOnExternalAsec(installFlags)) { 13164 /* Apps on SD card are always in ASEC containers. */ 13165 isInAsec = true; 13166 } else if (installForwardLocked(installFlags) 13167 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13168 /* 13169 * Forward-locked apps are only in ASEC containers if they're the 13170 * new style 13171 */ 13172 isInAsec = true; 13173 } else { 13174 isInAsec = false; 13175 } 13176 13177 if (isInAsec) { 13178 return new AsecInstallArgs(codePath, instructionSets, 13179 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13180 } else { 13181 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13182 } 13183 } 13184 13185 static abstract class InstallArgs { 13186 /** @see InstallParams#origin */ 13187 final OriginInfo origin; 13188 /** @see InstallParams#move */ 13189 final MoveInfo move; 13190 13191 final IPackageInstallObserver2 observer; 13192 // Always refers to PackageManager flags only 13193 final int installFlags; 13194 final String installerPackageName; 13195 final String volumeUuid; 13196 final UserHandle user; 13197 final String abiOverride; 13198 final String[] installGrantPermissions; 13199 /** If non-null, drop an async trace when the install completes */ 13200 final String traceMethod; 13201 final int traceCookie; 13202 final Certificate[][] certificates; 13203 13204 // The list of instruction sets supported by this app. This is currently 13205 // only used during the rmdex() phase to clean up resources. We can get rid of this 13206 // if we move dex files under the common app path. 13207 /* nullable */ String[] instructionSets; 13208 13209 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13210 int installFlags, String installerPackageName, String volumeUuid, 13211 UserHandle user, String[] instructionSets, 13212 String abiOverride, String[] installGrantPermissions, 13213 String traceMethod, int traceCookie, Certificate[][] certificates) { 13214 this.origin = origin; 13215 this.move = move; 13216 this.installFlags = installFlags; 13217 this.observer = observer; 13218 this.installerPackageName = installerPackageName; 13219 this.volumeUuid = volumeUuid; 13220 this.user = user; 13221 this.instructionSets = instructionSets; 13222 this.abiOverride = abiOverride; 13223 this.installGrantPermissions = installGrantPermissions; 13224 this.traceMethod = traceMethod; 13225 this.traceCookie = traceCookie; 13226 this.certificates = certificates; 13227 } 13228 13229 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13230 abstract int doPreInstall(int status); 13231 13232 /** 13233 * Rename package into final resting place. All paths on the given 13234 * scanned package should be updated to reflect the rename. 13235 */ 13236 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13237 abstract int doPostInstall(int status, int uid); 13238 13239 /** @see PackageSettingBase#codePathString */ 13240 abstract String getCodePath(); 13241 /** @see PackageSettingBase#resourcePathString */ 13242 abstract String getResourcePath(); 13243 13244 // Need installer lock especially for dex file removal. 13245 abstract void cleanUpResourcesLI(); 13246 abstract boolean doPostDeleteLI(boolean delete); 13247 13248 /** 13249 * Called before the source arguments are copied. This is used mostly 13250 * for MoveParams when it needs to read the source file to put it in the 13251 * destination. 13252 */ 13253 int doPreCopy() { 13254 return PackageManager.INSTALL_SUCCEEDED; 13255 } 13256 13257 /** 13258 * Called after the source arguments are copied. This is used mostly for 13259 * MoveParams when it needs to read the source file to put it in the 13260 * destination. 13261 */ 13262 int doPostCopy(int uid) { 13263 return PackageManager.INSTALL_SUCCEEDED; 13264 } 13265 13266 protected boolean isFwdLocked() { 13267 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13268 } 13269 13270 protected boolean isExternalAsec() { 13271 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13272 } 13273 13274 protected boolean isEphemeral() { 13275 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13276 } 13277 13278 UserHandle getUser() { 13279 return user; 13280 } 13281 } 13282 13283 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13284 if (!allCodePaths.isEmpty()) { 13285 if (instructionSets == null) { 13286 throw new IllegalStateException("instructionSet == null"); 13287 } 13288 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13289 for (String codePath : allCodePaths) { 13290 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13291 try { 13292 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13293 } catch (InstallerException ignored) { 13294 } 13295 } 13296 } 13297 } 13298 } 13299 13300 /** 13301 * Logic to handle installation of non-ASEC applications, including copying 13302 * and renaming logic. 13303 */ 13304 class FileInstallArgs extends InstallArgs { 13305 private File codeFile; 13306 private File resourceFile; 13307 13308 // Example topology: 13309 // /data/app/com.example/base.apk 13310 // /data/app/com.example/split_foo.apk 13311 // /data/app/com.example/lib/arm/libfoo.so 13312 // /data/app/com.example/lib/arm64/libfoo.so 13313 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13314 13315 /** New install */ 13316 FileInstallArgs(InstallParams params) { 13317 super(params.origin, params.move, params.observer, params.installFlags, 13318 params.installerPackageName, params.volumeUuid, 13319 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13320 params.grantedRuntimePermissions, 13321 params.traceMethod, params.traceCookie, params.certificates); 13322 if (isFwdLocked()) { 13323 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13324 } 13325 } 13326 13327 /** Existing install */ 13328 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13329 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13330 null, null, null, 0, null /*certificates*/); 13331 this.codeFile = (codePath != null) ? new File(codePath) : null; 13332 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13333 } 13334 13335 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13337 try { 13338 return doCopyApk(imcs, temp); 13339 } finally { 13340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13341 } 13342 } 13343 13344 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13345 if (origin.staged) { 13346 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13347 codeFile = origin.file; 13348 resourceFile = origin.file; 13349 return PackageManager.INSTALL_SUCCEEDED; 13350 } 13351 13352 try { 13353 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13354 final File tempDir = 13355 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13356 codeFile = tempDir; 13357 resourceFile = tempDir; 13358 } catch (IOException e) { 13359 Slog.w(TAG, "Failed to create copy file: " + e); 13360 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13361 } 13362 13363 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13364 @Override 13365 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13366 if (!FileUtils.isValidExtFilename(name)) { 13367 throw new IllegalArgumentException("Invalid filename: " + name); 13368 } 13369 try { 13370 final File file = new File(codeFile, name); 13371 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13372 O_RDWR | O_CREAT, 0644); 13373 Os.chmod(file.getAbsolutePath(), 0644); 13374 return new ParcelFileDescriptor(fd); 13375 } catch (ErrnoException e) { 13376 throw new RemoteException("Failed to open: " + e.getMessage()); 13377 } 13378 } 13379 }; 13380 13381 int ret = PackageManager.INSTALL_SUCCEEDED; 13382 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13383 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13384 Slog.e(TAG, "Failed to copy package"); 13385 return ret; 13386 } 13387 13388 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13389 NativeLibraryHelper.Handle handle = null; 13390 try { 13391 handle = NativeLibraryHelper.Handle.create(codeFile); 13392 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13393 abiOverride); 13394 } catch (IOException e) { 13395 Slog.e(TAG, "Copying native libraries failed", e); 13396 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13397 } finally { 13398 IoUtils.closeQuietly(handle); 13399 } 13400 13401 return ret; 13402 } 13403 13404 int doPreInstall(int status) { 13405 if (status != PackageManager.INSTALL_SUCCEEDED) { 13406 cleanUp(); 13407 } 13408 return status; 13409 } 13410 13411 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13412 if (status != PackageManager.INSTALL_SUCCEEDED) { 13413 cleanUp(); 13414 return false; 13415 } 13416 13417 final File targetDir = codeFile.getParentFile(); 13418 final File beforeCodeFile = codeFile; 13419 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13420 13421 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13422 try { 13423 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13424 } catch (ErrnoException e) { 13425 Slog.w(TAG, "Failed to rename", e); 13426 return false; 13427 } 13428 13429 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13430 Slog.w(TAG, "Failed to restorecon"); 13431 return false; 13432 } 13433 13434 // Reflect the rename internally 13435 codeFile = afterCodeFile; 13436 resourceFile = afterCodeFile; 13437 13438 // Reflect the rename in scanned details 13439 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13440 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13441 afterCodeFile, pkg.baseCodePath)); 13442 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13443 afterCodeFile, pkg.splitCodePaths)); 13444 13445 // Reflect the rename in app info 13446 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13447 pkg.setApplicationInfoCodePath(pkg.codePath); 13448 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13449 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13450 pkg.setApplicationInfoResourcePath(pkg.codePath); 13451 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13452 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13453 13454 return true; 13455 } 13456 13457 int doPostInstall(int status, int uid) { 13458 if (status != PackageManager.INSTALL_SUCCEEDED) { 13459 cleanUp(); 13460 } 13461 return status; 13462 } 13463 13464 @Override 13465 String getCodePath() { 13466 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13467 } 13468 13469 @Override 13470 String getResourcePath() { 13471 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13472 } 13473 13474 private boolean cleanUp() { 13475 if (codeFile == null || !codeFile.exists()) { 13476 return false; 13477 } 13478 13479 removeCodePathLI(codeFile); 13480 13481 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13482 resourceFile.delete(); 13483 } 13484 13485 return true; 13486 } 13487 13488 void cleanUpResourcesLI() { 13489 // Try enumerating all code paths before deleting 13490 List<String> allCodePaths = Collections.EMPTY_LIST; 13491 if (codeFile != null && codeFile.exists()) { 13492 try { 13493 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13494 allCodePaths = pkg.getAllCodePaths(); 13495 } catch (PackageParserException e) { 13496 // Ignored; we tried our best 13497 } 13498 } 13499 13500 cleanUp(); 13501 removeDexFiles(allCodePaths, instructionSets); 13502 } 13503 13504 boolean doPostDeleteLI(boolean delete) { 13505 // XXX err, shouldn't we respect the delete flag? 13506 cleanUpResourcesLI(); 13507 return true; 13508 } 13509 } 13510 13511 private boolean isAsecExternal(String cid) { 13512 final String asecPath = PackageHelper.getSdFilesystem(cid); 13513 return !asecPath.startsWith(mAsecInternalPath); 13514 } 13515 13516 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13517 PackageManagerException { 13518 if (copyRet < 0) { 13519 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13520 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13521 throw new PackageManagerException(copyRet, message); 13522 } 13523 } 13524 } 13525 13526 /** 13527 * Extract the MountService "container ID" from the full code path of an 13528 * .apk. 13529 */ 13530 static String cidFromCodePath(String fullCodePath) { 13531 int eidx = fullCodePath.lastIndexOf("/"); 13532 String subStr1 = fullCodePath.substring(0, eidx); 13533 int sidx = subStr1.lastIndexOf("/"); 13534 return subStr1.substring(sidx+1, eidx); 13535 } 13536 13537 /** 13538 * Logic to handle installation of ASEC applications, including copying and 13539 * renaming logic. 13540 */ 13541 class AsecInstallArgs extends InstallArgs { 13542 static final String RES_FILE_NAME = "pkg.apk"; 13543 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13544 13545 String cid; 13546 String packagePath; 13547 String resourcePath; 13548 13549 /** New install */ 13550 AsecInstallArgs(InstallParams params) { 13551 super(params.origin, params.move, params.observer, params.installFlags, 13552 params.installerPackageName, params.volumeUuid, 13553 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13554 params.grantedRuntimePermissions, 13555 params.traceMethod, params.traceCookie, params.certificates); 13556 } 13557 13558 /** Existing install */ 13559 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13560 boolean isExternal, boolean isForwardLocked) { 13561 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13562 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13563 instructionSets, null, null, null, 0, null /*certificates*/); 13564 // Hackily pretend we're still looking at a full code path 13565 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13566 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13567 } 13568 13569 // Extract cid from fullCodePath 13570 int eidx = fullCodePath.lastIndexOf("/"); 13571 String subStr1 = fullCodePath.substring(0, eidx); 13572 int sidx = subStr1.lastIndexOf("/"); 13573 cid = subStr1.substring(sidx+1, eidx); 13574 setMountPath(subStr1); 13575 } 13576 13577 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13578 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13579 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13580 instructionSets, null, null, null, 0, null /*certificates*/); 13581 this.cid = cid; 13582 setMountPath(PackageHelper.getSdDir(cid)); 13583 } 13584 13585 void createCopyFile() { 13586 cid = mInstallerService.allocateExternalStageCidLegacy(); 13587 } 13588 13589 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13590 if (origin.staged && origin.cid != null) { 13591 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13592 cid = origin.cid; 13593 setMountPath(PackageHelper.getSdDir(cid)); 13594 return PackageManager.INSTALL_SUCCEEDED; 13595 } 13596 13597 if (temp) { 13598 createCopyFile(); 13599 } else { 13600 /* 13601 * Pre-emptively destroy the container since it's destroyed if 13602 * copying fails due to it existing anyway. 13603 */ 13604 PackageHelper.destroySdDir(cid); 13605 } 13606 13607 final String newMountPath = imcs.copyPackageToContainer( 13608 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13609 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13610 13611 if (newMountPath != null) { 13612 setMountPath(newMountPath); 13613 return PackageManager.INSTALL_SUCCEEDED; 13614 } else { 13615 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13616 } 13617 } 13618 13619 @Override 13620 String getCodePath() { 13621 return packagePath; 13622 } 13623 13624 @Override 13625 String getResourcePath() { 13626 return resourcePath; 13627 } 13628 13629 int doPreInstall(int status) { 13630 if (status != PackageManager.INSTALL_SUCCEEDED) { 13631 // Destroy container 13632 PackageHelper.destroySdDir(cid); 13633 } else { 13634 boolean mounted = PackageHelper.isContainerMounted(cid); 13635 if (!mounted) { 13636 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13637 Process.SYSTEM_UID); 13638 if (newMountPath != null) { 13639 setMountPath(newMountPath); 13640 } else { 13641 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13642 } 13643 } 13644 } 13645 return status; 13646 } 13647 13648 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13649 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13650 String newMountPath = null; 13651 if (PackageHelper.isContainerMounted(cid)) { 13652 // Unmount the container 13653 if (!PackageHelper.unMountSdDir(cid)) { 13654 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13655 return false; 13656 } 13657 } 13658 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13659 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13660 " which might be stale. Will try to clean up."); 13661 // Clean up the stale container and proceed to recreate. 13662 if (!PackageHelper.destroySdDir(newCacheId)) { 13663 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13664 return false; 13665 } 13666 // Successfully cleaned up stale container. Try to rename again. 13667 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13668 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13669 + " inspite of cleaning it up."); 13670 return false; 13671 } 13672 } 13673 if (!PackageHelper.isContainerMounted(newCacheId)) { 13674 Slog.w(TAG, "Mounting container " + newCacheId); 13675 newMountPath = PackageHelper.mountSdDir(newCacheId, 13676 getEncryptKey(), Process.SYSTEM_UID); 13677 } else { 13678 newMountPath = PackageHelper.getSdDir(newCacheId); 13679 } 13680 if (newMountPath == null) { 13681 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13682 return false; 13683 } 13684 Log.i(TAG, "Succesfully renamed " + cid + 13685 " to " + newCacheId + 13686 " at new path: " + newMountPath); 13687 cid = newCacheId; 13688 13689 final File beforeCodeFile = new File(packagePath); 13690 setMountPath(newMountPath); 13691 final File afterCodeFile = new File(packagePath); 13692 13693 // Reflect the rename in scanned details 13694 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13695 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13696 afterCodeFile, pkg.baseCodePath)); 13697 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13698 afterCodeFile, pkg.splitCodePaths)); 13699 13700 // Reflect the rename in app info 13701 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13702 pkg.setApplicationInfoCodePath(pkg.codePath); 13703 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13704 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13705 pkg.setApplicationInfoResourcePath(pkg.codePath); 13706 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13707 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13708 13709 return true; 13710 } 13711 13712 private void setMountPath(String mountPath) { 13713 final File mountFile = new File(mountPath); 13714 13715 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13716 if (monolithicFile.exists()) { 13717 packagePath = monolithicFile.getAbsolutePath(); 13718 if (isFwdLocked()) { 13719 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13720 } else { 13721 resourcePath = packagePath; 13722 } 13723 } else { 13724 packagePath = mountFile.getAbsolutePath(); 13725 resourcePath = packagePath; 13726 } 13727 } 13728 13729 int doPostInstall(int status, int uid) { 13730 if (status != PackageManager.INSTALL_SUCCEEDED) { 13731 cleanUp(); 13732 } else { 13733 final int groupOwner; 13734 final String protectedFile; 13735 if (isFwdLocked()) { 13736 groupOwner = UserHandle.getSharedAppGid(uid); 13737 protectedFile = RES_FILE_NAME; 13738 } else { 13739 groupOwner = -1; 13740 protectedFile = null; 13741 } 13742 13743 if (uid < Process.FIRST_APPLICATION_UID 13744 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13745 Slog.e(TAG, "Failed to finalize " + cid); 13746 PackageHelper.destroySdDir(cid); 13747 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13748 } 13749 13750 boolean mounted = PackageHelper.isContainerMounted(cid); 13751 if (!mounted) { 13752 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13753 } 13754 } 13755 return status; 13756 } 13757 13758 private void cleanUp() { 13759 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13760 13761 // Destroy secure container 13762 PackageHelper.destroySdDir(cid); 13763 } 13764 13765 private List<String> getAllCodePaths() { 13766 final File codeFile = new File(getCodePath()); 13767 if (codeFile != null && codeFile.exists()) { 13768 try { 13769 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13770 return pkg.getAllCodePaths(); 13771 } catch (PackageParserException e) { 13772 // Ignored; we tried our best 13773 } 13774 } 13775 return Collections.EMPTY_LIST; 13776 } 13777 13778 void cleanUpResourcesLI() { 13779 // Enumerate all code paths before deleting 13780 cleanUpResourcesLI(getAllCodePaths()); 13781 } 13782 13783 private void cleanUpResourcesLI(List<String> allCodePaths) { 13784 cleanUp(); 13785 removeDexFiles(allCodePaths, instructionSets); 13786 } 13787 13788 String getPackageName() { 13789 return getAsecPackageName(cid); 13790 } 13791 13792 boolean doPostDeleteLI(boolean delete) { 13793 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13794 final List<String> allCodePaths = getAllCodePaths(); 13795 boolean mounted = PackageHelper.isContainerMounted(cid); 13796 if (mounted) { 13797 // Unmount first 13798 if (PackageHelper.unMountSdDir(cid)) { 13799 mounted = false; 13800 } 13801 } 13802 if (!mounted && delete) { 13803 cleanUpResourcesLI(allCodePaths); 13804 } 13805 return !mounted; 13806 } 13807 13808 @Override 13809 int doPreCopy() { 13810 if (isFwdLocked()) { 13811 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13812 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13813 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13814 } 13815 } 13816 13817 return PackageManager.INSTALL_SUCCEEDED; 13818 } 13819 13820 @Override 13821 int doPostCopy(int uid) { 13822 if (isFwdLocked()) { 13823 if (uid < Process.FIRST_APPLICATION_UID 13824 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13825 RES_FILE_NAME)) { 13826 Slog.e(TAG, "Failed to finalize " + cid); 13827 PackageHelper.destroySdDir(cid); 13828 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13829 } 13830 } 13831 13832 return PackageManager.INSTALL_SUCCEEDED; 13833 } 13834 } 13835 13836 /** 13837 * Logic to handle movement of existing installed applications. 13838 */ 13839 class MoveInstallArgs extends InstallArgs { 13840 private File codeFile; 13841 private File resourceFile; 13842 13843 /** New install */ 13844 MoveInstallArgs(InstallParams params) { 13845 super(params.origin, params.move, params.observer, params.installFlags, 13846 params.installerPackageName, params.volumeUuid, 13847 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13848 params.grantedRuntimePermissions, 13849 params.traceMethod, params.traceCookie, params.certificates); 13850 } 13851 13852 int copyApk(IMediaContainerService imcs, boolean temp) { 13853 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13854 + move.fromUuid + " to " + move.toUuid); 13855 synchronized (mInstaller) { 13856 try { 13857 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13858 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13859 } catch (InstallerException e) { 13860 Slog.w(TAG, "Failed to move app", e); 13861 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13862 } 13863 } 13864 13865 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13866 resourceFile = codeFile; 13867 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13868 13869 return PackageManager.INSTALL_SUCCEEDED; 13870 } 13871 13872 int doPreInstall(int status) { 13873 if (status != PackageManager.INSTALL_SUCCEEDED) { 13874 cleanUp(move.toUuid); 13875 } 13876 return status; 13877 } 13878 13879 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13880 if (status != PackageManager.INSTALL_SUCCEEDED) { 13881 cleanUp(move.toUuid); 13882 return false; 13883 } 13884 13885 // Reflect the move in app info 13886 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13887 pkg.setApplicationInfoCodePath(pkg.codePath); 13888 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13889 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13890 pkg.setApplicationInfoResourcePath(pkg.codePath); 13891 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13892 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13893 13894 return true; 13895 } 13896 13897 int doPostInstall(int status, int uid) { 13898 if (status == PackageManager.INSTALL_SUCCEEDED) { 13899 cleanUp(move.fromUuid); 13900 } else { 13901 cleanUp(move.toUuid); 13902 } 13903 return status; 13904 } 13905 13906 @Override 13907 String getCodePath() { 13908 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13909 } 13910 13911 @Override 13912 String getResourcePath() { 13913 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13914 } 13915 13916 private boolean cleanUp(String volumeUuid) { 13917 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13918 move.dataAppName); 13919 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13920 final int[] userIds = sUserManager.getUserIds(); 13921 synchronized (mInstallLock) { 13922 // Clean up both app data and code 13923 // All package moves are frozen until finished 13924 for (int userId : userIds) { 13925 try { 13926 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13927 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13928 } catch (InstallerException e) { 13929 Slog.w(TAG, String.valueOf(e)); 13930 } 13931 } 13932 removeCodePathLI(codeFile); 13933 } 13934 return true; 13935 } 13936 13937 void cleanUpResourcesLI() { 13938 throw new UnsupportedOperationException(); 13939 } 13940 13941 boolean doPostDeleteLI(boolean delete) { 13942 throw new UnsupportedOperationException(); 13943 } 13944 } 13945 13946 static String getAsecPackageName(String packageCid) { 13947 int idx = packageCid.lastIndexOf("-"); 13948 if (idx == -1) { 13949 return packageCid; 13950 } 13951 return packageCid.substring(0, idx); 13952 } 13953 13954 // Utility method used to create code paths based on package name and available index. 13955 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13956 String idxStr = ""; 13957 int idx = 1; 13958 // Fall back to default value of idx=1 if prefix is not 13959 // part of oldCodePath 13960 if (oldCodePath != null) { 13961 String subStr = oldCodePath; 13962 // Drop the suffix right away 13963 if (suffix != null && subStr.endsWith(suffix)) { 13964 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13965 } 13966 // If oldCodePath already contains prefix find out the 13967 // ending index to either increment or decrement. 13968 int sidx = subStr.lastIndexOf(prefix); 13969 if (sidx != -1) { 13970 subStr = subStr.substring(sidx + prefix.length()); 13971 if (subStr != null) { 13972 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13973 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13974 } 13975 try { 13976 idx = Integer.parseInt(subStr); 13977 if (idx <= 1) { 13978 idx++; 13979 } else { 13980 idx--; 13981 } 13982 } catch(NumberFormatException e) { 13983 } 13984 } 13985 } 13986 } 13987 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13988 return prefix + idxStr; 13989 } 13990 13991 private File getNextCodePath(File targetDir, String packageName) { 13992 int suffix = 1; 13993 File result; 13994 do { 13995 result = new File(targetDir, packageName + "-" + suffix); 13996 suffix++; 13997 } while (result.exists()); 13998 return result; 13999 } 14000 14001 // Utility method that returns the relative package path with respect 14002 // to the installation directory. Like say for /data/data/com.test-1.apk 14003 // string com.test-1 is returned. 14004 static String deriveCodePathName(String codePath) { 14005 if (codePath == null) { 14006 return null; 14007 } 14008 final File codeFile = new File(codePath); 14009 final String name = codeFile.getName(); 14010 if (codeFile.isDirectory()) { 14011 return name; 14012 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14013 final int lastDot = name.lastIndexOf('.'); 14014 return name.substring(0, lastDot); 14015 } else { 14016 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14017 return null; 14018 } 14019 } 14020 14021 static class PackageInstalledInfo { 14022 String name; 14023 int uid; 14024 // The set of users that originally had this package installed. 14025 int[] origUsers; 14026 // The set of users that now have this package installed. 14027 int[] newUsers; 14028 PackageParser.Package pkg; 14029 int returnCode; 14030 String returnMsg; 14031 PackageRemovedInfo removedInfo; 14032 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14033 14034 public void setError(int code, String msg) { 14035 setReturnCode(code); 14036 setReturnMessage(msg); 14037 Slog.w(TAG, msg); 14038 } 14039 14040 public void setError(String msg, PackageParserException e) { 14041 setReturnCode(e.error); 14042 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14043 Slog.w(TAG, msg, e); 14044 } 14045 14046 public void setError(String msg, PackageManagerException e) { 14047 returnCode = e.error; 14048 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14049 Slog.w(TAG, msg, e); 14050 } 14051 14052 public void setReturnCode(int returnCode) { 14053 this.returnCode = returnCode; 14054 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14055 for (int i = 0; i < childCount; i++) { 14056 addedChildPackages.valueAt(i).returnCode = returnCode; 14057 } 14058 } 14059 14060 private void setReturnMessage(String returnMsg) { 14061 this.returnMsg = returnMsg; 14062 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14063 for (int i = 0; i < childCount; i++) { 14064 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14065 } 14066 } 14067 14068 // In some error cases we want to convey more info back to the observer 14069 String origPackage; 14070 String origPermission; 14071 } 14072 14073 /* 14074 * Install a non-existing package. 14075 */ 14076 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14077 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14078 PackageInstalledInfo res) { 14079 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14080 14081 // Remember this for later, in case we need to rollback this install 14082 String pkgName = pkg.packageName; 14083 14084 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14085 14086 synchronized(mPackages) { 14087 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14088 // A package with the same name is already installed, though 14089 // it has been renamed to an older name. The package we 14090 // are trying to install should be installed as an update to 14091 // the existing one, but that has not been requested, so bail. 14092 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14093 + " without first uninstalling package running as " 14094 + mSettings.mRenamedPackages.get(pkgName)); 14095 return; 14096 } 14097 if (mPackages.containsKey(pkgName)) { 14098 // Don't allow installation over an existing package with the same name. 14099 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14100 + " without first uninstalling."); 14101 return; 14102 } 14103 } 14104 14105 try { 14106 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14107 System.currentTimeMillis(), user); 14108 14109 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14110 14111 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14112 prepareAppDataAfterInstallLIF(newPackage); 14113 14114 } else { 14115 // Remove package from internal structures, but keep around any 14116 // data that might have already existed 14117 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14118 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14119 } 14120 } catch (PackageManagerException e) { 14121 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14122 } 14123 14124 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14125 } 14126 14127 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14128 // Can't rotate keys during boot or if sharedUser. 14129 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14130 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14131 return false; 14132 } 14133 // app is using upgradeKeySets; make sure all are valid 14134 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14135 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14136 for (int i = 0; i < upgradeKeySets.length; i++) { 14137 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14138 Slog.wtf(TAG, "Package " 14139 + (oldPs.name != null ? oldPs.name : "<null>") 14140 + " contains upgrade-key-set reference to unknown key-set: " 14141 + upgradeKeySets[i] 14142 + " reverting to signatures check."); 14143 return false; 14144 } 14145 } 14146 return true; 14147 } 14148 14149 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14150 // Upgrade keysets are being used. Determine if new package has a superset of the 14151 // required keys. 14152 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14154 for (int i = 0; i < upgradeKeySets.length; i++) { 14155 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14156 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14157 return true; 14158 } 14159 } 14160 return false; 14161 } 14162 14163 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14164 try (DigestInputStream digestStream = 14165 new DigestInputStream(new FileInputStream(file), digest)) { 14166 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14167 } 14168 } 14169 14170 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14171 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14172 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14173 14174 final PackageParser.Package oldPackage; 14175 final String pkgName = pkg.packageName; 14176 final int[] allUsers; 14177 final int[] installedUsers; 14178 14179 synchronized(mPackages) { 14180 oldPackage = mPackages.get(pkgName); 14181 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14182 14183 // don't allow upgrade to target a release SDK from a pre-release SDK 14184 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14185 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14186 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14187 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14188 if (oldTargetsPreRelease 14189 && !newTargetsPreRelease 14190 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14191 Slog.w(TAG, "Can't install package targeting released sdk"); 14192 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14193 return; 14194 } 14195 14196 // don't allow an upgrade from full to ephemeral 14197 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14198 if (isEphemeral && !oldIsEphemeral) { 14199 // can't downgrade from full to ephemeral 14200 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14201 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14202 return; 14203 } 14204 14205 // verify signatures are valid 14206 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14207 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14208 if (!checkUpgradeKeySetLP(ps, pkg)) { 14209 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14210 "New package not signed by keys specified by upgrade-keysets: " 14211 + pkgName); 14212 return; 14213 } 14214 } else { 14215 // default to original signature matching 14216 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14217 != PackageManager.SIGNATURE_MATCH) { 14218 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14219 "New package has a different signature: " + pkgName); 14220 return; 14221 } 14222 } 14223 14224 // don't allow a system upgrade unless the upgrade hash matches 14225 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14226 byte[] digestBytes = null; 14227 try { 14228 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14229 updateDigest(digest, new File(pkg.baseCodePath)); 14230 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14231 for (String path : pkg.splitCodePaths) { 14232 updateDigest(digest, new File(path)); 14233 } 14234 } 14235 digestBytes = digest.digest(); 14236 } catch (NoSuchAlgorithmException | IOException e) { 14237 res.setError(INSTALL_FAILED_INVALID_APK, 14238 "Could not compute hash: " + pkgName); 14239 return; 14240 } 14241 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14242 res.setError(INSTALL_FAILED_INVALID_APK, 14243 "New package fails restrict-update check: " + pkgName); 14244 return; 14245 } 14246 // retain upgrade restriction 14247 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14248 } 14249 14250 // Check for shared user id changes 14251 String invalidPackageName = 14252 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14253 if (invalidPackageName != null) { 14254 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14255 "Package " + invalidPackageName + " tried to change user " 14256 + oldPackage.mSharedUserId); 14257 return; 14258 } 14259 14260 // In case of rollback, remember per-user/profile install state 14261 allUsers = sUserManager.getUserIds(); 14262 installedUsers = ps.queryInstalledUsers(allUsers, true); 14263 } 14264 14265 // Update what is removed 14266 res.removedInfo = new PackageRemovedInfo(); 14267 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14268 res.removedInfo.removedPackage = oldPackage.packageName; 14269 res.removedInfo.isUpdate = true; 14270 res.removedInfo.origUsers = installedUsers; 14271 final int childCount = (oldPackage.childPackages != null) 14272 ? oldPackage.childPackages.size() : 0; 14273 for (int i = 0; i < childCount; i++) { 14274 boolean childPackageUpdated = false; 14275 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14276 if (res.addedChildPackages != null) { 14277 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14278 if (childRes != null) { 14279 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14280 childRes.removedInfo.removedPackage = childPkg.packageName; 14281 childRes.removedInfo.isUpdate = true; 14282 childPackageUpdated = true; 14283 } 14284 } 14285 if (!childPackageUpdated) { 14286 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14287 childRemovedRes.removedPackage = childPkg.packageName; 14288 childRemovedRes.isUpdate = false; 14289 childRemovedRes.dataRemoved = true; 14290 synchronized (mPackages) { 14291 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14292 if (childPs != null) { 14293 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14294 } 14295 } 14296 if (res.removedInfo.removedChildPackages == null) { 14297 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14298 } 14299 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14300 } 14301 } 14302 14303 boolean sysPkg = (isSystemApp(oldPackage)); 14304 if (sysPkg) { 14305 // Set the system/privileged flags as needed 14306 final boolean privileged = 14307 (oldPackage.applicationInfo.privateFlags 14308 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14309 final int systemPolicyFlags = policyFlags 14310 | PackageParser.PARSE_IS_SYSTEM 14311 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14312 14313 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14314 user, allUsers, installerPackageName, res); 14315 } else { 14316 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14317 user, allUsers, installerPackageName, res); 14318 } 14319 } 14320 14321 public List<String> getPreviousCodePaths(String packageName) { 14322 final PackageSetting ps = mSettings.mPackages.get(packageName); 14323 final List<String> result = new ArrayList<String>(); 14324 if (ps != null && ps.oldCodePaths != null) { 14325 result.addAll(ps.oldCodePaths); 14326 } 14327 return result; 14328 } 14329 14330 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14331 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14332 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14333 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14334 + deletedPackage); 14335 14336 String pkgName = deletedPackage.packageName; 14337 boolean deletedPkg = true; 14338 boolean addedPkg = false; 14339 boolean updatedSettings = false; 14340 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14341 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14342 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14343 14344 final long origUpdateTime = (pkg.mExtras != null) 14345 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14346 14347 // First delete the existing package while retaining the data directory 14348 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14349 res.removedInfo, true, pkg)) { 14350 // If the existing package wasn't successfully deleted 14351 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14352 deletedPkg = false; 14353 } else { 14354 // Successfully deleted the old package; proceed with replace. 14355 14356 // If deleted package lived in a container, give users a chance to 14357 // relinquish resources before killing. 14358 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14359 if (DEBUG_INSTALL) { 14360 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14361 } 14362 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14363 final ArrayList<String> pkgList = new ArrayList<String>(1); 14364 pkgList.add(deletedPackage.applicationInfo.packageName); 14365 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14366 } 14367 14368 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14369 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14370 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14371 14372 try { 14373 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14374 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14375 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14376 14377 // Update the in-memory copy of the previous code paths. 14378 PackageSetting ps = mSettings.mPackages.get(pkgName); 14379 if (!killApp) { 14380 if (ps.oldCodePaths == null) { 14381 ps.oldCodePaths = new ArraySet<>(); 14382 } 14383 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14384 if (deletedPackage.splitCodePaths != null) { 14385 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14386 } 14387 } else { 14388 ps.oldCodePaths = null; 14389 } 14390 if (ps.childPackageNames != null) { 14391 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14392 final String childPkgName = ps.childPackageNames.get(i); 14393 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14394 childPs.oldCodePaths = ps.oldCodePaths; 14395 } 14396 } 14397 prepareAppDataAfterInstallLIF(newPackage); 14398 addedPkg = true; 14399 } catch (PackageManagerException e) { 14400 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14401 } 14402 } 14403 14404 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14405 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14406 14407 // Revert all internal state mutations and added folders for the failed install 14408 if (addedPkg) { 14409 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14410 res.removedInfo, true, null); 14411 } 14412 14413 // Restore the old package 14414 if (deletedPkg) { 14415 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14416 File restoreFile = new File(deletedPackage.codePath); 14417 // Parse old package 14418 boolean oldExternal = isExternal(deletedPackage); 14419 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14420 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14421 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14422 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14423 try { 14424 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14425 null); 14426 } catch (PackageManagerException e) { 14427 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14428 + e.getMessage()); 14429 return; 14430 } 14431 14432 synchronized (mPackages) { 14433 // Ensure the installer package name up to date 14434 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14435 14436 // Update permissions for restored package 14437 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14438 14439 mSettings.writeLPr(); 14440 } 14441 14442 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14443 } 14444 } else { 14445 synchronized (mPackages) { 14446 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14447 if (ps != null) { 14448 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14449 if (res.removedInfo.removedChildPackages != null) { 14450 final int childCount = res.removedInfo.removedChildPackages.size(); 14451 // Iterate in reverse as we may modify the collection 14452 for (int i = childCount - 1; i >= 0; i--) { 14453 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14454 if (res.addedChildPackages.containsKey(childPackageName)) { 14455 res.removedInfo.removedChildPackages.removeAt(i); 14456 } else { 14457 PackageRemovedInfo childInfo = res.removedInfo 14458 .removedChildPackages.valueAt(i); 14459 childInfo.removedForAllUsers = mPackages.get( 14460 childInfo.removedPackage) == null; 14461 } 14462 } 14463 } 14464 } 14465 } 14466 } 14467 } 14468 14469 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14470 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14471 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14472 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14473 + ", old=" + deletedPackage); 14474 14475 final boolean disabledSystem; 14476 14477 // Remove existing system package 14478 removePackageLI(deletedPackage, true); 14479 14480 synchronized (mPackages) { 14481 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14482 } 14483 if (!disabledSystem) { 14484 // We didn't need to disable the .apk as a current system package, 14485 // which means we are replacing another update that is already 14486 // installed. We need to make sure to delete the older one's .apk. 14487 res.removedInfo.args = createInstallArgsForExisting(0, 14488 deletedPackage.applicationInfo.getCodePath(), 14489 deletedPackage.applicationInfo.getResourcePath(), 14490 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14491 } else { 14492 res.removedInfo.args = null; 14493 } 14494 14495 // Successfully disabled the old package. Now proceed with re-installation 14496 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14497 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14498 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14499 14500 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14501 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14502 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14503 14504 PackageParser.Package newPackage = null; 14505 try { 14506 // Add the package to the internal data structures 14507 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14508 14509 // Set the update and install times 14510 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14511 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14512 System.currentTimeMillis()); 14513 14514 // Update the package dynamic state if succeeded 14515 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14516 // Now that the install succeeded make sure we remove data 14517 // directories for any child package the update removed. 14518 final int deletedChildCount = (deletedPackage.childPackages != null) 14519 ? deletedPackage.childPackages.size() : 0; 14520 final int newChildCount = (newPackage.childPackages != null) 14521 ? newPackage.childPackages.size() : 0; 14522 for (int i = 0; i < deletedChildCount; i++) { 14523 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14524 boolean childPackageDeleted = true; 14525 for (int j = 0; j < newChildCount; j++) { 14526 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14527 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14528 childPackageDeleted = false; 14529 break; 14530 } 14531 } 14532 if (childPackageDeleted) { 14533 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14534 deletedChildPkg.packageName); 14535 if (ps != null && res.removedInfo.removedChildPackages != null) { 14536 PackageRemovedInfo removedChildRes = res.removedInfo 14537 .removedChildPackages.get(deletedChildPkg.packageName); 14538 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14539 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14540 } 14541 } 14542 } 14543 14544 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14545 prepareAppDataAfterInstallLIF(newPackage); 14546 } 14547 } catch (PackageManagerException e) { 14548 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14549 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14550 } 14551 14552 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14553 // Re installation failed. Restore old information 14554 // Remove new pkg information 14555 if (newPackage != null) { 14556 removeInstalledPackageLI(newPackage, true); 14557 } 14558 // Add back the old system package 14559 try { 14560 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14561 } catch (PackageManagerException e) { 14562 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14563 } 14564 14565 synchronized (mPackages) { 14566 if (disabledSystem) { 14567 enableSystemPackageLPw(deletedPackage); 14568 } 14569 14570 // Ensure the installer package name up to date 14571 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14572 14573 // Update permissions for restored package 14574 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14575 14576 mSettings.writeLPr(); 14577 } 14578 14579 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14580 + " after failed upgrade"); 14581 } 14582 } 14583 14584 /** 14585 * Checks whether the parent or any of the child packages have a change shared 14586 * user. For a package to be a valid update the shred users of the parent and 14587 * the children should match. We may later support changing child shared users. 14588 * @param oldPkg The updated package. 14589 * @param newPkg The update package. 14590 * @return The shared user that change between the versions. 14591 */ 14592 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14593 PackageParser.Package newPkg) { 14594 // Check parent shared user 14595 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14596 return newPkg.packageName; 14597 } 14598 // Check child shared users 14599 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14600 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14601 for (int i = 0; i < newChildCount; i++) { 14602 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14603 // If this child was present, did it have the same shared user? 14604 for (int j = 0; j < oldChildCount; j++) { 14605 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14606 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14607 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14608 return newChildPkg.packageName; 14609 } 14610 } 14611 } 14612 return null; 14613 } 14614 14615 private void removeNativeBinariesLI(PackageSetting ps) { 14616 // Remove the lib path for the parent package 14617 if (ps != null) { 14618 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14619 // Remove the lib path for the child packages 14620 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14621 for (int i = 0; i < childCount; i++) { 14622 PackageSetting childPs = null; 14623 synchronized (mPackages) { 14624 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14625 } 14626 if (childPs != null) { 14627 NativeLibraryHelper.removeNativeBinariesLI(childPs 14628 .legacyNativeLibraryPathString); 14629 } 14630 } 14631 } 14632 } 14633 14634 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14635 // Enable the parent package 14636 mSettings.enableSystemPackageLPw(pkg.packageName); 14637 // Enable the child packages 14638 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14639 for (int i = 0; i < childCount; i++) { 14640 PackageParser.Package childPkg = pkg.childPackages.get(i); 14641 mSettings.enableSystemPackageLPw(childPkg.packageName); 14642 } 14643 } 14644 14645 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14646 PackageParser.Package newPkg) { 14647 // Disable the parent package (parent always replaced) 14648 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14649 // Disable the child packages 14650 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14651 for (int i = 0; i < childCount; i++) { 14652 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14653 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14654 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14655 } 14656 return disabled; 14657 } 14658 14659 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14660 String installerPackageName) { 14661 // Enable the parent package 14662 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14663 // Enable the child packages 14664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14665 for (int i = 0; i < childCount; i++) { 14666 PackageParser.Package childPkg = pkg.childPackages.get(i); 14667 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14668 } 14669 } 14670 14671 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14672 // Collect all used permissions in the UID 14673 ArraySet<String> usedPermissions = new ArraySet<>(); 14674 final int packageCount = su.packages.size(); 14675 for (int i = 0; i < packageCount; i++) { 14676 PackageSetting ps = su.packages.valueAt(i); 14677 if (ps.pkg == null) { 14678 continue; 14679 } 14680 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14681 for (int j = 0; j < requestedPermCount; j++) { 14682 String permission = ps.pkg.requestedPermissions.get(j); 14683 BasePermission bp = mSettings.mPermissions.get(permission); 14684 if (bp != null) { 14685 usedPermissions.add(permission); 14686 } 14687 } 14688 } 14689 14690 PermissionsState permissionsState = su.getPermissionsState(); 14691 // Prune install permissions 14692 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14693 final int installPermCount = installPermStates.size(); 14694 for (int i = installPermCount - 1; i >= 0; i--) { 14695 PermissionState permissionState = installPermStates.get(i); 14696 if (!usedPermissions.contains(permissionState.getName())) { 14697 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14698 if (bp != null) { 14699 permissionsState.revokeInstallPermission(bp); 14700 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14701 PackageManager.MASK_PERMISSION_FLAGS, 0); 14702 } 14703 } 14704 } 14705 14706 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14707 14708 // Prune runtime permissions 14709 for (int userId : allUserIds) { 14710 List<PermissionState> runtimePermStates = permissionsState 14711 .getRuntimePermissionStates(userId); 14712 final int runtimePermCount = runtimePermStates.size(); 14713 for (int i = runtimePermCount - 1; i >= 0; i--) { 14714 PermissionState permissionState = runtimePermStates.get(i); 14715 if (!usedPermissions.contains(permissionState.getName())) { 14716 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14717 if (bp != null) { 14718 permissionsState.revokeRuntimePermission(bp, userId); 14719 permissionsState.updatePermissionFlags(bp, userId, 14720 PackageManager.MASK_PERMISSION_FLAGS, 0); 14721 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14722 runtimePermissionChangedUserIds, userId); 14723 } 14724 } 14725 } 14726 } 14727 14728 return runtimePermissionChangedUserIds; 14729 } 14730 14731 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14732 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14733 // Update the parent package setting 14734 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14735 res, user); 14736 // Update the child packages setting 14737 final int childCount = (newPackage.childPackages != null) 14738 ? newPackage.childPackages.size() : 0; 14739 for (int i = 0; i < childCount; i++) { 14740 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14741 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14742 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14743 childRes.origUsers, childRes, user); 14744 } 14745 } 14746 14747 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14748 String installerPackageName, int[] allUsers, int[] installedForUsers, 14749 PackageInstalledInfo res, UserHandle user) { 14750 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14751 14752 String pkgName = newPackage.packageName; 14753 synchronized (mPackages) { 14754 //write settings. the installStatus will be incomplete at this stage. 14755 //note that the new package setting would have already been 14756 //added to mPackages. It hasn't been persisted yet. 14757 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14758 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14759 mSettings.writeLPr(); 14760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14761 } 14762 14763 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14764 synchronized (mPackages) { 14765 updatePermissionsLPw(newPackage.packageName, newPackage, 14766 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14767 ? UPDATE_PERMISSIONS_ALL : 0)); 14768 // For system-bundled packages, we assume that installing an upgraded version 14769 // of the package implies that the user actually wants to run that new code, 14770 // so we enable the package. 14771 PackageSetting ps = mSettings.mPackages.get(pkgName); 14772 final int userId = user.getIdentifier(); 14773 if (ps != null) { 14774 if (isSystemApp(newPackage)) { 14775 if (DEBUG_INSTALL) { 14776 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14777 } 14778 // Enable system package for requested users 14779 if (res.origUsers != null) { 14780 for (int origUserId : res.origUsers) { 14781 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14782 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14783 origUserId, installerPackageName); 14784 } 14785 } 14786 } 14787 // Also convey the prior install/uninstall state 14788 if (allUsers != null && installedForUsers != null) { 14789 for (int currentUserId : allUsers) { 14790 final boolean installed = ArrayUtils.contains( 14791 installedForUsers, currentUserId); 14792 if (DEBUG_INSTALL) { 14793 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14794 } 14795 ps.setInstalled(installed, currentUserId); 14796 } 14797 // these install state changes will be persisted in the 14798 // upcoming call to mSettings.writeLPr(). 14799 } 14800 } 14801 // It's implied that when a user requests installation, they want the app to be 14802 // installed and enabled. 14803 if (userId != UserHandle.USER_ALL) { 14804 ps.setInstalled(true, userId); 14805 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14806 } 14807 } 14808 res.name = pkgName; 14809 res.uid = newPackage.applicationInfo.uid; 14810 res.pkg = newPackage; 14811 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14812 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14813 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14814 //to update install status 14815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14816 mSettings.writeLPr(); 14817 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14818 } 14819 14820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14821 } 14822 14823 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14824 try { 14825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14826 installPackageLI(args, res); 14827 } finally { 14828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14829 } 14830 } 14831 14832 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14833 final int installFlags = args.installFlags; 14834 final String installerPackageName = args.installerPackageName; 14835 final String volumeUuid = args.volumeUuid; 14836 final File tmpPackageFile = new File(args.getCodePath()); 14837 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14838 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14839 || (args.volumeUuid != null)); 14840 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14841 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14842 boolean replace = false; 14843 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14844 if (args.move != null) { 14845 // moving a complete application; perform an initial scan on the new install location 14846 scanFlags |= SCAN_INITIAL; 14847 } 14848 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14849 scanFlags |= SCAN_DONT_KILL_APP; 14850 } 14851 14852 // Result object to be returned 14853 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14854 14855 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14856 14857 // Sanity check 14858 if (ephemeral && (forwardLocked || onExternal)) { 14859 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14860 + " external=" + onExternal); 14861 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14862 return; 14863 } 14864 14865 // Retrieve PackageSettings and parse package 14866 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14867 | PackageParser.PARSE_ENFORCE_CODE 14868 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14869 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14870 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14871 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14872 PackageParser pp = new PackageParser(); 14873 pp.setSeparateProcesses(mSeparateProcesses); 14874 pp.setDisplayMetrics(mMetrics); 14875 14876 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14877 final PackageParser.Package pkg; 14878 try { 14879 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14880 } catch (PackageParserException e) { 14881 res.setError("Failed parse during installPackageLI", e); 14882 return; 14883 } finally { 14884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14885 } 14886 14887 // If we are installing a clustered package add results for the children 14888 if (pkg.childPackages != null) { 14889 synchronized (mPackages) { 14890 final int childCount = pkg.childPackages.size(); 14891 for (int i = 0; i < childCount; i++) { 14892 PackageParser.Package childPkg = pkg.childPackages.get(i); 14893 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14894 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14895 childRes.pkg = childPkg; 14896 childRes.name = childPkg.packageName; 14897 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14898 if (childPs != null) { 14899 childRes.origUsers = childPs.queryInstalledUsers( 14900 sUserManager.getUserIds(), true); 14901 } 14902 if ((mPackages.containsKey(childPkg.packageName))) { 14903 childRes.removedInfo = new PackageRemovedInfo(); 14904 childRes.removedInfo.removedPackage = childPkg.packageName; 14905 } 14906 if (res.addedChildPackages == null) { 14907 res.addedChildPackages = new ArrayMap<>(); 14908 } 14909 res.addedChildPackages.put(childPkg.packageName, childRes); 14910 } 14911 } 14912 } 14913 14914 // If package doesn't declare API override, mark that we have an install 14915 // time CPU ABI override. 14916 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14917 pkg.cpuAbiOverride = args.abiOverride; 14918 } 14919 14920 String pkgName = res.name = pkg.packageName; 14921 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14922 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14923 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14924 return; 14925 } 14926 } 14927 14928 try { 14929 // either use what we've been given or parse directly from the APK 14930 if (args.certificates != null) { 14931 try { 14932 PackageParser.populateCertificates(pkg, args.certificates); 14933 } catch (PackageParserException e) { 14934 // there was something wrong with the certificates we were given; 14935 // try to pull them from the APK 14936 PackageParser.collectCertificates(pkg, parseFlags); 14937 } 14938 } else { 14939 PackageParser.collectCertificates(pkg, parseFlags); 14940 } 14941 } catch (PackageParserException e) { 14942 res.setError("Failed collect during installPackageLI", e); 14943 return; 14944 } 14945 14946 // Get rid of all references to package scan path via parser. 14947 pp = null; 14948 String oldCodePath = null; 14949 boolean systemApp = false; 14950 synchronized (mPackages) { 14951 // Check if installing already existing package 14952 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14953 String oldName = mSettings.mRenamedPackages.get(pkgName); 14954 if (pkg.mOriginalPackages != null 14955 && pkg.mOriginalPackages.contains(oldName) 14956 && mPackages.containsKey(oldName)) { 14957 // This package is derived from an original package, 14958 // and this device has been updating from that original 14959 // name. We must continue using the original name, so 14960 // rename the new package here. 14961 pkg.setPackageName(oldName); 14962 pkgName = pkg.packageName; 14963 replace = true; 14964 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14965 + oldName + " pkgName=" + pkgName); 14966 } else if (mPackages.containsKey(pkgName)) { 14967 // This package, under its official name, already exists 14968 // on the device; we should replace it. 14969 replace = true; 14970 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14971 } 14972 14973 // Child packages are installed through the parent package 14974 if (pkg.parentPackage != null) { 14975 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14976 "Package " + pkg.packageName + " is child of package " 14977 + pkg.parentPackage.parentPackage + ". Child packages " 14978 + "can be updated only through the parent package."); 14979 return; 14980 } 14981 14982 if (replace) { 14983 // Prevent apps opting out from runtime permissions 14984 PackageParser.Package oldPackage = mPackages.get(pkgName); 14985 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14986 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14987 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14988 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14989 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14990 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14991 + " doesn't support runtime permissions but the old" 14992 + " target SDK " + oldTargetSdk + " does."); 14993 return; 14994 } 14995 14996 // Prevent installing of child packages 14997 if (oldPackage.parentPackage != null) { 14998 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14999 "Package " + pkg.packageName + " is child of package " 15000 + oldPackage.parentPackage + ". Child packages " 15001 + "can be updated only through the parent package."); 15002 return; 15003 } 15004 } 15005 } 15006 15007 PackageSetting ps = mSettings.mPackages.get(pkgName); 15008 if (ps != null) { 15009 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15010 15011 // Quick sanity check that we're signed correctly if updating; 15012 // we'll check this again later when scanning, but we want to 15013 // bail early here before tripping over redefined permissions. 15014 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15015 if (!checkUpgradeKeySetLP(ps, pkg)) { 15016 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15017 + pkg.packageName + " upgrade keys do not match the " 15018 + "previously installed version"); 15019 return; 15020 } 15021 } else { 15022 try { 15023 verifySignaturesLP(ps, pkg); 15024 } catch (PackageManagerException e) { 15025 res.setError(e.error, e.getMessage()); 15026 return; 15027 } 15028 } 15029 15030 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15031 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15032 systemApp = (ps.pkg.applicationInfo.flags & 15033 ApplicationInfo.FLAG_SYSTEM) != 0; 15034 } 15035 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15036 } 15037 15038 // Check whether the newly-scanned package wants to define an already-defined perm 15039 int N = pkg.permissions.size(); 15040 for (int i = N-1; i >= 0; i--) { 15041 PackageParser.Permission perm = pkg.permissions.get(i); 15042 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15043 if (bp != null) { 15044 // If the defining package is signed with our cert, it's okay. This 15045 // also includes the "updating the same package" case, of course. 15046 // "updating same package" could also involve key-rotation. 15047 final boolean sigsOk; 15048 if (bp.sourcePackage.equals(pkg.packageName) 15049 && (bp.packageSetting instanceof PackageSetting) 15050 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15051 scanFlags))) { 15052 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15053 } else { 15054 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15055 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15056 } 15057 if (!sigsOk) { 15058 // If the owning package is the system itself, we log but allow 15059 // install to proceed; we fail the install on all other permission 15060 // redefinitions. 15061 if (!bp.sourcePackage.equals("android")) { 15062 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15063 + pkg.packageName + " attempting to redeclare permission " 15064 + perm.info.name + " already owned by " + bp.sourcePackage); 15065 res.origPermission = perm.info.name; 15066 res.origPackage = bp.sourcePackage; 15067 return; 15068 } else { 15069 Slog.w(TAG, "Package " + pkg.packageName 15070 + " attempting to redeclare system permission " 15071 + perm.info.name + "; ignoring new declaration"); 15072 pkg.permissions.remove(i); 15073 } 15074 } 15075 } 15076 } 15077 } 15078 15079 if (systemApp) { 15080 if (onExternal) { 15081 // Abort update; system app can't be replaced with app on sdcard 15082 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15083 "Cannot install updates to system apps on sdcard"); 15084 return; 15085 } else if (ephemeral) { 15086 // Abort update; system app can't be replaced with an ephemeral app 15087 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15088 "Cannot update a system app with an ephemeral app"); 15089 return; 15090 } 15091 } 15092 15093 if (args.move != null) { 15094 // We did an in-place move, so dex is ready to roll 15095 scanFlags |= SCAN_NO_DEX; 15096 scanFlags |= SCAN_MOVE; 15097 15098 synchronized (mPackages) { 15099 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15100 if (ps == null) { 15101 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15102 "Missing settings for moved package " + pkgName); 15103 } 15104 15105 // We moved the entire application as-is, so bring over the 15106 // previously derived ABI information. 15107 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15108 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15109 } 15110 15111 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15112 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15113 scanFlags |= SCAN_NO_DEX; 15114 15115 try { 15116 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15117 args.abiOverride : pkg.cpuAbiOverride); 15118 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15119 true /* extract libs */); 15120 } catch (PackageManagerException pme) { 15121 Slog.e(TAG, "Error deriving application ABI", pme); 15122 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15123 return; 15124 } 15125 15126 // Shared libraries for the package need to be updated. 15127 synchronized (mPackages) { 15128 try { 15129 updateSharedLibrariesLPw(pkg, null); 15130 } catch (PackageManagerException e) { 15131 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15132 } 15133 } 15134 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15135 // Do not run PackageDexOptimizer through the local performDexOpt 15136 // method because `pkg` may not be in `mPackages` yet. 15137 // 15138 // Also, don't fail application installs if the dexopt step fails. 15139 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15140 null /* instructionSets */, false /* checkProfiles */, 15141 getCompilerFilterForReason(REASON_INSTALL)); 15142 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 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; 16342 while (conn.mContainerService == null && 16343 (now = SystemClock.uptimeMillis()) < timeout) { 16344 try { 16345 conn.wait(timeout - now); 16346 } catch (InterruptedException e) { 16347 } 16348 } 16349 } 16350 if (conn.mContainerService == null) { 16351 return; 16352 } 16353 16354 final UserEnvironment userEnv = new UserEnvironment(curUser); 16355 clearDirectory(conn.mContainerService, 16356 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16357 if (allData) { 16358 clearDirectory(conn.mContainerService, 16359 userEnv.buildExternalStorageAppDataDirs(packageName)); 16360 clearDirectory(conn.mContainerService, 16361 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16362 } 16363 } 16364 } finally { 16365 mContext.unbindService(conn); 16366 } 16367 } 16368 } 16369 16370 @Override 16371 public void clearApplicationProfileData(String packageName) { 16372 enforceSystemOrRoot("Only the system can clear all profile data"); 16373 16374 final PackageParser.Package pkg; 16375 synchronized (mPackages) { 16376 pkg = mPackages.get(packageName); 16377 } 16378 16379 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16380 synchronized (mInstallLock) { 16381 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16382 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16383 true /* removeBaseMarker */); 16384 } 16385 } 16386 } 16387 16388 @Override 16389 public void clearApplicationUserData(final String packageName, 16390 final IPackageDataObserver observer, final int userId) { 16391 mContext.enforceCallingOrSelfPermission( 16392 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16393 16394 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16395 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16396 16397 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16398 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16399 } 16400 // Queue up an async operation since the package deletion may take a little while. 16401 mHandler.post(new Runnable() { 16402 public void run() { 16403 mHandler.removeCallbacks(this); 16404 final boolean succeeded; 16405 try (PackageFreezer freezer = freezePackage(packageName, 16406 "clearApplicationUserData")) { 16407 synchronized (mInstallLock) { 16408 succeeded = clearApplicationUserDataLIF(packageName, userId); 16409 } 16410 clearExternalStorageDataSync(packageName, userId, true); 16411 } 16412 if (succeeded) { 16413 // invoke DeviceStorageMonitor's update method to clear any notifications 16414 DeviceStorageMonitorInternal dsm = LocalServices 16415 .getService(DeviceStorageMonitorInternal.class); 16416 if (dsm != null) { 16417 dsm.checkMemory(); 16418 } 16419 } 16420 if(observer != null) { 16421 try { 16422 observer.onRemoveCompleted(packageName, succeeded); 16423 } catch (RemoteException e) { 16424 Log.i(TAG, "Observer no longer exists."); 16425 } 16426 } //end if observer 16427 } //end run 16428 }); 16429 } 16430 16431 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16432 if (packageName == null) { 16433 Slog.w(TAG, "Attempt to delete null packageName."); 16434 return false; 16435 } 16436 16437 // Try finding details about the requested package 16438 PackageParser.Package pkg; 16439 synchronized (mPackages) { 16440 pkg = mPackages.get(packageName); 16441 if (pkg == null) { 16442 final PackageSetting ps = mSettings.mPackages.get(packageName); 16443 if (ps != null) { 16444 pkg = ps.pkg; 16445 } 16446 } 16447 16448 if (pkg == null) { 16449 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16450 return false; 16451 } 16452 16453 PackageSetting ps = (PackageSetting) pkg.mExtras; 16454 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16455 } 16456 16457 clearAppDataLIF(pkg, userId, 16458 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16459 16460 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16461 removeKeystoreDataIfNeeded(userId, appId); 16462 16463 UserManagerInternal umInternal = getUserManagerInternal(); 16464 final int flags; 16465 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16466 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16467 } else if (umInternal.isUserRunning(userId)) { 16468 flags = StorageManager.FLAG_STORAGE_DE; 16469 } else { 16470 flags = 0; 16471 } 16472 prepareAppDataContentsLIF(pkg, userId, flags); 16473 16474 return true; 16475 } 16476 16477 /** 16478 * Reverts user permission state changes (permissions and flags) in 16479 * all packages for a given user. 16480 * 16481 * @param userId The device user for which to do a reset. 16482 */ 16483 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16484 final int packageCount = mPackages.size(); 16485 for (int i = 0; i < packageCount; i++) { 16486 PackageParser.Package pkg = mPackages.valueAt(i); 16487 PackageSetting ps = (PackageSetting) pkg.mExtras; 16488 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16489 } 16490 } 16491 16492 private void resetNetworkPolicies(int userId) { 16493 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16494 } 16495 16496 /** 16497 * Reverts user permission state changes (permissions and flags). 16498 * 16499 * @param ps The package for which to reset. 16500 * @param userId The device user for which to do a reset. 16501 */ 16502 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16503 final PackageSetting ps, final int userId) { 16504 if (ps.pkg == null) { 16505 return; 16506 } 16507 16508 // These are flags that can change base on user actions. 16509 final int userSettableMask = FLAG_PERMISSION_USER_SET 16510 | FLAG_PERMISSION_USER_FIXED 16511 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16512 | FLAG_PERMISSION_REVIEW_REQUIRED; 16513 16514 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16515 | FLAG_PERMISSION_POLICY_FIXED; 16516 16517 boolean writeInstallPermissions = false; 16518 boolean writeRuntimePermissions = false; 16519 16520 final int permissionCount = ps.pkg.requestedPermissions.size(); 16521 for (int i = 0; i < permissionCount; i++) { 16522 String permission = ps.pkg.requestedPermissions.get(i); 16523 16524 BasePermission bp = mSettings.mPermissions.get(permission); 16525 if (bp == null) { 16526 continue; 16527 } 16528 16529 // If shared user we just reset the state to which only this app contributed. 16530 if (ps.sharedUser != null) { 16531 boolean used = false; 16532 final int packageCount = ps.sharedUser.packages.size(); 16533 for (int j = 0; j < packageCount; j++) { 16534 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16535 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16536 && pkg.pkg.requestedPermissions.contains(permission)) { 16537 used = true; 16538 break; 16539 } 16540 } 16541 if (used) { 16542 continue; 16543 } 16544 } 16545 16546 PermissionsState permissionsState = ps.getPermissionsState(); 16547 16548 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16549 16550 // Always clear the user settable flags. 16551 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16552 bp.name) != null; 16553 // If permission review is enabled and this is a legacy app, mark the 16554 // permission as requiring a review as this is the initial state. 16555 int flags = 0; 16556 if (Build.PERMISSIONS_REVIEW_REQUIRED 16557 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16558 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16559 } 16560 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16561 if (hasInstallState) { 16562 writeInstallPermissions = true; 16563 } else { 16564 writeRuntimePermissions = true; 16565 } 16566 } 16567 16568 // Below is only runtime permission handling. 16569 if (!bp.isRuntime()) { 16570 continue; 16571 } 16572 16573 // Never clobber system or policy. 16574 if ((oldFlags & policyOrSystemFlags) != 0) { 16575 continue; 16576 } 16577 16578 // If this permission was granted by default, make sure it is. 16579 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16580 if (permissionsState.grantRuntimePermission(bp, userId) 16581 != PERMISSION_OPERATION_FAILURE) { 16582 writeRuntimePermissions = true; 16583 } 16584 // If permission review is enabled the permissions for a legacy apps 16585 // are represented as constantly granted runtime ones, so don't revoke. 16586 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16587 // Otherwise, reset the permission. 16588 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16589 switch (revokeResult) { 16590 case PERMISSION_OPERATION_SUCCESS: 16591 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16592 writeRuntimePermissions = true; 16593 final int appId = ps.appId; 16594 mHandler.post(new Runnable() { 16595 @Override 16596 public void run() { 16597 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16598 } 16599 }); 16600 } break; 16601 } 16602 } 16603 } 16604 16605 // Synchronously write as we are taking permissions away. 16606 if (writeRuntimePermissions) { 16607 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16608 } 16609 16610 // Synchronously write as we are taking permissions away. 16611 if (writeInstallPermissions) { 16612 mSettings.writeLPr(); 16613 } 16614 } 16615 16616 /** 16617 * Remove entries from the keystore daemon. Will only remove it if the 16618 * {@code appId} is valid. 16619 */ 16620 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16621 if (appId < 0) { 16622 return; 16623 } 16624 16625 final KeyStore keyStore = KeyStore.getInstance(); 16626 if (keyStore != null) { 16627 if (userId == UserHandle.USER_ALL) { 16628 for (final int individual : sUserManager.getUserIds()) { 16629 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16630 } 16631 } else { 16632 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16633 } 16634 } else { 16635 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16636 } 16637 } 16638 16639 @Override 16640 public void deleteApplicationCacheFiles(final String packageName, 16641 final IPackageDataObserver observer) { 16642 final int userId = UserHandle.getCallingUserId(); 16643 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16644 } 16645 16646 @Override 16647 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16648 final IPackageDataObserver observer) { 16649 mContext.enforceCallingOrSelfPermission( 16650 android.Manifest.permission.DELETE_CACHE_FILES, null); 16651 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16652 /* requireFullPermission= */ true, /* checkShell= */ false, 16653 "delete application cache files"); 16654 16655 final PackageParser.Package pkg; 16656 synchronized (mPackages) { 16657 pkg = mPackages.get(packageName); 16658 } 16659 16660 // Queue up an async operation since the package deletion may take a little while. 16661 mHandler.post(new Runnable() { 16662 public void run() { 16663 synchronized (mInstallLock) { 16664 final int flags = StorageManager.FLAG_STORAGE_DE 16665 | StorageManager.FLAG_STORAGE_CE; 16666 // We're only clearing cache files, so we don't care if the 16667 // app is unfrozen and still able to run 16668 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16669 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16670 } 16671 clearExternalStorageDataSync(packageName, userId, false); 16672 if (observer != null) { 16673 try { 16674 observer.onRemoveCompleted(packageName, true); 16675 } catch (RemoteException e) { 16676 Log.i(TAG, "Observer no longer exists."); 16677 } 16678 } 16679 } 16680 }); 16681 } 16682 16683 @Override 16684 public void getPackageSizeInfo(final String packageName, int userHandle, 16685 final IPackageStatsObserver observer) { 16686 mContext.enforceCallingOrSelfPermission( 16687 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16688 if (packageName == null) { 16689 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16690 } 16691 16692 PackageStats stats = new PackageStats(packageName, userHandle); 16693 16694 /* 16695 * Queue up an async operation since the package measurement may take a 16696 * little while. 16697 */ 16698 Message msg = mHandler.obtainMessage(INIT_COPY); 16699 msg.obj = new MeasureParams(stats, observer); 16700 mHandler.sendMessage(msg); 16701 } 16702 16703 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16704 final PackageSetting ps; 16705 synchronized (mPackages) { 16706 ps = mSettings.mPackages.get(packageName); 16707 if (ps == null) { 16708 Slog.w(TAG, "Failed to find settings for " + packageName); 16709 return false; 16710 } 16711 } 16712 try { 16713 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16714 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16715 ps.getCeDataInode(userId), ps.codePathString, stats); 16716 } catch (InstallerException e) { 16717 Slog.w(TAG, String.valueOf(e)); 16718 return false; 16719 } 16720 16721 // For now, ignore code size of packages on system partition 16722 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16723 stats.codeSize = 0; 16724 } 16725 16726 return true; 16727 } 16728 16729 private int getUidTargetSdkVersionLockedLPr(int uid) { 16730 Object obj = mSettings.getUserIdLPr(uid); 16731 if (obj instanceof SharedUserSetting) { 16732 final SharedUserSetting sus = (SharedUserSetting) obj; 16733 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16734 final Iterator<PackageSetting> it = sus.packages.iterator(); 16735 while (it.hasNext()) { 16736 final PackageSetting ps = it.next(); 16737 if (ps.pkg != null) { 16738 int v = ps.pkg.applicationInfo.targetSdkVersion; 16739 if (v < vers) vers = v; 16740 } 16741 } 16742 return vers; 16743 } else if (obj instanceof PackageSetting) { 16744 final PackageSetting ps = (PackageSetting) obj; 16745 if (ps.pkg != null) { 16746 return ps.pkg.applicationInfo.targetSdkVersion; 16747 } 16748 } 16749 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16750 } 16751 16752 @Override 16753 public void addPreferredActivity(IntentFilter filter, int match, 16754 ComponentName[] set, ComponentName activity, int userId) { 16755 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16756 "Adding preferred"); 16757 } 16758 16759 private void addPreferredActivityInternal(IntentFilter filter, int match, 16760 ComponentName[] set, ComponentName activity, boolean always, int userId, 16761 String opname) { 16762 // writer 16763 int callingUid = Binder.getCallingUid(); 16764 enforceCrossUserPermission(callingUid, userId, 16765 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16766 if (filter.countActions() == 0) { 16767 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16768 return; 16769 } 16770 synchronized (mPackages) { 16771 if (mContext.checkCallingOrSelfPermission( 16772 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16773 != PackageManager.PERMISSION_GRANTED) { 16774 if (getUidTargetSdkVersionLockedLPr(callingUid) 16775 < Build.VERSION_CODES.FROYO) { 16776 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16777 + callingUid); 16778 return; 16779 } 16780 mContext.enforceCallingOrSelfPermission( 16781 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16782 } 16783 16784 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16785 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16786 + userId + ":"); 16787 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16788 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16789 scheduleWritePackageRestrictionsLocked(userId); 16790 } 16791 } 16792 16793 @Override 16794 public void replacePreferredActivity(IntentFilter filter, int match, 16795 ComponentName[] set, ComponentName activity, int userId) { 16796 if (filter.countActions() != 1) { 16797 throw new IllegalArgumentException( 16798 "replacePreferredActivity expects filter to have only 1 action."); 16799 } 16800 if (filter.countDataAuthorities() != 0 16801 || filter.countDataPaths() != 0 16802 || filter.countDataSchemes() > 1 16803 || filter.countDataTypes() != 0) { 16804 throw new IllegalArgumentException( 16805 "replacePreferredActivity expects filter to have no data authorities, " + 16806 "paths, or types; and at most one scheme."); 16807 } 16808 16809 final int callingUid = Binder.getCallingUid(); 16810 enforceCrossUserPermission(callingUid, userId, 16811 true /* requireFullPermission */, false /* checkShell */, 16812 "replace preferred activity"); 16813 synchronized (mPackages) { 16814 if (mContext.checkCallingOrSelfPermission( 16815 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16816 != PackageManager.PERMISSION_GRANTED) { 16817 if (getUidTargetSdkVersionLockedLPr(callingUid) 16818 < Build.VERSION_CODES.FROYO) { 16819 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16820 + Binder.getCallingUid()); 16821 return; 16822 } 16823 mContext.enforceCallingOrSelfPermission( 16824 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16825 } 16826 16827 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16828 if (pir != null) { 16829 // Get all of the existing entries that exactly match this filter. 16830 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16831 if (existing != null && existing.size() == 1) { 16832 PreferredActivity cur = existing.get(0); 16833 if (DEBUG_PREFERRED) { 16834 Slog.i(TAG, "Checking replace of preferred:"); 16835 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16836 if (!cur.mPref.mAlways) { 16837 Slog.i(TAG, " -- CUR; not mAlways!"); 16838 } else { 16839 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16840 Slog.i(TAG, " -- CUR: mSet=" 16841 + Arrays.toString(cur.mPref.mSetComponents)); 16842 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16843 Slog.i(TAG, " -- NEW: mMatch=" 16844 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16845 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16846 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16847 } 16848 } 16849 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16850 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16851 && cur.mPref.sameSet(set)) { 16852 // Setting the preferred activity to what it happens to be already 16853 if (DEBUG_PREFERRED) { 16854 Slog.i(TAG, "Replacing with same preferred activity " 16855 + cur.mPref.mShortComponent + " for user " 16856 + userId + ":"); 16857 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16858 } 16859 return; 16860 } 16861 } 16862 16863 if (existing != null) { 16864 if (DEBUG_PREFERRED) { 16865 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16866 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16867 } 16868 for (int i = 0; i < existing.size(); i++) { 16869 PreferredActivity pa = existing.get(i); 16870 if (DEBUG_PREFERRED) { 16871 Slog.i(TAG, "Removing existing preferred activity " 16872 + pa.mPref.mComponent + ":"); 16873 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16874 } 16875 pir.removeFilter(pa); 16876 } 16877 } 16878 } 16879 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16880 "Replacing preferred"); 16881 } 16882 } 16883 16884 @Override 16885 public void clearPackagePreferredActivities(String packageName) { 16886 final int uid = Binder.getCallingUid(); 16887 // writer 16888 synchronized (mPackages) { 16889 PackageParser.Package pkg = mPackages.get(packageName); 16890 if (pkg == null || pkg.applicationInfo.uid != uid) { 16891 if (mContext.checkCallingOrSelfPermission( 16892 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16893 != PackageManager.PERMISSION_GRANTED) { 16894 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16895 < Build.VERSION_CODES.FROYO) { 16896 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16897 + Binder.getCallingUid()); 16898 return; 16899 } 16900 mContext.enforceCallingOrSelfPermission( 16901 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16902 } 16903 } 16904 16905 int user = UserHandle.getCallingUserId(); 16906 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16907 scheduleWritePackageRestrictionsLocked(user); 16908 } 16909 } 16910 } 16911 16912 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16913 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16914 ArrayList<PreferredActivity> removed = null; 16915 boolean changed = false; 16916 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16917 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16918 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16919 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16920 continue; 16921 } 16922 Iterator<PreferredActivity> it = pir.filterIterator(); 16923 while (it.hasNext()) { 16924 PreferredActivity pa = it.next(); 16925 // Mark entry for removal only if it matches the package name 16926 // and the entry is of type "always". 16927 if (packageName == null || 16928 (pa.mPref.mComponent.getPackageName().equals(packageName) 16929 && pa.mPref.mAlways)) { 16930 if (removed == null) { 16931 removed = new ArrayList<PreferredActivity>(); 16932 } 16933 removed.add(pa); 16934 } 16935 } 16936 if (removed != null) { 16937 for (int j=0; j<removed.size(); j++) { 16938 PreferredActivity pa = removed.get(j); 16939 pir.removeFilter(pa); 16940 } 16941 changed = true; 16942 } 16943 } 16944 return changed; 16945 } 16946 16947 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16948 private void clearIntentFilterVerificationsLPw(int userId) { 16949 final int packageCount = mPackages.size(); 16950 for (int i = 0; i < packageCount; i++) { 16951 PackageParser.Package pkg = mPackages.valueAt(i); 16952 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16953 } 16954 } 16955 16956 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16957 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16958 if (userId == UserHandle.USER_ALL) { 16959 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16960 sUserManager.getUserIds())) { 16961 for (int oneUserId : sUserManager.getUserIds()) { 16962 scheduleWritePackageRestrictionsLocked(oneUserId); 16963 } 16964 } 16965 } else { 16966 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16967 scheduleWritePackageRestrictionsLocked(userId); 16968 } 16969 } 16970 } 16971 16972 void clearDefaultBrowserIfNeeded(String packageName) { 16973 for (int oneUserId : sUserManager.getUserIds()) { 16974 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16975 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16976 if (packageName.equals(defaultBrowserPackageName)) { 16977 setDefaultBrowserPackageName(null, oneUserId); 16978 } 16979 } 16980 } 16981 16982 @Override 16983 public void resetApplicationPreferences(int userId) { 16984 mContext.enforceCallingOrSelfPermission( 16985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16986 final long identity = Binder.clearCallingIdentity(); 16987 // writer 16988 try { 16989 synchronized (mPackages) { 16990 clearPackagePreferredActivitiesLPw(null, userId); 16991 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16992 // TODO: We have to reset the default SMS and Phone. This requires 16993 // significant refactoring to keep all default apps in the package 16994 // manager (cleaner but more work) or have the services provide 16995 // callbacks to the package manager to request a default app reset. 16996 applyFactoryDefaultBrowserLPw(userId); 16997 clearIntentFilterVerificationsLPw(userId); 16998 primeDomainVerificationsLPw(userId); 16999 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17000 scheduleWritePackageRestrictionsLocked(userId); 17001 } 17002 resetNetworkPolicies(userId); 17003 } finally { 17004 Binder.restoreCallingIdentity(identity); 17005 } 17006 } 17007 17008 @Override 17009 public int getPreferredActivities(List<IntentFilter> outFilters, 17010 List<ComponentName> outActivities, String packageName) { 17011 17012 int num = 0; 17013 final int userId = UserHandle.getCallingUserId(); 17014 // reader 17015 synchronized (mPackages) { 17016 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17017 if (pir != null) { 17018 final Iterator<PreferredActivity> it = pir.filterIterator(); 17019 while (it.hasNext()) { 17020 final PreferredActivity pa = it.next(); 17021 if (packageName == null 17022 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17023 && pa.mPref.mAlways)) { 17024 if (outFilters != null) { 17025 outFilters.add(new IntentFilter(pa)); 17026 } 17027 if (outActivities != null) { 17028 outActivities.add(pa.mPref.mComponent); 17029 } 17030 } 17031 } 17032 } 17033 } 17034 17035 return num; 17036 } 17037 17038 @Override 17039 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17040 int userId) { 17041 int callingUid = Binder.getCallingUid(); 17042 if (callingUid != Process.SYSTEM_UID) { 17043 throw new SecurityException( 17044 "addPersistentPreferredActivity can only be run by the system"); 17045 } 17046 if (filter.countActions() == 0) { 17047 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17048 return; 17049 } 17050 synchronized (mPackages) { 17051 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17052 ":"); 17053 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17054 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17055 new PersistentPreferredActivity(filter, activity)); 17056 scheduleWritePackageRestrictionsLocked(userId); 17057 } 17058 } 17059 17060 @Override 17061 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17062 int callingUid = Binder.getCallingUid(); 17063 if (callingUid != Process.SYSTEM_UID) { 17064 throw new SecurityException( 17065 "clearPackagePersistentPreferredActivities can only be run by the system"); 17066 } 17067 ArrayList<PersistentPreferredActivity> removed = null; 17068 boolean changed = false; 17069 synchronized (mPackages) { 17070 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17071 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17072 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17073 .valueAt(i); 17074 if (userId != thisUserId) { 17075 continue; 17076 } 17077 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17078 while (it.hasNext()) { 17079 PersistentPreferredActivity ppa = it.next(); 17080 // Mark entry for removal only if it matches the package name. 17081 if (ppa.mComponent.getPackageName().equals(packageName)) { 17082 if (removed == null) { 17083 removed = new ArrayList<PersistentPreferredActivity>(); 17084 } 17085 removed.add(ppa); 17086 } 17087 } 17088 if (removed != null) { 17089 for (int j=0; j<removed.size(); j++) { 17090 PersistentPreferredActivity ppa = removed.get(j); 17091 ppir.removeFilter(ppa); 17092 } 17093 changed = true; 17094 } 17095 } 17096 17097 if (changed) { 17098 scheduleWritePackageRestrictionsLocked(userId); 17099 } 17100 } 17101 } 17102 17103 /** 17104 * Common machinery for picking apart a restored XML blob and passing 17105 * it to a caller-supplied functor to be applied to the running system. 17106 */ 17107 private void restoreFromXml(XmlPullParser parser, int userId, 17108 String expectedStartTag, BlobXmlRestorer functor) 17109 throws IOException, XmlPullParserException { 17110 int type; 17111 while ((type = parser.next()) != XmlPullParser.START_TAG 17112 && type != XmlPullParser.END_DOCUMENT) { 17113 } 17114 if (type != XmlPullParser.START_TAG) { 17115 // oops didn't find a start tag?! 17116 if (DEBUG_BACKUP) { 17117 Slog.e(TAG, "Didn't find start tag during restore"); 17118 } 17119 return; 17120 } 17121Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17122 // this is supposed to be TAG_PREFERRED_BACKUP 17123 if (!expectedStartTag.equals(parser.getName())) { 17124 if (DEBUG_BACKUP) { 17125 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17126 } 17127 return; 17128 } 17129 17130 // skip interfering stuff, then we're aligned with the backing implementation 17131 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17132Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17133 functor.apply(parser, userId); 17134 } 17135 17136 private interface BlobXmlRestorer { 17137 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17138 } 17139 17140 /** 17141 * Non-Binder method, support for the backup/restore mechanism: write the 17142 * full set of preferred activities in its canonical XML format. Returns the 17143 * XML output as a byte array, or null if there is none. 17144 */ 17145 @Override 17146 public byte[] getPreferredActivityBackup(int userId) { 17147 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17148 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17149 } 17150 17151 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17152 try { 17153 final XmlSerializer serializer = new FastXmlSerializer(); 17154 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17155 serializer.startDocument(null, true); 17156 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17157 17158 synchronized (mPackages) { 17159 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17160 } 17161 17162 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17163 serializer.endDocument(); 17164 serializer.flush(); 17165 } catch (Exception e) { 17166 if (DEBUG_BACKUP) { 17167 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17168 } 17169 return null; 17170 } 17171 17172 return dataStream.toByteArray(); 17173 } 17174 17175 @Override 17176 public void restorePreferredActivities(byte[] backup, int userId) { 17177 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17178 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17179 } 17180 17181 try { 17182 final XmlPullParser parser = Xml.newPullParser(); 17183 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17184 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17185 new BlobXmlRestorer() { 17186 @Override 17187 public void apply(XmlPullParser parser, int userId) 17188 throws XmlPullParserException, IOException { 17189 synchronized (mPackages) { 17190 mSettings.readPreferredActivitiesLPw(parser, userId); 17191 } 17192 } 17193 } ); 17194 } catch (Exception e) { 17195 if (DEBUG_BACKUP) { 17196 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17197 } 17198 } 17199 } 17200 17201 /** 17202 * Non-Binder method, support for the backup/restore mechanism: write the 17203 * default browser (etc) settings in its canonical XML format. Returns the default 17204 * browser XML representation as a byte array, or null if there is none. 17205 */ 17206 @Override 17207 public byte[] getDefaultAppsBackup(int userId) { 17208 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17209 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17210 } 17211 17212 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17213 try { 17214 final XmlSerializer serializer = new FastXmlSerializer(); 17215 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17216 serializer.startDocument(null, true); 17217 serializer.startTag(null, TAG_DEFAULT_APPS); 17218 17219 synchronized (mPackages) { 17220 mSettings.writeDefaultAppsLPr(serializer, userId); 17221 } 17222 17223 serializer.endTag(null, TAG_DEFAULT_APPS); 17224 serializer.endDocument(); 17225 serializer.flush(); 17226 } catch (Exception e) { 17227 if (DEBUG_BACKUP) { 17228 Slog.e(TAG, "Unable to write default apps for backup", e); 17229 } 17230 return null; 17231 } 17232 17233 return dataStream.toByteArray(); 17234 } 17235 17236 @Override 17237 public void restoreDefaultApps(byte[] backup, int userId) { 17238 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17239 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17240 } 17241 17242 try { 17243 final XmlPullParser parser = Xml.newPullParser(); 17244 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17245 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17246 new BlobXmlRestorer() { 17247 @Override 17248 public void apply(XmlPullParser parser, int userId) 17249 throws XmlPullParserException, IOException { 17250 synchronized (mPackages) { 17251 mSettings.readDefaultAppsLPw(parser, userId); 17252 } 17253 } 17254 } ); 17255 } catch (Exception e) { 17256 if (DEBUG_BACKUP) { 17257 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17258 } 17259 } 17260 } 17261 17262 @Override 17263 public byte[] getIntentFilterVerificationBackup(int userId) { 17264 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17265 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17266 } 17267 17268 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17269 try { 17270 final XmlSerializer serializer = new FastXmlSerializer(); 17271 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17272 serializer.startDocument(null, true); 17273 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17274 17275 synchronized (mPackages) { 17276 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17277 } 17278 17279 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17280 serializer.endDocument(); 17281 serializer.flush(); 17282 } catch (Exception e) { 17283 if (DEBUG_BACKUP) { 17284 Slog.e(TAG, "Unable to write default apps for backup", e); 17285 } 17286 return null; 17287 } 17288 17289 return dataStream.toByteArray(); 17290 } 17291 17292 @Override 17293 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17294 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17295 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17296 } 17297 17298 try { 17299 final XmlPullParser parser = Xml.newPullParser(); 17300 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17301 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17302 new BlobXmlRestorer() { 17303 @Override 17304 public void apply(XmlPullParser parser, int userId) 17305 throws XmlPullParserException, IOException { 17306 synchronized (mPackages) { 17307 mSettings.readAllDomainVerificationsLPr(parser, userId); 17308 mSettings.writeLPr(); 17309 } 17310 } 17311 } ); 17312 } catch (Exception e) { 17313 if (DEBUG_BACKUP) { 17314 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17315 } 17316 } 17317 } 17318 17319 @Override 17320 public byte[] getPermissionGrantBackup(int userId) { 17321 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17322 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17323 } 17324 17325 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17326 try { 17327 final XmlSerializer serializer = new FastXmlSerializer(); 17328 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17329 serializer.startDocument(null, true); 17330 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17331 17332 synchronized (mPackages) { 17333 serializeRuntimePermissionGrantsLPr(serializer, userId); 17334 } 17335 17336 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17337 serializer.endDocument(); 17338 serializer.flush(); 17339 } catch (Exception e) { 17340 if (DEBUG_BACKUP) { 17341 Slog.e(TAG, "Unable to write default apps for backup", e); 17342 } 17343 return null; 17344 } 17345 17346 return dataStream.toByteArray(); 17347 } 17348 17349 @Override 17350 public void restorePermissionGrants(byte[] backup, int userId) { 17351 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17352 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17353 } 17354 17355 try { 17356 final XmlPullParser parser = Xml.newPullParser(); 17357 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17358 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17359 new BlobXmlRestorer() { 17360 @Override 17361 public void apply(XmlPullParser parser, int userId) 17362 throws XmlPullParserException, IOException { 17363 synchronized (mPackages) { 17364 processRestoredPermissionGrantsLPr(parser, userId); 17365 } 17366 } 17367 } ); 17368 } catch (Exception e) { 17369 if (DEBUG_BACKUP) { 17370 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17371 } 17372 } 17373 } 17374 17375 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17376 throws IOException { 17377 serializer.startTag(null, TAG_ALL_GRANTS); 17378 17379 final int N = mSettings.mPackages.size(); 17380 for (int i = 0; i < N; i++) { 17381 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17382 boolean pkgGrantsKnown = false; 17383 17384 PermissionsState packagePerms = ps.getPermissionsState(); 17385 17386 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17387 final int grantFlags = state.getFlags(); 17388 // only look at grants that are not system/policy fixed 17389 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17390 final boolean isGranted = state.isGranted(); 17391 // And only back up the user-twiddled state bits 17392 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17393 final String packageName = mSettings.mPackages.keyAt(i); 17394 if (!pkgGrantsKnown) { 17395 serializer.startTag(null, TAG_GRANT); 17396 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17397 pkgGrantsKnown = true; 17398 } 17399 17400 final boolean userSet = 17401 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17402 final boolean userFixed = 17403 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17404 final boolean revoke = 17405 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17406 17407 serializer.startTag(null, TAG_PERMISSION); 17408 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17409 if (isGranted) { 17410 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17411 } 17412 if (userSet) { 17413 serializer.attribute(null, ATTR_USER_SET, "true"); 17414 } 17415 if (userFixed) { 17416 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17417 } 17418 if (revoke) { 17419 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17420 } 17421 serializer.endTag(null, TAG_PERMISSION); 17422 } 17423 } 17424 } 17425 17426 if (pkgGrantsKnown) { 17427 serializer.endTag(null, TAG_GRANT); 17428 } 17429 } 17430 17431 serializer.endTag(null, TAG_ALL_GRANTS); 17432 } 17433 17434 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17435 throws XmlPullParserException, IOException { 17436 String pkgName = null; 17437 int outerDepth = parser.getDepth(); 17438 int type; 17439 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17440 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17441 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17442 continue; 17443 } 17444 17445 final String tagName = parser.getName(); 17446 if (tagName.equals(TAG_GRANT)) { 17447 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17448 if (DEBUG_BACKUP) { 17449 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17450 } 17451 } else if (tagName.equals(TAG_PERMISSION)) { 17452 17453 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17454 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17455 17456 int newFlagSet = 0; 17457 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17458 newFlagSet |= FLAG_PERMISSION_USER_SET; 17459 } 17460 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17461 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17462 } 17463 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17464 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17465 } 17466 if (DEBUG_BACKUP) { 17467 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17468 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17469 } 17470 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17471 if (ps != null) { 17472 // Already installed so we apply the grant immediately 17473 if (DEBUG_BACKUP) { 17474 Slog.v(TAG, " + already installed; applying"); 17475 } 17476 PermissionsState perms = ps.getPermissionsState(); 17477 BasePermission bp = mSettings.mPermissions.get(permName); 17478 if (bp != null) { 17479 if (isGranted) { 17480 perms.grantRuntimePermission(bp, userId); 17481 } 17482 if (newFlagSet != 0) { 17483 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17484 } 17485 } 17486 } else { 17487 // Need to wait for post-restore install to apply the grant 17488 if (DEBUG_BACKUP) { 17489 Slog.v(TAG, " - not yet installed; saving for later"); 17490 } 17491 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17492 isGranted, newFlagSet, userId); 17493 } 17494 } else { 17495 PackageManagerService.reportSettingsProblem(Log.WARN, 17496 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17497 XmlUtils.skipCurrentTag(parser); 17498 } 17499 } 17500 17501 scheduleWriteSettingsLocked(); 17502 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17503 } 17504 17505 @Override 17506 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17507 int sourceUserId, int targetUserId, int flags) { 17508 mContext.enforceCallingOrSelfPermission( 17509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17510 int callingUid = Binder.getCallingUid(); 17511 enforceOwnerRights(ownerPackage, callingUid); 17512 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17513 if (intentFilter.countActions() == 0) { 17514 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17515 return; 17516 } 17517 synchronized (mPackages) { 17518 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17519 ownerPackage, targetUserId, flags); 17520 CrossProfileIntentResolver resolver = 17521 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17522 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17523 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17524 if (existing != null) { 17525 int size = existing.size(); 17526 for (int i = 0; i < size; i++) { 17527 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17528 return; 17529 } 17530 } 17531 } 17532 resolver.addFilter(newFilter); 17533 scheduleWritePackageRestrictionsLocked(sourceUserId); 17534 } 17535 } 17536 17537 @Override 17538 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17539 mContext.enforceCallingOrSelfPermission( 17540 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17541 int callingUid = Binder.getCallingUid(); 17542 enforceOwnerRights(ownerPackage, callingUid); 17543 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17544 synchronized (mPackages) { 17545 CrossProfileIntentResolver resolver = 17546 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17547 ArraySet<CrossProfileIntentFilter> set = 17548 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17549 for (CrossProfileIntentFilter filter : set) { 17550 if (filter.getOwnerPackage().equals(ownerPackage)) { 17551 resolver.removeFilter(filter); 17552 } 17553 } 17554 scheduleWritePackageRestrictionsLocked(sourceUserId); 17555 } 17556 } 17557 17558 // Enforcing that callingUid is owning pkg on userId 17559 private void enforceOwnerRights(String pkg, int callingUid) { 17560 // The system owns everything. 17561 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17562 return; 17563 } 17564 int callingUserId = UserHandle.getUserId(callingUid); 17565 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17566 if (pi == null) { 17567 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17568 + callingUserId); 17569 } 17570 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17571 throw new SecurityException("Calling uid " + callingUid 17572 + " does not own package " + pkg); 17573 } 17574 } 17575 17576 @Override 17577 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17578 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17579 } 17580 17581 private Intent getHomeIntent() { 17582 Intent intent = new Intent(Intent.ACTION_MAIN); 17583 intent.addCategory(Intent.CATEGORY_HOME); 17584 return intent; 17585 } 17586 17587 private IntentFilter getHomeFilter() { 17588 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17589 filter.addCategory(Intent.CATEGORY_HOME); 17590 filter.addCategory(Intent.CATEGORY_DEFAULT); 17591 return filter; 17592 } 17593 17594 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17595 int userId) { 17596 Intent intent = getHomeIntent(); 17597 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17598 PackageManager.GET_META_DATA, userId); 17599 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17600 true, false, false, userId); 17601 17602 allHomeCandidates.clear(); 17603 if (list != null) { 17604 for (ResolveInfo ri : list) { 17605 allHomeCandidates.add(ri); 17606 } 17607 } 17608 return (preferred == null || preferred.activityInfo == null) 17609 ? null 17610 : new ComponentName(preferred.activityInfo.packageName, 17611 preferred.activityInfo.name); 17612 } 17613 17614 @Override 17615 public void setHomeActivity(ComponentName comp, int userId) { 17616 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17617 getHomeActivitiesAsUser(homeActivities, userId); 17618 17619 boolean found = false; 17620 17621 final int size = homeActivities.size(); 17622 final ComponentName[] set = new ComponentName[size]; 17623 for (int i = 0; i < size; i++) { 17624 final ResolveInfo candidate = homeActivities.get(i); 17625 final ActivityInfo info = candidate.activityInfo; 17626 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17627 set[i] = activityName; 17628 if (!found && activityName.equals(comp)) { 17629 found = true; 17630 } 17631 } 17632 if (!found) { 17633 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17634 + userId); 17635 } 17636 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17637 set, comp, userId); 17638 } 17639 17640 private @Nullable String getSetupWizardPackageName() { 17641 final Intent intent = new Intent(Intent.ACTION_MAIN); 17642 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17643 17644 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17645 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17646 | MATCH_DISABLED_COMPONENTS, 17647 UserHandle.myUserId()); 17648 if (matches.size() == 1) { 17649 return matches.get(0).getComponentInfo().packageName; 17650 } else { 17651 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17652 + ": matches=" + matches); 17653 return null; 17654 } 17655 } 17656 17657 @Override 17658 public void setApplicationEnabledSetting(String appPackageName, 17659 int newState, int flags, int userId, String callingPackage) { 17660 if (!sUserManager.exists(userId)) return; 17661 if (callingPackage == null) { 17662 callingPackage = Integer.toString(Binder.getCallingUid()); 17663 } 17664 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17665 } 17666 17667 @Override 17668 public void setComponentEnabledSetting(ComponentName componentName, 17669 int newState, int flags, int userId) { 17670 if (!sUserManager.exists(userId)) return; 17671 setEnabledSetting(componentName.getPackageName(), 17672 componentName.getClassName(), newState, flags, userId, null); 17673 } 17674 17675 private void setEnabledSetting(final String packageName, String className, int newState, 17676 final int flags, int userId, String callingPackage) { 17677 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17678 || newState == COMPONENT_ENABLED_STATE_ENABLED 17679 || newState == COMPONENT_ENABLED_STATE_DISABLED 17680 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17681 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17682 throw new IllegalArgumentException("Invalid new component state: " 17683 + newState); 17684 } 17685 PackageSetting pkgSetting; 17686 final int uid = Binder.getCallingUid(); 17687 final int permission; 17688 if (uid == Process.SYSTEM_UID) { 17689 permission = PackageManager.PERMISSION_GRANTED; 17690 } else { 17691 permission = mContext.checkCallingOrSelfPermission( 17692 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17693 } 17694 enforceCrossUserPermission(uid, userId, 17695 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17696 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17697 boolean sendNow = false; 17698 boolean isApp = (className == null); 17699 String componentName = isApp ? packageName : className; 17700 int packageUid = -1; 17701 ArrayList<String> components; 17702 17703 // writer 17704 synchronized (mPackages) { 17705 pkgSetting = mSettings.mPackages.get(packageName); 17706 if (pkgSetting == null) { 17707 if (className == null) { 17708 throw new IllegalArgumentException("Unknown package: " + packageName); 17709 } 17710 throw new IllegalArgumentException( 17711 "Unknown component: " + packageName + "/" + className); 17712 } 17713 } 17714 17715 // Limit who can change which apps 17716 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17717 // Don't allow apps that don't have permission to modify other apps 17718 if (!allowedByPermission) { 17719 throw new SecurityException( 17720 "Permission Denial: attempt to change component state from pid=" 17721 + Binder.getCallingPid() 17722 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17723 } 17724 // Don't allow changing profile and device owners. 17725 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17726 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17727 } 17728 } 17729 17730 synchronized (mPackages) { 17731 if (uid == Process.SHELL_UID) { 17732 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17733 int oldState = pkgSetting.getEnabled(userId); 17734 if (className == null 17735 && 17736 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17737 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17738 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17739 && 17740 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17741 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17742 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17743 // ok 17744 } else { 17745 throw new SecurityException( 17746 "Shell cannot change component state for " + packageName + "/" 17747 + className + " to " + newState); 17748 } 17749 } 17750 if (className == null) { 17751 // We're dealing with an application/package level state change 17752 if (pkgSetting.getEnabled(userId) == newState) { 17753 // Nothing to do 17754 return; 17755 } 17756 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17757 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17758 // Don't care about who enables an app. 17759 callingPackage = null; 17760 } 17761 pkgSetting.setEnabled(newState, userId, callingPackage); 17762 // pkgSetting.pkg.mSetEnabled = newState; 17763 } else { 17764 // We're dealing with a component level state change 17765 // First, verify that this is a valid class name. 17766 PackageParser.Package pkg = pkgSetting.pkg; 17767 if (pkg == null || !pkg.hasComponentClassName(className)) { 17768 if (pkg != null && 17769 pkg.applicationInfo.targetSdkVersion >= 17770 Build.VERSION_CODES.JELLY_BEAN) { 17771 throw new IllegalArgumentException("Component class " + className 17772 + " does not exist in " + packageName); 17773 } else { 17774 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17775 + className + " does not exist in " + packageName); 17776 } 17777 } 17778 switch (newState) { 17779 case COMPONENT_ENABLED_STATE_ENABLED: 17780 if (!pkgSetting.enableComponentLPw(className, userId)) { 17781 return; 17782 } 17783 break; 17784 case COMPONENT_ENABLED_STATE_DISABLED: 17785 if (!pkgSetting.disableComponentLPw(className, userId)) { 17786 return; 17787 } 17788 break; 17789 case COMPONENT_ENABLED_STATE_DEFAULT: 17790 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17791 return; 17792 } 17793 break; 17794 default: 17795 Slog.e(TAG, "Invalid new component state: " + newState); 17796 return; 17797 } 17798 } 17799 scheduleWritePackageRestrictionsLocked(userId); 17800 components = mPendingBroadcasts.get(userId, packageName); 17801 final boolean newPackage = components == null; 17802 if (newPackage) { 17803 components = new ArrayList<String>(); 17804 } 17805 if (!components.contains(componentName)) { 17806 components.add(componentName); 17807 } 17808 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17809 sendNow = true; 17810 // Purge entry from pending broadcast list if another one exists already 17811 // since we are sending one right away. 17812 mPendingBroadcasts.remove(userId, packageName); 17813 } else { 17814 if (newPackage) { 17815 mPendingBroadcasts.put(userId, packageName, components); 17816 } 17817 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17818 // Schedule a message 17819 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17820 } 17821 } 17822 } 17823 17824 long callingId = Binder.clearCallingIdentity(); 17825 try { 17826 if (sendNow) { 17827 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17828 sendPackageChangedBroadcast(packageName, 17829 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17830 } 17831 } finally { 17832 Binder.restoreCallingIdentity(callingId); 17833 } 17834 } 17835 17836 @Override 17837 public void flushPackageRestrictionsAsUser(int userId) { 17838 if (!sUserManager.exists(userId)) { 17839 return; 17840 } 17841 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17842 false /* checkShell */, "flushPackageRestrictions"); 17843 synchronized (mPackages) { 17844 mSettings.writePackageRestrictionsLPr(userId); 17845 mDirtyUsers.remove(userId); 17846 if (mDirtyUsers.isEmpty()) { 17847 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17848 } 17849 } 17850 } 17851 17852 private void sendPackageChangedBroadcast(String packageName, 17853 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17854 if (DEBUG_INSTALL) 17855 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17856 + componentNames); 17857 Bundle extras = new Bundle(4); 17858 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17859 String nameList[] = new String[componentNames.size()]; 17860 componentNames.toArray(nameList); 17861 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17862 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17863 extras.putInt(Intent.EXTRA_UID, packageUid); 17864 // If this is not reporting a change of the overall package, then only send it 17865 // to registered receivers. We don't want to launch a swath of apps for every 17866 // little component state change. 17867 final int flags = !componentNames.contains(packageName) 17868 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17869 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17870 new int[] {UserHandle.getUserId(packageUid)}); 17871 } 17872 17873 @Override 17874 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17875 if (!sUserManager.exists(userId)) return; 17876 final int uid = Binder.getCallingUid(); 17877 final int permission = mContext.checkCallingOrSelfPermission( 17878 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17879 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17880 enforceCrossUserPermission(uid, userId, 17881 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17882 // writer 17883 synchronized (mPackages) { 17884 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17885 allowedByPermission, uid, userId)) { 17886 scheduleWritePackageRestrictionsLocked(userId); 17887 } 17888 } 17889 } 17890 17891 @Override 17892 public String getInstallerPackageName(String packageName) { 17893 // reader 17894 synchronized (mPackages) { 17895 return mSettings.getInstallerPackageNameLPr(packageName); 17896 } 17897 } 17898 17899 public boolean isOrphaned(String packageName) { 17900 // reader 17901 synchronized (mPackages) { 17902 return mSettings.isOrphaned(packageName); 17903 } 17904 } 17905 17906 @Override 17907 public int getApplicationEnabledSetting(String packageName, int userId) { 17908 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17909 int uid = Binder.getCallingUid(); 17910 enforceCrossUserPermission(uid, userId, 17911 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17912 // reader 17913 synchronized (mPackages) { 17914 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17915 } 17916 } 17917 17918 @Override 17919 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17920 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17921 int uid = Binder.getCallingUid(); 17922 enforceCrossUserPermission(uid, userId, 17923 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17924 // reader 17925 synchronized (mPackages) { 17926 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17927 } 17928 } 17929 17930 @Override 17931 public void enterSafeMode() { 17932 enforceSystemOrRoot("Only the system can request entering safe mode"); 17933 17934 if (!mSystemReady) { 17935 mSafeMode = true; 17936 } 17937 } 17938 17939 @Override 17940 public void systemReady() { 17941 mSystemReady = true; 17942 17943 // Read the compatibilty setting when the system is ready. 17944 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17945 mContext.getContentResolver(), 17946 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17947 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17948 if (DEBUG_SETTINGS) { 17949 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17950 } 17951 17952 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17953 17954 synchronized (mPackages) { 17955 // Verify that all of the preferred activity components actually 17956 // exist. It is possible for applications to be updated and at 17957 // that point remove a previously declared activity component that 17958 // had been set as a preferred activity. We try to clean this up 17959 // the next time we encounter that preferred activity, but it is 17960 // possible for the user flow to never be able to return to that 17961 // situation so here we do a sanity check to make sure we haven't 17962 // left any junk around. 17963 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17964 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17965 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17966 removed.clear(); 17967 for (PreferredActivity pa : pir.filterSet()) { 17968 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17969 removed.add(pa); 17970 } 17971 } 17972 if (removed.size() > 0) { 17973 for (int r=0; r<removed.size(); r++) { 17974 PreferredActivity pa = removed.get(r); 17975 Slog.w(TAG, "Removing dangling preferred activity: " 17976 + pa.mPref.mComponent); 17977 pir.removeFilter(pa); 17978 } 17979 mSettings.writePackageRestrictionsLPr( 17980 mSettings.mPreferredActivities.keyAt(i)); 17981 } 17982 } 17983 17984 for (int userId : UserManagerService.getInstance().getUserIds()) { 17985 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17986 grantPermissionsUserIds = ArrayUtils.appendInt( 17987 grantPermissionsUserIds, userId); 17988 } 17989 } 17990 } 17991 sUserManager.systemReady(); 17992 17993 // If we upgraded grant all default permissions before kicking off. 17994 for (int userId : grantPermissionsUserIds) { 17995 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17996 } 17997 17998 // Kick off any messages waiting for system ready 17999 if (mPostSystemReadyMessages != null) { 18000 for (Message msg : mPostSystemReadyMessages) { 18001 msg.sendToTarget(); 18002 } 18003 mPostSystemReadyMessages = null; 18004 } 18005 18006 // Watch for external volumes that come and go over time 18007 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18008 storage.registerListener(mStorageListener); 18009 18010 mInstallerService.systemReady(); 18011 mPackageDexOptimizer.systemReady(); 18012 18013 MountServiceInternal mountServiceInternal = LocalServices.getService( 18014 MountServiceInternal.class); 18015 mountServiceInternal.addExternalStoragePolicy( 18016 new MountServiceInternal.ExternalStorageMountPolicy() { 18017 @Override 18018 public int getMountMode(int uid, String packageName) { 18019 if (Process.isIsolated(uid)) { 18020 return Zygote.MOUNT_EXTERNAL_NONE; 18021 } 18022 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18023 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18024 } 18025 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18026 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18027 } 18028 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18029 return Zygote.MOUNT_EXTERNAL_READ; 18030 } 18031 return Zygote.MOUNT_EXTERNAL_WRITE; 18032 } 18033 18034 @Override 18035 public boolean hasExternalStorage(int uid, String packageName) { 18036 return true; 18037 } 18038 }); 18039 18040 // Now that we're mostly running, clean up stale users and apps 18041 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18042 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18043 } 18044 18045 @Override 18046 public boolean isSafeMode() { 18047 return mSafeMode; 18048 } 18049 18050 @Override 18051 public boolean hasSystemUidErrors() { 18052 return mHasSystemUidErrors; 18053 } 18054 18055 static String arrayToString(int[] array) { 18056 StringBuffer buf = new StringBuffer(128); 18057 buf.append('['); 18058 if (array != null) { 18059 for (int i=0; i<array.length; i++) { 18060 if (i > 0) buf.append(", "); 18061 buf.append(array[i]); 18062 } 18063 } 18064 buf.append(']'); 18065 return buf.toString(); 18066 } 18067 18068 static class DumpState { 18069 public static final int DUMP_LIBS = 1 << 0; 18070 public static final int DUMP_FEATURES = 1 << 1; 18071 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18072 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18073 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18074 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18075 public static final int DUMP_PERMISSIONS = 1 << 6; 18076 public static final int DUMP_PACKAGES = 1 << 7; 18077 public static final int DUMP_SHARED_USERS = 1 << 8; 18078 public static final int DUMP_MESSAGES = 1 << 9; 18079 public static final int DUMP_PROVIDERS = 1 << 10; 18080 public static final int DUMP_VERIFIERS = 1 << 11; 18081 public static final int DUMP_PREFERRED = 1 << 12; 18082 public static final int DUMP_PREFERRED_XML = 1 << 13; 18083 public static final int DUMP_KEYSETS = 1 << 14; 18084 public static final int DUMP_VERSION = 1 << 15; 18085 public static final int DUMP_INSTALLS = 1 << 16; 18086 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18087 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18088 public static final int DUMP_FROZEN = 1 << 19; 18089 public static final int DUMP_DEXOPT = 1 << 20; 18090 18091 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18092 18093 private int mTypes; 18094 18095 private int mOptions; 18096 18097 private boolean mTitlePrinted; 18098 18099 private SharedUserSetting mSharedUser; 18100 18101 public boolean isDumping(int type) { 18102 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18103 return true; 18104 } 18105 18106 return (mTypes & type) != 0; 18107 } 18108 18109 public void setDump(int type) { 18110 mTypes |= type; 18111 } 18112 18113 public boolean isOptionEnabled(int option) { 18114 return (mOptions & option) != 0; 18115 } 18116 18117 public void setOptionEnabled(int option) { 18118 mOptions |= option; 18119 } 18120 18121 public boolean onTitlePrinted() { 18122 final boolean printed = mTitlePrinted; 18123 mTitlePrinted = true; 18124 return printed; 18125 } 18126 18127 public boolean getTitlePrinted() { 18128 return mTitlePrinted; 18129 } 18130 18131 public void setTitlePrinted(boolean enabled) { 18132 mTitlePrinted = enabled; 18133 } 18134 18135 public SharedUserSetting getSharedUser() { 18136 return mSharedUser; 18137 } 18138 18139 public void setSharedUser(SharedUserSetting user) { 18140 mSharedUser = user; 18141 } 18142 } 18143 18144 @Override 18145 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18146 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18147 (new PackageManagerShellCommand(this)).exec( 18148 this, in, out, err, args, resultReceiver); 18149 } 18150 18151 @Override 18152 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18153 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18154 != PackageManager.PERMISSION_GRANTED) { 18155 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18156 + Binder.getCallingPid() 18157 + ", uid=" + Binder.getCallingUid() 18158 + " without permission " 18159 + android.Manifest.permission.DUMP); 18160 return; 18161 } 18162 18163 DumpState dumpState = new DumpState(); 18164 boolean fullPreferred = false; 18165 boolean checkin = false; 18166 18167 String packageName = null; 18168 ArraySet<String> permissionNames = null; 18169 18170 int opti = 0; 18171 while (opti < args.length) { 18172 String opt = args[opti]; 18173 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18174 break; 18175 } 18176 opti++; 18177 18178 if ("-a".equals(opt)) { 18179 // Right now we only know how to print all. 18180 } else if ("-h".equals(opt)) { 18181 pw.println("Package manager dump options:"); 18182 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18183 pw.println(" --checkin: dump for a checkin"); 18184 pw.println(" -f: print details of intent filters"); 18185 pw.println(" -h: print this help"); 18186 pw.println(" cmd may be one of:"); 18187 pw.println(" l[ibraries]: list known shared libraries"); 18188 pw.println(" f[eatures]: list device features"); 18189 pw.println(" k[eysets]: print known keysets"); 18190 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18191 pw.println(" perm[issions]: dump permissions"); 18192 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18193 pw.println(" pref[erred]: print preferred package settings"); 18194 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18195 pw.println(" prov[iders]: dump content providers"); 18196 pw.println(" p[ackages]: dump installed packages"); 18197 pw.println(" s[hared-users]: dump shared user IDs"); 18198 pw.println(" m[essages]: print collected runtime messages"); 18199 pw.println(" v[erifiers]: print package verifier info"); 18200 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18201 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18202 pw.println(" version: print database version info"); 18203 pw.println(" write: write current settings now"); 18204 pw.println(" installs: details about install sessions"); 18205 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18206 pw.println(" dexopt: dump dexopt state"); 18207 pw.println(" <package.name>: info about given package"); 18208 return; 18209 } else if ("--checkin".equals(opt)) { 18210 checkin = true; 18211 } else if ("-f".equals(opt)) { 18212 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18213 } else { 18214 pw.println("Unknown argument: " + opt + "; use -h for help"); 18215 } 18216 } 18217 18218 // Is the caller requesting to dump a particular piece of data? 18219 if (opti < args.length) { 18220 String cmd = args[opti]; 18221 opti++; 18222 // Is this a package name? 18223 if ("android".equals(cmd) || cmd.contains(".")) { 18224 packageName = cmd; 18225 // When dumping a single package, we always dump all of its 18226 // filter information since the amount of data will be reasonable. 18227 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18228 } else if ("check-permission".equals(cmd)) { 18229 if (opti >= args.length) { 18230 pw.println("Error: check-permission missing permission argument"); 18231 return; 18232 } 18233 String perm = args[opti]; 18234 opti++; 18235 if (opti >= args.length) { 18236 pw.println("Error: check-permission missing package argument"); 18237 return; 18238 } 18239 String pkg = args[opti]; 18240 opti++; 18241 int user = UserHandle.getUserId(Binder.getCallingUid()); 18242 if (opti < args.length) { 18243 try { 18244 user = Integer.parseInt(args[opti]); 18245 } catch (NumberFormatException e) { 18246 pw.println("Error: check-permission user argument is not a number: " 18247 + args[opti]); 18248 return; 18249 } 18250 } 18251 pw.println(checkPermission(perm, pkg, user)); 18252 return; 18253 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18254 dumpState.setDump(DumpState.DUMP_LIBS); 18255 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18256 dumpState.setDump(DumpState.DUMP_FEATURES); 18257 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18258 if (opti >= args.length) { 18259 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18260 | DumpState.DUMP_SERVICE_RESOLVERS 18261 | DumpState.DUMP_RECEIVER_RESOLVERS 18262 | DumpState.DUMP_CONTENT_RESOLVERS); 18263 } else { 18264 while (opti < args.length) { 18265 String name = args[opti]; 18266 if ("a".equals(name) || "activity".equals(name)) { 18267 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18268 } else if ("s".equals(name) || "service".equals(name)) { 18269 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18270 } else if ("r".equals(name) || "receiver".equals(name)) { 18271 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18272 } else if ("c".equals(name) || "content".equals(name)) { 18273 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18274 } else { 18275 pw.println("Error: unknown resolver table type: " + name); 18276 return; 18277 } 18278 opti++; 18279 } 18280 } 18281 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18282 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18283 } else if ("permission".equals(cmd)) { 18284 if (opti >= args.length) { 18285 pw.println("Error: permission requires permission name"); 18286 return; 18287 } 18288 permissionNames = new ArraySet<>(); 18289 while (opti < args.length) { 18290 permissionNames.add(args[opti]); 18291 opti++; 18292 } 18293 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18294 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18295 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18296 dumpState.setDump(DumpState.DUMP_PREFERRED); 18297 } else if ("preferred-xml".equals(cmd)) { 18298 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18299 if (opti < args.length && "--full".equals(args[opti])) { 18300 fullPreferred = true; 18301 opti++; 18302 } 18303 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18304 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18305 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18306 dumpState.setDump(DumpState.DUMP_PACKAGES); 18307 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18308 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18309 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18310 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18311 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18312 dumpState.setDump(DumpState.DUMP_MESSAGES); 18313 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18314 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18315 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18316 || "intent-filter-verifiers".equals(cmd)) { 18317 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18318 } else if ("version".equals(cmd)) { 18319 dumpState.setDump(DumpState.DUMP_VERSION); 18320 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18321 dumpState.setDump(DumpState.DUMP_KEYSETS); 18322 } else if ("installs".equals(cmd)) { 18323 dumpState.setDump(DumpState.DUMP_INSTALLS); 18324 } else if ("frozen".equals(cmd)) { 18325 dumpState.setDump(DumpState.DUMP_FROZEN); 18326 } else if ("dexopt".equals(cmd)) { 18327 dumpState.setDump(DumpState.DUMP_DEXOPT); 18328 } else if ("write".equals(cmd)) { 18329 synchronized (mPackages) { 18330 mSettings.writeLPr(); 18331 pw.println("Settings written."); 18332 return; 18333 } 18334 } 18335 } 18336 18337 if (checkin) { 18338 pw.println("vers,1"); 18339 } 18340 18341 // reader 18342 synchronized (mPackages) { 18343 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18344 if (!checkin) { 18345 if (dumpState.onTitlePrinted()) 18346 pw.println(); 18347 pw.println("Database versions:"); 18348 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18349 } 18350 } 18351 18352 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18353 if (!checkin) { 18354 if (dumpState.onTitlePrinted()) 18355 pw.println(); 18356 pw.println("Verifiers:"); 18357 pw.print(" Required: "); 18358 pw.print(mRequiredVerifierPackage); 18359 pw.print(" (uid="); 18360 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18361 UserHandle.USER_SYSTEM)); 18362 pw.println(")"); 18363 } else if (mRequiredVerifierPackage != null) { 18364 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18365 pw.print(","); 18366 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18367 UserHandle.USER_SYSTEM)); 18368 } 18369 } 18370 18371 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18372 packageName == null) { 18373 if (mIntentFilterVerifierComponent != null) { 18374 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18375 if (!checkin) { 18376 if (dumpState.onTitlePrinted()) 18377 pw.println(); 18378 pw.println("Intent Filter Verifier:"); 18379 pw.print(" Using: "); 18380 pw.print(verifierPackageName); 18381 pw.print(" (uid="); 18382 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18383 UserHandle.USER_SYSTEM)); 18384 pw.println(")"); 18385 } else if (verifierPackageName != null) { 18386 pw.print("ifv,"); pw.print(verifierPackageName); 18387 pw.print(","); 18388 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18389 UserHandle.USER_SYSTEM)); 18390 } 18391 } else { 18392 pw.println(); 18393 pw.println("No Intent Filter Verifier available!"); 18394 } 18395 } 18396 18397 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18398 boolean printedHeader = false; 18399 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18400 while (it.hasNext()) { 18401 String name = it.next(); 18402 SharedLibraryEntry ent = mSharedLibraries.get(name); 18403 if (!checkin) { 18404 if (!printedHeader) { 18405 if (dumpState.onTitlePrinted()) 18406 pw.println(); 18407 pw.println("Libraries:"); 18408 printedHeader = true; 18409 } 18410 pw.print(" "); 18411 } else { 18412 pw.print("lib,"); 18413 } 18414 pw.print(name); 18415 if (!checkin) { 18416 pw.print(" -> "); 18417 } 18418 if (ent.path != null) { 18419 if (!checkin) { 18420 pw.print("(jar) "); 18421 pw.print(ent.path); 18422 } else { 18423 pw.print(",jar,"); 18424 pw.print(ent.path); 18425 } 18426 } else { 18427 if (!checkin) { 18428 pw.print("(apk) "); 18429 pw.print(ent.apk); 18430 } else { 18431 pw.print(",apk,"); 18432 pw.print(ent.apk); 18433 } 18434 } 18435 pw.println(); 18436 } 18437 } 18438 18439 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18440 if (dumpState.onTitlePrinted()) 18441 pw.println(); 18442 if (!checkin) { 18443 pw.println("Features:"); 18444 } 18445 18446 for (FeatureInfo feat : mAvailableFeatures.values()) { 18447 if (checkin) { 18448 pw.print("feat,"); 18449 pw.print(feat.name); 18450 pw.print(","); 18451 pw.println(feat.version); 18452 } else { 18453 pw.print(" "); 18454 pw.print(feat.name); 18455 if (feat.version > 0) { 18456 pw.print(" version="); 18457 pw.print(feat.version); 18458 } 18459 pw.println(); 18460 } 18461 } 18462 } 18463 18464 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18465 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18466 : "Activity Resolver Table:", " ", packageName, 18467 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18468 dumpState.setTitlePrinted(true); 18469 } 18470 } 18471 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18472 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18473 : "Receiver Resolver Table:", " ", packageName, 18474 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18475 dumpState.setTitlePrinted(true); 18476 } 18477 } 18478 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18479 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18480 : "Service Resolver Table:", " ", packageName, 18481 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18482 dumpState.setTitlePrinted(true); 18483 } 18484 } 18485 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18486 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18487 : "Provider Resolver Table:", " ", packageName, 18488 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18489 dumpState.setTitlePrinted(true); 18490 } 18491 } 18492 18493 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18494 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18495 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18496 int user = mSettings.mPreferredActivities.keyAt(i); 18497 if (pir.dump(pw, 18498 dumpState.getTitlePrinted() 18499 ? "\nPreferred Activities User " + user + ":" 18500 : "Preferred Activities User " + user + ":", " ", 18501 packageName, true, false)) { 18502 dumpState.setTitlePrinted(true); 18503 } 18504 } 18505 } 18506 18507 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18508 pw.flush(); 18509 FileOutputStream fout = new FileOutputStream(fd); 18510 BufferedOutputStream str = new BufferedOutputStream(fout); 18511 XmlSerializer serializer = new FastXmlSerializer(); 18512 try { 18513 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18514 serializer.startDocument(null, true); 18515 serializer.setFeature( 18516 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18517 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18518 serializer.endDocument(); 18519 serializer.flush(); 18520 } catch (IllegalArgumentException e) { 18521 pw.println("Failed writing: " + e); 18522 } catch (IllegalStateException e) { 18523 pw.println("Failed writing: " + e); 18524 } catch (IOException e) { 18525 pw.println("Failed writing: " + e); 18526 } 18527 } 18528 18529 if (!checkin 18530 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18531 && packageName == null) { 18532 pw.println(); 18533 int count = mSettings.mPackages.size(); 18534 if (count == 0) { 18535 pw.println("No applications!"); 18536 pw.println(); 18537 } else { 18538 final String prefix = " "; 18539 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18540 if (allPackageSettings.size() == 0) { 18541 pw.println("No domain preferred apps!"); 18542 pw.println(); 18543 } else { 18544 pw.println("App verification status:"); 18545 pw.println(); 18546 count = 0; 18547 for (PackageSetting ps : allPackageSettings) { 18548 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18549 if (ivi == null || ivi.getPackageName() == null) continue; 18550 pw.println(prefix + "Package: " + ivi.getPackageName()); 18551 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18552 pw.println(prefix + "Status: " + ivi.getStatusString()); 18553 pw.println(); 18554 count++; 18555 } 18556 if (count == 0) { 18557 pw.println(prefix + "No app verification established."); 18558 pw.println(); 18559 } 18560 for (int userId : sUserManager.getUserIds()) { 18561 pw.println("App linkages for user " + userId + ":"); 18562 pw.println(); 18563 count = 0; 18564 for (PackageSetting ps : allPackageSettings) { 18565 final long status = ps.getDomainVerificationStatusForUser(userId); 18566 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18567 continue; 18568 } 18569 pw.println(prefix + "Package: " + ps.name); 18570 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18571 String statusStr = IntentFilterVerificationInfo. 18572 getStatusStringFromValue(status); 18573 pw.println(prefix + "Status: " + statusStr); 18574 pw.println(); 18575 count++; 18576 } 18577 if (count == 0) { 18578 pw.println(prefix + "No configured app linkages."); 18579 pw.println(); 18580 } 18581 } 18582 } 18583 } 18584 } 18585 18586 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18587 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18588 if (packageName == null && permissionNames == null) { 18589 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18590 if (iperm == 0) { 18591 if (dumpState.onTitlePrinted()) 18592 pw.println(); 18593 pw.println("AppOp Permissions:"); 18594 } 18595 pw.print(" AppOp Permission "); 18596 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18597 pw.println(":"); 18598 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18599 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18600 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18601 } 18602 } 18603 } 18604 } 18605 18606 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18607 boolean printedSomething = false; 18608 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18609 if (packageName != null && !packageName.equals(p.info.packageName)) { 18610 continue; 18611 } 18612 if (!printedSomething) { 18613 if (dumpState.onTitlePrinted()) 18614 pw.println(); 18615 pw.println("Registered ContentProviders:"); 18616 printedSomething = true; 18617 } 18618 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18619 pw.print(" "); pw.println(p.toString()); 18620 } 18621 printedSomething = false; 18622 for (Map.Entry<String, PackageParser.Provider> entry : 18623 mProvidersByAuthority.entrySet()) { 18624 PackageParser.Provider p = entry.getValue(); 18625 if (packageName != null && !packageName.equals(p.info.packageName)) { 18626 continue; 18627 } 18628 if (!printedSomething) { 18629 if (dumpState.onTitlePrinted()) 18630 pw.println(); 18631 pw.println("ContentProvider Authorities:"); 18632 printedSomething = true; 18633 } 18634 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18635 pw.print(" "); pw.println(p.toString()); 18636 if (p.info != null && p.info.applicationInfo != null) { 18637 final String appInfo = p.info.applicationInfo.toString(); 18638 pw.print(" applicationInfo="); pw.println(appInfo); 18639 } 18640 } 18641 } 18642 18643 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18644 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18645 } 18646 18647 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18648 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18649 } 18650 18651 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18652 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18653 } 18654 18655 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18656 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18657 } 18658 18659 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18660 // XXX should handle packageName != null by dumping only install data that 18661 // the given package is involved with. 18662 if (dumpState.onTitlePrinted()) pw.println(); 18663 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18664 } 18665 18666 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18667 // XXX should handle packageName != null by dumping only install data that 18668 // the given package is involved with. 18669 if (dumpState.onTitlePrinted()) pw.println(); 18670 18671 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18672 ipw.println(); 18673 ipw.println("Frozen packages:"); 18674 ipw.increaseIndent(); 18675 if (mFrozenPackages.size() == 0) { 18676 ipw.println("(none)"); 18677 } else { 18678 for (int i = 0; i < mFrozenPackages.size(); i++) { 18679 ipw.println(mFrozenPackages.valueAt(i)); 18680 } 18681 } 18682 ipw.decreaseIndent(); 18683 } 18684 18685 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18686 if (dumpState.onTitlePrinted()) pw.println(); 18687 dumpDexoptStateLPr(pw, packageName); 18688 } 18689 18690 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18691 if (dumpState.onTitlePrinted()) pw.println(); 18692 mSettings.dumpReadMessagesLPr(pw, dumpState); 18693 18694 pw.println(); 18695 pw.println("Package warning messages:"); 18696 BufferedReader in = null; 18697 String line = null; 18698 try { 18699 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18700 while ((line = in.readLine()) != null) { 18701 if (line.contains("ignored: updated version")) continue; 18702 pw.println(line); 18703 } 18704 } catch (IOException ignored) { 18705 } finally { 18706 IoUtils.closeQuietly(in); 18707 } 18708 } 18709 18710 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18711 BufferedReader in = null; 18712 String line = null; 18713 try { 18714 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18715 while ((line = in.readLine()) != null) { 18716 if (line.contains("ignored: updated version")) continue; 18717 pw.print("msg,"); 18718 pw.println(line); 18719 } 18720 } catch (IOException ignored) { 18721 } finally { 18722 IoUtils.closeQuietly(in); 18723 } 18724 } 18725 } 18726 } 18727 18728 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18729 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18730 ipw.println(); 18731 ipw.println("Dexopt state:"); 18732 ipw.increaseIndent(); 18733 Collection<PackageParser.Package> packages = null; 18734 if (packageName != null) { 18735 PackageParser.Package targetPackage = mPackages.get(packageName); 18736 if (targetPackage != null) { 18737 packages = Collections.singletonList(targetPackage); 18738 } else { 18739 ipw.println("Unable to find package: " + packageName); 18740 return; 18741 } 18742 } else { 18743 packages = mPackages.values(); 18744 } 18745 18746 for (PackageParser.Package pkg : packages) { 18747 ipw.println("[" + pkg.packageName + "]"); 18748 ipw.increaseIndent(); 18749 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18750 ipw.decreaseIndent(); 18751 } 18752 } 18753 18754 private String dumpDomainString(String packageName) { 18755 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18756 .getList(); 18757 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18758 18759 ArraySet<String> result = new ArraySet<>(); 18760 if (iviList.size() > 0) { 18761 for (IntentFilterVerificationInfo ivi : iviList) { 18762 for (String host : ivi.getDomains()) { 18763 result.add(host); 18764 } 18765 } 18766 } 18767 if (filters != null && filters.size() > 0) { 18768 for (IntentFilter filter : filters) { 18769 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18770 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18771 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18772 result.addAll(filter.getHostsList()); 18773 } 18774 } 18775 } 18776 18777 StringBuilder sb = new StringBuilder(result.size() * 16); 18778 for (String domain : result) { 18779 if (sb.length() > 0) sb.append(" "); 18780 sb.append(domain); 18781 } 18782 return sb.toString(); 18783 } 18784 18785 // ------- apps on sdcard specific code ------- 18786 static final boolean DEBUG_SD_INSTALL = false; 18787 18788 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18789 18790 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18791 18792 private boolean mMediaMounted = false; 18793 18794 static String getEncryptKey() { 18795 try { 18796 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18797 SD_ENCRYPTION_KEYSTORE_NAME); 18798 if (sdEncKey == null) { 18799 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18800 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18801 if (sdEncKey == null) { 18802 Slog.e(TAG, "Failed to create encryption keys"); 18803 return null; 18804 } 18805 } 18806 return sdEncKey; 18807 } catch (NoSuchAlgorithmException nsae) { 18808 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18809 return null; 18810 } catch (IOException ioe) { 18811 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18812 return null; 18813 } 18814 } 18815 18816 /* 18817 * Update media status on PackageManager. 18818 */ 18819 @Override 18820 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18821 int callingUid = Binder.getCallingUid(); 18822 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18823 throw new SecurityException("Media status can only be updated by the system"); 18824 } 18825 // reader; this apparently protects mMediaMounted, but should probably 18826 // be a different lock in that case. 18827 synchronized (mPackages) { 18828 Log.i(TAG, "Updating external media status from " 18829 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18830 + (mediaStatus ? "mounted" : "unmounted")); 18831 if (DEBUG_SD_INSTALL) 18832 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18833 + ", mMediaMounted=" + mMediaMounted); 18834 if (mediaStatus == mMediaMounted) { 18835 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18836 : 0, -1); 18837 mHandler.sendMessage(msg); 18838 return; 18839 } 18840 mMediaMounted = mediaStatus; 18841 } 18842 // Queue up an async operation since the package installation may take a 18843 // little while. 18844 mHandler.post(new Runnable() { 18845 public void run() { 18846 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18847 } 18848 }); 18849 } 18850 18851 /** 18852 * Called by MountService when the initial ASECs to scan are available. 18853 * Should block until all the ASEC containers are finished being scanned. 18854 */ 18855 public void scanAvailableAsecs() { 18856 updateExternalMediaStatusInner(true, false, false); 18857 } 18858 18859 /* 18860 * Collect information of applications on external media, map them against 18861 * existing containers and update information based on current mount status. 18862 * Please note that we always have to report status if reportStatus has been 18863 * set to true especially when unloading packages. 18864 */ 18865 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18866 boolean externalStorage) { 18867 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18868 int[] uidArr = EmptyArray.INT; 18869 18870 final String[] list = PackageHelper.getSecureContainerList(); 18871 if (ArrayUtils.isEmpty(list)) { 18872 Log.i(TAG, "No secure containers found"); 18873 } else { 18874 // Process list of secure containers and categorize them 18875 // as active or stale based on their package internal state. 18876 18877 // reader 18878 synchronized (mPackages) { 18879 for (String cid : list) { 18880 // Leave stages untouched for now; installer service owns them 18881 if (PackageInstallerService.isStageName(cid)) continue; 18882 18883 if (DEBUG_SD_INSTALL) 18884 Log.i(TAG, "Processing container " + cid); 18885 String pkgName = getAsecPackageName(cid); 18886 if (pkgName == null) { 18887 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18888 continue; 18889 } 18890 if (DEBUG_SD_INSTALL) 18891 Log.i(TAG, "Looking for pkg : " + pkgName); 18892 18893 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18894 if (ps == null) { 18895 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18896 continue; 18897 } 18898 18899 /* 18900 * Skip packages that are not external if we're unmounting 18901 * external storage. 18902 */ 18903 if (externalStorage && !isMounted && !isExternal(ps)) { 18904 continue; 18905 } 18906 18907 final AsecInstallArgs args = new AsecInstallArgs(cid, 18908 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18909 // The package status is changed only if the code path 18910 // matches between settings and the container id. 18911 if (ps.codePathString != null 18912 && ps.codePathString.startsWith(args.getCodePath())) { 18913 if (DEBUG_SD_INSTALL) { 18914 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18915 + " at code path: " + ps.codePathString); 18916 } 18917 18918 // We do have a valid package installed on sdcard 18919 processCids.put(args, ps.codePathString); 18920 final int uid = ps.appId; 18921 if (uid != -1) { 18922 uidArr = ArrayUtils.appendInt(uidArr, uid); 18923 } 18924 } else { 18925 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18926 + ps.codePathString); 18927 } 18928 } 18929 } 18930 18931 Arrays.sort(uidArr); 18932 } 18933 18934 // Process packages with valid entries. 18935 if (isMounted) { 18936 if (DEBUG_SD_INSTALL) 18937 Log.i(TAG, "Loading packages"); 18938 loadMediaPackages(processCids, uidArr, externalStorage); 18939 startCleaningPackages(); 18940 mInstallerService.onSecureContainersAvailable(); 18941 } else { 18942 if (DEBUG_SD_INSTALL) 18943 Log.i(TAG, "Unloading packages"); 18944 unloadMediaPackages(processCids, uidArr, reportStatus); 18945 } 18946 } 18947 18948 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18949 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18950 final int size = infos.size(); 18951 final String[] packageNames = new String[size]; 18952 final int[] packageUids = new int[size]; 18953 for (int i = 0; i < size; i++) { 18954 final ApplicationInfo info = infos.get(i); 18955 packageNames[i] = info.packageName; 18956 packageUids[i] = info.uid; 18957 } 18958 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18959 finishedReceiver); 18960 } 18961 18962 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18963 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18964 sendResourcesChangedBroadcast(mediaStatus, replacing, 18965 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18966 } 18967 18968 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18969 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18970 int size = pkgList.length; 18971 if (size > 0) { 18972 // Send broadcasts here 18973 Bundle extras = new Bundle(); 18974 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18975 if (uidArr != null) { 18976 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18977 } 18978 if (replacing) { 18979 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18980 } 18981 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18982 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18983 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18984 } 18985 } 18986 18987 /* 18988 * Look at potentially valid container ids from processCids If package 18989 * information doesn't match the one on record or package scanning fails, 18990 * the cid is added to list of removeCids. We currently don't delete stale 18991 * containers. 18992 */ 18993 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18994 boolean externalStorage) { 18995 ArrayList<String> pkgList = new ArrayList<String>(); 18996 Set<AsecInstallArgs> keys = processCids.keySet(); 18997 18998 for (AsecInstallArgs args : keys) { 18999 String codePath = processCids.get(args); 19000 if (DEBUG_SD_INSTALL) 19001 Log.i(TAG, "Loading container : " + args.cid); 19002 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19003 try { 19004 // Make sure there are no container errors first. 19005 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19006 Slog.e(TAG, "Failed to mount cid : " + args.cid 19007 + " when installing from sdcard"); 19008 continue; 19009 } 19010 // Check code path here. 19011 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19012 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19013 + " does not match one in settings " + codePath); 19014 continue; 19015 } 19016 // Parse package 19017 int parseFlags = mDefParseFlags; 19018 if (args.isExternalAsec()) { 19019 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19020 } 19021 if (args.isFwdLocked()) { 19022 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19023 } 19024 19025 synchronized (mInstallLock) { 19026 PackageParser.Package pkg = null; 19027 try { 19028 // Sadly we don't know the package name yet to freeze it 19029 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19030 SCAN_IGNORE_FROZEN, 0, null); 19031 } catch (PackageManagerException e) { 19032 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19033 } 19034 // Scan the package 19035 if (pkg != null) { 19036 /* 19037 * TODO why is the lock being held? doPostInstall is 19038 * called in other places without the lock. This needs 19039 * to be straightened out. 19040 */ 19041 // writer 19042 synchronized (mPackages) { 19043 retCode = PackageManager.INSTALL_SUCCEEDED; 19044 pkgList.add(pkg.packageName); 19045 // Post process args 19046 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19047 pkg.applicationInfo.uid); 19048 } 19049 } else { 19050 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19051 } 19052 } 19053 19054 } finally { 19055 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19056 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19057 } 19058 } 19059 } 19060 // writer 19061 synchronized (mPackages) { 19062 // If the platform SDK has changed since the last time we booted, 19063 // we need to re-grant app permission to catch any new ones that 19064 // appear. This is really a hack, and means that apps can in some 19065 // cases get permissions that the user didn't initially explicitly 19066 // allow... it would be nice to have some better way to handle 19067 // this situation. 19068 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19069 : mSettings.getInternalVersion(); 19070 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19071 : StorageManager.UUID_PRIVATE_INTERNAL; 19072 19073 int updateFlags = UPDATE_PERMISSIONS_ALL; 19074 if (ver.sdkVersion != mSdkVersion) { 19075 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19076 + mSdkVersion + "; regranting permissions for external"); 19077 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19078 } 19079 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19080 19081 // Yay, everything is now upgraded 19082 ver.forceCurrent(); 19083 19084 // can downgrade to reader 19085 // Persist settings 19086 mSettings.writeLPr(); 19087 } 19088 // Send a broadcast to let everyone know we are done processing 19089 if (pkgList.size() > 0) { 19090 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19091 } 19092 } 19093 19094 /* 19095 * Utility method to unload a list of specified containers 19096 */ 19097 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19098 // Just unmount all valid containers. 19099 for (AsecInstallArgs arg : cidArgs) { 19100 synchronized (mInstallLock) { 19101 arg.doPostDeleteLI(false); 19102 } 19103 } 19104 } 19105 19106 /* 19107 * Unload packages mounted on external media. This involves deleting package 19108 * data from internal structures, sending broadcasts about disabled packages, 19109 * gc'ing to free up references, unmounting all secure containers 19110 * corresponding to packages on external media, and posting a 19111 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19112 * that we always have to post this message if status has been requested no 19113 * matter what. 19114 */ 19115 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19116 final boolean reportStatus) { 19117 if (DEBUG_SD_INSTALL) 19118 Log.i(TAG, "unloading media packages"); 19119 ArrayList<String> pkgList = new ArrayList<String>(); 19120 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19121 final Set<AsecInstallArgs> keys = processCids.keySet(); 19122 for (AsecInstallArgs args : keys) { 19123 String pkgName = args.getPackageName(); 19124 if (DEBUG_SD_INSTALL) 19125 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19126 // Delete package internally 19127 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19128 synchronized (mInstallLock) { 19129 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19130 final boolean res; 19131 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19132 "unloadMediaPackages")) { 19133 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19134 null); 19135 } 19136 if (res) { 19137 pkgList.add(pkgName); 19138 } else { 19139 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19140 failedList.add(args); 19141 } 19142 } 19143 } 19144 19145 // reader 19146 synchronized (mPackages) { 19147 // We didn't update the settings after removing each package; 19148 // write them now for all packages. 19149 mSettings.writeLPr(); 19150 } 19151 19152 // We have to absolutely send UPDATED_MEDIA_STATUS only 19153 // after confirming that all the receivers processed the ordered 19154 // broadcast when packages get disabled, force a gc to clean things up. 19155 // and unload all the containers. 19156 if (pkgList.size() > 0) { 19157 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19158 new IIntentReceiver.Stub() { 19159 public void performReceive(Intent intent, int resultCode, String data, 19160 Bundle extras, boolean ordered, boolean sticky, 19161 int sendingUser) throws RemoteException { 19162 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19163 reportStatus ? 1 : 0, 1, keys); 19164 mHandler.sendMessage(msg); 19165 } 19166 }); 19167 } else { 19168 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19169 keys); 19170 mHandler.sendMessage(msg); 19171 } 19172 } 19173 19174 private void loadPrivatePackages(final VolumeInfo vol) { 19175 mHandler.post(new Runnable() { 19176 @Override 19177 public void run() { 19178 loadPrivatePackagesInner(vol); 19179 } 19180 }); 19181 } 19182 19183 private void loadPrivatePackagesInner(VolumeInfo vol) { 19184 final String volumeUuid = vol.fsUuid; 19185 if (TextUtils.isEmpty(volumeUuid)) { 19186 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19187 return; 19188 } 19189 19190 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19191 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19192 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19193 19194 final VersionInfo ver; 19195 final List<PackageSetting> packages; 19196 synchronized (mPackages) { 19197 ver = mSettings.findOrCreateVersion(volumeUuid); 19198 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19199 } 19200 19201 for (PackageSetting ps : packages) { 19202 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19203 synchronized (mInstallLock) { 19204 final PackageParser.Package pkg; 19205 try { 19206 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19207 loaded.add(pkg.applicationInfo); 19208 19209 } catch (PackageManagerException e) { 19210 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19211 } 19212 19213 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19214 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19215 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19216 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19217 } 19218 } 19219 } 19220 19221 // Reconcile app data for all started/unlocked users 19222 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19223 final UserManager um = mContext.getSystemService(UserManager.class); 19224 UserManagerInternal umInternal = getUserManagerInternal(); 19225 for (UserInfo user : um.getUsers()) { 19226 final int flags; 19227 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19228 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19229 } else if (umInternal.isUserRunning(user.id)) { 19230 flags = StorageManager.FLAG_STORAGE_DE; 19231 } else { 19232 continue; 19233 } 19234 19235 try { 19236 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19237 synchronized (mInstallLock) { 19238 reconcileAppsDataLI(volumeUuid, user.id, flags); 19239 } 19240 } catch (IllegalStateException e) { 19241 // Device was probably ejected, and we'll process that event momentarily 19242 Slog.w(TAG, "Failed to prepare storage: " + e); 19243 } 19244 } 19245 19246 synchronized (mPackages) { 19247 int updateFlags = UPDATE_PERMISSIONS_ALL; 19248 if (ver.sdkVersion != mSdkVersion) { 19249 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19250 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19251 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19252 } 19253 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19254 19255 // Yay, everything is now upgraded 19256 ver.forceCurrent(); 19257 19258 mSettings.writeLPr(); 19259 } 19260 19261 for (PackageFreezer freezer : freezers) { 19262 freezer.close(); 19263 } 19264 19265 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19266 sendResourcesChangedBroadcast(true, false, loaded, null); 19267 } 19268 19269 private void unloadPrivatePackages(final VolumeInfo vol) { 19270 mHandler.post(new Runnable() { 19271 @Override 19272 public void run() { 19273 unloadPrivatePackagesInner(vol); 19274 } 19275 }); 19276 } 19277 19278 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19279 final String volumeUuid = vol.fsUuid; 19280 if (TextUtils.isEmpty(volumeUuid)) { 19281 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19282 return; 19283 } 19284 19285 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19286 synchronized (mInstallLock) { 19287 synchronized (mPackages) { 19288 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19289 for (PackageSetting ps : packages) { 19290 if (ps.pkg == null) continue; 19291 19292 final ApplicationInfo info = ps.pkg.applicationInfo; 19293 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19294 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19295 19296 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19297 "unloadPrivatePackagesInner")) { 19298 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19299 false, null)) { 19300 unloaded.add(info); 19301 } else { 19302 Slog.w(TAG, "Failed to unload " + ps.codePath); 19303 } 19304 } 19305 19306 // Try very hard to release any references to this package 19307 // so we don't risk the system server being killed due to 19308 // open FDs 19309 AttributeCache.instance().removePackage(ps.name); 19310 } 19311 19312 mSettings.writeLPr(); 19313 } 19314 } 19315 19316 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19317 sendResourcesChangedBroadcast(false, false, unloaded, null); 19318 19319 // Try very hard to release any references to this path so we don't risk 19320 // the system server being killed due to open FDs 19321 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19322 19323 for (int i = 0; i < 3; i++) { 19324 System.gc(); 19325 System.runFinalization(); 19326 } 19327 } 19328 19329 /** 19330 * Prepare storage areas for given user on all mounted devices. 19331 */ 19332 void prepareUserData(int userId, int userSerial, int flags) { 19333 synchronized (mInstallLock) { 19334 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19335 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19336 final String volumeUuid = vol.getFsUuid(); 19337 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19338 } 19339 } 19340 } 19341 19342 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19343 boolean allowRecover) { 19344 // Prepare storage and verify that serial numbers are consistent; if 19345 // there's a mismatch we need to destroy to avoid leaking data 19346 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19347 try { 19348 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19349 19350 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19351 UserManagerService.enforceSerialNumber( 19352 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19353 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19354 UserManagerService.enforceSerialNumber( 19355 Environment.getDataSystemDeDirectory(userId), userSerial); 19356 } 19357 } 19358 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19359 UserManagerService.enforceSerialNumber( 19360 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19361 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19362 UserManagerService.enforceSerialNumber( 19363 Environment.getDataSystemCeDirectory(userId), userSerial); 19364 } 19365 } 19366 19367 synchronized (mInstallLock) { 19368 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19369 } 19370 } catch (Exception e) { 19371 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19372 + " because we failed to prepare: " + e); 19373 destroyUserDataLI(volumeUuid, userId, 19374 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19375 19376 if (allowRecover) { 19377 // Try one last time; if we fail again we're really in trouble 19378 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19379 } 19380 } 19381 } 19382 19383 /** 19384 * Destroy storage areas for given user on all mounted devices. 19385 */ 19386 void destroyUserData(int userId, int flags) { 19387 synchronized (mInstallLock) { 19388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19389 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19390 final String volumeUuid = vol.getFsUuid(); 19391 destroyUserDataLI(volumeUuid, userId, flags); 19392 } 19393 } 19394 } 19395 19396 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19397 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19398 try { 19399 // Clean up app data, profile data, and media data 19400 mInstaller.destroyUserData(volumeUuid, userId, flags); 19401 19402 // Clean up system data 19403 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19404 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19405 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19406 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19407 } 19408 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19409 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19410 } 19411 } 19412 19413 // Data with special labels is now gone, so finish the job 19414 storage.destroyUserStorage(volumeUuid, userId, flags); 19415 19416 } catch (Exception e) { 19417 logCriticalInfo(Log.WARN, 19418 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19419 } 19420 } 19421 19422 /** 19423 * Examine all users present on given mounted volume, and destroy data 19424 * belonging to users that are no longer valid, or whose user ID has been 19425 * recycled. 19426 */ 19427 private void reconcileUsers(String volumeUuid) { 19428 final List<File> files = new ArrayList<>(); 19429 Collections.addAll(files, FileUtils 19430 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19431 Collections.addAll(files, FileUtils 19432 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19433 Collections.addAll(files, FileUtils 19434 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19435 Collections.addAll(files, FileUtils 19436 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19437 for (File file : files) { 19438 if (!file.isDirectory()) continue; 19439 19440 final int userId; 19441 final UserInfo info; 19442 try { 19443 userId = Integer.parseInt(file.getName()); 19444 info = sUserManager.getUserInfo(userId); 19445 } catch (NumberFormatException e) { 19446 Slog.w(TAG, "Invalid user directory " + file); 19447 continue; 19448 } 19449 19450 boolean destroyUser = false; 19451 if (info == null) { 19452 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19453 + " because no matching user was found"); 19454 destroyUser = true; 19455 } else if (!mOnlyCore) { 19456 try { 19457 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19458 } catch (IOException e) { 19459 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19460 + " because we failed to enforce serial number: " + e); 19461 destroyUser = true; 19462 } 19463 } 19464 19465 if (destroyUser) { 19466 synchronized (mInstallLock) { 19467 destroyUserDataLI(volumeUuid, userId, 19468 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19469 } 19470 } 19471 } 19472 } 19473 19474 private void assertPackageKnown(String volumeUuid, String packageName) 19475 throws PackageManagerException { 19476 synchronized (mPackages) { 19477 final PackageSetting ps = mSettings.mPackages.get(packageName); 19478 if (ps == null) { 19479 throw new PackageManagerException("Package " + packageName + " is unknown"); 19480 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19481 throw new PackageManagerException( 19482 "Package " + packageName + " found on unknown volume " + volumeUuid 19483 + "; expected volume " + ps.volumeUuid); 19484 } 19485 } 19486 } 19487 19488 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19489 throws PackageManagerException { 19490 synchronized (mPackages) { 19491 final PackageSetting ps = mSettings.mPackages.get(packageName); 19492 if (ps == null) { 19493 throw new PackageManagerException("Package " + packageName + " is unknown"); 19494 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19495 throw new PackageManagerException( 19496 "Package " + packageName + " found on unknown volume " + volumeUuid 19497 + "; expected volume " + ps.volumeUuid); 19498 } else if (!ps.getInstalled(userId)) { 19499 throw new PackageManagerException( 19500 "Package " + packageName + " not installed for user " + userId); 19501 } 19502 } 19503 } 19504 19505 /** 19506 * Examine all apps present on given mounted volume, and destroy apps that 19507 * aren't expected, either due to uninstallation or reinstallation on 19508 * another volume. 19509 */ 19510 private void reconcileApps(String volumeUuid) { 19511 final File[] files = FileUtils 19512 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19513 for (File file : files) { 19514 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19515 && !PackageInstallerService.isStageName(file.getName()); 19516 if (!isPackage) { 19517 // Ignore entries which are not packages 19518 continue; 19519 } 19520 19521 try { 19522 final PackageLite pkg = PackageParser.parsePackageLite(file, 19523 PackageParser.PARSE_MUST_BE_APK); 19524 assertPackageKnown(volumeUuid, pkg.packageName); 19525 19526 } catch (PackageParserException | PackageManagerException e) { 19527 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19528 synchronized (mInstallLock) { 19529 removeCodePathLI(file); 19530 } 19531 } 19532 } 19533 } 19534 19535 /** 19536 * Reconcile all app data for the given user. 19537 * <p> 19538 * Verifies that directories exist and that ownership and labeling is 19539 * correct for all installed apps on all mounted volumes. 19540 */ 19541 void reconcileAppsData(int userId, int flags) { 19542 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19543 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19544 final String volumeUuid = vol.getFsUuid(); 19545 synchronized (mInstallLock) { 19546 reconcileAppsDataLI(volumeUuid, userId, flags); 19547 } 19548 } 19549 } 19550 19551 /** 19552 * Reconcile all app data on given mounted volume. 19553 * <p> 19554 * Destroys app data that isn't expected, either due to uninstallation or 19555 * reinstallation on another volume. 19556 * <p> 19557 * Verifies that directories exist and that ownership and labeling is 19558 * correct for all installed apps. 19559 */ 19560 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19561 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19562 + Integer.toHexString(flags)); 19563 19564 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19565 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19566 19567 boolean restoreconNeeded = false; 19568 19569 // First look for stale data that doesn't belong, and check if things 19570 // have changed since we did our last restorecon 19571 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19572 if (StorageManager.isFileEncryptedNativeOrEmulated() 19573 && !StorageManager.isUserKeyUnlocked(userId)) { 19574 throw new RuntimeException( 19575 "Yikes, someone asked us to reconcile CE storage while " + userId 19576 + " was still locked; this would have caused massive data loss!"); 19577 } 19578 19579 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19580 19581 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19582 for (File file : files) { 19583 final String packageName = file.getName(); 19584 try { 19585 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19586 } catch (PackageManagerException e) { 19587 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19588 try { 19589 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19590 StorageManager.FLAG_STORAGE_CE, 0); 19591 } catch (InstallerException e2) { 19592 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19593 } 19594 } 19595 } 19596 } 19597 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19598 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19599 19600 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19601 for (File file : files) { 19602 final String packageName = file.getName(); 19603 try { 19604 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19605 } catch (PackageManagerException e) { 19606 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19607 try { 19608 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19609 StorageManager.FLAG_STORAGE_DE, 0); 19610 } catch (InstallerException e2) { 19611 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19612 } 19613 } 19614 } 19615 } 19616 19617 // Ensure that data directories are ready to roll for all packages 19618 // installed for this volume and user 19619 final List<PackageSetting> packages; 19620 synchronized (mPackages) { 19621 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19622 } 19623 int preparedCount = 0; 19624 for (PackageSetting ps : packages) { 19625 final String packageName = ps.name; 19626 if (ps.pkg == null) { 19627 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19628 // TODO: might be due to legacy ASEC apps; we should circle back 19629 // and reconcile again once they're scanned 19630 continue; 19631 } 19632 19633 if (ps.getInstalled(userId)) { 19634 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19635 19636 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19637 // We may have just shuffled around app data directories, so 19638 // prepare them one more time 19639 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19640 } 19641 19642 preparedCount++; 19643 } 19644 } 19645 19646 if (restoreconNeeded) { 19647 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19648 SELinuxMMAC.setRestoreconDone(ceDir); 19649 } 19650 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19651 SELinuxMMAC.setRestoreconDone(deDir); 19652 } 19653 } 19654 19655 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19656 + " packages; restoreconNeeded was " + restoreconNeeded); 19657 } 19658 19659 /** 19660 * Prepare app data for the given app just after it was installed or 19661 * upgraded. This method carefully only touches users that it's installed 19662 * for, and it forces a restorecon to handle any seinfo changes. 19663 * <p> 19664 * Verifies that directories exist and that ownership and labeling is 19665 * correct for all installed apps. If there is an ownership mismatch, it 19666 * will try recovering system apps by wiping data; third-party app data is 19667 * left intact. 19668 * <p> 19669 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19670 */ 19671 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19672 final PackageSetting ps; 19673 synchronized (mPackages) { 19674 ps = mSettings.mPackages.get(pkg.packageName); 19675 mSettings.writeKernelMappingLPr(ps); 19676 } 19677 19678 final UserManager um = mContext.getSystemService(UserManager.class); 19679 UserManagerInternal umInternal = getUserManagerInternal(); 19680 for (UserInfo user : um.getUsers()) { 19681 final int flags; 19682 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19683 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19684 } else if (umInternal.isUserRunning(user.id)) { 19685 flags = StorageManager.FLAG_STORAGE_DE; 19686 } else { 19687 continue; 19688 } 19689 19690 if (ps.getInstalled(user.id)) { 19691 // Whenever an app changes, force a restorecon of its data 19692 // TODO: when user data is locked, mark that we're still dirty 19693 prepareAppDataLIF(pkg, user.id, flags, true); 19694 } 19695 } 19696 } 19697 19698 /** 19699 * Prepare app data for the given app. 19700 * <p> 19701 * Verifies that directories exist and that ownership and labeling is 19702 * correct for all installed apps. If there is an ownership mismatch, this 19703 * will try recovering system apps by wiping data; third-party app data is 19704 * left intact. 19705 */ 19706 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19707 boolean restoreconNeeded) { 19708 if (pkg == null) { 19709 Slog.wtf(TAG, "Package was null!", new Throwable()); 19710 return; 19711 } 19712 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19713 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19714 for (int i = 0; i < childCount; i++) { 19715 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19716 } 19717 } 19718 19719 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19720 boolean restoreconNeeded) { 19721 if (DEBUG_APP_DATA) { 19722 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19723 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19724 } 19725 19726 final String volumeUuid = pkg.volumeUuid; 19727 final String packageName = pkg.packageName; 19728 final ApplicationInfo app = pkg.applicationInfo; 19729 final int appId = UserHandle.getAppId(app.uid); 19730 19731 Preconditions.checkNotNull(app.seinfo); 19732 19733 try { 19734 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19735 appId, app.seinfo, app.targetSdkVersion); 19736 } catch (InstallerException e) { 19737 if (app.isSystemApp()) { 19738 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19739 + ", but trying to recover: " + e); 19740 destroyAppDataLeafLIF(pkg, userId, flags); 19741 try { 19742 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19743 appId, app.seinfo, app.targetSdkVersion); 19744 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19745 } catch (InstallerException e2) { 19746 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19747 } 19748 } else { 19749 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19750 } 19751 } 19752 19753 if (restoreconNeeded) { 19754 try { 19755 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19756 app.seinfo); 19757 } catch (InstallerException e) { 19758 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19759 } 19760 } 19761 19762 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19763 try { 19764 // CE storage is unlocked right now, so read out the inode and 19765 // remember for use later when it's locked 19766 // TODO: mark this structure as dirty so we persist it! 19767 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19768 StorageManager.FLAG_STORAGE_CE); 19769 synchronized (mPackages) { 19770 final PackageSetting ps = mSettings.mPackages.get(packageName); 19771 if (ps != null) { 19772 ps.setCeDataInode(ceDataInode, userId); 19773 } 19774 } 19775 } catch (InstallerException e) { 19776 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19777 } 19778 } 19779 19780 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19781 } 19782 19783 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19784 if (pkg == null) { 19785 Slog.wtf(TAG, "Package was null!", new Throwable()); 19786 return; 19787 } 19788 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19789 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19790 for (int i = 0; i < childCount; i++) { 19791 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19792 } 19793 } 19794 19795 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19796 final String volumeUuid = pkg.volumeUuid; 19797 final String packageName = pkg.packageName; 19798 final ApplicationInfo app = pkg.applicationInfo; 19799 19800 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19801 // Create a native library symlink only if we have native libraries 19802 // and if the native libraries are 32 bit libraries. We do not provide 19803 // this symlink for 64 bit libraries. 19804 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19805 final String nativeLibPath = app.nativeLibraryDir; 19806 try { 19807 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19808 nativeLibPath, userId); 19809 } catch (InstallerException e) { 19810 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19811 } 19812 } 19813 } 19814 } 19815 19816 /** 19817 * For system apps on non-FBE devices, this method migrates any existing 19818 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19819 * requested by the app. 19820 */ 19821 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19822 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19823 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19824 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19825 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19826 try { 19827 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19828 storageTarget); 19829 } catch (InstallerException e) { 19830 logCriticalInfo(Log.WARN, 19831 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19832 } 19833 return true; 19834 } else { 19835 return false; 19836 } 19837 } 19838 19839 public PackageFreezer freezePackage(String packageName, String killReason) { 19840 return new PackageFreezer(packageName, killReason); 19841 } 19842 19843 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19844 String killReason) { 19845 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19846 return new PackageFreezer(); 19847 } else { 19848 return freezePackage(packageName, killReason); 19849 } 19850 } 19851 19852 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19853 String killReason) { 19854 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19855 return new PackageFreezer(); 19856 } else { 19857 return freezePackage(packageName, killReason); 19858 } 19859 } 19860 19861 /** 19862 * Class that freezes and kills the given package upon creation, and 19863 * unfreezes it upon closing. This is typically used when doing surgery on 19864 * app code/data to prevent the app from running while you're working. 19865 */ 19866 private class PackageFreezer implements AutoCloseable { 19867 private final String mPackageName; 19868 private final PackageFreezer[] mChildren; 19869 19870 private final boolean mWeFroze; 19871 19872 private final AtomicBoolean mClosed = new AtomicBoolean(); 19873 private final CloseGuard mCloseGuard = CloseGuard.get(); 19874 19875 /** 19876 * Create and return a stub freezer that doesn't actually do anything, 19877 * typically used when someone requested 19878 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19879 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19880 */ 19881 public PackageFreezer() { 19882 mPackageName = null; 19883 mChildren = null; 19884 mWeFroze = false; 19885 mCloseGuard.open("close"); 19886 } 19887 19888 public PackageFreezer(String packageName, String killReason) { 19889 synchronized (mPackages) { 19890 mPackageName = packageName; 19891 mWeFroze = mFrozenPackages.add(mPackageName); 19892 19893 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19894 if (ps != null) { 19895 killApplication(ps.name, ps.appId, killReason); 19896 } 19897 19898 final PackageParser.Package p = mPackages.get(packageName); 19899 if (p != null && p.childPackages != null) { 19900 final int N = p.childPackages.size(); 19901 mChildren = new PackageFreezer[N]; 19902 for (int i = 0; i < N; i++) { 19903 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19904 killReason); 19905 } 19906 } else { 19907 mChildren = null; 19908 } 19909 } 19910 mCloseGuard.open("close"); 19911 } 19912 19913 @Override 19914 protected void finalize() throws Throwable { 19915 try { 19916 mCloseGuard.warnIfOpen(); 19917 close(); 19918 } finally { 19919 super.finalize(); 19920 } 19921 } 19922 19923 @Override 19924 public void close() { 19925 mCloseGuard.close(); 19926 if (mClosed.compareAndSet(false, true)) { 19927 synchronized (mPackages) { 19928 if (mWeFroze) { 19929 mFrozenPackages.remove(mPackageName); 19930 } 19931 19932 if (mChildren != null) { 19933 for (PackageFreezer freezer : mChildren) { 19934 freezer.close(); 19935 } 19936 } 19937 } 19938 } 19939 } 19940 } 19941 19942 /** 19943 * Verify that given package is currently frozen. 19944 */ 19945 private void checkPackageFrozen(String packageName) { 19946 synchronized (mPackages) { 19947 if (!mFrozenPackages.contains(packageName)) { 19948 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19949 } 19950 } 19951 } 19952 19953 @Override 19954 public int movePackage(final String packageName, final String volumeUuid) { 19955 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19956 19957 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19958 final int moveId = mNextMoveId.getAndIncrement(); 19959 mHandler.post(new Runnable() { 19960 @Override 19961 public void run() { 19962 try { 19963 movePackageInternal(packageName, volumeUuid, moveId, user); 19964 } catch (PackageManagerException e) { 19965 Slog.w(TAG, "Failed to move " + packageName, e); 19966 mMoveCallbacks.notifyStatusChanged(moveId, 19967 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19968 } 19969 } 19970 }); 19971 return moveId; 19972 } 19973 19974 private void movePackageInternal(final String packageName, final String volumeUuid, 19975 final int moveId, UserHandle user) throws PackageManagerException { 19976 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19977 final PackageManager pm = mContext.getPackageManager(); 19978 19979 final boolean currentAsec; 19980 final String currentVolumeUuid; 19981 final File codeFile; 19982 final String installerPackageName; 19983 final String packageAbiOverride; 19984 final int appId; 19985 final String seinfo; 19986 final String label; 19987 final int targetSdkVersion; 19988 final PackageFreezer freezer; 19989 final int[] installedUserIds; 19990 19991 // reader 19992 synchronized (mPackages) { 19993 final PackageParser.Package pkg = mPackages.get(packageName); 19994 final PackageSetting ps = mSettings.mPackages.get(packageName); 19995 if (pkg == null || ps == null) { 19996 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19997 } 19998 19999 if (pkg.applicationInfo.isSystemApp()) { 20000 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20001 "Cannot move system application"); 20002 } 20003 20004 if (pkg.applicationInfo.isExternalAsec()) { 20005 currentAsec = true; 20006 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20007 } else if (pkg.applicationInfo.isForwardLocked()) { 20008 currentAsec = true; 20009 currentVolumeUuid = "forward_locked"; 20010 } else { 20011 currentAsec = false; 20012 currentVolumeUuid = ps.volumeUuid; 20013 20014 final File probe = new File(pkg.codePath); 20015 final File probeOat = new File(probe, "oat"); 20016 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20017 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20018 "Move only supported for modern cluster style installs"); 20019 } 20020 } 20021 20022 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20023 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20024 "Package already moved to " + volumeUuid); 20025 } 20026 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20027 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20028 "Device admin cannot be moved"); 20029 } 20030 20031 if (mFrozenPackages.contains(packageName)) { 20032 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20033 "Failed to move already frozen package"); 20034 } 20035 20036 codeFile = new File(pkg.codePath); 20037 installerPackageName = ps.installerPackageName; 20038 packageAbiOverride = ps.cpuAbiOverrideString; 20039 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20040 seinfo = pkg.applicationInfo.seinfo; 20041 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20042 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20043 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20044 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20045 } 20046 20047 final Bundle extras = new Bundle(); 20048 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20049 extras.putString(Intent.EXTRA_TITLE, label); 20050 mMoveCallbacks.notifyCreated(moveId, extras); 20051 20052 int installFlags; 20053 final boolean moveCompleteApp; 20054 final File measurePath; 20055 20056 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20057 installFlags = INSTALL_INTERNAL; 20058 moveCompleteApp = !currentAsec; 20059 measurePath = Environment.getDataAppDirectory(volumeUuid); 20060 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20061 installFlags = INSTALL_EXTERNAL; 20062 moveCompleteApp = false; 20063 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20064 } else { 20065 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20066 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20067 || !volume.isMountedWritable()) { 20068 freezer.close(); 20069 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20070 "Move location not mounted private volume"); 20071 } 20072 20073 Preconditions.checkState(!currentAsec); 20074 20075 installFlags = INSTALL_INTERNAL; 20076 moveCompleteApp = true; 20077 measurePath = Environment.getDataAppDirectory(volumeUuid); 20078 } 20079 20080 final PackageStats stats = new PackageStats(null, -1); 20081 synchronized (mInstaller) { 20082 for (int userId : installedUserIds) { 20083 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20084 freezer.close(); 20085 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20086 "Failed to measure package size"); 20087 } 20088 } 20089 } 20090 20091 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20092 + stats.dataSize); 20093 20094 final long startFreeBytes = measurePath.getFreeSpace(); 20095 final long sizeBytes; 20096 if (moveCompleteApp) { 20097 sizeBytes = stats.codeSize + stats.dataSize; 20098 } else { 20099 sizeBytes = stats.codeSize; 20100 } 20101 20102 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20103 freezer.close(); 20104 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20105 "Not enough free space to move"); 20106 } 20107 20108 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20109 20110 final CountDownLatch installedLatch = new CountDownLatch(1); 20111 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20112 @Override 20113 public void onUserActionRequired(Intent intent) throws RemoteException { 20114 throw new IllegalStateException(); 20115 } 20116 20117 @Override 20118 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20119 Bundle extras) throws RemoteException { 20120 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20121 + PackageManager.installStatusToString(returnCode, msg)); 20122 20123 installedLatch.countDown(); 20124 freezer.close(); 20125 20126 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20127 switch (status) { 20128 case PackageInstaller.STATUS_SUCCESS: 20129 mMoveCallbacks.notifyStatusChanged(moveId, 20130 PackageManager.MOVE_SUCCEEDED); 20131 break; 20132 case PackageInstaller.STATUS_FAILURE_STORAGE: 20133 mMoveCallbacks.notifyStatusChanged(moveId, 20134 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20135 break; 20136 default: 20137 mMoveCallbacks.notifyStatusChanged(moveId, 20138 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20139 break; 20140 } 20141 } 20142 }; 20143 20144 final MoveInfo move; 20145 if (moveCompleteApp) { 20146 // Kick off a thread to report progress estimates 20147 new Thread() { 20148 @Override 20149 public void run() { 20150 while (true) { 20151 try { 20152 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20153 break; 20154 } 20155 } catch (InterruptedException ignored) { 20156 } 20157 20158 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20159 final int progress = 10 + (int) MathUtils.constrain( 20160 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20161 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20162 } 20163 } 20164 }.start(); 20165 20166 final String dataAppName = codeFile.getName(); 20167 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20168 dataAppName, appId, seinfo, targetSdkVersion); 20169 } else { 20170 move = null; 20171 } 20172 20173 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20174 20175 final Message msg = mHandler.obtainMessage(INIT_COPY); 20176 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20177 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20178 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20179 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20180 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20181 msg.obj = params; 20182 20183 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20184 System.identityHashCode(msg.obj)); 20185 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20186 System.identityHashCode(msg.obj)); 20187 20188 mHandler.sendMessage(msg); 20189 } 20190 20191 @Override 20192 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20193 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20194 20195 final int realMoveId = mNextMoveId.getAndIncrement(); 20196 final Bundle extras = new Bundle(); 20197 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20198 mMoveCallbacks.notifyCreated(realMoveId, extras); 20199 20200 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20201 @Override 20202 public void onCreated(int moveId, Bundle extras) { 20203 // Ignored 20204 } 20205 20206 @Override 20207 public void onStatusChanged(int moveId, int status, long estMillis) { 20208 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20209 } 20210 }; 20211 20212 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20213 storage.setPrimaryStorageUuid(volumeUuid, callback); 20214 return realMoveId; 20215 } 20216 20217 @Override 20218 public int getMoveStatus(int moveId) { 20219 mContext.enforceCallingOrSelfPermission( 20220 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20221 return mMoveCallbacks.mLastStatus.get(moveId); 20222 } 20223 20224 @Override 20225 public void registerMoveCallback(IPackageMoveObserver callback) { 20226 mContext.enforceCallingOrSelfPermission( 20227 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20228 mMoveCallbacks.register(callback); 20229 } 20230 20231 @Override 20232 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20233 mContext.enforceCallingOrSelfPermission( 20234 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20235 mMoveCallbacks.unregister(callback); 20236 } 20237 20238 @Override 20239 public boolean setInstallLocation(int loc) { 20240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20241 null); 20242 if (getInstallLocation() == loc) { 20243 return true; 20244 } 20245 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20246 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20247 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20248 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20249 return true; 20250 } 20251 return false; 20252 } 20253 20254 @Override 20255 public int getInstallLocation() { 20256 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20257 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20258 PackageHelper.APP_INSTALL_AUTO); 20259 } 20260 20261 /** Called by UserManagerService */ 20262 void cleanUpUser(UserManagerService userManager, int userHandle) { 20263 synchronized (mPackages) { 20264 mDirtyUsers.remove(userHandle); 20265 mUserNeedsBadging.delete(userHandle); 20266 mSettings.removeUserLPw(userHandle); 20267 mPendingBroadcasts.remove(userHandle); 20268 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20269 removeUnusedPackagesLPw(userManager, userHandle); 20270 } 20271 } 20272 20273 /** 20274 * We're removing userHandle and would like to remove any downloaded packages 20275 * that are no longer in use by any other user. 20276 * @param userHandle the user being removed 20277 */ 20278 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20279 final boolean DEBUG_CLEAN_APKS = false; 20280 int [] users = userManager.getUserIds(); 20281 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20282 while (psit.hasNext()) { 20283 PackageSetting ps = psit.next(); 20284 if (ps.pkg == null) { 20285 continue; 20286 } 20287 final String packageName = ps.pkg.packageName; 20288 // Skip over if system app 20289 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20290 continue; 20291 } 20292 if (DEBUG_CLEAN_APKS) { 20293 Slog.i(TAG, "Checking package " + packageName); 20294 } 20295 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20296 if (keep) { 20297 if (DEBUG_CLEAN_APKS) { 20298 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20299 } 20300 } else { 20301 for (int i = 0; i < users.length; i++) { 20302 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20303 keep = true; 20304 if (DEBUG_CLEAN_APKS) { 20305 Slog.i(TAG, " Keeping package " + packageName + " for user " 20306 + users[i]); 20307 } 20308 break; 20309 } 20310 } 20311 } 20312 if (!keep) { 20313 if (DEBUG_CLEAN_APKS) { 20314 Slog.i(TAG, " Removing package " + packageName); 20315 } 20316 mHandler.post(new Runnable() { 20317 public void run() { 20318 deletePackageX(packageName, userHandle, 0); 20319 } //end run 20320 }); 20321 } 20322 } 20323 } 20324 20325 /** Called by UserManagerService */ 20326 void createNewUser(int userId) { 20327 synchronized (mInstallLock) { 20328 mSettings.createNewUserLI(this, mInstaller, userId); 20329 } 20330 synchronized (mPackages) { 20331 scheduleWritePackageRestrictionsLocked(userId); 20332 scheduleWritePackageListLocked(userId); 20333 applyFactoryDefaultBrowserLPw(userId); 20334 primeDomainVerificationsLPw(userId); 20335 } 20336 } 20337 20338 void onBeforeUserStartUninitialized(final int userId) { 20339 synchronized (mPackages) { 20340 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20341 return; 20342 } 20343 } 20344 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20345 // If permission review for legacy apps is required, we represent 20346 // dagerous permissions for such apps as always granted runtime 20347 // permissions to keep per user flag state whether review is needed. 20348 // Hence, if a new user is added we have to propagate dangerous 20349 // permission grants for these legacy apps. 20350 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20351 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20352 | UPDATE_PERMISSIONS_REPLACE_ALL); 20353 } 20354 } 20355 20356 @Override 20357 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20358 mContext.enforceCallingOrSelfPermission( 20359 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20360 "Only package verification agents can read the verifier device identity"); 20361 20362 synchronized (mPackages) { 20363 return mSettings.getVerifierDeviceIdentityLPw(); 20364 } 20365 } 20366 20367 @Override 20368 public void setPermissionEnforced(String permission, boolean enforced) { 20369 // TODO: Now that we no longer change GID for storage, this should to away. 20370 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20371 "setPermissionEnforced"); 20372 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20373 synchronized (mPackages) { 20374 if (mSettings.mReadExternalStorageEnforced == null 20375 || mSettings.mReadExternalStorageEnforced != enforced) { 20376 mSettings.mReadExternalStorageEnforced = enforced; 20377 mSettings.writeLPr(); 20378 } 20379 } 20380 // kill any non-foreground processes so we restart them and 20381 // grant/revoke the GID. 20382 final IActivityManager am = ActivityManagerNative.getDefault(); 20383 if (am != null) { 20384 final long token = Binder.clearCallingIdentity(); 20385 try { 20386 am.killProcessesBelowForeground("setPermissionEnforcement"); 20387 } catch (RemoteException e) { 20388 } finally { 20389 Binder.restoreCallingIdentity(token); 20390 } 20391 } 20392 } else { 20393 throw new IllegalArgumentException("No selective enforcement for " + permission); 20394 } 20395 } 20396 20397 @Override 20398 @Deprecated 20399 public boolean isPermissionEnforced(String permission) { 20400 return true; 20401 } 20402 20403 @Override 20404 public boolean isStorageLow() { 20405 final long token = Binder.clearCallingIdentity(); 20406 try { 20407 final DeviceStorageMonitorInternal 20408 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20409 if (dsm != null) { 20410 return dsm.isMemoryLow(); 20411 } else { 20412 return false; 20413 } 20414 } finally { 20415 Binder.restoreCallingIdentity(token); 20416 } 20417 } 20418 20419 @Override 20420 public IPackageInstaller getPackageInstaller() { 20421 return mInstallerService; 20422 } 20423 20424 private boolean userNeedsBadging(int userId) { 20425 int index = mUserNeedsBadging.indexOfKey(userId); 20426 if (index < 0) { 20427 final UserInfo userInfo; 20428 final long token = Binder.clearCallingIdentity(); 20429 try { 20430 userInfo = sUserManager.getUserInfo(userId); 20431 } finally { 20432 Binder.restoreCallingIdentity(token); 20433 } 20434 final boolean b; 20435 if (userInfo != null && userInfo.isManagedProfile()) { 20436 b = true; 20437 } else { 20438 b = false; 20439 } 20440 mUserNeedsBadging.put(userId, b); 20441 return b; 20442 } 20443 return mUserNeedsBadging.valueAt(index); 20444 } 20445 20446 @Override 20447 public KeySet getKeySetByAlias(String packageName, String alias) { 20448 if (packageName == null || alias == null) { 20449 return null; 20450 } 20451 synchronized(mPackages) { 20452 final PackageParser.Package pkg = mPackages.get(packageName); 20453 if (pkg == null) { 20454 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20455 throw new IllegalArgumentException("Unknown package: " + packageName); 20456 } 20457 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20458 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20459 } 20460 } 20461 20462 @Override 20463 public KeySet getSigningKeySet(String packageName) { 20464 if (packageName == null) { 20465 return null; 20466 } 20467 synchronized(mPackages) { 20468 final PackageParser.Package pkg = mPackages.get(packageName); 20469 if (pkg == null) { 20470 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20471 throw new IllegalArgumentException("Unknown package: " + packageName); 20472 } 20473 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20474 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20475 throw new SecurityException("May not access signing KeySet of other apps."); 20476 } 20477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20478 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20479 } 20480 } 20481 20482 @Override 20483 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20484 if (packageName == null || ks == null) { 20485 return false; 20486 } 20487 synchronized(mPackages) { 20488 final PackageParser.Package pkg = mPackages.get(packageName); 20489 if (pkg == null) { 20490 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20491 throw new IllegalArgumentException("Unknown package: " + packageName); 20492 } 20493 IBinder ksh = ks.getToken(); 20494 if (ksh instanceof KeySetHandle) { 20495 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20496 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20497 } 20498 return false; 20499 } 20500 } 20501 20502 @Override 20503 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20504 if (packageName == null || ks == null) { 20505 return false; 20506 } 20507 synchronized(mPackages) { 20508 final PackageParser.Package pkg = mPackages.get(packageName); 20509 if (pkg == null) { 20510 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20511 throw new IllegalArgumentException("Unknown package: " + packageName); 20512 } 20513 IBinder ksh = ks.getToken(); 20514 if (ksh instanceof KeySetHandle) { 20515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20516 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20517 } 20518 return false; 20519 } 20520 } 20521 20522 private void deletePackageIfUnusedLPr(final String packageName) { 20523 PackageSetting ps = mSettings.mPackages.get(packageName); 20524 if (ps == null) { 20525 return; 20526 } 20527 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20528 // TODO Implement atomic delete if package is unused 20529 // It is currently possible that the package will be deleted even if it is installed 20530 // after this method returns. 20531 mHandler.post(new Runnable() { 20532 public void run() { 20533 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20534 } 20535 }); 20536 } 20537 } 20538 20539 /** 20540 * Check and throw if the given before/after packages would be considered a 20541 * downgrade. 20542 */ 20543 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20544 throws PackageManagerException { 20545 if (after.versionCode < before.mVersionCode) { 20546 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20547 "Update version code " + after.versionCode + " is older than current " 20548 + before.mVersionCode); 20549 } else if (after.versionCode == before.mVersionCode) { 20550 if (after.baseRevisionCode < before.baseRevisionCode) { 20551 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20552 "Update base revision code " + after.baseRevisionCode 20553 + " is older than current " + before.baseRevisionCode); 20554 } 20555 20556 if (!ArrayUtils.isEmpty(after.splitNames)) { 20557 for (int i = 0; i < after.splitNames.length; i++) { 20558 final String splitName = after.splitNames[i]; 20559 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20560 if (j != -1) { 20561 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20562 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20563 "Update split " + splitName + " revision code " 20564 + after.splitRevisionCodes[i] + " is older than current " 20565 + before.splitRevisionCodes[j]); 20566 } 20567 } 20568 } 20569 } 20570 } 20571 } 20572 20573 private static class MoveCallbacks extends Handler { 20574 private static final int MSG_CREATED = 1; 20575 private static final int MSG_STATUS_CHANGED = 2; 20576 20577 private final RemoteCallbackList<IPackageMoveObserver> 20578 mCallbacks = new RemoteCallbackList<>(); 20579 20580 private final SparseIntArray mLastStatus = new SparseIntArray(); 20581 20582 public MoveCallbacks(Looper looper) { 20583 super(looper); 20584 } 20585 20586 public void register(IPackageMoveObserver callback) { 20587 mCallbacks.register(callback); 20588 } 20589 20590 public void unregister(IPackageMoveObserver callback) { 20591 mCallbacks.unregister(callback); 20592 } 20593 20594 @Override 20595 public void handleMessage(Message msg) { 20596 final SomeArgs args = (SomeArgs) msg.obj; 20597 final int n = mCallbacks.beginBroadcast(); 20598 for (int i = 0; i < n; i++) { 20599 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20600 try { 20601 invokeCallback(callback, msg.what, args); 20602 } catch (RemoteException ignored) { 20603 } 20604 } 20605 mCallbacks.finishBroadcast(); 20606 args.recycle(); 20607 } 20608 20609 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20610 throws RemoteException { 20611 switch (what) { 20612 case MSG_CREATED: { 20613 callback.onCreated(args.argi1, (Bundle) args.arg2); 20614 break; 20615 } 20616 case MSG_STATUS_CHANGED: { 20617 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20618 break; 20619 } 20620 } 20621 } 20622 20623 private void notifyCreated(int moveId, Bundle extras) { 20624 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20625 20626 final SomeArgs args = SomeArgs.obtain(); 20627 args.argi1 = moveId; 20628 args.arg2 = extras; 20629 obtainMessage(MSG_CREATED, args).sendToTarget(); 20630 } 20631 20632 private void notifyStatusChanged(int moveId, int status) { 20633 notifyStatusChanged(moveId, status, -1); 20634 } 20635 20636 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20637 Slog.v(TAG, "Move " + moveId + " status " + status); 20638 20639 final SomeArgs args = SomeArgs.obtain(); 20640 args.argi1 = moveId; 20641 args.argi2 = status; 20642 args.arg3 = estMillis; 20643 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20644 20645 synchronized (mLastStatus) { 20646 mLastStatus.put(moveId, status); 20647 } 20648 } 20649 } 20650 20651 private final static class OnPermissionChangeListeners extends Handler { 20652 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20653 20654 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20655 new RemoteCallbackList<>(); 20656 20657 public OnPermissionChangeListeners(Looper looper) { 20658 super(looper); 20659 } 20660 20661 @Override 20662 public void handleMessage(Message msg) { 20663 switch (msg.what) { 20664 case MSG_ON_PERMISSIONS_CHANGED: { 20665 final int uid = msg.arg1; 20666 handleOnPermissionsChanged(uid); 20667 } break; 20668 } 20669 } 20670 20671 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20672 mPermissionListeners.register(listener); 20673 20674 } 20675 20676 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20677 mPermissionListeners.unregister(listener); 20678 } 20679 20680 public void onPermissionsChanged(int uid) { 20681 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20682 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20683 } 20684 } 20685 20686 private void handleOnPermissionsChanged(int uid) { 20687 final int count = mPermissionListeners.beginBroadcast(); 20688 try { 20689 for (int i = 0; i < count; i++) { 20690 IOnPermissionsChangeListener callback = mPermissionListeners 20691 .getBroadcastItem(i); 20692 try { 20693 callback.onPermissionsChanged(uid); 20694 } catch (RemoteException e) { 20695 Log.e(TAG, "Permission listener is dead", e); 20696 } 20697 } 20698 } finally { 20699 mPermissionListeners.finishBroadcast(); 20700 } 20701 } 20702 } 20703 20704 private class PackageManagerInternalImpl extends PackageManagerInternal { 20705 @Override 20706 public void setLocationPackagesProvider(PackagesProvider provider) { 20707 synchronized (mPackages) { 20708 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20709 } 20710 } 20711 20712 @Override 20713 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20714 synchronized (mPackages) { 20715 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20716 } 20717 } 20718 20719 @Override 20720 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20721 synchronized (mPackages) { 20722 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20723 } 20724 } 20725 20726 @Override 20727 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20728 synchronized (mPackages) { 20729 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20730 } 20731 } 20732 20733 @Override 20734 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20735 synchronized (mPackages) { 20736 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20737 } 20738 } 20739 20740 @Override 20741 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20742 synchronized (mPackages) { 20743 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20744 } 20745 } 20746 20747 @Override 20748 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20749 synchronized (mPackages) { 20750 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20751 packageName, userId); 20752 } 20753 } 20754 20755 @Override 20756 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20757 synchronized (mPackages) { 20758 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20759 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20760 packageName, userId); 20761 } 20762 } 20763 20764 @Override 20765 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20766 synchronized (mPackages) { 20767 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20768 packageName, userId); 20769 } 20770 } 20771 20772 @Override 20773 public void setKeepUninstalledPackages(final List<String> packageList) { 20774 Preconditions.checkNotNull(packageList); 20775 List<String> removedFromList = null; 20776 synchronized (mPackages) { 20777 if (mKeepUninstalledPackages != null) { 20778 final int packagesCount = mKeepUninstalledPackages.size(); 20779 for (int i = 0; i < packagesCount; i++) { 20780 String oldPackage = mKeepUninstalledPackages.get(i); 20781 if (packageList != null && packageList.contains(oldPackage)) { 20782 continue; 20783 } 20784 if (removedFromList == null) { 20785 removedFromList = new ArrayList<>(); 20786 } 20787 removedFromList.add(oldPackage); 20788 } 20789 } 20790 mKeepUninstalledPackages = new ArrayList<>(packageList); 20791 if (removedFromList != null) { 20792 final int removedCount = removedFromList.size(); 20793 for (int i = 0; i < removedCount; i++) { 20794 deletePackageIfUnusedLPr(removedFromList.get(i)); 20795 } 20796 } 20797 } 20798 } 20799 20800 @Override 20801 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20802 synchronized (mPackages) { 20803 // If we do not support permission review, done. 20804 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20805 return false; 20806 } 20807 20808 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20809 if (packageSetting == null) { 20810 return false; 20811 } 20812 20813 // Permission review applies only to apps not supporting the new permission model. 20814 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20815 return false; 20816 } 20817 20818 // Legacy apps have the permission and get user consent on launch. 20819 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20820 return permissionsState.isPermissionReviewRequired(userId); 20821 } 20822 } 20823 20824 @Override 20825 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20826 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20827 } 20828 20829 @Override 20830 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20831 int userId) { 20832 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20833 } 20834 20835 @Override 20836 public void setDeviceAndProfileOwnerPackages( 20837 int deviceOwnerUserId, String deviceOwnerPackage, 20838 SparseArray<String> profileOwnerPackages) { 20839 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20840 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20841 } 20842 20843 @Override 20844 public boolean canPackageBeWiped(int userId, String packageName) { 20845 return mProtectedPackages.canPackageBeWiped(userId, 20846 packageName); 20847 } 20848 } 20849 20850 @Override 20851 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20852 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20853 synchronized (mPackages) { 20854 final long identity = Binder.clearCallingIdentity(); 20855 try { 20856 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20857 packageNames, userId); 20858 } finally { 20859 Binder.restoreCallingIdentity(identity); 20860 } 20861 } 20862 } 20863 20864 private static void enforceSystemOrPhoneCaller(String tag) { 20865 int callingUid = Binder.getCallingUid(); 20866 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20867 throw new SecurityException( 20868 "Cannot call " + tag + " from UID " + callingUid); 20869 } 20870 } 20871 20872 boolean isHistoricalPackageUsageAvailable() { 20873 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20874 } 20875 20876 /** 20877 * Return a <b>copy</b> of the collection of packages known to the package manager. 20878 * @return A copy of the values of mPackages. 20879 */ 20880 Collection<PackageParser.Package> getPackages() { 20881 synchronized (mPackages) { 20882 return new ArrayList<>(mPackages.values()); 20883 } 20884 } 20885 20886 /** 20887 * Logs process start information (including base APK hash) to the security log. 20888 * @hide 20889 */ 20890 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20891 String apkFile, int pid) { 20892 if (!SecurityLog.isLoggingEnabled()) { 20893 return; 20894 } 20895 Bundle data = new Bundle(); 20896 data.putLong("startTimestamp", System.currentTimeMillis()); 20897 data.putString("processName", processName); 20898 data.putInt("uid", uid); 20899 data.putString("seinfo", seinfo); 20900 data.putString("apkFile", apkFile); 20901 data.putInt("pid", pid); 20902 Message msg = mProcessLoggingHandler.obtainMessage( 20903 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20904 msg.setData(data); 20905 mProcessLoggingHandler.sendMessage(msg); 20906 } 20907} 20908