PackageManagerService.java revision efc1c4d50104e9b9a7581c9b60703727805897f0
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralResolveInfo; 125import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.PatternMatcher; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.UserManagerInternal; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.provider.Settings.Global; 200import android.provider.Settings.Secure; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 // STOPSHIP; b/30256615 369 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 370 371 private static final int RADIO_UID = Process.PHONE_UID; 372 private static final int LOG_UID = Process.LOG_UID; 373 private static final int NFC_UID = Process.NFC_UID; 374 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 375 private static final int SHELL_UID = Process.SHELL_UID; 376 377 // Cap the size of permission trees that 3rd party apps can define 378 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 379 380 // Suffix used during package installation when copying/moving 381 // package apks to install directory. 382 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 383 384 static final int SCAN_NO_DEX = 1<<1; 385 static final int SCAN_FORCE_DEX = 1<<2; 386 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 387 static final int SCAN_NEW_INSTALL = 1<<4; 388 static final int SCAN_NO_PATHS = 1<<5; 389 static final int SCAN_UPDATE_TIME = 1<<6; 390 static final int SCAN_DEFER_DEX = 1<<7; 391 static final int SCAN_BOOTING = 1<<8; 392 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 393 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 394 static final int SCAN_REPLACING = 1<<11; 395 static final int SCAN_REQUIRE_KNOWN = 1<<12; 396 static final int SCAN_MOVE = 1<<13; 397 static final int SCAN_INITIAL = 1<<14; 398 static final int SCAN_CHECK_ONLY = 1<<15; 399 static final int SCAN_DONT_KILL_APP = 1<<17; 400 static final int SCAN_IGNORE_FROZEN = 1<<18; 401 402 static final int REMOVE_CHATTY = 1<<16; 403 404 private static final int[] EMPTY_INT_ARRAY = new int[0]; 405 406 /** 407 * Timeout (in milliseconds) after which the watchdog should declare that 408 * our handler thread is wedged. The usual default for such things is one 409 * minute but we sometimes do very lengthy I/O operations on this thread, 410 * such as installing multi-gigabyte applications, so ours needs to be longer. 411 */ 412 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 413 414 /** 415 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 416 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 417 * settings entry if available, otherwise we use the hardcoded default. If it's been 418 * more than this long since the last fstrim, we force one during the boot sequence. 419 * 420 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 421 * one gets run at the next available charging+idle time. This final mandatory 422 * no-fstrim check kicks in only of the other scheduling criteria is never met. 423 */ 424 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 425 426 /** 427 * Whether verification is enabled by default. 428 */ 429 private static final boolean DEFAULT_VERIFY_ENABLE = true; 430 431 /** 432 * The default maximum time to wait for the verification agent to return in 433 * milliseconds. 434 */ 435 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 436 437 /** 438 * The default response for package verification timeout. 439 * 440 * This can be either PackageManager.VERIFICATION_ALLOW or 441 * PackageManager.VERIFICATION_REJECT. 442 */ 443 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 444 445 static final String PLATFORM_PACKAGE_NAME = "android"; 446 447 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 448 449 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 450 DEFAULT_CONTAINER_PACKAGE, 451 "com.android.defcontainer.DefaultContainerService"); 452 453 private static final String KILL_APP_REASON_GIDS_CHANGED = 454 "permission grant or revoke changed gids"; 455 456 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 457 "permissions revoked"; 458 459 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 460 461 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 462 463 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 464 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 465 466 /** Permission grant: not grant the permission. */ 467 private static final int GRANT_DENIED = 1; 468 469 /** Permission grant: grant the permission as an install permission. */ 470 private static final int GRANT_INSTALL = 2; 471 472 /** Permission grant: grant the permission as a runtime one. */ 473 private static final int GRANT_RUNTIME = 3; 474 475 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 476 private static final int GRANT_UPGRADE = 4; 477 478 /** Canonical intent used to identify what counts as a "web browser" app */ 479 private static final Intent sBrowserIntent; 480 static { 481 sBrowserIntent = new Intent(); 482 sBrowserIntent.setAction(Intent.ACTION_VIEW); 483 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 484 sBrowserIntent.setData(Uri.parse("http:")); 485 } 486 487 /** 488 * The set of all protected actions [i.e. those actions for which a high priority 489 * intent filter is disallowed]. 490 */ 491 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 492 static { 493 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 495 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 496 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 497 } 498 499 // Compilation reasons. 500 public static final int REASON_FIRST_BOOT = 0; 501 public static final int REASON_BOOT = 1; 502 public static final int REASON_INSTALL = 2; 503 public static final int REASON_BACKGROUND_DEXOPT = 3; 504 public static final int REASON_AB_OTA = 4; 505 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 506 public static final int REASON_SHARED_APK = 6; 507 public static final int REASON_FORCED_DEXOPT = 7; 508 public static final int REASON_CORE_APP = 8; 509 510 public static final int REASON_LAST = REASON_CORE_APP; 511 512 /** Special library name that skips shared libraries check during compilation. */ 513 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 514 515 final ServiceThread mHandlerThread; 516 517 final PackageHandler mHandler; 518 519 private final ProcessLoggingHandler mProcessLoggingHandler; 520 521 /** 522 * Messages for {@link #mHandler} that need to wait for system ready before 523 * being dispatched. 524 */ 525 private ArrayList<Message> mPostSystemReadyMessages; 526 527 final int mSdkVersion = Build.VERSION.SDK_INT; 528 529 final Context mContext; 530 final boolean mFactoryTest; 531 final boolean mOnlyCore; 532 final DisplayMetrics mMetrics; 533 final int mDefParseFlags; 534 final String[] mSeparateProcesses; 535 final boolean mIsUpgrade; 536 final boolean mIsPreNUpgrade; 537 final boolean mIsPreNMR1Upgrade; 538 539 /** The location for ASEC container files on internal storage. */ 540 final String mAsecInternalPath; 541 542 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 543 // LOCK HELD. Can be called with mInstallLock held. 544 @GuardedBy("mInstallLock") 545 final Installer mInstaller; 546 547 /** Directory where installed third-party apps stored */ 548 final File mAppInstallDir; 549 final File mEphemeralInstallDir; 550 551 /** 552 * Directory to which applications installed internally have their 553 * 32 bit native libraries copied. 554 */ 555 private File mAppLib32InstallDir; 556 557 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 558 // apps. 559 final File mDrmAppPrivateInstallDir; 560 561 // ---------------------------------------------------------------- 562 563 // Lock for state used when installing and doing other long running 564 // operations. Methods that must be called with this lock held have 565 // the suffix "LI". 566 final Object mInstallLock = new Object(); 567 568 // ---------------------------------------------------------------- 569 570 // Keys are String (package name), values are Package. This also serves 571 // as the lock for the global state. Methods that must be called with 572 // this lock held have the prefix "LP". 573 @GuardedBy("mPackages") 574 final ArrayMap<String, PackageParser.Package> mPackages = 575 new ArrayMap<String, PackageParser.Package>(); 576 577 final ArrayMap<String, Set<String>> mKnownCodebase = 578 new ArrayMap<String, Set<String>>(); 579 580 // Tracks available target package names -> overlay package paths. 581 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 582 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 583 584 /** 585 * Tracks new system packages [received in an OTA] that we expect to 586 * find updated user-installed versions. Keys are package name, values 587 * are package location. 588 */ 589 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 590 /** 591 * Tracks high priority intent filters for protected actions. During boot, certain 592 * filter actions are protected and should never be allowed to have a high priority 593 * intent filter for them. However, there is one, and only one exception -- the 594 * setup wizard. It must be able to define a high priority intent filter for these 595 * actions to ensure there are no escapes from the wizard. We need to delay processing 596 * of these during boot as we need to look at all of the system packages in order 597 * to know which component is the setup wizard. 598 */ 599 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 600 /** 601 * Whether or not processing protected filters should be deferred. 602 */ 603 private boolean mDeferProtectedFilters = true; 604 605 /** 606 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 607 */ 608 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 609 /** 610 * Whether or not system app permissions should be promoted from install to runtime. 611 */ 612 boolean mPromoteSystemApps; 613 614 @GuardedBy("mPackages") 615 final Settings mSettings; 616 617 /** 618 * Set of package names that are currently "frozen", which means active 619 * surgery is being done on the code/data for that package. The platform 620 * will refuse to launch frozen packages to avoid race conditions. 621 * 622 * @see PackageFreezer 623 */ 624 @GuardedBy("mPackages") 625 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 626 627 final ProtectedPackages mProtectedPackages; 628 629 boolean mFirstBoot; 630 631 // System configuration read by SystemConfig. 632 final int[] mGlobalGids; 633 final SparseArray<ArraySet<String>> mSystemPermissions; 634 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 635 636 // If mac_permissions.xml was found for seinfo labeling. 637 boolean mFoundPolicyFile; 638 639 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 640 641 public static final class SharedLibraryEntry { 642 public final String path; 643 public final String apk; 644 645 SharedLibraryEntry(String _path, String _apk) { 646 path = _path; 647 apk = _apk; 648 } 649 } 650 651 // Currently known shared libraries. 652 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 653 new ArrayMap<String, SharedLibraryEntry>(); 654 655 // All available activities, for your resolving pleasure. 656 final ActivityIntentResolver mActivities = 657 new ActivityIntentResolver(); 658 659 // All available receivers, for your resolving pleasure. 660 final ActivityIntentResolver mReceivers = 661 new ActivityIntentResolver(); 662 663 // All available services, for your resolving pleasure. 664 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 665 666 // All available providers, for your resolving pleasure. 667 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 668 669 // Mapping from provider base names (first directory in content URI codePath) 670 // to the provider information. 671 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 672 new ArrayMap<String, PackageParser.Provider>(); 673 674 // Mapping from instrumentation class names to info about them. 675 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 676 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 677 678 // Mapping from permission names to info about them. 679 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 680 new ArrayMap<String, PackageParser.PermissionGroup>(); 681 682 // Packages whose data we have transfered into another package, thus 683 // should no longer exist. 684 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 685 686 // Broadcast actions that are only available to the system. 687 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 688 689 /** List of packages waiting for verification. */ 690 final SparseArray<PackageVerificationState> mPendingVerification 691 = new SparseArray<PackageVerificationState>(); 692 693 /** Set of packages associated with each app op permission. */ 694 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 695 696 final PackageInstallerService mInstallerService; 697 698 private final PackageDexOptimizer mPackageDexOptimizer; 699 700 private AtomicInteger mNextMoveId = new AtomicInteger(); 701 private final MoveCallbacks mMoveCallbacks; 702 703 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 704 705 // Cache of users who need badging. 706 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 707 708 /** Token for keys in mPendingVerification. */ 709 private int mPendingVerificationToken = 0; 710 711 volatile boolean mSystemReady; 712 volatile boolean mSafeMode; 713 volatile boolean mHasSystemUidErrors; 714 715 ApplicationInfo mAndroidApplication; 716 final ActivityInfo mResolveActivity = new ActivityInfo(); 717 final ResolveInfo mResolveInfo = new ResolveInfo(); 718 ComponentName mResolveComponentName; 719 PackageParser.Package mPlatformPackage; 720 ComponentName mCustomResolverComponentName; 721 722 boolean mResolverReplaced = false; 723 724 private final @Nullable ComponentName mIntentFilterVerifierComponent; 725 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 726 727 private int mIntentFilterVerificationToken = 0; 728 729 /** Component that knows whether or not an ephemeral application exists */ 730 final ComponentName mEphemeralResolverComponent; 731 /** The service connection to the ephemeral resolver */ 732 final EphemeralResolverConnection mEphemeralResolverConnection; 733 734 /** Component used to install ephemeral applications */ 735 final ComponentName mEphemeralInstallerComponent; 736 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 737 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 738 739 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 740 = new SparseArray<IntentFilterVerificationState>(); 741 742 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 743 744 // List of packages names to keep cached, even if they are uninstalled for all users 745 private List<String> mKeepUninstalledPackages; 746 747 private UserManagerInternal mUserManagerInternal; 748 749 private static class IFVerificationParams { 750 PackageParser.Package pkg; 751 boolean replacing; 752 int userId; 753 int verifierUid; 754 755 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 756 int _userId, int _verifierUid) { 757 pkg = _pkg; 758 replacing = _replacing; 759 userId = _userId; 760 replacing = _replacing; 761 verifierUid = _verifierUid; 762 } 763 } 764 765 private interface IntentFilterVerifier<T extends IntentFilter> { 766 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 767 T filter, String packageName); 768 void startVerifications(int userId); 769 void receiveVerificationResponse(int verificationId); 770 } 771 772 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 773 private Context mContext; 774 private ComponentName mIntentFilterVerifierComponent; 775 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 776 777 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 778 mContext = context; 779 mIntentFilterVerifierComponent = verifierComponent; 780 } 781 782 private String getDefaultScheme() { 783 return IntentFilter.SCHEME_HTTPS; 784 } 785 786 @Override 787 public void startVerifications(int userId) { 788 // Launch verifications requests 789 int count = mCurrentIntentFilterVerifications.size(); 790 for (int n=0; n<count; n++) { 791 int verificationId = mCurrentIntentFilterVerifications.get(n); 792 final IntentFilterVerificationState ivs = 793 mIntentFilterVerificationStates.get(verificationId); 794 795 String packageName = ivs.getPackageName(); 796 797 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 798 final int filterCount = filters.size(); 799 ArraySet<String> domainsSet = new ArraySet<>(); 800 for (int m=0; m<filterCount; m++) { 801 PackageParser.ActivityIntentInfo filter = filters.get(m); 802 domainsSet.addAll(filter.getHostsList()); 803 } 804 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 805 synchronized (mPackages) { 806 if (mSettings.createIntentFilterVerificationIfNeededLPw( 807 packageName, domainsList) != null) { 808 scheduleWriteSettingsLocked(); 809 } 810 } 811 sendVerificationRequest(userId, verificationId, ivs); 812 } 813 mCurrentIntentFilterVerifications.clear(); 814 } 815 816 private void sendVerificationRequest(int userId, int verificationId, 817 IntentFilterVerificationState ivs) { 818 819 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 822 verificationId); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 825 getDefaultScheme()); 826 verificationIntent.putExtra( 827 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 828 ivs.getHostsString()); 829 verificationIntent.putExtra( 830 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 831 ivs.getPackageName()); 832 verificationIntent.setComponent(mIntentFilterVerifierComponent); 833 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 834 835 UserHandle user = new UserHandle(userId); 836 mContext.sendBroadcastAsUser(verificationIntent, user); 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 838 "Sending IntentFilter verification broadcast"); 839 } 840 841 public void receiveVerificationResponse(int verificationId) { 842 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 843 844 final boolean verified = ivs.isVerified(); 845 846 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 847 final int count = filters.size(); 848 if (DEBUG_DOMAIN_VERIFICATION) { 849 Slog.i(TAG, "Received verification response " + verificationId 850 + " for " + count + " filters, verified=" + verified); 851 } 852 for (int n=0; n<count; n++) { 853 PackageParser.ActivityIntentInfo filter = filters.get(n); 854 filter.setVerified(verified); 855 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 857 + " verified with result:" + verified + " and hosts:" 858 + ivs.getHostsString()); 859 } 860 861 mIntentFilterVerificationStates.remove(verificationId); 862 863 final String packageName = ivs.getPackageName(); 864 IntentFilterVerificationInfo ivi = null; 865 866 synchronized (mPackages) { 867 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 868 } 869 if (ivi == null) { 870 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 871 + verificationId + " packageName:" + packageName); 872 return; 873 } 874 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 875 "Updating IntentFilterVerificationInfo for package " + packageName 876 +" verificationId:" + verificationId); 877 878 synchronized (mPackages) { 879 if (verified) { 880 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 881 } else { 882 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 883 } 884 scheduleWriteSettingsLocked(); 885 886 final int userId = ivs.getUserId(); 887 if (userId != UserHandle.USER_ALL) { 888 final int userStatus = 889 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 890 891 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 892 boolean needUpdate = false; 893 894 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 895 // already been set by the User thru the Disambiguation dialog 896 switch (userStatus) { 897 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 898 if (verified) { 899 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 900 } else { 901 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 902 } 903 needUpdate = true; 904 break; 905 906 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 907 if (verified) { 908 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 909 needUpdate = true; 910 } 911 break; 912 913 default: 914 // Nothing to do 915 } 916 917 if (needUpdate) { 918 mSettings.updateIntentFilterVerificationStatusLPw( 919 packageName, updatedStatus, userId); 920 scheduleWritePackageRestrictionsLocked(userId); 921 } 922 } 923 } 924 } 925 926 @Override 927 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 928 ActivityIntentInfo filter, String packageName) { 929 if (!hasValidDomains(filter)) { 930 return false; 931 } 932 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 933 if (ivs == null) { 934 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 935 packageName); 936 } 937 if (DEBUG_DOMAIN_VERIFICATION) { 938 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 939 } 940 ivs.addFilter(filter); 941 return true; 942 } 943 944 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 945 int userId, int verificationId, String packageName) { 946 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 947 verifierUid, userId, packageName); 948 ivs.setPendingState(); 949 synchronized (mPackages) { 950 mIntentFilterVerificationStates.append(verificationId, ivs); 951 mCurrentIntentFilterVerifications.add(verificationId); 952 } 953 return ivs; 954 } 955 } 956 957 private static boolean hasValidDomains(ActivityIntentInfo filter) { 958 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 959 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 960 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 961 } 962 963 // Set of pending broadcasts for aggregating enable/disable of components. 964 static class PendingPackageBroadcasts { 965 // for each user id, a map of <package name -> components within that package> 966 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 967 968 public PendingPackageBroadcasts() { 969 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 970 } 971 972 public ArrayList<String> get(int userId, String packageName) { 973 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 974 return packages.get(packageName); 975 } 976 977 public void put(int userId, String packageName, ArrayList<String> components) { 978 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 979 packages.put(packageName, components); 980 } 981 982 public void remove(int userId, String packageName) { 983 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 984 if (packages != null) { 985 packages.remove(packageName); 986 } 987 } 988 989 public void remove(int userId) { 990 mUidMap.remove(userId); 991 } 992 993 public int userIdCount() { 994 return mUidMap.size(); 995 } 996 997 public int userIdAt(int n) { 998 return mUidMap.keyAt(n); 999 } 1000 1001 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1002 return mUidMap.get(userId); 1003 } 1004 1005 public int size() { 1006 // total number of pending broadcast entries across all userIds 1007 int num = 0; 1008 for (int i = 0; i< mUidMap.size(); i++) { 1009 num += mUidMap.valueAt(i).size(); 1010 } 1011 return num; 1012 } 1013 1014 public void clear() { 1015 mUidMap.clear(); 1016 } 1017 1018 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1019 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1020 if (map == null) { 1021 map = new ArrayMap<String, ArrayList<String>>(); 1022 mUidMap.put(userId, map); 1023 } 1024 return map; 1025 } 1026 } 1027 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1028 1029 // Service Connection to remote media container service to copy 1030 // package uri's from external media onto secure containers 1031 // or internal storage. 1032 private IMediaContainerService mContainerService = null; 1033 1034 static final int SEND_PENDING_BROADCAST = 1; 1035 static final int MCS_BOUND = 3; 1036 static final int END_COPY = 4; 1037 static final int INIT_COPY = 5; 1038 static final int MCS_UNBIND = 6; 1039 static final int START_CLEANING_PACKAGE = 7; 1040 static final int FIND_INSTALL_LOC = 8; 1041 static final int POST_INSTALL = 9; 1042 static final int MCS_RECONNECT = 10; 1043 static final int MCS_GIVE_UP = 11; 1044 static final int UPDATED_MEDIA_STATUS = 12; 1045 static final int WRITE_SETTINGS = 13; 1046 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1047 static final int PACKAGE_VERIFIED = 15; 1048 static final int CHECK_PENDING_VERIFICATION = 16; 1049 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1050 static final int INTENT_FILTER_VERIFIED = 18; 1051 static final int WRITE_PACKAGE_LIST = 19; 1052 1053 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1054 1055 // Delay time in millisecs 1056 static final int BROADCAST_DELAY = 10 * 1000; 1057 1058 static UserManagerService sUserManager; 1059 1060 // Stores a list of users whose package restrictions file needs to be updated 1061 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1062 1063 final private DefaultContainerConnection mDefContainerConn = 1064 new DefaultContainerConnection(); 1065 class DefaultContainerConnection implements ServiceConnection { 1066 public void onServiceConnected(ComponentName name, IBinder service) { 1067 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1068 IMediaContainerService imcs = 1069 IMediaContainerService.Stub.asInterface(service); 1070 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1071 } 1072 1073 public void onServiceDisconnected(ComponentName name) { 1074 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1075 } 1076 } 1077 1078 // Recordkeeping of restore-after-install operations that are currently in flight 1079 // between the Package Manager and the Backup Manager 1080 static class PostInstallData { 1081 public InstallArgs args; 1082 public PackageInstalledInfo res; 1083 1084 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1085 args = _a; 1086 res = _r; 1087 } 1088 } 1089 1090 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1091 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1092 1093 // XML tags for backup/restore of various bits of state 1094 private static final String TAG_PREFERRED_BACKUP = "pa"; 1095 private static final String TAG_DEFAULT_APPS = "da"; 1096 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1097 1098 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1099 private static final String TAG_ALL_GRANTS = "rt-grants"; 1100 private static final String TAG_GRANT = "grant"; 1101 private static final String ATTR_PACKAGE_NAME = "pkg"; 1102 1103 private static final String TAG_PERMISSION = "perm"; 1104 private static final String ATTR_PERMISSION_NAME = "name"; 1105 private static final String ATTR_IS_GRANTED = "g"; 1106 private static final String ATTR_USER_SET = "set"; 1107 private static final String ATTR_USER_FIXED = "fixed"; 1108 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1109 1110 // System/policy permission grants are not backed up 1111 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_POLICY_FIXED 1113 | FLAG_PERMISSION_SYSTEM_FIXED 1114 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1115 1116 // And we back up these user-adjusted states 1117 private static final int USER_RUNTIME_GRANT_MASK = 1118 FLAG_PERMISSION_USER_SET 1119 | FLAG_PERMISSION_USER_FIXED 1120 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1121 1122 final @Nullable String mRequiredVerifierPackage; 1123 final @NonNull String mRequiredInstallerPackage; 1124 final @Nullable String mSetupWizardPackage; 1125 final @NonNull String mServicesSystemSharedLibraryPackageName; 1126 final @NonNull String mSharedSystemSharedLibraryPackageName; 1127 1128 private final PackageUsage mPackageUsage = new PackageUsage(); 1129 private final CompilerStats mCompilerStats = new CompilerStats(); 1130 1131 class PackageHandler extends Handler { 1132 private boolean mBound = false; 1133 final ArrayList<HandlerParams> mPendingInstalls = 1134 new ArrayList<HandlerParams>(); 1135 1136 private boolean connectToService() { 1137 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1138 " DefaultContainerService"); 1139 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1140 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1141 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1142 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1143 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1144 mBound = true; 1145 return true; 1146 } 1147 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1148 return false; 1149 } 1150 1151 private void disconnectService() { 1152 mContainerService = null; 1153 mBound = false; 1154 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1155 mContext.unbindService(mDefContainerConn); 1156 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1157 } 1158 1159 PackageHandler(Looper looper) { 1160 super(looper); 1161 } 1162 1163 public void handleMessage(Message msg) { 1164 try { 1165 doHandleMessage(msg); 1166 } finally { 1167 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1168 } 1169 } 1170 1171 void doHandleMessage(Message msg) { 1172 switch (msg.what) { 1173 case INIT_COPY: { 1174 HandlerParams params = (HandlerParams) msg.obj; 1175 int idx = mPendingInstalls.size(); 1176 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1177 // If a bind was already initiated we dont really 1178 // need to do anything. The pending install 1179 // will be processed later on. 1180 if (!mBound) { 1181 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1182 System.identityHashCode(mHandler)); 1183 // If this is the only one pending we might 1184 // have to bind to the service again. 1185 if (!connectToService()) { 1186 Slog.e(TAG, "Failed to bind to media container service"); 1187 params.serviceError(); 1188 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1189 System.identityHashCode(mHandler)); 1190 if (params.traceMethod != null) { 1191 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1192 params.traceCookie); 1193 } 1194 return; 1195 } else { 1196 // Once we bind to the service, the first 1197 // pending request will be processed. 1198 mPendingInstalls.add(idx, params); 1199 } 1200 } else { 1201 mPendingInstalls.add(idx, params); 1202 // Already bound to the service. Just make 1203 // sure we trigger off processing the first request. 1204 if (idx == 0) { 1205 mHandler.sendEmptyMessage(MCS_BOUND); 1206 } 1207 } 1208 break; 1209 } 1210 case MCS_BOUND: { 1211 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1212 if (msg.obj != null) { 1213 mContainerService = (IMediaContainerService) msg.obj; 1214 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1215 System.identityHashCode(mHandler)); 1216 } 1217 if (mContainerService == null) { 1218 if (!mBound) { 1219 // Something seriously wrong since we are not bound and we are not 1220 // waiting for connection. Bail out. 1221 Slog.e(TAG, "Cannot bind to media container service"); 1222 for (HandlerParams params : mPendingInstalls) { 1223 // Indicate service bind error 1224 params.serviceError(); 1225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1226 System.identityHashCode(params)); 1227 if (params.traceMethod != null) { 1228 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1229 params.traceMethod, params.traceCookie); 1230 } 1231 return; 1232 } 1233 mPendingInstalls.clear(); 1234 } else { 1235 Slog.w(TAG, "Waiting to connect to media container service"); 1236 } 1237 } else if (mPendingInstalls.size() > 0) { 1238 HandlerParams params = mPendingInstalls.get(0); 1239 if (params != null) { 1240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1241 System.identityHashCode(params)); 1242 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1243 if (params.startCopy()) { 1244 // We are done... look for more work or to 1245 // go idle. 1246 if (DEBUG_SD_INSTALL) Log.i(TAG, 1247 "Checking for more work or unbind..."); 1248 // Delete pending install 1249 if (mPendingInstalls.size() > 0) { 1250 mPendingInstalls.remove(0); 1251 } 1252 if (mPendingInstalls.size() == 0) { 1253 if (mBound) { 1254 if (DEBUG_SD_INSTALL) Log.i(TAG, 1255 "Posting delayed MCS_UNBIND"); 1256 removeMessages(MCS_UNBIND); 1257 Message ubmsg = obtainMessage(MCS_UNBIND); 1258 // Unbind after a little delay, to avoid 1259 // continual thrashing. 1260 sendMessageDelayed(ubmsg, 10000); 1261 } 1262 } else { 1263 // There are more pending requests in queue. 1264 // Just post MCS_BOUND message to trigger processing 1265 // of next pending install. 1266 if (DEBUG_SD_INSTALL) Log.i(TAG, 1267 "Posting MCS_BOUND for next work"); 1268 mHandler.sendEmptyMessage(MCS_BOUND); 1269 } 1270 } 1271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1272 } 1273 } else { 1274 // Should never happen ideally. 1275 Slog.w(TAG, "Empty queue"); 1276 } 1277 break; 1278 } 1279 case MCS_RECONNECT: { 1280 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1281 if (mPendingInstalls.size() > 0) { 1282 if (mBound) { 1283 disconnectService(); 1284 } 1285 if (!connectToService()) { 1286 Slog.e(TAG, "Failed to bind to media container service"); 1287 for (HandlerParams params : mPendingInstalls) { 1288 // Indicate service bind error 1289 params.serviceError(); 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1291 System.identityHashCode(params)); 1292 } 1293 mPendingInstalls.clear(); 1294 } 1295 } 1296 break; 1297 } 1298 case MCS_UNBIND: { 1299 // If there is no actual work left, then time to unbind. 1300 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1301 1302 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1303 if (mBound) { 1304 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1305 1306 disconnectService(); 1307 } 1308 } else if (mPendingInstalls.size() > 0) { 1309 // There are more pending requests in queue. 1310 // Just post MCS_BOUND message to trigger processing 1311 // of next pending install. 1312 mHandler.sendEmptyMessage(MCS_BOUND); 1313 } 1314 1315 break; 1316 } 1317 case MCS_GIVE_UP: { 1318 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1319 HandlerParams params = mPendingInstalls.remove(0); 1320 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1321 System.identityHashCode(params)); 1322 break; 1323 } 1324 case SEND_PENDING_BROADCAST: { 1325 String packages[]; 1326 ArrayList<String> components[]; 1327 int size = 0; 1328 int uids[]; 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 synchronized (mPackages) { 1331 if (mPendingBroadcasts == null) { 1332 return; 1333 } 1334 size = mPendingBroadcasts.size(); 1335 if (size <= 0) { 1336 // Nothing to be done. Just return 1337 return; 1338 } 1339 packages = new String[size]; 1340 components = new ArrayList[size]; 1341 uids = new int[size]; 1342 int i = 0; // filling out the above arrays 1343 1344 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1345 int packageUserId = mPendingBroadcasts.userIdAt(n); 1346 Iterator<Map.Entry<String, ArrayList<String>>> it 1347 = mPendingBroadcasts.packagesForUserId(packageUserId) 1348 .entrySet().iterator(); 1349 while (it.hasNext() && i < size) { 1350 Map.Entry<String, ArrayList<String>> ent = it.next(); 1351 packages[i] = ent.getKey(); 1352 components[i] = ent.getValue(); 1353 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1354 uids[i] = (ps != null) 1355 ? UserHandle.getUid(packageUserId, ps.appId) 1356 : -1; 1357 i++; 1358 } 1359 } 1360 size = i; 1361 mPendingBroadcasts.clear(); 1362 } 1363 // Send broadcasts 1364 for (int i = 0; i < size; i++) { 1365 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1366 } 1367 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1368 break; 1369 } 1370 case START_CLEANING_PACKAGE: { 1371 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1372 final String packageName = (String)msg.obj; 1373 final int userId = msg.arg1; 1374 final boolean andCode = msg.arg2 != 0; 1375 synchronized (mPackages) { 1376 if (userId == UserHandle.USER_ALL) { 1377 int[] users = sUserManager.getUserIds(); 1378 for (int user : users) { 1379 mSettings.addPackageToCleanLPw( 1380 new PackageCleanItem(user, packageName, andCode)); 1381 } 1382 } else { 1383 mSettings.addPackageToCleanLPw( 1384 new PackageCleanItem(userId, packageName, andCode)); 1385 } 1386 } 1387 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1388 startCleaningPackages(); 1389 } break; 1390 case POST_INSTALL: { 1391 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1392 1393 PostInstallData data = mRunningInstalls.get(msg.arg1); 1394 final boolean didRestore = (msg.arg2 != 0); 1395 mRunningInstalls.delete(msg.arg1); 1396 1397 if (data != null) { 1398 InstallArgs args = data.args; 1399 PackageInstalledInfo parentRes = data.res; 1400 1401 final boolean grantPermissions = (args.installFlags 1402 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1403 final boolean killApp = (args.installFlags 1404 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1405 final String[] grantedPermissions = args.installGrantPermissions; 1406 1407 // Handle the parent package 1408 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1409 grantedPermissions, didRestore, args.installerPackageName, 1410 args.observer); 1411 1412 // Handle the child packages 1413 final int childCount = (parentRes.addedChildPackages != null) 1414 ? parentRes.addedChildPackages.size() : 0; 1415 for (int i = 0; i < childCount; i++) { 1416 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1417 handlePackagePostInstall(childRes, grantPermissions, killApp, 1418 grantedPermissions, false, args.installerPackageName, 1419 args.observer); 1420 } 1421 1422 // Log tracing if needed 1423 if (args.traceMethod != null) { 1424 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1425 args.traceCookie); 1426 } 1427 } else { 1428 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1429 } 1430 1431 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1432 } break; 1433 case UPDATED_MEDIA_STATUS: { 1434 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1435 boolean reportStatus = msg.arg1 == 1; 1436 boolean doGc = msg.arg2 == 1; 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1438 if (doGc) { 1439 // Force a gc to clear up stale containers. 1440 Runtime.getRuntime().gc(); 1441 } 1442 if (msg.obj != null) { 1443 @SuppressWarnings("unchecked") 1444 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1446 // Unload containers 1447 unloadAllContainers(args); 1448 } 1449 if (reportStatus) { 1450 try { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1452 PackageHelper.getMountService().finishMediaUpdate(); 1453 } catch (RemoteException e) { 1454 Log.e(TAG, "MountService not running?"); 1455 } 1456 } 1457 } break; 1458 case WRITE_SETTINGS: { 1459 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1460 synchronized (mPackages) { 1461 removeMessages(WRITE_SETTINGS); 1462 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1463 mSettings.writeLPr(); 1464 mDirtyUsers.clear(); 1465 } 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1467 } break; 1468 case WRITE_PACKAGE_RESTRICTIONS: { 1469 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1470 synchronized (mPackages) { 1471 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1472 for (int userId : mDirtyUsers) { 1473 mSettings.writePackageRestrictionsLPr(userId); 1474 } 1475 mDirtyUsers.clear(); 1476 } 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1478 } break; 1479 case WRITE_PACKAGE_LIST: { 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1481 synchronized (mPackages) { 1482 removeMessages(WRITE_PACKAGE_LIST); 1483 mSettings.writePackageListLPr(msg.arg1); 1484 } 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1486 } break; 1487 case CHECK_PENDING_VERIFICATION: { 1488 final int verificationId = msg.arg1; 1489 final PackageVerificationState state = mPendingVerification.get(verificationId); 1490 1491 if ((state != null) && !state.timeoutExtended()) { 1492 final InstallArgs args = state.getInstallArgs(); 1493 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1494 1495 Slog.i(TAG, "Verification timed out for " + originUri); 1496 mPendingVerification.remove(verificationId); 1497 1498 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1499 1500 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1501 Slog.i(TAG, "Continuing with installation of " + originUri); 1502 state.setVerifierResponse(Binder.getCallingUid(), 1503 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1504 broadcastPackageVerified(verificationId, originUri, 1505 PackageManager.VERIFICATION_ALLOW, 1506 state.getInstallArgs().getUser()); 1507 try { 1508 ret = args.copyApk(mContainerService, true); 1509 } catch (RemoteException e) { 1510 Slog.e(TAG, "Could not contact the ContainerService"); 1511 } 1512 } else { 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_REJECT, 1515 state.getInstallArgs().getUser()); 1516 } 1517 1518 Trace.asyncTraceEnd( 1519 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1520 1521 processPendingInstall(args, ret); 1522 mHandler.sendEmptyMessage(MCS_UNBIND); 1523 } 1524 break; 1525 } 1526 case PACKAGE_VERIFIED: { 1527 final int verificationId = msg.arg1; 1528 1529 final PackageVerificationState state = mPendingVerification.get(verificationId); 1530 if (state == null) { 1531 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1532 break; 1533 } 1534 1535 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1536 1537 state.setVerifierResponse(response.callerUid, response.code); 1538 1539 if (state.isVerificationComplete()) { 1540 mPendingVerification.remove(verificationId); 1541 1542 final InstallArgs args = state.getInstallArgs(); 1543 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1544 1545 int ret; 1546 if (state.isInstallAllowed()) { 1547 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1548 broadcastPackageVerified(verificationId, originUri, 1549 response.code, state.getInstallArgs().getUser()); 1550 try { 1551 ret = args.copyApk(mContainerService, true); 1552 } catch (RemoteException e) { 1553 Slog.e(TAG, "Could not contact the ContainerService"); 1554 } 1555 } else { 1556 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1557 } 1558 1559 Trace.asyncTraceEnd( 1560 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1561 1562 processPendingInstall(args, ret); 1563 mHandler.sendEmptyMessage(MCS_UNBIND); 1564 } 1565 1566 break; 1567 } 1568 case START_INTENT_FILTER_VERIFICATIONS: { 1569 IFVerificationParams params = (IFVerificationParams) msg.obj; 1570 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1571 params.replacing, params.pkg); 1572 break; 1573 } 1574 case INTENT_FILTER_VERIFIED: { 1575 final int verificationId = msg.arg1; 1576 1577 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1578 verificationId); 1579 if (state == null) { 1580 Slog.w(TAG, "Invalid IntentFilter verification token " 1581 + verificationId + " received"); 1582 break; 1583 } 1584 1585 final int userId = state.getUserId(); 1586 1587 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1588 "Processing IntentFilter verification with token:" 1589 + verificationId + " and userId:" + userId); 1590 1591 final IntentFilterVerificationResponse response = 1592 (IntentFilterVerificationResponse) msg.obj; 1593 1594 state.setVerifierResponse(response.callerUid, response.code); 1595 1596 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1597 "IntentFilter verification with token:" + verificationId 1598 + " and userId:" + userId 1599 + " is settings verifier response with response code:" 1600 + response.code); 1601 1602 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1603 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1604 + response.getFailedDomainsString()); 1605 } 1606 1607 if (state.isVerificationComplete()) { 1608 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1609 } else { 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "IntentFilter verification with token:" + verificationId 1612 + " was not said to be complete"); 1613 } 1614 1615 break; 1616 } 1617 } 1618 } 1619 } 1620 1621 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1622 boolean killApp, String[] grantedPermissions, 1623 boolean launchedForRestore, String installerPackage, 1624 IPackageInstallObserver2 installObserver) { 1625 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1626 // Send the removed broadcasts 1627 if (res.removedInfo != null) { 1628 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1629 } 1630 1631 // Now that we successfully installed the package, grant runtime 1632 // permissions if requested before broadcasting the install. 1633 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1634 >= Build.VERSION_CODES.M) { 1635 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1636 } 1637 1638 final boolean update = res.removedInfo != null 1639 && res.removedInfo.removedPackage != null; 1640 1641 // If this is the first time we have child packages for a disabled privileged 1642 // app that had no children, we grant requested runtime permissions to the new 1643 // children if the parent on the system image had them already granted. 1644 if (res.pkg.parentPackage != null) { 1645 synchronized (mPackages) { 1646 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1647 } 1648 } 1649 1650 synchronized (mPackages) { 1651 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1652 } 1653 1654 final String packageName = res.pkg.applicationInfo.packageName; 1655 Bundle extras = new Bundle(1); 1656 extras.putInt(Intent.EXTRA_UID, res.uid); 1657 1658 // Determine the set of users who are adding this package for 1659 // the first time vs. those who are seeing an update. 1660 int[] firstUsers = EMPTY_INT_ARRAY; 1661 int[] updateUsers = EMPTY_INT_ARRAY; 1662 if (res.origUsers == null || res.origUsers.length == 0) { 1663 firstUsers = res.newUsers; 1664 } else { 1665 for (int newUser : res.newUsers) { 1666 boolean isNew = true; 1667 for (int origUser : res.origUsers) { 1668 if (origUser == newUser) { 1669 isNew = false; 1670 break; 1671 } 1672 } 1673 if (isNew) { 1674 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1675 } else { 1676 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1677 } 1678 } 1679 } 1680 1681 // Send installed broadcasts if the install/update is not ephemeral 1682 if (!isEphemeral(res.pkg)) { 1683 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1684 1685 // Send added for users that see the package for the first time 1686 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1687 extras, 0 /*flags*/, null /*targetPackage*/, 1688 null /*finishedReceiver*/, firstUsers); 1689 1690 // Send added for users that don't see the package for the first time 1691 if (update) { 1692 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1693 } 1694 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1695 extras, 0 /*flags*/, null /*targetPackage*/, 1696 null /*finishedReceiver*/, updateUsers); 1697 1698 // Send replaced for users that don't see the package for the first time 1699 if (update) { 1700 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1701 packageName, extras, 0 /*flags*/, 1702 null /*targetPackage*/, null /*finishedReceiver*/, 1703 updateUsers); 1704 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1705 null /*package*/, null /*extras*/, 0 /*flags*/, 1706 packageName /*targetPackage*/, 1707 null /*finishedReceiver*/, updateUsers); 1708 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1709 // First-install and we did a restore, so we're responsible for the 1710 // first-launch broadcast. 1711 if (DEBUG_BACKUP) { 1712 Slog.i(TAG, "Post-restore of " + packageName 1713 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1714 } 1715 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1716 } 1717 1718 // Send broadcast package appeared if forward locked/external for all users 1719 // treat asec-hosted packages like removable media on upgrade 1720 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1721 if (DEBUG_INSTALL) { 1722 Slog.i(TAG, "upgrading pkg " + res.pkg 1723 + " is ASEC-hosted -> AVAILABLE"); 1724 } 1725 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1726 ArrayList<String> pkgList = new ArrayList<>(1); 1727 pkgList.add(packageName); 1728 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1729 } 1730 } 1731 1732 // Work that needs to happen on first install within each user 1733 if (firstUsers != null && firstUsers.length > 0) { 1734 synchronized (mPackages) { 1735 for (int userId : firstUsers) { 1736 // If this app is a browser and it's newly-installed for some 1737 // users, clear any default-browser state in those users. The 1738 // app's nature doesn't depend on the user, so we can just check 1739 // its browser nature in any user and generalize. 1740 if (packageIsBrowser(packageName, userId)) { 1741 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1742 } 1743 1744 // We may also need to apply pending (restored) runtime 1745 // permission grants within these users. 1746 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1747 } 1748 } 1749 } 1750 1751 // Log current value of "unknown sources" setting 1752 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1753 getUnknownSourcesSettings()); 1754 1755 // Force a gc to clear up things 1756 Runtime.getRuntime().gc(); 1757 1758 // Remove the replaced package's older resources safely now 1759 // We delete after a gc for applications on sdcard. 1760 if (res.removedInfo != null && res.removedInfo.args != null) { 1761 synchronized (mInstallLock) { 1762 res.removedInfo.args.doPostDeleteLI(true); 1763 } 1764 } 1765 } 1766 1767 // If someone is watching installs - notify them 1768 if (installObserver != null) { 1769 try { 1770 Bundle extras = extrasForInstallResult(res); 1771 installObserver.onPackageInstalled(res.name, res.returnCode, 1772 res.returnMsg, extras); 1773 } catch (RemoteException e) { 1774 Slog.i(TAG, "Observer no longer exists."); 1775 } 1776 } 1777 } 1778 1779 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1780 PackageParser.Package pkg) { 1781 if (pkg.parentPackage == null) { 1782 return; 1783 } 1784 if (pkg.requestedPermissions == null) { 1785 return; 1786 } 1787 final PackageSetting disabledSysParentPs = mSettings 1788 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1789 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1790 || !disabledSysParentPs.isPrivileged() 1791 || (disabledSysParentPs.childPackageNames != null 1792 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1793 return; 1794 } 1795 final int[] allUserIds = sUserManager.getUserIds(); 1796 final int permCount = pkg.requestedPermissions.size(); 1797 for (int i = 0; i < permCount; i++) { 1798 String permission = pkg.requestedPermissions.get(i); 1799 BasePermission bp = mSettings.mPermissions.get(permission); 1800 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1801 continue; 1802 } 1803 for (int userId : allUserIds) { 1804 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1805 permission, userId)) { 1806 grantRuntimePermission(pkg.packageName, permission, userId); 1807 } 1808 } 1809 } 1810 } 1811 1812 private StorageEventListener mStorageListener = new StorageEventListener() { 1813 @Override 1814 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1815 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1816 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1817 final String volumeUuid = vol.getFsUuid(); 1818 1819 // Clean up any users or apps that were removed or recreated 1820 // while this volume was missing 1821 reconcileUsers(volumeUuid); 1822 reconcileApps(volumeUuid); 1823 1824 // Clean up any install sessions that expired or were 1825 // cancelled while this volume was missing 1826 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1827 1828 loadPrivatePackages(vol); 1829 1830 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1831 unloadPrivatePackages(vol); 1832 } 1833 } 1834 1835 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1836 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1837 updateExternalMediaStatus(true, false); 1838 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1839 updateExternalMediaStatus(false, false); 1840 } 1841 } 1842 } 1843 1844 @Override 1845 public void onVolumeForgotten(String fsUuid) { 1846 if (TextUtils.isEmpty(fsUuid)) { 1847 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1848 return; 1849 } 1850 1851 // Remove any apps installed on the forgotten volume 1852 synchronized (mPackages) { 1853 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1854 for (PackageSetting ps : packages) { 1855 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1856 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1857 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1858 } 1859 1860 mSettings.onVolumeForgotten(fsUuid); 1861 mSettings.writeLPr(); 1862 } 1863 } 1864 }; 1865 1866 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1867 String[] grantedPermissions) { 1868 for (int userId : userIds) { 1869 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1870 } 1871 1872 // We could have touched GID membership, so flush out packages.list 1873 synchronized (mPackages) { 1874 mSettings.writePackageListLPr(); 1875 } 1876 } 1877 1878 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1879 String[] grantedPermissions) { 1880 SettingBase sb = (SettingBase) pkg.mExtras; 1881 if (sb == null) { 1882 return; 1883 } 1884 1885 PermissionsState permissionsState = sb.getPermissionsState(); 1886 1887 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1888 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1889 1890 for (String permission : pkg.requestedPermissions) { 1891 final BasePermission bp; 1892 synchronized (mPackages) { 1893 bp = mSettings.mPermissions.get(permission); 1894 } 1895 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1896 && (grantedPermissions == null 1897 || ArrayUtils.contains(grantedPermissions, permission))) { 1898 final int flags = permissionsState.getPermissionFlags(permission, userId); 1899 // Installer cannot change immutable permissions. 1900 if ((flags & immutableFlags) == 0) { 1901 grantRuntimePermission(pkg.packageName, permission, userId); 1902 } 1903 } 1904 } 1905 } 1906 1907 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1908 Bundle extras = null; 1909 switch (res.returnCode) { 1910 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1911 extras = new Bundle(); 1912 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1913 res.origPermission); 1914 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1915 res.origPackage); 1916 break; 1917 } 1918 case PackageManager.INSTALL_SUCCEEDED: { 1919 extras = new Bundle(); 1920 extras.putBoolean(Intent.EXTRA_REPLACING, 1921 res.removedInfo != null && res.removedInfo.removedPackage != null); 1922 break; 1923 } 1924 } 1925 return extras; 1926 } 1927 1928 void scheduleWriteSettingsLocked() { 1929 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1930 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1931 } 1932 } 1933 1934 void scheduleWritePackageListLocked(int userId) { 1935 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1936 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1937 msg.arg1 = userId; 1938 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1939 } 1940 } 1941 1942 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1943 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1944 scheduleWritePackageRestrictionsLocked(userId); 1945 } 1946 1947 void scheduleWritePackageRestrictionsLocked(int userId) { 1948 final int[] userIds = (userId == UserHandle.USER_ALL) 1949 ? sUserManager.getUserIds() : new int[]{userId}; 1950 for (int nextUserId : userIds) { 1951 if (!sUserManager.exists(nextUserId)) return; 1952 mDirtyUsers.add(nextUserId); 1953 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1954 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1955 } 1956 } 1957 } 1958 1959 public static PackageManagerService main(Context context, Installer installer, 1960 boolean factoryTest, boolean onlyCore) { 1961 // Self-check for initial settings. 1962 PackageManagerServiceCompilerMapping.checkProperties(); 1963 1964 PackageManagerService m = new PackageManagerService(context, installer, 1965 factoryTest, onlyCore); 1966 m.enableSystemUserPackages(); 1967 ServiceManager.addService("package", m); 1968 return m; 1969 } 1970 1971 private void enableSystemUserPackages() { 1972 if (!UserManager.isSplitSystemUser()) { 1973 return; 1974 } 1975 // For system user, enable apps based on the following conditions: 1976 // - app is whitelisted or belong to one of these groups: 1977 // -- system app which has no launcher icons 1978 // -- system app which has INTERACT_ACROSS_USERS permission 1979 // -- system IME app 1980 // - app is not in the blacklist 1981 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1982 Set<String> enableApps = new ArraySet<>(); 1983 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1984 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1985 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1986 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1987 enableApps.addAll(wlApps); 1988 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1989 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1990 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1991 enableApps.removeAll(blApps); 1992 Log.i(TAG, "Applications installed for system user: " + enableApps); 1993 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1994 UserHandle.SYSTEM); 1995 final int allAppsSize = allAps.size(); 1996 synchronized (mPackages) { 1997 for (int i = 0; i < allAppsSize; i++) { 1998 String pName = allAps.get(i); 1999 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2000 // Should not happen, but we shouldn't be failing if it does 2001 if (pkgSetting == null) { 2002 continue; 2003 } 2004 boolean install = enableApps.contains(pName); 2005 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2006 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2007 + " for system user"); 2008 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2009 } 2010 } 2011 } 2012 } 2013 2014 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2015 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2016 Context.DISPLAY_SERVICE); 2017 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2018 } 2019 2020 /** 2021 * Requests that files preopted on a secondary system partition be copied to the data partition 2022 * if possible. Note that the actual copying of the files is accomplished by init for security 2023 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2024 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2025 */ 2026 private static void requestCopyPreoptedFiles() { 2027 final int WAIT_TIME_MS = 100; 2028 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2029 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2030 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2031 // We will wait for up to 100 seconds. 2032 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2033 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2034 try { 2035 Thread.sleep(WAIT_TIME_MS); 2036 } catch (InterruptedException e) { 2037 // Do nothing 2038 } 2039 if (SystemClock.uptimeMillis() > timeEnd) { 2040 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2041 Slog.wtf(TAG, "cppreopt did not finish!"); 2042 break; 2043 } 2044 } 2045 } 2046 } 2047 2048 public PackageManagerService(Context context, Installer installer, 2049 boolean factoryTest, boolean onlyCore) { 2050 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2051 SystemClock.uptimeMillis()); 2052 2053 if (mSdkVersion <= 0) { 2054 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2055 } 2056 2057 mContext = context; 2058 mFactoryTest = factoryTest; 2059 mOnlyCore = onlyCore; 2060 mMetrics = new DisplayMetrics(); 2061 mSettings = new Settings(mPackages); 2062 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2063 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2064 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2065 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2066 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2067 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2068 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2069 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2070 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2071 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2072 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2073 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2074 2075 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2076 if (separateProcesses != null && separateProcesses.length() > 0) { 2077 if ("*".equals(separateProcesses)) { 2078 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2079 mSeparateProcesses = null; 2080 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2081 } else { 2082 mDefParseFlags = 0; 2083 mSeparateProcesses = separateProcesses.split(","); 2084 Slog.w(TAG, "Running with debug.separate_processes: " 2085 + separateProcesses); 2086 } 2087 } else { 2088 mDefParseFlags = 0; 2089 mSeparateProcesses = null; 2090 } 2091 2092 mInstaller = installer; 2093 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2094 "*dexopt*"); 2095 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2096 2097 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2098 FgThread.get().getLooper()); 2099 2100 getDefaultDisplayMetrics(context, mMetrics); 2101 2102 SystemConfig systemConfig = SystemConfig.getInstance(); 2103 mGlobalGids = systemConfig.getGlobalGids(); 2104 mSystemPermissions = systemConfig.getSystemPermissions(); 2105 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2106 2107 mProtectedPackages = new ProtectedPackages(mContext); 2108 2109 synchronized (mInstallLock) { 2110 // writer 2111 synchronized (mPackages) { 2112 mHandlerThread = new ServiceThread(TAG, 2113 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2114 mHandlerThread.start(); 2115 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2116 mProcessLoggingHandler = new ProcessLoggingHandler(); 2117 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2118 2119 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2120 2121 File dataDir = Environment.getDataDirectory(); 2122 mAppInstallDir = new File(dataDir, "app"); 2123 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2124 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2125 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2126 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2127 2128 sUserManager = new UserManagerService(context, this, mPackages); 2129 2130 // Propagate permission configuration in to package manager. 2131 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2132 = systemConfig.getPermissions(); 2133 for (int i=0; i<permConfig.size(); i++) { 2134 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2135 BasePermission bp = mSettings.mPermissions.get(perm.name); 2136 if (bp == null) { 2137 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2138 mSettings.mPermissions.put(perm.name, bp); 2139 } 2140 if (perm.gids != null) { 2141 bp.setGids(perm.gids, perm.perUser); 2142 } 2143 } 2144 2145 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2146 for (int i=0; i<libConfig.size(); i++) { 2147 mSharedLibraries.put(libConfig.keyAt(i), 2148 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2149 } 2150 2151 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2152 2153 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2154 2155 if (mFirstBoot) { 2156 requestCopyPreoptedFiles(); 2157 } 2158 2159 String customResolverActivity = Resources.getSystem().getString( 2160 R.string.config_customResolverActivity); 2161 if (TextUtils.isEmpty(customResolverActivity)) { 2162 customResolverActivity = null; 2163 } else { 2164 mCustomResolverComponentName = ComponentName.unflattenFromString( 2165 customResolverActivity); 2166 } 2167 2168 long startTime = SystemClock.uptimeMillis(); 2169 2170 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2171 startTime); 2172 2173 // Set flag to monitor and not change apk file paths when 2174 // scanning install directories. 2175 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2176 2177 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2178 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2179 2180 if (bootClassPath == null) { 2181 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2182 } 2183 2184 if (systemServerClassPath == null) { 2185 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2186 } 2187 2188 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2189 final String[] dexCodeInstructionSets = 2190 getDexCodeInstructionSets( 2191 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2192 2193 /** 2194 * Ensure all external libraries have had dexopt run on them. 2195 */ 2196 if (mSharedLibraries.size() > 0) { 2197 // NOTE: For now, we're compiling these system "shared libraries" 2198 // (and framework jars) into all available architectures. It's possible 2199 // to compile them only when we come across an app that uses them (there's 2200 // already logic for that in scanPackageLI) but that adds some complexity. 2201 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2202 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2203 final String lib = libEntry.path; 2204 if (lib == null) { 2205 continue; 2206 } 2207 2208 try { 2209 // Shared libraries do not have profiles so we perform a full 2210 // AOT compilation (if needed). 2211 int dexoptNeeded = DexFile.getDexOptNeeded( 2212 lib, dexCodeInstructionSet, 2213 getCompilerFilterForReason(REASON_SHARED_APK), 2214 false /* newProfile */); 2215 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2216 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2217 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2218 getCompilerFilterForReason(REASON_SHARED_APK), 2219 StorageManager.UUID_PRIVATE_INTERNAL, 2220 SKIP_SHARED_LIBRARY_CHECK); 2221 } 2222 } catch (FileNotFoundException e) { 2223 Slog.w(TAG, "Library not found: " + lib); 2224 } catch (IOException | InstallerException e) { 2225 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2226 + e.getMessage()); 2227 } 2228 } 2229 } 2230 } 2231 2232 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2233 2234 final VersionInfo ver = mSettings.getInternalVersion(); 2235 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2236 2237 // when upgrading from pre-M, promote system app permissions from install to runtime 2238 mPromoteSystemApps = 2239 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2240 2241 // When upgrading from pre-N, we need to handle package extraction like first boot, 2242 // as there is no profiling data available. 2243 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2244 2245 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2246 2247 // save off the names of pre-existing system packages prior to scanning; we don't 2248 // want to automatically grant runtime permissions for new system apps 2249 if (mPromoteSystemApps) { 2250 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2251 while (pkgSettingIter.hasNext()) { 2252 PackageSetting ps = pkgSettingIter.next(); 2253 if (isSystemApp(ps)) { 2254 mExistingSystemPackages.add(ps.name); 2255 } 2256 } 2257 } 2258 2259 // Collect vendor overlay packages. 2260 // (Do this before scanning any apps.) 2261 // For security and version matching reason, only consider 2262 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2263 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2264 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2265 | PackageParser.PARSE_IS_SYSTEM 2266 | PackageParser.PARSE_IS_SYSTEM_DIR 2267 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2268 2269 // Find base frameworks (resource packages without code). 2270 scanDirTracedLI(frameworkDir, mDefParseFlags 2271 | PackageParser.PARSE_IS_SYSTEM 2272 | PackageParser.PARSE_IS_SYSTEM_DIR 2273 | PackageParser.PARSE_IS_PRIVILEGED, 2274 scanFlags | SCAN_NO_DEX, 0); 2275 2276 // Collected privileged system packages. 2277 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2278 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2279 | PackageParser.PARSE_IS_SYSTEM 2280 | PackageParser.PARSE_IS_SYSTEM_DIR 2281 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2282 2283 // Collect ordinary system packages. 2284 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2285 scanDirTracedLI(systemAppDir, mDefParseFlags 2286 | PackageParser.PARSE_IS_SYSTEM 2287 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2288 2289 // Collect all vendor packages. 2290 File vendorAppDir = new File("/vendor/app"); 2291 try { 2292 vendorAppDir = vendorAppDir.getCanonicalFile(); 2293 } catch (IOException e) { 2294 // failed to look up canonical path, continue with original one 2295 } 2296 scanDirTracedLI(vendorAppDir, mDefParseFlags 2297 | PackageParser.PARSE_IS_SYSTEM 2298 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2299 2300 // Collect all OEM packages. 2301 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2302 scanDirTracedLI(oemAppDir, mDefParseFlags 2303 | PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2305 2306 // Prune any system packages that no longer exist. 2307 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2308 if (!mOnlyCore) { 2309 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2310 while (psit.hasNext()) { 2311 PackageSetting ps = psit.next(); 2312 2313 /* 2314 * If this is not a system app, it can't be a 2315 * disable system app. 2316 */ 2317 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2318 continue; 2319 } 2320 2321 /* 2322 * If the package is scanned, it's not erased. 2323 */ 2324 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2325 if (scannedPkg != null) { 2326 /* 2327 * If the system app is both scanned and in the 2328 * disabled packages list, then it must have been 2329 * added via OTA. Remove it from the currently 2330 * scanned package so the previously user-installed 2331 * application can be scanned. 2332 */ 2333 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2334 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2335 + ps.name + "; removing system app. Last known codePath=" 2336 + ps.codePathString + ", installStatus=" + ps.installStatus 2337 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2338 + scannedPkg.mVersionCode); 2339 removePackageLI(scannedPkg, true); 2340 mExpectingBetter.put(ps.name, ps.codePath); 2341 } 2342 2343 continue; 2344 } 2345 2346 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2347 psit.remove(); 2348 logCriticalInfo(Log.WARN, "System package " + ps.name 2349 + " no longer exists; it's data will be wiped"); 2350 // Actual deletion of code and data will be handled by later 2351 // reconciliation step 2352 } else { 2353 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2354 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2355 possiblyDeletedUpdatedSystemApps.add(ps.name); 2356 } 2357 } 2358 } 2359 } 2360 2361 //look for any incomplete package installations 2362 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2363 for (int i = 0; i < deletePkgsList.size(); i++) { 2364 // Actual deletion of code and data will be handled by later 2365 // reconciliation step 2366 final String packageName = deletePkgsList.get(i).name; 2367 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2368 synchronized (mPackages) { 2369 mSettings.removePackageLPw(packageName); 2370 } 2371 } 2372 2373 //delete tmp files 2374 deleteTempPackageFiles(); 2375 2376 // Remove any shared userIDs that have no associated packages 2377 mSettings.pruneSharedUsersLPw(); 2378 2379 if (!mOnlyCore) { 2380 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2381 SystemClock.uptimeMillis()); 2382 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2383 2384 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2385 | PackageParser.PARSE_FORWARD_LOCK, 2386 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2387 2388 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2389 | PackageParser.PARSE_IS_EPHEMERAL, 2390 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2391 2392 /** 2393 * Remove disable package settings for any updated system 2394 * apps that were removed via an OTA. If they're not a 2395 * previously-updated app, remove them completely. 2396 * Otherwise, just revoke their system-level permissions. 2397 */ 2398 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2399 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2400 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2401 2402 String msg; 2403 if (deletedPkg == null) { 2404 msg = "Updated system package " + deletedAppName 2405 + " no longer exists; it's data will be wiped"; 2406 // Actual deletion of code and data will be handled by later 2407 // reconciliation step 2408 } else { 2409 msg = "Updated system app + " + deletedAppName 2410 + " no longer present; removing system privileges for " 2411 + deletedAppName; 2412 2413 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2414 2415 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2416 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2417 } 2418 logCriticalInfo(Log.WARN, msg); 2419 } 2420 2421 /** 2422 * Make sure all system apps that we expected to appear on 2423 * the userdata partition actually showed up. If they never 2424 * appeared, crawl back and revive the system version. 2425 */ 2426 for (int i = 0; i < mExpectingBetter.size(); i++) { 2427 final String packageName = mExpectingBetter.keyAt(i); 2428 if (!mPackages.containsKey(packageName)) { 2429 final File scanFile = mExpectingBetter.valueAt(i); 2430 2431 logCriticalInfo(Log.WARN, "Expected better " + packageName 2432 + " but never showed up; reverting to system"); 2433 2434 int reparseFlags = mDefParseFlags; 2435 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2436 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR 2438 | PackageParser.PARSE_IS_PRIVILEGED; 2439 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2440 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR; 2442 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2443 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR; 2445 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2446 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR; 2448 } else { 2449 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2450 continue; 2451 } 2452 2453 mSettings.enableSystemPackageLPw(packageName); 2454 2455 try { 2456 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2457 } catch (PackageManagerException e) { 2458 Slog.e(TAG, "Failed to parse original system package: " 2459 + e.getMessage()); 2460 } 2461 } 2462 } 2463 } 2464 mExpectingBetter.clear(); 2465 2466 // Resolve protected action filters. Only the setup wizard is allowed to 2467 // have a high priority filter for these actions. 2468 mSetupWizardPackage = getSetupWizardPackageName(); 2469 if (mProtectedFilters.size() > 0) { 2470 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2471 Slog.i(TAG, "No setup wizard;" 2472 + " All protected intents capped to priority 0"); 2473 } 2474 for (ActivityIntentInfo filter : mProtectedFilters) { 2475 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2476 if (DEBUG_FILTERS) { 2477 Slog.i(TAG, "Found setup wizard;" 2478 + " allow priority " + filter.getPriority() + ";" 2479 + " package: " + filter.activity.info.packageName 2480 + " activity: " + filter.activity.className 2481 + " priority: " + filter.getPriority()); 2482 } 2483 // skip setup wizard; allow it to keep the high priority filter 2484 continue; 2485 } 2486 Slog.w(TAG, "Protected action; cap priority to 0;" 2487 + " package: " + filter.activity.info.packageName 2488 + " activity: " + filter.activity.className 2489 + " origPrio: " + filter.getPriority()); 2490 filter.setPriority(0); 2491 } 2492 } 2493 mDeferProtectedFilters = false; 2494 mProtectedFilters.clear(); 2495 2496 // Now that we know all of the shared libraries, update all clients to have 2497 // the correct library paths. 2498 updateAllSharedLibrariesLPw(); 2499 2500 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2501 // NOTE: We ignore potential failures here during a system scan (like 2502 // the rest of the commands above) because there's precious little we 2503 // can do about it. A settings error is reported, though. 2504 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2505 false /* boot complete */); 2506 } 2507 2508 // Now that we know all the packages we are keeping, 2509 // read and update their last usage times. 2510 mPackageUsage.read(mPackages); 2511 mCompilerStats.read(); 2512 2513 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2514 SystemClock.uptimeMillis()); 2515 Slog.i(TAG, "Time to scan packages: " 2516 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2517 + " seconds"); 2518 2519 // If the platform SDK has changed since the last time we booted, 2520 // we need to re-grant app permission to catch any new ones that 2521 // appear. This is really a hack, and means that apps can in some 2522 // cases get permissions that the user didn't initially explicitly 2523 // allow... it would be nice to have some better way to handle 2524 // this situation. 2525 int updateFlags = UPDATE_PERMISSIONS_ALL; 2526 if (ver.sdkVersion != mSdkVersion) { 2527 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2528 + mSdkVersion + "; regranting permissions for internal storage"); 2529 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2530 } 2531 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2532 ver.sdkVersion = mSdkVersion; 2533 2534 // If this is the first boot or an update from pre-M, and it is a normal 2535 // boot, then we need to initialize the default preferred apps across 2536 // all defined users. 2537 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2538 for (UserInfo user : sUserManager.getUsers(true)) { 2539 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2540 applyFactoryDefaultBrowserLPw(user.id); 2541 primeDomainVerificationsLPw(user.id); 2542 } 2543 } 2544 2545 // Prepare storage for system user really early during boot, 2546 // since core system apps like SettingsProvider and SystemUI 2547 // can't wait for user to start 2548 final int storageFlags; 2549 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2550 storageFlags = StorageManager.FLAG_STORAGE_DE; 2551 } else { 2552 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2553 } 2554 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2555 storageFlags); 2556 2557 // If this is first boot after an OTA, and a normal boot, then 2558 // we need to clear code cache directories. 2559 // Note that we do *not* clear the application profiles. These remain valid 2560 // across OTAs and are used to drive profile verification (post OTA) and 2561 // profile compilation (without waiting to collect a fresh set of profiles). 2562 if (mIsUpgrade && !onlyCore) { 2563 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2564 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2565 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2566 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2567 // No apps are running this early, so no need to freeze 2568 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2569 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2570 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2571 } 2572 } 2573 ver.fingerprint = Build.FINGERPRINT; 2574 } 2575 2576 checkDefaultBrowser(); 2577 2578 // clear only after permissions and other defaults have been updated 2579 mExistingSystemPackages.clear(); 2580 mPromoteSystemApps = false; 2581 2582 // All the changes are done during package scanning. 2583 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2584 2585 // can downgrade to reader 2586 mSettings.writeLPr(); 2587 2588 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2589 // early on (before the package manager declares itself as early) because other 2590 // components in the system server might ask for package contexts for these apps. 2591 // 2592 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2593 // (i.e, that the data partition is unavailable). 2594 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2595 long start = System.nanoTime(); 2596 List<PackageParser.Package> coreApps = new ArrayList<>(); 2597 for (PackageParser.Package pkg : mPackages.values()) { 2598 if (pkg.coreApp) { 2599 coreApps.add(pkg); 2600 } 2601 } 2602 2603 int[] stats = performDexOptUpgrade(coreApps, false, 2604 getCompilerFilterForReason(REASON_CORE_APP)); 2605 2606 final int elapsedTimeSeconds = 2607 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2608 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2609 2610 if (DEBUG_DEXOPT) { 2611 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2612 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2613 } 2614 2615 2616 // TODO: Should we log these stats to tron too ? 2617 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2618 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2619 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2620 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2621 } 2622 2623 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2624 SystemClock.uptimeMillis()); 2625 2626 if (!mOnlyCore) { 2627 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2628 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2629 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2630 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2631 mIntentFilterVerifierComponent); 2632 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2633 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2634 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2635 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2636 } else { 2637 mRequiredVerifierPackage = null; 2638 mRequiredInstallerPackage = null; 2639 mIntentFilterVerifierComponent = null; 2640 mIntentFilterVerifier = null; 2641 mServicesSystemSharedLibraryPackageName = null; 2642 mSharedSystemSharedLibraryPackageName = null; 2643 } 2644 2645 mInstallerService = new PackageInstallerService(context, this); 2646 2647 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2648 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2649 // both the installer and resolver must be present to enable ephemeral 2650 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2651 if (DEBUG_EPHEMERAL) { 2652 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2653 + " installer:" + ephemeralInstallerComponent); 2654 } 2655 mEphemeralResolverComponent = ephemeralResolverComponent; 2656 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2657 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2658 mEphemeralResolverConnection = 2659 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2660 } else { 2661 if (DEBUG_EPHEMERAL) { 2662 final String missingComponent = 2663 (ephemeralResolverComponent == null) 2664 ? (ephemeralInstallerComponent == null) 2665 ? "resolver and installer" 2666 : "resolver" 2667 : "installer"; 2668 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2669 } 2670 mEphemeralResolverComponent = null; 2671 mEphemeralInstallerComponent = null; 2672 mEphemeralResolverConnection = null; 2673 } 2674 2675 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2676 } // synchronized (mPackages) 2677 } // synchronized (mInstallLock) 2678 2679 // Now after opening every single application zip, make sure they 2680 // are all flushed. Not really needed, but keeps things nice and 2681 // tidy. 2682 Runtime.getRuntime().gc(); 2683 2684 // The initial scanning above does many calls into installd while 2685 // holding the mPackages lock, but we're mostly interested in yelling 2686 // once we have a booted system. 2687 mInstaller.setWarnIfHeld(mPackages); 2688 2689 // Expose private service for system components to use. 2690 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2691 } 2692 2693 @Override 2694 public boolean isFirstBoot() { 2695 return mFirstBoot; 2696 } 2697 2698 @Override 2699 public boolean isOnlyCoreApps() { 2700 return mOnlyCore; 2701 } 2702 2703 @Override 2704 public boolean isUpgrade() { 2705 return mIsUpgrade; 2706 } 2707 2708 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2709 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2710 2711 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2712 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2713 UserHandle.USER_SYSTEM); 2714 if (matches.size() == 1) { 2715 return matches.get(0).getComponentInfo().packageName; 2716 } else { 2717 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2718 return null; 2719 } 2720 } 2721 2722 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2723 synchronized (mPackages) { 2724 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2725 if (libraryEntry == null) { 2726 throw new IllegalStateException("Missing required shared library:" + libraryName); 2727 } 2728 return libraryEntry.apk; 2729 } 2730 } 2731 2732 private @NonNull String getRequiredInstallerLPr() { 2733 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2734 intent.addCategory(Intent.CATEGORY_DEFAULT); 2735 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2736 2737 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2738 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2739 UserHandle.USER_SYSTEM); 2740 if (matches.size() == 1) { 2741 ResolveInfo resolveInfo = matches.get(0); 2742 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2743 throw new RuntimeException("The installer must be a privileged app"); 2744 } 2745 return matches.get(0).getComponentInfo().packageName; 2746 } else { 2747 throw new RuntimeException("There must be exactly one installer; found " + matches); 2748 } 2749 } 2750 2751 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2752 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2753 2754 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2755 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2756 UserHandle.USER_SYSTEM); 2757 ResolveInfo best = null; 2758 final int N = matches.size(); 2759 for (int i = 0; i < N; i++) { 2760 final ResolveInfo cur = matches.get(i); 2761 final String packageName = cur.getComponentInfo().packageName; 2762 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2763 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2764 continue; 2765 } 2766 2767 if (best == null || cur.priority > best.priority) { 2768 best = cur; 2769 } 2770 } 2771 2772 if (best != null) { 2773 return best.getComponentInfo().getComponentName(); 2774 } else { 2775 throw new RuntimeException("There must be at least one intent filter verifier"); 2776 } 2777 } 2778 2779 private @Nullable ComponentName getEphemeralResolverLPr() { 2780 final String[] packageArray = 2781 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2782 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2783 if (DEBUG_EPHEMERAL) { 2784 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2785 } 2786 return null; 2787 } 2788 2789 final int resolveFlags = 2790 MATCH_DIRECT_BOOT_AWARE 2791 | MATCH_DIRECT_BOOT_UNAWARE 2792 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2793 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2794 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2795 resolveFlags, UserHandle.USER_SYSTEM); 2796 2797 final int N = resolvers.size(); 2798 if (N == 0) { 2799 if (DEBUG_EPHEMERAL) { 2800 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2801 } 2802 return null; 2803 } 2804 2805 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2806 for (int i = 0; i < N; i++) { 2807 final ResolveInfo info = resolvers.get(i); 2808 2809 if (info.serviceInfo == null) { 2810 continue; 2811 } 2812 2813 final String packageName = info.serviceInfo.packageName; 2814 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2815 if (DEBUG_EPHEMERAL) { 2816 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2817 + " pkg: " + packageName + ", info:" + info); 2818 } 2819 continue; 2820 } 2821 2822 if (DEBUG_EPHEMERAL) { 2823 Slog.v(TAG, "Ephemeral resolver found;" 2824 + " pkg: " + packageName + ", info:" + info); 2825 } 2826 return new ComponentName(packageName, info.serviceInfo.name); 2827 } 2828 if (DEBUG_EPHEMERAL) { 2829 Slog.v(TAG, "Ephemeral resolver NOT found"); 2830 } 2831 return null; 2832 } 2833 2834 private @Nullable ComponentName getEphemeralInstallerLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2836 intent.addCategory(Intent.CATEGORY_DEFAULT); 2837 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2838 2839 final int resolveFlags = 2840 MATCH_DIRECT_BOOT_AWARE 2841 | MATCH_DIRECT_BOOT_UNAWARE 2842 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2843 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2844 resolveFlags, UserHandle.USER_SYSTEM); 2845 if (matches.size() == 0) { 2846 return null; 2847 } else if (matches.size() == 1) { 2848 return matches.get(0).getComponentInfo().getComponentName(); 2849 } else { 2850 throw new RuntimeException( 2851 "There must be at most one ephemeral installer; found " + matches); 2852 } 2853 } 2854 2855 private void primeDomainVerificationsLPw(int userId) { 2856 if (DEBUG_DOMAIN_VERIFICATION) { 2857 Slog.d(TAG, "Priming domain verifications in user " + userId); 2858 } 2859 2860 SystemConfig systemConfig = SystemConfig.getInstance(); 2861 ArraySet<String> packages = systemConfig.getLinkedApps(); 2862 ArraySet<String> domains = new ArraySet<String>(); 2863 2864 for (String packageName : packages) { 2865 PackageParser.Package pkg = mPackages.get(packageName); 2866 if (pkg != null) { 2867 if (!pkg.isSystemApp()) { 2868 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2869 continue; 2870 } 2871 2872 domains.clear(); 2873 for (PackageParser.Activity a : pkg.activities) { 2874 for (ActivityIntentInfo filter : a.intents) { 2875 if (hasValidDomains(filter)) { 2876 domains.addAll(filter.getHostsList()); 2877 } 2878 } 2879 } 2880 2881 if (domains.size() > 0) { 2882 if (DEBUG_DOMAIN_VERIFICATION) { 2883 Slog.v(TAG, " + " + packageName); 2884 } 2885 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2886 // state w.r.t. the formal app-linkage "no verification attempted" state; 2887 // and then 'always' in the per-user state actually used for intent resolution. 2888 final IntentFilterVerificationInfo ivi; 2889 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2890 new ArrayList<String>(domains)); 2891 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2892 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2893 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2894 } else { 2895 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2896 + "' does not handle web links"); 2897 } 2898 } else { 2899 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2900 } 2901 } 2902 2903 scheduleWritePackageRestrictionsLocked(userId); 2904 scheduleWriteSettingsLocked(); 2905 } 2906 2907 private void applyFactoryDefaultBrowserLPw(int userId) { 2908 // The default browser app's package name is stored in a string resource, 2909 // with a product-specific overlay used for vendor customization. 2910 String browserPkg = mContext.getResources().getString( 2911 com.android.internal.R.string.default_browser); 2912 if (!TextUtils.isEmpty(browserPkg)) { 2913 // non-empty string => required to be a known package 2914 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2915 if (ps == null) { 2916 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2917 browserPkg = null; 2918 } else { 2919 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2920 } 2921 } 2922 2923 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2924 // default. If there's more than one, just leave everything alone. 2925 if (browserPkg == null) { 2926 calculateDefaultBrowserLPw(userId); 2927 } 2928 } 2929 2930 private void calculateDefaultBrowserLPw(int userId) { 2931 List<String> allBrowsers = resolveAllBrowserApps(userId); 2932 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2933 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2934 } 2935 2936 private List<String> resolveAllBrowserApps(int userId) { 2937 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2938 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2939 PackageManager.MATCH_ALL, userId); 2940 2941 final int count = list.size(); 2942 List<String> result = new ArrayList<String>(count); 2943 for (int i=0; i<count; i++) { 2944 ResolveInfo info = list.get(i); 2945 if (info.activityInfo == null 2946 || !info.handleAllWebDataURI 2947 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2948 || result.contains(info.activityInfo.packageName)) { 2949 continue; 2950 } 2951 result.add(info.activityInfo.packageName); 2952 } 2953 2954 return result; 2955 } 2956 2957 private boolean packageIsBrowser(String packageName, int userId) { 2958 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2959 PackageManager.MATCH_ALL, userId); 2960 final int N = list.size(); 2961 for (int i = 0; i < N; i++) { 2962 ResolveInfo info = list.get(i); 2963 if (packageName.equals(info.activityInfo.packageName)) { 2964 return true; 2965 } 2966 } 2967 return false; 2968 } 2969 2970 private void checkDefaultBrowser() { 2971 final int myUserId = UserHandle.myUserId(); 2972 final String packageName = getDefaultBrowserPackageName(myUserId); 2973 if (packageName != null) { 2974 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2975 if (info == null) { 2976 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2977 synchronized (mPackages) { 2978 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2979 } 2980 } 2981 } 2982 } 2983 2984 @Override 2985 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2986 throws RemoteException { 2987 try { 2988 return super.onTransact(code, data, reply, flags); 2989 } catch (RuntimeException e) { 2990 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2991 Slog.wtf(TAG, "Package Manager Crash", e); 2992 } 2993 throw e; 2994 } 2995 } 2996 2997 static int[] appendInts(int[] cur, int[] add) { 2998 if (add == null) return cur; 2999 if (cur == null) return add; 3000 final int N = add.length; 3001 for (int i=0; i<N; i++) { 3002 cur = appendInt(cur, add[i]); 3003 } 3004 return cur; 3005 } 3006 3007 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3008 if (!sUserManager.exists(userId)) return null; 3009 if (ps == null) { 3010 return null; 3011 } 3012 final PackageParser.Package p = ps.pkg; 3013 if (p == null) { 3014 return null; 3015 } 3016 3017 final PermissionsState permissionsState = ps.getPermissionsState(); 3018 3019 // Compute GIDs only if requested 3020 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3021 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3022 // Compute granted permissions only if package has requested permissions 3023 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3024 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3025 final PackageUserState state = ps.readUserState(userId); 3026 3027 return PackageParser.generatePackageInfo(p, gids, flags, 3028 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3029 } 3030 3031 @Override 3032 public void checkPackageStartable(String packageName, int userId) { 3033 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3034 3035 synchronized (mPackages) { 3036 final PackageSetting ps = mSettings.mPackages.get(packageName); 3037 if (ps == null) { 3038 throw new SecurityException("Package " + packageName + " was not found!"); 3039 } 3040 3041 if (!ps.getInstalled(userId)) { 3042 throw new SecurityException( 3043 "Package " + packageName + " was not installed for user " + userId + "!"); 3044 } 3045 3046 if (mSafeMode && !ps.isSystem()) { 3047 throw new SecurityException("Package " + packageName + " not a system app!"); 3048 } 3049 3050 if (mFrozenPackages.contains(packageName)) { 3051 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3052 } 3053 3054 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3055 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3056 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3057 } 3058 } 3059 } 3060 3061 @Override 3062 public boolean isPackageAvailable(String packageName, int userId) { 3063 if (!sUserManager.exists(userId)) return false; 3064 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3065 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3066 synchronized (mPackages) { 3067 PackageParser.Package p = mPackages.get(packageName); 3068 if (p != null) { 3069 final PackageSetting ps = (PackageSetting) p.mExtras; 3070 if (ps != null) { 3071 final PackageUserState state = ps.readUserState(userId); 3072 if (state != null) { 3073 return PackageParser.isAvailable(state); 3074 } 3075 } 3076 } 3077 } 3078 return false; 3079 } 3080 3081 @Override 3082 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3083 if (!sUserManager.exists(userId)) return null; 3084 flags = updateFlagsForPackage(flags, userId, packageName); 3085 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3086 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3087 // reader 3088 synchronized (mPackages) { 3089 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3090 PackageParser.Package p = null; 3091 if (matchFactoryOnly) { 3092 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3093 if (ps != null) { 3094 return generatePackageInfo(ps, flags, userId); 3095 } 3096 } 3097 if (p == null) { 3098 p = mPackages.get(packageName); 3099 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3100 return null; 3101 } 3102 } 3103 if (DEBUG_PACKAGE_INFO) 3104 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3105 if (p != null) { 3106 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3107 } 3108 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3109 final PackageSetting ps = mSettings.mPackages.get(packageName); 3110 return generatePackageInfo(ps, flags, userId); 3111 } 3112 } 3113 return null; 3114 } 3115 3116 @Override 3117 public String[] currentToCanonicalPackageNames(String[] names) { 3118 String[] out = new String[names.length]; 3119 // reader 3120 synchronized (mPackages) { 3121 for (int i=names.length-1; i>=0; i--) { 3122 PackageSetting ps = mSettings.mPackages.get(names[i]); 3123 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3124 } 3125 } 3126 return out; 3127 } 3128 3129 @Override 3130 public String[] canonicalToCurrentPackageNames(String[] names) { 3131 String[] out = new String[names.length]; 3132 // reader 3133 synchronized (mPackages) { 3134 for (int i=names.length-1; i>=0; i--) { 3135 String cur = mSettings.mRenamedPackages.get(names[i]); 3136 out[i] = cur != null ? cur : names[i]; 3137 } 3138 } 3139 return out; 3140 } 3141 3142 @Override 3143 public int getPackageUid(String packageName, int flags, int userId) { 3144 if (!sUserManager.exists(userId)) return -1; 3145 flags = updateFlagsForPackage(flags, userId, packageName); 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3147 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3148 3149 // reader 3150 synchronized (mPackages) { 3151 final PackageParser.Package p = mPackages.get(packageName); 3152 if (p != null && p.isMatch(flags)) { 3153 return UserHandle.getUid(userId, p.applicationInfo.uid); 3154 } 3155 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3156 final PackageSetting ps = mSettings.mPackages.get(packageName); 3157 if (ps != null && ps.isMatch(flags)) { 3158 return UserHandle.getUid(userId, ps.appId); 3159 } 3160 } 3161 } 3162 3163 return -1; 3164 } 3165 3166 @Override 3167 public int[] getPackageGids(String packageName, int flags, int userId) { 3168 if (!sUserManager.exists(userId)) return null; 3169 flags = updateFlagsForPackage(flags, userId, packageName); 3170 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3171 false /* requireFullPermission */, false /* checkShell */, 3172 "getPackageGids"); 3173 3174 // reader 3175 synchronized (mPackages) { 3176 final PackageParser.Package p = mPackages.get(packageName); 3177 if (p != null && p.isMatch(flags)) { 3178 PackageSetting ps = (PackageSetting) p.mExtras; 3179 return ps.getPermissionsState().computeGids(userId); 3180 } 3181 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3182 final PackageSetting ps = mSettings.mPackages.get(packageName); 3183 if (ps != null && ps.isMatch(flags)) { 3184 return ps.getPermissionsState().computeGids(userId); 3185 } 3186 } 3187 } 3188 3189 return null; 3190 } 3191 3192 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3193 if (bp.perm != null) { 3194 return PackageParser.generatePermissionInfo(bp.perm, flags); 3195 } 3196 PermissionInfo pi = new PermissionInfo(); 3197 pi.name = bp.name; 3198 pi.packageName = bp.sourcePackage; 3199 pi.nonLocalizedLabel = bp.name; 3200 pi.protectionLevel = bp.protectionLevel; 3201 return pi; 3202 } 3203 3204 @Override 3205 public PermissionInfo getPermissionInfo(String name, int flags) { 3206 // reader 3207 synchronized (mPackages) { 3208 final BasePermission p = mSettings.mPermissions.get(name); 3209 if (p != null) { 3210 return generatePermissionInfo(p, flags); 3211 } 3212 return null; 3213 } 3214 } 3215 3216 @Override 3217 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3218 int flags) { 3219 // reader 3220 synchronized (mPackages) { 3221 if (group != null && !mPermissionGroups.containsKey(group)) { 3222 // This is thrown as NameNotFoundException 3223 return null; 3224 } 3225 3226 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3227 for (BasePermission p : mSettings.mPermissions.values()) { 3228 if (group == null) { 3229 if (p.perm == null || p.perm.info.group == null) { 3230 out.add(generatePermissionInfo(p, flags)); 3231 } 3232 } else { 3233 if (p.perm != null && group.equals(p.perm.info.group)) { 3234 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3235 } 3236 } 3237 } 3238 return new ParceledListSlice<>(out); 3239 } 3240 } 3241 3242 @Override 3243 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3244 // reader 3245 synchronized (mPackages) { 3246 return PackageParser.generatePermissionGroupInfo( 3247 mPermissionGroups.get(name), flags); 3248 } 3249 } 3250 3251 @Override 3252 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3253 // reader 3254 synchronized (mPackages) { 3255 final int N = mPermissionGroups.size(); 3256 ArrayList<PermissionGroupInfo> out 3257 = new ArrayList<PermissionGroupInfo>(N); 3258 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3259 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3260 } 3261 return new ParceledListSlice<>(out); 3262 } 3263 } 3264 3265 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3266 int userId) { 3267 if (!sUserManager.exists(userId)) return null; 3268 PackageSetting ps = mSettings.mPackages.get(packageName); 3269 if (ps != null) { 3270 if (ps.pkg == null) { 3271 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3272 if (pInfo != null) { 3273 return pInfo.applicationInfo; 3274 } 3275 return null; 3276 } 3277 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3278 ps.readUserState(userId), userId); 3279 } 3280 return null; 3281 } 3282 3283 @Override 3284 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3285 if (!sUserManager.exists(userId)) return null; 3286 flags = updateFlagsForApplication(flags, userId, packageName); 3287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3288 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3289 // writer 3290 synchronized (mPackages) { 3291 PackageParser.Package p = mPackages.get(packageName); 3292 if (DEBUG_PACKAGE_INFO) Log.v( 3293 TAG, "getApplicationInfo " + packageName 3294 + ": " + p); 3295 if (p != null) { 3296 PackageSetting ps = mSettings.mPackages.get(packageName); 3297 if (ps == null) return null; 3298 // Note: isEnabledLP() does not apply here - always return info 3299 return PackageParser.generateApplicationInfo( 3300 p, flags, ps.readUserState(userId), userId); 3301 } 3302 if ("android".equals(packageName)||"system".equals(packageName)) { 3303 return mAndroidApplication; 3304 } 3305 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3306 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3307 } 3308 } 3309 return null; 3310 } 3311 3312 @Override 3313 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3314 final IPackageDataObserver observer) { 3315 mContext.enforceCallingOrSelfPermission( 3316 android.Manifest.permission.CLEAR_APP_CACHE, null); 3317 // Queue up an async operation since clearing cache may take a little while. 3318 mHandler.post(new Runnable() { 3319 public void run() { 3320 mHandler.removeCallbacks(this); 3321 boolean success = true; 3322 synchronized (mInstallLock) { 3323 try { 3324 mInstaller.freeCache(volumeUuid, freeStorageSize); 3325 } catch (InstallerException e) { 3326 Slog.w(TAG, "Couldn't clear application caches: " + e); 3327 success = false; 3328 } 3329 } 3330 if (observer != null) { 3331 try { 3332 observer.onRemoveCompleted(null, success); 3333 } catch (RemoteException e) { 3334 Slog.w(TAG, "RemoveException when invoking call back"); 3335 } 3336 } 3337 } 3338 }); 3339 } 3340 3341 @Override 3342 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3343 final IntentSender pi) { 3344 mContext.enforceCallingOrSelfPermission( 3345 android.Manifest.permission.CLEAR_APP_CACHE, null); 3346 // Queue up an async operation since clearing cache may take a little while. 3347 mHandler.post(new Runnable() { 3348 public void run() { 3349 mHandler.removeCallbacks(this); 3350 boolean success = true; 3351 synchronized (mInstallLock) { 3352 try { 3353 mInstaller.freeCache(volumeUuid, freeStorageSize); 3354 } catch (InstallerException e) { 3355 Slog.w(TAG, "Couldn't clear application caches: " + e); 3356 success = false; 3357 } 3358 } 3359 if(pi != null) { 3360 try { 3361 // Callback via pending intent 3362 int code = success ? 1 : 0; 3363 pi.sendIntent(null, code, null, 3364 null, null); 3365 } catch (SendIntentException e1) { 3366 Slog.i(TAG, "Failed to send pending intent"); 3367 } 3368 } 3369 } 3370 }); 3371 } 3372 3373 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3374 synchronized (mInstallLock) { 3375 try { 3376 mInstaller.freeCache(volumeUuid, freeStorageSize); 3377 } catch (InstallerException e) { 3378 throw new IOException("Failed to free enough space", e); 3379 } 3380 } 3381 } 3382 3383 /** 3384 * Update given flags based on encryption status of current user. 3385 */ 3386 private int updateFlags(int flags, int userId) { 3387 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3388 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3389 // Caller expressed an explicit opinion about what encryption 3390 // aware/unaware components they want to see, so fall through and 3391 // give them what they want 3392 } else { 3393 // Caller expressed no opinion, so match based on user state 3394 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3395 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3396 } else { 3397 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3398 } 3399 } 3400 return flags; 3401 } 3402 3403 private UserManagerInternal getUserManagerInternal() { 3404 if (mUserManagerInternal == null) { 3405 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3406 } 3407 return mUserManagerInternal; 3408 } 3409 3410 /** 3411 * Update given flags when being used to request {@link PackageInfo}. 3412 */ 3413 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3414 boolean triaged = true; 3415 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3416 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3417 // Caller is asking for component details, so they'd better be 3418 // asking for specific encryption matching behavior, or be triaged 3419 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3420 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3421 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3422 triaged = false; 3423 } 3424 } 3425 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3426 | PackageManager.MATCH_SYSTEM_ONLY 3427 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3428 triaged = false; 3429 } 3430 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3431 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3432 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3433 } 3434 return updateFlags(flags, userId); 3435 } 3436 3437 /** 3438 * Update given flags when being used to request {@link ApplicationInfo}. 3439 */ 3440 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3441 return updateFlagsForPackage(flags, userId, cookie); 3442 } 3443 3444 /** 3445 * Update given flags when being used to request {@link ComponentInfo}. 3446 */ 3447 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3448 if (cookie instanceof Intent) { 3449 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3450 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3451 } 3452 } 3453 3454 boolean triaged = true; 3455 // Caller is asking for component details, so they'd better be 3456 // asking for specific encryption matching behavior, or be triaged 3457 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3458 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3459 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3460 triaged = false; 3461 } 3462 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3463 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3464 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3465 } 3466 3467 return updateFlags(flags, userId); 3468 } 3469 3470 /** 3471 * Update given flags when being used to request {@link ResolveInfo}. 3472 */ 3473 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3474 // Safe mode means we shouldn't match any third-party components 3475 if (mSafeMode) { 3476 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3477 } 3478 3479 return updateFlagsForComponent(flags, userId, cookie); 3480 } 3481 3482 @Override 3483 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3484 if (!sUserManager.exists(userId)) return null; 3485 flags = updateFlagsForComponent(flags, userId, component); 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3487 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3488 synchronized (mPackages) { 3489 PackageParser.Activity a = mActivities.mActivities.get(component); 3490 3491 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3492 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3493 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3494 if (ps == null) return null; 3495 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3496 userId); 3497 } 3498 if (mResolveComponentName.equals(component)) { 3499 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3500 new PackageUserState(), userId); 3501 } 3502 } 3503 return null; 3504 } 3505 3506 @Override 3507 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3508 String resolvedType) { 3509 synchronized (mPackages) { 3510 if (component.equals(mResolveComponentName)) { 3511 // The resolver supports EVERYTHING! 3512 return true; 3513 } 3514 PackageParser.Activity a = mActivities.mActivities.get(component); 3515 if (a == null) { 3516 return false; 3517 } 3518 for (int i=0; i<a.intents.size(); i++) { 3519 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3520 intent.getData(), intent.getCategories(), TAG) >= 0) { 3521 return true; 3522 } 3523 } 3524 return false; 3525 } 3526 } 3527 3528 @Override 3529 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3530 if (!sUserManager.exists(userId)) return null; 3531 flags = updateFlagsForComponent(flags, userId, component); 3532 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3533 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3534 synchronized (mPackages) { 3535 PackageParser.Activity a = mReceivers.mActivities.get(component); 3536 if (DEBUG_PACKAGE_INFO) Log.v( 3537 TAG, "getReceiverInfo " + component + ": " + a); 3538 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3539 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3540 if (ps == null) return null; 3541 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3542 userId); 3543 } 3544 } 3545 return null; 3546 } 3547 3548 @Override 3549 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3550 if (!sUserManager.exists(userId)) return null; 3551 flags = updateFlagsForComponent(flags, userId, component); 3552 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3553 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3554 synchronized (mPackages) { 3555 PackageParser.Service s = mServices.mServices.get(component); 3556 if (DEBUG_PACKAGE_INFO) Log.v( 3557 TAG, "getServiceInfo " + component + ": " + s); 3558 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3559 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3560 if (ps == null) return null; 3561 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3562 userId); 3563 } 3564 } 3565 return null; 3566 } 3567 3568 @Override 3569 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3570 if (!sUserManager.exists(userId)) return null; 3571 flags = updateFlagsForComponent(flags, userId, component); 3572 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3573 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3574 synchronized (mPackages) { 3575 PackageParser.Provider p = mProviders.mProviders.get(component); 3576 if (DEBUG_PACKAGE_INFO) Log.v( 3577 TAG, "getProviderInfo " + component + ": " + p); 3578 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3579 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3580 if (ps == null) return null; 3581 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3582 userId); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public String[] getSystemSharedLibraryNames() { 3590 Set<String> libSet; 3591 synchronized (mPackages) { 3592 libSet = mSharedLibraries.keySet(); 3593 int size = libSet.size(); 3594 if (size > 0) { 3595 String[] libs = new String[size]; 3596 libSet.toArray(libs); 3597 return libs; 3598 } 3599 } 3600 return null; 3601 } 3602 3603 @Override 3604 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3605 synchronized (mPackages) { 3606 return mServicesSystemSharedLibraryPackageName; 3607 } 3608 } 3609 3610 @Override 3611 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3612 synchronized (mPackages) { 3613 return mSharedSystemSharedLibraryPackageName; 3614 } 3615 } 3616 3617 @Override 3618 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3619 synchronized (mPackages) { 3620 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3621 3622 final FeatureInfo fi = new FeatureInfo(); 3623 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3624 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3625 res.add(fi); 3626 3627 return new ParceledListSlice<>(res); 3628 } 3629 } 3630 3631 @Override 3632 public boolean hasSystemFeature(String name, int version) { 3633 synchronized (mPackages) { 3634 final FeatureInfo feat = mAvailableFeatures.get(name); 3635 if (feat == null) { 3636 return false; 3637 } else { 3638 return feat.version >= version; 3639 } 3640 } 3641 } 3642 3643 @Override 3644 public int checkPermission(String permName, String pkgName, int userId) { 3645 if (!sUserManager.exists(userId)) { 3646 return PackageManager.PERMISSION_DENIED; 3647 } 3648 3649 synchronized (mPackages) { 3650 final PackageParser.Package p = mPackages.get(pkgName); 3651 if (p != null && p.mExtras != null) { 3652 final PackageSetting ps = (PackageSetting) p.mExtras; 3653 final PermissionsState permissionsState = ps.getPermissionsState(); 3654 if (permissionsState.hasPermission(permName, userId)) { 3655 return PackageManager.PERMISSION_GRANTED; 3656 } 3657 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3658 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3659 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3660 return PackageManager.PERMISSION_GRANTED; 3661 } 3662 } 3663 } 3664 3665 return PackageManager.PERMISSION_DENIED; 3666 } 3667 3668 @Override 3669 public int checkUidPermission(String permName, int uid) { 3670 final int userId = UserHandle.getUserId(uid); 3671 3672 if (!sUserManager.exists(userId)) { 3673 return PackageManager.PERMISSION_DENIED; 3674 } 3675 3676 synchronized (mPackages) { 3677 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3678 if (obj != null) { 3679 final SettingBase ps = (SettingBase) obj; 3680 final PermissionsState permissionsState = ps.getPermissionsState(); 3681 if (permissionsState.hasPermission(permName, userId)) { 3682 return PackageManager.PERMISSION_GRANTED; 3683 } 3684 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3685 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3686 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3687 return PackageManager.PERMISSION_GRANTED; 3688 } 3689 } else { 3690 ArraySet<String> perms = mSystemPermissions.get(uid); 3691 if (perms != null) { 3692 if (perms.contains(permName)) { 3693 return PackageManager.PERMISSION_GRANTED; 3694 } 3695 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3696 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3697 return PackageManager.PERMISSION_GRANTED; 3698 } 3699 } 3700 } 3701 } 3702 3703 return PackageManager.PERMISSION_DENIED; 3704 } 3705 3706 @Override 3707 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3708 if (UserHandle.getCallingUserId() != userId) { 3709 mContext.enforceCallingPermission( 3710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3711 "isPermissionRevokedByPolicy for user " + userId); 3712 } 3713 3714 if (checkPermission(permission, packageName, userId) 3715 == PackageManager.PERMISSION_GRANTED) { 3716 return false; 3717 } 3718 3719 final long identity = Binder.clearCallingIdentity(); 3720 try { 3721 final int flags = getPermissionFlags(permission, packageName, userId); 3722 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3723 } finally { 3724 Binder.restoreCallingIdentity(identity); 3725 } 3726 } 3727 3728 @Override 3729 public String getPermissionControllerPackageName() { 3730 synchronized (mPackages) { 3731 return mRequiredInstallerPackage; 3732 } 3733 } 3734 3735 /** 3736 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3737 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3738 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3739 * @param message the message to log on security exception 3740 */ 3741 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3742 boolean checkShell, String message) { 3743 if (userId < 0) { 3744 throw new IllegalArgumentException("Invalid userId " + userId); 3745 } 3746 if (checkShell) { 3747 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3748 } 3749 if (userId == UserHandle.getUserId(callingUid)) return; 3750 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3751 if (requireFullPermission) { 3752 mContext.enforceCallingOrSelfPermission( 3753 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3754 } else { 3755 try { 3756 mContext.enforceCallingOrSelfPermission( 3757 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3758 } catch (SecurityException se) { 3759 mContext.enforceCallingOrSelfPermission( 3760 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3761 } 3762 } 3763 } 3764 } 3765 3766 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3767 if (callingUid == Process.SHELL_UID) { 3768 if (userHandle >= 0 3769 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3770 throw new SecurityException("Shell does not have permission to access user " 3771 + userHandle); 3772 } else if (userHandle < 0) { 3773 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3774 + Debug.getCallers(3)); 3775 } 3776 } 3777 } 3778 3779 private BasePermission findPermissionTreeLP(String permName) { 3780 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3781 if (permName.startsWith(bp.name) && 3782 permName.length() > bp.name.length() && 3783 permName.charAt(bp.name.length()) == '.') { 3784 return bp; 3785 } 3786 } 3787 return null; 3788 } 3789 3790 private BasePermission checkPermissionTreeLP(String permName) { 3791 if (permName != null) { 3792 BasePermission bp = findPermissionTreeLP(permName); 3793 if (bp != null) { 3794 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3795 return bp; 3796 } 3797 throw new SecurityException("Calling uid " 3798 + Binder.getCallingUid() 3799 + " is not allowed to add to permission tree " 3800 + bp.name + " owned by uid " + bp.uid); 3801 } 3802 } 3803 throw new SecurityException("No permission tree found for " + permName); 3804 } 3805 3806 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3807 if (s1 == null) { 3808 return s2 == null; 3809 } 3810 if (s2 == null) { 3811 return false; 3812 } 3813 if (s1.getClass() != s2.getClass()) { 3814 return false; 3815 } 3816 return s1.equals(s2); 3817 } 3818 3819 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3820 if (pi1.icon != pi2.icon) return false; 3821 if (pi1.logo != pi2.logo) return false; 3822 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3823 if (!compareStrings(pi1.name, pi2.name)) return false; 3824 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3825 // We'll take care of setting this one. 3826 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3827 // These are not currently stored in settings. 3828 //if (!compareStrings(pi1.group, pi2.group)) return false; 3829 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3830 //if (pi1.labelRes != pi2.labelRes) return false; 3831 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3832 return true; 3833 } 3834 3835 int permissionInfoFootprint(PermissionInfo info) { 3836 int size = info.name.length(); 3837 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3838 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3839 return size; 3840 } 3841 3842 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3843 int size = 0; 3844 for (BasePermission perm : mSettings.mPermissions.values()) { 3845 if (perm.uid == tree.uid) { 3846 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3847 } 3848 } 3849 return size; 3850 } 3851 3852 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3853 // We calculate the max size of permissions defined by this uid and throw 3854 // if that plus the size of 'info' would exceed our stated maximum. 3855 if (tree.uid != Process.SYSTEM_UID) { 3856 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3857 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3858 throw new SecurityException("Permission tree size cap exceeded"); 3859 } 3860 } 3861 } 3862 3863 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3864 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3865 throw new SecurityException("Label must be specified in permission"); 3866 } 3867 BasePermission tree = checkPermissionTreeLP(info.name); 3868 BasePermission bp = mSettings.mPermissions.get(info.name); 3869 boolean added = bp == null; 3870 boolean changed = true; 3871 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3872 if (added) { 3873 enforcePermissionCapLocked(info, tree); 3874 bp = new BasePermission(info.name, tree.sourcePackage, 3875 BasePermission.TYPE_DYNAMIC); 3876 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3877 throw new SecurityException( 3878 "Not allowed to modify non-dynamic permission " 3879 + info.name); 3880 } else { 3881 if (bp.protectionLevel == fixedLevel 3882 && bp.perm.owner.equals(tree.perm.owner) 3883 && bp.uid == tree.uid 3884 && comparePermissionInfos(bp.perm.info, info)) { 3885 changed = false; 3886 } 3887 } 3888 bp.protectionLevel = fixedLevel; 3889 info = new PermissionInfo(info); 3890 info.protectionLevel = fixedLevel; 3891 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3892 bp.perm.info.packageName = tree.perm.info.packageName; 3893 bp.uid = tree.uid; 3894 if (added) { 3895 mSettings.mPermissions.put(info.name, bp); 3896 } 3897 if (changed) { 3898 if (!async) { 3899 mSettings.writeLPr(); 3900 } else { 3901 scheduleWriteSettingsLocked(); 3902 } 3903 } 3904 return added; 3905 } 3906 3907 @Override 3908 public boolean addPermission(PermissionInfo info) { 3909 synchronized (mPackages) { 3910 return addPermissionLocked(info, false); 3911 } 3912 } 3913 3914 @Override 3915 public boolean addPermissionAsync(PermissionInfo info) { 3916 synchronized (mPackages) { 3917 return addPermissionLocked(info, true); 3918 } 3919 } 3920 3921 @Override 3922 public void removePermission(String name) { 3923 synchronized (mPackages) { 3924 checkPermissionTreeLP(name); 3925 BasePermission bp = mSettings.mPermissions.get(name); 3926 if (bp != null) { 3927 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3928 throw new SecurityException( 3929 "Not allowed to modify non-dynamic permission " 3930 + name); 3931 } 3932 mSettings.mPermissions.remove(name); 3933 mSettings.writeLPr(); 3934 } 3935 } 3936 } 3937 3938 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3939 BasePermission bp) { 3940 int index = pkg.requestedPermissions.indexOf(bp.name); 3941 if (index == -1) { 3942 throw new SecurityException("Package " + pkg.packageName 3943 + " has not requested permission " + bp.name); 3944 } 3945 if (!bp.isRuntime() && !bp.isDevelopment()) { 3946 throw new SecurityException("Permission " + bp.name 3947 + " is not a changeable permission type"); 3948 } 3949 } 3950 3951 @Override 3952 public void grantRuntimePermission(String packageName, String name, final int userId) { 3953 if (!sUserManager.exists(userId)) { 3954 Log.e(TAG, "No such user:" + userId); 3955 return; 3956 } 3957 3958 mContext.enforceCallingOrSelfPermission( 3959 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3960 "grantRuntimePermission"); 3961 3962 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3963 true /* requireFullPermission */, true /* checkShell */, 3964 "grantRuntimePermission"); 3965 3966 final int uid; 3967 final SettingBase sb; 3968 3969 synchronized (mPackages) { 3970 final PackageParser.Package pkg = mPackages.get(packageName); 3971 if (pkg == null) { 3972 throw new IllegalArgumentException("Unknown package: " + packageName); 3973 } 3974 3975 final BasePermission bp = mSettings.mPermissions.get(name); 3976 if (bp == null) { 3977 throw new IllegalArgumentException("Unknown permission: " + name); 3978 } 3979 3980 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3981 3982 // If a permission review is required for legacy apps we represent 3983 // their permissions as always granted runtime ones since we need 3984 // to keep the review required permission flag per user while an 3985 // install permission's state is shared across all users. 3986 if (Build.PERMISSIONS_REVIEW_REQUIRED 3987 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3988 && bp.isRuntime()) { 3989 return; 3990 } 3991 3992 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3993 sb = (SettingBase) pkg.mExtras; 3994 if (sb == null) { 3995 throw new IllegalArgumentException("Unknown package: " + packageName); 3996 } 3997 3998 final PermissionsState permissionsState = sb.getPermissionsState(); 3999 4000 final int flags = permissionsState.getPermissionFlags(name, userId); 4001 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4002 throw new SecurityException("Cannot grant system fixed permission " 4003 + name + " for package " + packageName); 4004 } 4005 4006 if (bp.isDevelopment()) { 4007 // Development permissions must be handled specially, since they are not 4008 // normal runtime permissions. For now they apply to all users. 4009 if (permissionsState.grantInstallPermission(bp) != 4010 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4011 scheduleWriteSettingsLocked(); 4012 } 4013 return; 4014 } 4015 4016 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4017 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4018 return; 4019 } 4020 4021 final int result = permissionsState.grantRuntimePermission(bp, userId); 4022 switch (result) { 4023 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4024 return; 4025 } 4026 4027 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4028 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4029 mHandler.post(new Runnable() { 4030 @Override 4031 public void run() { 4032 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4033 } 4034 }); 4035 } 4036 break; 4037 } 4038 4039 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4040 4041 // Not critical if that is lost - app has to request again. 4042 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4043 } 4044 4045 // Only need to do this if user is initialized. Otherwise it's a new user 4046 // and there are no processes running as the user yet and there's no need 4047 // to make an expensive call to remount processes for the changed permissions. 4048 if (READ_EXTERNAL_STORAGE.equals(name) 4049 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4050 final long token = Binder.clearCallingIdentity(); 4051 try { 4052 if (sUserManager.isInitialized(userId)) { 4053 MountServiceInternal mountServiceInternal = LocalServices.getService( 4054 MountServiceInternal.class); 4055 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4056 } 4057 } finally { 4058 Binder.restoreCallingIdentity(token); 4059 } 4060 } 4061 } 4062 4063 @Override 4064 public void revokeRuntimePermission(String packageName, String name, int userId) { 4065 if (!sUserManager.exists(userId)) { 4066 Log.e(TAG, "No such user:" + userId); 4067 return; 4068 } 4069 4070 mContext.enforceCallingOrSelfPermission( 4071 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4072 "revokeRuntimePermission"); 4073 4074 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4075 true /* requireFullPermission */, true /* checkShell */, 4076 "revokeRuntimePermission"); 4077 4078 final int appId; 4079 4080 synchronized (mPackages) { 4081 final PackageParser.Package pkg = mPackages.get(packageName); 4082 if (pkg == null) { 4083 throw new IllegalArgumentException("Unknown package: " + packageName); 4084 } 4085 4086 final BasePermission bp = mSettings.mPermissions.get(name); 4087 if (bp == null) { 4088 throw new IllegalArgumentException("Unknown permission: " + name); 4089 } 4090 4091 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4092 4093 // If a permission review is required for legacy apps we represent 4094 // their permissions as always granted runtime ones since we need 4095 // to keep the review required permission flag per user while an 4096 // install permission's state is shared across all users. 4097 if (Build.PERMISSIONS_REVIEW_REQUIRED 4098 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4099 && bp.isRuntime()) { 4100 return; 4101 } 4102 4103 SettingBase sb = (SettingBase) pkg.mExtras; 4104 if (sb == null) { 4105 throw new IllegalArgumentException("Unknown package: " + packageName); 4106 } 4107 4108 final PermissionsState permissionsState = sb.getPermissionsState(); 4109 4110 final int flags = permissionsState.getPermissionFlags(name, userId); 4111 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4112 throw new SecurityException("Cannot revoke system fixed permission " 4113 + name + " for package " + packageName); 4114 } 4115 4116 if (bp.isDevelopment()) { 4117 // Development permissions must be handled specially, since they are not 4118 // normal runtime permissions. For now they apply to all users. 4119 if (permissionsState.revokeInstallPermission(bp) != 4120 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4121 scheduleWriteSettingsLocked(); 4122 } 4123 return; 4124 } 4125 4126 if (permissionsState.revokeRuntimePermission(bp, userId) == 4127 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4128 return; 4129 } 4130 4131 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4132 4133 // Critical, after this call app should never have the permission. 4134 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4135 4136 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4137 } 4138 4139 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4140 } 4141 4142 @Override 4143 public void resetRuntimePermissions() { 4144 mContext.enforceCallingOrSelfPermission( 4145 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4146 "revokeRuntimePermission"); 4147 4148 int callingUid = Binder.getCallingUid(); 4149 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4150 mContext.enforceCallingOrSelfPermission( 4151 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4152 "resetRuntimePermissions"); 4153 } 4154 4155 synchronized (mPackages) { 4156 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4157 for (int userId : UserManagerService.getInstance().getUserIds()) { 4158 final int packageCount = mPackages.size(); 4159 for (int i = 0; i < packageCount; i++) { 4160 PackageParser.Package pkg = mPackages.valueAt(i); 4161 if (!(pkg.mExtras instanceof PackageSetting)) { 4162 continue; 4163 } 4164 PackageSetting ps = (PackageSetting) pkg.mExtras; 4165 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4166 } 4167 } 4168 } 4169 } 4170 4171 @Override 4172 public int getPermissionFlags(String name, String packageName, int userId) { 4173 if (!sUserManager.exists(userId)) { 4174 return 0; 4175 } 4176 4177 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4178 4179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4180 true /* requireFullPermission */, false /* checkShell */, 4181 "getPermissionFlags"); 4182 4183 synchronized (mPackages) { 4184 final PackageParser.Package pkg = mPackages.get(packageName); 4185 if (pkg == null) { 4186 return 0; 4187 } 4188 4189 final BasePermission bp = mSettings.mPermissions.get(name); 4190 if (bp == null) { 4191 return 0; 4192 } 4193 4194 SettingBase sb = (SettingBase) pkg.mExtras; 4195 if (sb == null) { 4196 return 0; 4197 } 4198 4199 PermissionsState permissionsState = sb.getPermissionsState(); 4200 return permissionsState.getPermissionFlags(name, userId); 4201 } 4202 } 4203 4204 @Override 4205 public void updatePermissionFlags(String name, String packageName, int flagMask, 4206 int flagValues, int userId) { 4207 if (!sUserManager.exists(userId)) { 4208 return; 4209 } 4210 4211 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4212 4213 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4214 true /* requireFullPermission */, true /* checkShell */, 4215 "updatePermissionFlags"); 4216 4217 // Only the system can change these flags and nothing else. 4218 if (getCallingUid() != Process.SYSTEM_UID) { 4219 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4220 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4221 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4222 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4223 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4224 } 4225 4226 synchronized (mPackages) { 4227 final PackageParser.Package pkg = mPackages.get(packageName); 4228 if (pkg == null) { 4229 throw new IllegalArgumentException("Unknown package: " + packageName); 4230 } 4231 4232 final BasePermission bp = mSettings.mPermissions.get(name); 4233 if (bp == null) { 4234 throw new IllegalArgumentException("Unknown permission: " + name); 4235 } 4236 4237 SettingBase sb = (SettingBase) pkg.mExtras; 4238 if (sb == null) { 4239 throw new IllegalArgumentException("Unknown package: " + packageName); 4240 } 4241 4242 PermissionsState permissionsState = sb.getPermissionsState(); 4243 4244 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4245 4246 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4247 // Install and runtime permissions are stored in different places, 4248 // so figure out what permission changed and persist the change. 4249 if (permissionsState.getInstallPermissionState(name) != null) { 4250 scheduleWriteSettingsLocked(); 4251 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4252 || hadState) { 4253 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4254 } 4255 } 4256 } 4257 } 4258 4259 /** 4260 * Update the permission flags for all packages and runtime permissions of a user in order 4261 * to allow device or profile owner to remove POLICY_FIXED. 4262 */ 4263 @Override 4264 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4265 if (!sUserManager.exists(userId)) { 4266 return; 4267 } 4268 4269 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4270 4271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4272 true /* requireFullPermission */, true /* checkShell */, 4273 "updatePermissionFlagsForAllApps"); 4274 4275 // Only the system can change system fixed flags. 4276 if (getCallingUid() != Process.SYSTEM_UID) { 4277 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4278 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4279 } 4280 4281 synchronized (mPackages) { 4282 boolean changed = false; 4283 final int packageCount = mPackages.size(); 4284 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4285 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4286 SettingBase sb = (SettingBase) pkg.mExtras; 4287 if (sb == null) { 4288 continue; 4289 } 4290 PermissionsState permissionsState = sb.getPermissionsState(); 4291 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4292 userId, flagMask, flagValues); 4293 } 4294 if (changed) { 4295 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4296 } 4297 } 4298 } 4299 4300 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4301 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4302 != PackageManager.PERMISSION_GRANTED 4303 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4304 != PackageManager.PERMISSION_GRANTED) { 4305 throw new SecurityException(message + " requires " 4306 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4307 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4308 } 4309 } 4310 4311 @Override 4312 public boolean shouldShowRequestPermissionRationale(String permissionName, 4313 String packageName, int userId) { 4314 if (UserHandle.getCallingUserId() != userId) { 4315 mContext.enforceCallingPermission( 4316 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4317 "canShowRequestPermissionRationale for user " + userId); 4318 } 4319 4320 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4321 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4322 return false; 4323 } 4324 4325 if (checkPermission(permissionName, packageName, userId) 4326 == PackageManager.PERMISSION_GRANTED) { 4327 return false; 4328 } 4329 4330 final int flags; 4331 4332 final long identity = Binder.clearCallingIdentity(); 4333 try { 4334 flags = getPermissionFlags(permissionName, 4335 packageName, userId); 4336 } finally { 4337 Binder.restoreCallingIdentity(identity); 4338 } 4339 4340 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4341 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4342 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4343 4344 if ((flags & fixedFlags) != 0) { 4345 return false; 4346 } 4347 4348 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4349 } 4350 4351 @Override 4352 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4353 mContext.enforceCallingOrSelfPermission( 4354 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4355 "addOnPermissionsChangeListener"); 4356 4357 synchronized (mPackages) { 4358 mOnPermissionChangeListeners.addListenerLocked(listener); 4359 } 4360 } 4361 4362 @Override 4363 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4364 synchronized (mPackages) { 4365 mOnPermissionChangeListeners.removeListenerLocked(listener); 4366 } 4367 } 4368 4369 @Override 4370 public boolean isProtectedBroadcast(String actionName) { 4371 synchronized (mPackages) { 4372 if (mProtectedBroadcasts.contains(actionName)) { 4373 return true; 4374 } else if (actionName != null) { 4375 // TODO: remove these terrible hacks 4376 if (actionName.startsWith("android.net.netmon.lingerExpired") 4377 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4378 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4379 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4380 return true; 4381 } 4382 } 4383 } 4384 return false; 4385 } 4386 4387 @Override 4388 public int checkSignatures(String pkg1, String pkg2) { 4389 synchronized (mPackages) { 4390 final PackageParser.Package p1 = mPackages.get(pkg1); 4391 final PackageParser.Package p2 = mPackages.get(pkg2); 4392 if (p1 == null || p1.mExtras == null 4393 || p2 == null || p2.mExtras == null) { 4394 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4395 } 4396 return compareSignatures(p1.mSignatures, p2.mSignatures); 4397 } 4398 } 4399 4400 @Override 4401 public int checkUidSignatures(int uid1, int uid2) { 4402 // Map to base uids. 4403 uid1 = UserHandle.getAppId(uid1); 4404 uid2 = UserHandle.getAppId(uid2); 4405 // reader 4406 synchronized (mPackages) { 4407 Signature[] s1; 4408 Signature[] s2; 4409 Object obj = mSettings.getUserIdLPr(uid1); 4410 if (obj != null) { 4411 if (obj instanceof SharedUserSetting) { 4412 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4413 } else if (obj instanceof PackageSetting) { 4414 s1 = ((PackageSetting)obj).signatures.mSignatures; 4415 } else { 4416 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4417 } 4418 } else { 4419 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4420 } 4421 obj = mSettings.getUserIdLPr(uid2); 4422 if (obj != null) { 4423 if (obj instanceof SharedUserSetting) { 4424 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4425 } else if (obj instanceof PackageSetting) { 4426 s2 = ((PackageSetting)obj).signatures.mSignatures; 4427 } else { 4428 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4429 } 4430 } else { 4431 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4432 } 4433 return compareSignatures(s1, s2); 4434 } 4435 } 4436 4437 /** 4438 * This method should typically only be used when granting or revoking 4439 * permissions, since the app may immediately restart after this call. 4440 * <p> 4441 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4442 * guard your work against the app being relaunched. 4443 */ 4444 private void killUid(int appId, int userId, String reason) { 4445 final long identity = Binder.clearCallingIdentity(); 4446 try { 4447 IActivityManager am = ActivityManagerNative.getDefault(); 4448 if (am != null) { 4449 try { 4450 am.killUid(appId, userId, reason); 4451 } catch (RemoteException e) { 4452 /* ignore - same process */ 4453 } 4454 } 4455 } finally { 4456 Binder.restoreCallingIdentity(identity); 4457 } 4458 } 4459 4460 /** 4461 * Compares two sets of signatures. Returns: 4462 * <br /> 4463 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4464 * <br /> 4465 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4466 * <br /> 4467 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4468 * <br /> 4469 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4470 * <br /> 4471 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4472 */ 4473 static int compareSignatures(Signature[] s1, Signature[] s2) { 4474 if (s1 == null) { 4475 return s2 == null 4476 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4477 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4478 } 4479 4480 if (s2 == null) { 4481 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4482 } 4483 4484 if (s1.length != s2.length) { 4485 return PackageManager.SIGNATURE_NO_MATCH; 4486 } 4487 4488 // Since both signature sets are of size 1, we can compare without HashSets. 4489 if (s1.length == 1) { 4490 return s1[0].equals(s2[0]) ? 4491 PackageManager.SIGNATURE_MATCH : 4492 PackageManager.SIGNATURE_NO_MATCH; 4493 } 4494 4495 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4496 for (Signature sig : s1) { 4497 set1.add(sig); 4498 } 4499 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4500 for (Signature sig : s2) { 4501 set2.add(sig); 4502 } 4503 // Make sure s2 contains all signatures in s1. 4504 if (set1.equals(set2)) { 4505 return PackageManager.SIGNATURE_MATCH; 4506 } 4507 return PackageManager.SIGNATURE_NO_MATCH; 4508 } 4509 4510 /** 4511 * If the database version for this type of package (internal storage or 4512 * external storage) is less than the version where package signatures 4513 * were updated, return true. 4514 */ 4515 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4516 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4517 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4518 } 4519 4520 /** 4521 * Used for backward compatibility to make sure any packages with 4522 * certificate chains get upgraded to the new style. {@code existingSigs} 4523 * will be in the old format (since they were stored on disk from before the 4524 * system upgrade) and {@code scannedSigs} will be in the newer format. 4525 */ 4526 private int compareSignaturesCompat(PackageSignatures existingSigs, 4527 PackageParser.Package scannedPkg) { 4528 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4529 return PackageManager.SIGNATURE_NO_MATCH; 4530 } 4531 4532 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4533 for (Signature sig : existingSigs.mSignatures) { 4534 existingSet.add(sig); 4535 } 4536 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4537 for (Signature sig : scannedPkg.mSignatures) { 4538 try { 4539 Signature[] chainSignatures = sig.getChainSignatures(); 4540 for (Signature chainSig : chainSignatures) { 4541 scannedCompatSet.add(chainSig); 4542 } 4543 } catch (CertificateEncodingException e) { 4544 scannedCompatSet.add(sig); 4545 } 4546 } 4547 /* 4548 * Make sure the expanded scanned set contains all signatures in the 4549 * existing one. 4550 */ 4551 if (scannedCompatSet.equals(existingSet)) { 4552 // Migrate the old signatures to the new scheme. 4553 existingSigs.assignSignatures(scannedPkg.mSignatures); 4554 // The new KeySets will be re-added later in the scanning process. 4555 synchronized (mPackages) { 4556 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4557 } 4558 return PackageManager.SIGNATURE_MATCH; 4559 } 4560 return PackageManager.SIGNATURE_NO_MATCH; 4561 } 4562 4563 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4564 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4565 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4566 } 4567 4568 private int compareSignaturesRecover(PackageSignatures existingSigs, 4569 PackageParser.Package scannedPkg) { 4570 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 String msg = null; 4575 try { 4576 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4577 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4578 + scannedPkg.packageName); 4579 return PackageManager.SIGNATURE_MATCH; 4580 } 4581 } catch (CertificateException e) { 4582 msg = e.getMessage(); 4583 } 4584 4585 logCriticalInfo(Log.INFO, 4586 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4587 return PackageManager.SIGNATURE_NO_MATCH; 4588 } 4589 4590 @Override 4591 public List<String> getAllPackages() { 4592 synchronized (mPackages) { 4593 return new ArrayList<String>(mPackages.keySet()); 4594 } 4595 } 4596 4597 @Override 4598 public String[] getPackagesForUid(int uid) { 4599 uid = UserHandle.getAppId(uid); 4600 // reader 4601 synchronized (mPackages) { 4602 Object obj = mSettings.getUserIdLPr(uid); 4603 if (obj instanceof SharedUserSetting) { 4604 final SharedUserSetting sus = (SharedUserSetting) obj; 4605 final int N = sus.packages.size(); 4606 final String[] res = new String[N]; 4607 for (int i = 0; i < N; i++) { 4608 res[i] = sus.packages.valueAt(i).name; 4609 } 4610 return res; 4611 } else if (obj instanceof PackageSetting) { 4612 final PackageSetting ps = (PackageSetting) obj; 4613 return new String[] { ps.name }; 4614 } 4615 } 4616 return null; 4617 } 4618 4619 @Override 4620 public String getNameForUid(int uid) { 4621 // reader 4622 synchronized (mPackages) { 4623 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4624 if (obj instanceof SharedUserSetting) { 4625 final SharedUserSetting sus = (SharedUserSetting) obj; 4626 return sus.name + ":" + sus.userId; 4627 } else if (obj instanceof PackageSetting) { 4628 final PackageSetting ps = (PackageSetting) obj; 4629 return ps.name; 4630 } 4631 } 4632 return null; 4633 } 4634 4635 @Override 4636 public int getUidForSharedUser(String sharedUserName) { 4637 if(sharedUserName == null) { 4638 return -1; 4639 } 4640 // reader 4641 synchronized (mPackages) { 4642 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4643 if (suid == null) { 4644 return -1; 4645 } 4646 return suid.userId; 4647 } 4648 } 4649 4650 @Override 4651 public int getFlagsForUid(int uid) { 4652 synchronized (mPackages) { 4653 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4654 if (obj instanceof SharedUserSetting) { 4655 final SharedUserSetting sus = (SharedUserSetting) obj; 4656 return sus.pkgFlags; 4657 } else if (obj instanceof PackageSetting) { 4658 final PackageSetting ps = (PackageSetting) obj; 4659 return ps.pkgFlags; 4660 } 4661 } 4662 return 0; 4663 } 4664 4665 @Override 4666 public int getPrivateFlagsForUid(int uid) { 4667 synchronized (mPackages) { 4668 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4669 if (obj instanceof SharedUserSetting) { 4670 final SharedUserSetting sus = (SharedUserSetting) obj; 4671 return sus.pkgPrivateFlags; 4672 } else if (obj instanceof PackageSetting) { 4673 final PackageSetting ps = (PackageSetting) obj; 4674 return ps.pkgPrivateFlags; 4675 } 4676 } 4677 return 0; 4678 } 4679 4680 @Override 4681 public boolean isUidPrivileged(int uid) { 4682 uid = UserHandle.getAppId(uid); 4683 // reader 4684 synchronized (mPackages) { 4685 Object obj = mSettings.getUserIdLPr(uid); 4686 if (obj instanceof SharedUserSetting) { 4687 final SharedUserSetting sus = (SharedUserSetting) obj; 4688 final Iterator<PackageSetting> it = sus.packages.iterator(); 4689 while (it.hasNext()) { 4690 if (it.next().isPrivileged()) { 4691 return true; 4692 } 4693 } 4694 } else if (obj instanceof PackageSetting) { 4695 final PackageSetting ps = (PackageSetting) obj; 4696 return ps.isPrivileged(); 4697 } 4698 } 4699 return false; 4700 } 4701 4702 @Override 4703 public String[] getAppOpPermissionPackages(String permissionName) { 4704 synchronized (mPackages) { 4705 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4706 if (pkgs == null) { 4707 return null; 4708 } 4709 return pkgs.toArray(new String[pkgs.size()]); 4710 } 4711 } 4712 4713 @Override 4714 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4715 int flags, int userId) { 4716 try { 4717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4718 4719 if (!sUserManager.exists(userId)) return null; 4720 flags = updateFlagsForResolve(flags, userId, intent); 4721 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4722 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4723 4724 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4725 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4726 flags, userId); 4727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4728 4729 final ResolveInfo bestChoice = 4730 chooseBestActivity(intent, resolvedType, flags, query, userId); 4731 return bestChoice; 4732 } finally { 4733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4734 } 4735 } 4736 4737 @Override 4738 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4739 IntentFilter filter, int match, ComponentName activity) { 4740 final int userId = UserHandle.getCallingUserId(); 4741 if (DEBUG_PREFERRED) { 4742 Log.v(TAG, "setLastChosenActivity intent=" + intent 4743 + " resolvedType=" + resolvedType 4744 + " flags=" + flags 4745 + " filter=" + filter 4746 + " match=" + match 4747 + " activity=" + activity); 4748 filter.dump(new PrintStreamPrinter(System.out), " "); 4749 } 4750 intent.setComponent(null); 4751 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4752 userId); 4753 // Find any earlier preferred or last chosen entries and nuke them 4754 findPreferredActivity(intent, resolvedType, 4755 flags, query, 0, false, true, false, userId); 4756 // Add the new activity as the last chosen for this filter 4757 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4758 "Setting last chosen"); 4759 } 4760 4761 @Override 4762 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4763 final int userId = UserHandle.getCallingUserId(); 4764 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4765 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4766 userId); 4767 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4768 false, false, false, userId); 4769 } 4770 4771 private boolean isEphemeralDisabled() { 4772 // ephemeral apps have been disabled across the board 4773 if (DISABLE_EPHEMERAL_APPS) { 4774 return true; 4775 } 4776 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4777 if (!mSystemReady) { 4778 return true; 4779 } 4780 return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0; 4781 } 4782 4783 private boolean isEphemeralAllowed( 4784 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4785 boolean skipPackageCheck) { 4786 // Short circuit and return early if possible. 4787 if (isEphemeralDisabled()) { 4788 return false; 4789 } 4790 final int callingUser = UserHandle.getCallingUserId(); 4791 if (callingUser != UserHandle.USER_SYSTEM) { 4792 return false; 4793 } 4794 if (mEphemeralResolverConnection == null) { 4795 return false; 4796 } 4797 if (intent.getComponent() != null) { 4798 return false; 4799 } 4800 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4801 return false; 4802 } 4803 if (!skipPackageCheck && intent.getPackage() != null) { 4804 return false; 4805 } 4806 final boolean isWebUri = hasWebURI(intent); 4807 if (!isWebUri || intent.getData().getHost() == null) { 4808 return false; 4809 } 4810 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4811 synchronized (mPackages) { 4812 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4813 for (int n = 0; n < count; n++) { 4814 ResolveInfo info = resolvedActivities.get(n); 4815 String packageName = info.activityInfo.packageName; 4816 PackageSetting ps = mSettings.mPackages.get(packageName); 4817 if (ps != null) { 4818 // Try to get the status from User settings first 4819 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4820 int status = (int) (packedStatus >> 32); 4821 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4822 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4823 if (DEBUG_EPHEMERAL) { 4824 Slog.v(TAG, "DENY ephemeral apps;" 4825 + " pkg: " + packageName + ", status: " + status); 4826 } 4827 return false; 4828 } 4829 } 4830 } 4831 } 4832 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4833 return true; 4834 } 4835 4836 private static EphemeralResolveInfo getEphemeralResolveInfo( 4837 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4838 String resolvedType, int userId, String packageName) { 4839 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4840 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4841 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4842 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4843 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4844 ephemeralPrefixCount); 4845 final int[] shaPrefix = digest.getDigestPrefix(); 4846 final byte[][] digestBytes = digest.getDigestBytes(); 4847 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4848 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4849 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4850 // No hash prefix match; there are no ephemeral apps for this domain. 4851 return null; 4852 } 4853 4854 // Go in reverse order so we match the narrowest scope first. 4855 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4856 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4857 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4858 continue; 4859 } 4860 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4861 // No filters; this should never happen. 4862 if (filters.isEmpty()) { 4863 continue; 4864 } 4865 if (packageName != null 4866 && !packageName.equals(ephemeralApplication.getPackageName())) { 4867 continue; 4868 } 4869 // We have a domain match; resolve the filters to see if anything matches. 4870 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4871 for (int j = filters.size() - 1; j >= 0; --j) { 4872 final EphemeralResolveIntentInfo intentInfo = 4873 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4874 ephemeralResolver.addFilter(intentInfo); 4875 } 4876 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4877 intent, resolvedType, false /*defaultOnly*/, userId); 4878 if (!matchedResolveInfoList.isEmpty()) { 4879 return matchedResolveInfoList.get(0); 4880 } 4881 } 4882 } 4883 // Hash or filter mis-match; no ephemeral apps for this domain. 4884 return null; 4885 } 4886 4887 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4888 int flags, List<ResolveInfo> query, int userId) { 4889 if (query != null) { 4890 final int N = query.size(); 4891 if (N == 1) { 4892 return query.get(0); 4893 } else if (N > 1) { 4894 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4895 // If there is more than one activity with the same priority, 4896 // then let the user decide between them. 4897 ResolveInfo r0 = query.get(0); 4898 ResolveInfo r1 = query.get(1); 4899 if (DEBUG_INTENT_MATCHING || debug) { 4900 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4901 + r1.activityInfo.name + "=" + r1.priority); 4902 } 4903 // If the first activity has a higher priority, or a different 4904 // default, then it is always desirable to pick it. 4905 if (r0.priority != r1.priority 4906 || r0.preferredOrder != r1.preferredOrder 4907 || r0.isDefault != r1.isDefault) { 4908 return query.get(0); 4909 } 4910 // If we have saved a preference for a preferred activity for 4911 // this Intent, use that. 4912 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4913 flags, query, r0.priority, true, false, debug, userId); 4914 if (ri != null) { 4915 return ri; 4916 } 4917 ri = new ResolveInfo(mResolveInfo); 4918 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4919 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4920 // If all of the options come from the same package, show the application's 4921 // label and icon instead of the generic resolver's. 4922 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4923 // and then throw away the ResolveInfo itself, meaning that the caller loses 4924 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4925 // a fallback for this case; we only set the target package's resources on 4926 // the ResolveInfo, not the ActivityInfo. 4927 final String intentPackage = intent.getPackage(); 4928 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4929 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4930 ri.resolvePackageName = intentPackage; 4931 if (userNeedsBadging(userId)) { 4932 ri.noResourceId = true; 4933 } else { 4934 ri.icon = appi.icon; 4935 } 4936 ri.iconResourceId = appi.icon; 4937 ri.labelRes = appi.labelRes; 4938 } 4939 ri.activityInfo.applicationInfo = new ApplicationInfo( 4940 ri.activityInfo.applicationInfo); 4941 if (userId != 0) { 4942 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4943 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4944 } 4945 // Make sure that the resolver is displayable in car mode 4946 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4947 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4948 return ri; 4949 } 4950 } 4951 return null; 4952 } 4953 4954 /** 4955 * Return true if the given list is not empty and all of its contents have 4956 * an activityInfo with the given package name. 4957 */ 4958 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4959 if (ArrayUtils.isEmpty(list)) { 4960 return false; 4961 } 4962 for (int i = 0, N = list.size(); i < N; i++) { 4963 final ResolveInfo ri = list.get(i); 4964 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4965 if (ai == null || !packageName.equals(ai.packageName)) { 4966 return false; 4967 } 4968 } 4969 return true; 4970 } 4971 4972 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4973 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4974 final int N = query.size(); 4975 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4976 .get(userId); 4977 // Get the list of persistent preferred activities that handle the intent 4978 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4979 List<PersistentPreferredActivity> pprefs = ppir != null 4980 ? ppir.queryIntent(intent, resolvedType, 4981 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4982 : null; 4983 if (pprefs != null && pprefs.size() > 0) { 4984 final int M = pprefs.size(); 4985 for (int i=0; i<M; i++) { 4986 final PersistentPreferredActivity ppa = pprefs.get(i); 4987 if (DEBUG_PREFERRED || debug) { 4988 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4989 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4990 + "\n component=" + ppa.mComponent); 4991 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4992 } 4993 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4994 flags | MATCH_DISABLED_COMPONENTS, userId); 4995 if (DEBUG_PREFERRED || debug) { 4996 Slog.v(TAG, "Found persistent preferred activity:"); 4997 if (ai != null) { 4998 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4999 } else { 5000 Slog.v(TAG, " null"); 5001 } 5002 } 5003 if (ai == null) { 5004 // This previously registered persistent preferred activity 5005 // component is no longer known. Ignore it and do NOT remove it. 5006 continue; 5007 } 5008 for (int j=0; j<N; j++) { 5009 final ResolveInfo ri = query.get(j); 5010 if (!ri.activityInfo.applicationInfo.packageName 5011 .equals(ai.applicationInfo.packageName)) { 5012 continue; 5013 } 5014 if (!ri.activityInfo.name.equals(ai.name)) { 5015 continue; 5016 } 5017 // Found a persistent preference that can handle the intent. 5018 if (DEBUG_PREFERRED || debug) { 5019 Slog.v(TAG, "Returning persistent preferred activity: " + 5020 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5021 } 5022 return ri; 5023 } 5024 } 5025 } 5026 return null; 5027 } 5028 5029 // TODO: handle preferred activities missing while user has amnesia 5030 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5031 List<ResolveInfo> query, int priority, boolean always, 5032 boolean removeMatches, boolean debug, int userId) { 5033 if (!sUserManager.exists(userId)) return null; 5034 flags = updateFlagsForResolve(flags, userId, intent); 5035 // writer 5036 synchronized (mPackages) { 5037 if (intent.getSelector() != null) { 5038 intent = intent.getSelector(); 5039 } 5040 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5041 5042 // Try to find a matching persistent preferred activity. 5043 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5044 debug, userId); 5045 5046 // If a persistent preferred activity matched, use it. 5047 if (pri != null) { 5048 return pri; 5049 } 5050 5051 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5052 // Get the list of preferred activities that handle the intent 5053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5054 List<PreferredActivity> prefs = pir != null 5055 ? pir.queryIntent(intent, resolvedType, 5056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5057 : null; 5058 if (prefs != null && prefs.size() > 0) { 5059 boolean changed = false; 5060 try { 5061 // First figure out how good the original match set is. 5062 // We will only allow preferred activities that came 5063 // from the same match quality. 5064 int match = 0; 5065 5066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5067 5068 final int N = query.size(); 5069 for (int j=0; j<N; j++) { 5070 final ResolveInfo ri = query.get(j); 5071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5072 + ": 0x" + Integer.toHexString(match)); 5073 if (ri.match > match) { 5074 match = ri.match; 5075 } 5076 } 5077 5078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5079 + Integer.toHexString(match)); 5080 5081 match &= IntentFilter.MATCH_CATEGORY_MASK; 5082 final int M = prefs.size(); 5083 for (int i=0; i<M; i++) { 5084 final PreferredActivity pa = prefs.get(i); 5085 if (DEBUG_PREFERRED || debug) { 5086 Slog.v(TAG, "Checking PreferredActivity ds=" 5087 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5088 + "\n component=" + pa.mPref.mComponent); 5089 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5090 } 5091 if (pa.mPref.mMatch != match) { 5092 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5093 + Integer.toHexString(pa.mPref.mMatch)); 5094 continue; 5095 } 5096 // If it's not an "always" type preferred activity and that's what we're 5097 // looking for, skip it. 5098 if (always && !pa.mPref.mAlways) { 5099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5100 continue; 5101 } 5102 final ActivityInfo ai = getActivityInfo( 5103 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5104 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5105 userId); 5106 if (DEBUG_PREFERRED || debug) { 5107 Slog.v(TAG, "Found preferred activity:"); 5108 if (ai != null) { 5109 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5110 } else { 5111 Slog.v(TAG, " null"); 5112 } 5113 } 5114 if (ai == null) { 5115 // This previously registered preferred activity 5116 // component is no longer known. Most likely an update 5117 // to the app was installed and in the new version this 5118 // component no longer exists. Clean it up by removing 5119 // it from the preferred activities list, and skip it. 5120 Slog.w(TAG, "Removing dangling preferred activity: " 5121 + pa.mPref.mComponent); 5122 pir.removeFilter(pa); 5123 changed = true; 5124 continue; 5125 } 5126 for (int j=0; j<N; j++) { 5127 final ResolveInfo ri = query.get(j); 5128 if (!ri.activityInfo.applicationInfo.packageName 5129 .equals(ai.applicationInfo.packageName)) { 5130 continue; 5131 } 5132 if (!ri.activityInfo.name.equals(ai.name)) { 5133 continue; 5134 } 5135 5136 if (removeMatches) { 5137 pir.removeFilter(pa); 5138 changed = true; 5139 if (DEBUG_PREFERRED) { 5140 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5141 } 5142 break; 5143 } 5144 5145 // Okay we found a previously set preferred or last chosen app. 5146 // If the result set is different from when this 5147 // was created, we need to clear it and re-ask the 5148 // user their preference, if we're looking for an "always" type entry. 5149 if (always && !pa.mPref.sameSet(query)) { 5150 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5151 + intent + " type " + resolvedType); 5152 if (DEBUG_PREFERRED) { 5153 Slog.v(TAG, "Removing preferred activity since set changed " 5154 + pa.mPref.mComponent); 5155 } 5156 pir.removeFilter(pa); 5157 // Re-add the filter as a "last chosen" entry (!always) 5158 PreferredActivity lastChosen = new PreferredActivity( 5159 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5160 pir.addFilter(lastChosen); 5161 changed = true; 5162 return null; 5163 } 5164 5165 // Yay! Either the set matched or we're looking for the last chosen 5166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5167 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5168 return ri; 5169 } 5170 } 5171 } finally { 5172 if (changed) { 5173 if (DEBUG_PREFERRED) { 5174 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5175 } 5176 scheduleWritePackageRestrictionsLocked(userId); 5177 } 5178 } 5179 } 5180 } 5181 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5182 return null; 5183 } 5184 5185 /* 5186 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5187 */ 5188 @Override 5189 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5190 int targetUserId) { 5191 mContext.enforceCallingOrSelfPermission( 5192 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5193 List<CrossProfileIntentFilter> matches = 5194 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5195 if (matches != null) { 5196 int size = matches.size(); 5197 for (int i = 0; i < size; i++) { 5198 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5199 } 5200 } 5201 if (hasWebURI(intent)) { 5202 // cross-profile app linking works only towards the parent. 5203 final UserInfo parent = getProfileParent(sourceUserId); 5204 synchronized(mPackages) { 5205 int flags = updateFlagsForResolve(0, parent.id, intent); 5206 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5207 intent, resolvedType, flags, sourceUserId, parent.id); 5208 return xpDomainInfo != null; 5209 } 5210 } 5211 return false; 5212 } 5213 5214 private UserInfo getProfileParent(int userId) { 5215 final long identity = Binder.clearCallingIdentity(); 5216 try { 5217 return sUserManager.getProfileParent(userId); 5218 } finally { 5219 Binder.restoreCallingIdentity(identity); 5220 } 5221 } 5222 5223 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5224 String resolvedType, int userId) { 5225 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5226 if (resolver != null) { 5227 return resolver.queryIntent(intent, resolvedType, false, userId); 5228 } 5229 return null; 5230 } 5231 5232 @Override 5233 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5234 String resolvedType, int flags, int userId) { 5235 try { 5236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5237 5238 return new ParceledListSlice<>( 5239 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5240 } finally { 5241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5242 } 5243 } 5244 5245 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5246 String resolvedType, int flags, int userId) { 5247 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5248 flags = updateFlagsForResolve(flags, userId, intent); 5249 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5250 false /* requireFullPermission */, false /* checkShell */, 5251 "query intent activities"); 5252 ComponentName comp = intent.getComponent(); 5253 if (comp == null) { 5254 if (intent.getSelector() != null) { 5255 intent = intent.getSelector(); 5256 comp = intent.getComponent(); 5257 } 5258 } 5259 5260 if (comp != null) { 5261 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5262 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5263 if (ai != null) { 5264 final ResolveInfo ri = new ResolveInfo(); 5265 ri.activityInfo = ai; 5266 list.add(ri); 5267 } 5268 return list; 5269 } 5270 5271 // reader 5272 boolean sortResult = false; 5273 boolean addEphemeral = false; 5274 boolean matchEphemeralPackage = false; 5275 List<ResolveInfo> result; 5276 final String pkgName = intent.getPackage(); 5277 synchronized (mPackages) { 5278 if (pkgName == null) { 5279 List<CrossProfileIntentFilter> matchingFilters = 5280 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5281 // Check for results that need to skip the current profile. 5282 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5283 resolvedType, flags, userId); 5284 if (xpResolveInfo != null) { 5285 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5286 xpResult.add(xpResolveInfo); 5287 return filterIfNotSystemUser(xpResult, userId); 5288 } 5289 5290 // Check for results in the current profile. 5291 result = filterIfNotSystemUser(mActivities.queryIntent( 5292 intent, resolvedType, flags, userId), userId); 5293 addEphemeral = 5294 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5295 5296 // Check for cross profile results. 5297 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5298 xpResolveInfo = queryCrossProfileIntents( 5299 matchingFilters, intent, resolvedType, flags, userId, 5300 hasNonNegativePriorityResult); 5301 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5302 boolean isVisibleToUser = filterIfNotSystemUser( 5303 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5304 if (isVisibleToUser) { 5305 result.add(xpResolveInfo); 5306 sortResult = true; 5307 } 5308 } 5309 if (hasWebURI(intent)) { 5310 CrossProfileDomainInfo xpDomainInfo = null; 5311 final UserInfo parent = getProfileParent(userId); 5312 if (parent != null) { 5313 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5314 flags, userId, parent.id); 5315 } 5316 if (xpDomainInfo != null) { 5317 if (xpResolveInfo != null) { 5318 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5319 // in the result. 5320 result.remove(xpResolveInfo); 5321 } 5322 if (result.size() == 0 && !addEphemeral) { 5323 result.add(xpDomainInfo.resolveInfo); 5324 return result; 5325 } 5326 } 5327 if (result.size() > 1 || addEphemeral) { 5328 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5329 intent, flags, result, xpDomainInfo, userId); 5330 sortResult = true; 5331 } 5332 } 5333 } else { 5334 final PackageParser.Package pkg = mPackages.get(pkgName); 5335 if (pkg != null) { 5336 result = filterIfNotSystemUser( 5337 mActivities.queryIntentForPackage( 5338 intent, resolvedType, flags, pkg.activities, userId), 5339 userId); 5340 } else { 5341 // the caller wants to resolve for a particular package; however, there 5342 // were no installed results, so, try to find an ephemeral result 5343 addEphemeral = isEphemeralAllowed( 5344 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5345 matchEphemeralPackage = true; 5346 result = new ArrayList<ResolveInfo>(); 5347 } 5348 } 5349 } 5350 if (addEphemeral) { 5351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5352 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5353 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5354 matchEphemeralPackage ? pkgName : null); 5355 if (ai != null) { 5356 if (DEBUG_EPHEMERAL) { 5357 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5358 } 5359 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5360 ephemeralInstaller.ephemeralResolveInfo = ai; 5361 // make sure this resolver is the default 5362 ephemeralInstaller.isDefault = true; 5363 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5364 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5365 // add a non-generic filter 5366 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5367 ephemeralInstaller.filter.addDataPath( 5368 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5369 result.add(ephemeralInstaller); 5370 } 5371 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5372 } 5373 if (sortResult) { 5374 Collections.sort(result, mResolvePrioritySorter); 5375 } 5376 return result; 5377 } 5378 5379 private static class CrossProfileDomainInfo { 5380 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5381 ResolveInfo resolveInfo; 5382 /* Best domain verification status of the activities found in the other profile */ 5383 int bestDomainVerificationStatus; 5384 } 5385 5386 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5387 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5388 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5389 sourceUserId)) { 5390 return null; 5391 } 5392 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5393 resolvedType, flags, parentUserId); 5394 5395 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5396 return null; 5397 } 5398 CrossProfileDomainInfo result = null; 5399 int size = resultTargetUser.size(); 5400 for (int i = 0; i < size; i++) { 5401 ResolveInfo riTargetUser = resultTargetUser.get(i); 5402 // Intent filter verification is only for filters that specify a host. So don't return 5403 // those that handle all web uris. 5404 if (riTargetUser.handleAllWebDataURI) { 5405 continue; 5406 } 5407 String packageName = riTargetUser.activityInfo.packageName; 5408 PackageSetting ps = mSettings.mPackages.get(packageName); 5409 if (ps == null) { 5410 continue; 5411 } 5412 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5413 int status = (int)(verificationState >> 32); 5414 if (result == null) { 5415 result = new CrossProfileDomainInfo(); 5416 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5417 sourceUserId, parentUserId); 5418 result.bestDomainVerificationStatus = status; 5419 } else { 5420 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5421 result.bestDomainVerificationStatus); 5422 } 5423 } 5424 // Don't consider matches with status NEVER across profiles. 5425 if (result != null && result.bestDomainVerificationStatus 5426 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5427 return null; 5428 } 5429 return result; 5430 } 5431 5432 /** 5433 * Verification statuses are ordered from the worse to the best, except for 5434 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5435 */ 5436 private int bestDomainVerificationStatus(int status1, int status2) { 5437 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5438 return status2; 5439 } 5440 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5441 return status1; 5442 } 5443 return (int) MathUtils.max(status1, status2); 5444 } 5445 5446 private boolean isUserEnabled(int userId) { 5447 long callingId = Binder.clearCallingIdentity(); 5448 try { 5449 UserInfo userInfo = sUserManager.getUserInfo(userId); 5450 return userInfo != null && userInfo.isEnabled(); 5451 } finally { 5452 Binder.restoreCallingIdentity(callingId); 5453 } 5454 } 5455 5456 /** 5457 * Filter out activities with systemUserOnly flag set, when current user is not System. 5458 * 5459 * @return filtered list 5460 */ 5461 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5462 if (userId == UserHandle.USER_SYSTEM) { 5463 return resolveInfos; 5464 } 5465 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5466 ResolveInfo info = resolveInfos.get(i); 5467 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5468 resolveInfos.remove(i); 5469 } 5470 } 5471 return resolveInfos; 5472 } 5473 5474 /** 5475 * @param resolveInfos list of resolve infos in descending priority order 5476 * @return if the list contains a resolve info with non-negative priority 5477 */ 5478 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5479 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5480 } 5481 5482 private static boolean hasWebURI(Intent intent) { 5483 if (intent.getData() == null) { 5484 return false; 5485 } 5486 final String scheme = intent.getScheme(); 5487 if (TextUtils.isEmpty(scheme)) { 5488 return false; 5489 } 5490 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5491 } 5492 5493 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5494 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5495 int userId) { 5496 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5497 5498 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5499 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5500 candidates.size()); 5501 } 5502 5503 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5504 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5505 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5506 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5507 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5508 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5509 5510 synchronized (mPackages) { 5511 final int count = candidates.size(); 5512 // First, try to use linked apps. Partition the candidates into four lists: 5513 // one for the final results, one for the "do not use ever", one for "undefined status" 5514 // and finally one for "browser app type". 5515 for (int n=0; n<count; n++) { 5516 ResolveInfo info = candidates.get(n); 5517 String packageName = info.activityInfo.packageName; 5518 PackageSetting ps = mSettings.mPackages.get(packageName); 5519 if (ps != null) { 5520 // Add to the special match all list (Browser use case) 5521 if (info.handleAllWebDataURI) { 5522 matchAllList.add(info); 5523 continue; 5524 } 5525 // Try to get the status from User settings first 5526 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5527 int status = (int)(packedStatus >> 32); 5528 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5529 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5530 if (DEBUG_DOMAIN_VERIFICATION) { 5531 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5532 + " : linkgen=" + linkGeneration); 5533 } 5534 // Use link-enabled generation as preferredOrder, i.e. 5535 // prefer newly-enabled over earlier-enabled. 5536 info.preferredOrder = linkGeneration; 5537 alwaysList.add(info); 5538 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5539 if (DEBUG_DOMAIN_VERIFICATION) { 5540 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5541 } 5542 neverList.add(info); 5543 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5546 } 5547 alwaysAskList.add(info); 5548 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5549 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5550 if (DEBUG_DOMAIN_VERIFICATION) { 5551 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5552 } 5553 undefinedList.add(info); 5554 } 5555 } 5556 } 5557 5558 // We'll want to include browser possibilities in a few cases 5559 boolean includeBrowser = false; 5560 5561 // First try to add the "always" resolution(s) for the current user, if any 5562 if (alwaysList.size() > 0) { 5563 result.addAll(alwaysList); 5564 } else { 5565 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5566 result.addAll(undefinedList); 5567 // Maybe add one for the other profile. 5568 if (xpDomainInfo != null && ( 5569 xpDomainInfo.bestDomainVerificationStatus 5570 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5571 result.add(xpDomainInfo.resolveInfo); 5572 } 5573 includeBrowser = true; 5574 } 5575 5576 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5577 // If there were 'always' entries their preferred order has been set, so we also 5578 // back that off to make the alternatives equivalent 5579 if (alwaysAskList.size() > 0) { 5580 for (ResolveInfo i : result) { 5581 i.preferredOrder = 0; 5582 } 5583 result.addAll(alwaysAskList); 5584 includeBrowser = true; 5585 } 5586 5587 if (includeBrowser) { 5588 // Also add browsers (all of them or only the default one) 5589 if (DEBUG_DOMAIN_VERIFICATION) { 5590 Slog.v(TAG, " ...including browsers in candidate set"); 5591 } 5592 if ((matchFlags & MATCH_ALL) != 0) { 5593 result.addAll(matchAllList); 5594 } else { 5595 // Browser/generic handling case. If there's a default browser, go straight 5596 // to that (but only if there is no other higher-priority match). 5597 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5598 int maxMatchPrio = 0; 5599 ResolveInfo defaultBrowserMatch = null; 5600 final int numCandidates = matchAllList.size(); 5601 for (int n = 0; n < numCandidates; n++) { 5602 ResolveInfo info = matchAllList.get(n); 5603 // track the highest overall match priority... 5604 if (info.priority > maxMatchPrio) { 5605 maxMatchPrio = info.priority; 5606 } 5607 // ...and the highest-priority default browser match 5608 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5609 if (defaultBrowserMatch == null 5610 || (defaultBrowserMatch.priority < info.priority)) { 5611 if (debug) { 5612 Slog.v(TAG, "Considering default browser match " + info); 5613 } 5614 defaultBrowserMatch = info; 5615 } 5616 } 5617 } 5618 if (defaultBrowserMatch != null 5619 && defaultBrowserMatch.priority >= maxMatchPrio 5620 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5621 { 5622 if (debug) { 5623 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5624 } 5625 result.add(defaultBrowserMatch); 5626 } else { 5627 result.addAll(matchAllList); 5628 } 5629 } 5630 5631 // If there is nothing selected, add all candidates and remove the ones that the user 5632 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5633 if (result.size() == 0) { 5634 result.addAll(candidates); 5635 result.removeAll(neverList); 5636 } 5637 } 5638 } 5639 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5640 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5641 result.size()); 5642 for (ResolveInfo info : result) { 5643 Slog.v(TAG, " + " + info.activityInfo); 5644 } 5645 } 5646 return result; 5647 } 5648 5649 // Returns a packed value as a long: 5650 // 5651 // high 'int'-sized word: link status: undefined/ask/never/always. 5652 // low 'int'-sized word: relative priority among 'always' results. 5653 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5654 long result = ps.getDomainVerificationStatusForUser(userId); 5655 // if none available, get the master status 5656 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5657 if (ps.getIntentFilterVerificationInfo() != null) { 5658 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5659 } 5660 } 5661 return result; 5662 } 5663 5664 private ResolveInfo querySkipCurrentProfileIntents( 5665 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5666 int flags, int sourceUserId) { 5667 if (matchingFilters != null) { 5668 int size = matchingFilters.size(); 5669 for (int i = 0; i < size; i ++) { 5670 CrossProfileIntentFilter filter = matchingFilters.get(i); 5671 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5672 // Checking if there are activities in the target user that can handle the 5673 // intent. 5674 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5675 resolvedType, flags, sourceUserId); 5676 if (resolveInfo != null) { 5677 return resolveInfo; 5678 } 5679 } 5680 } 5681 } 5682 return null; 5683 } 5684 5685 // Return matching ResolveInfo in target user if any. 5686 private ResolveInfo queryCrossProfileIntents( 5687 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5688 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5689 if (matchingFilters != null) { 5690 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5691 // match the same intent. For performance reasons, it is better not to 5692 // run queryIntent twice for the same userId 5693 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5694 int size = matchingFilters.size(); 5695 for (int i = 0; i < size; i++) { 5696 CrossProfileIntentFilter filter = matchingFilters.get(i); 5697 int targetUserId = filter.getTargetUserId(); 5698 boolean skipCurrentProfile = 5699 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5700 boolean skipCurrentProfileIfNoMatchFound = 5701 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5702 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5703 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5704 // Checking if there are activities in the target user that can handle the 5705 // intent. 5706 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5707 resolvedType, flags, sourceUserId); 5708 if (resolveInfo != null) return resolveInfo; 5709 alreadyTriedUserIds.put(targetUserId, true); 5710 } 5711 } 5712 } 5713 return null; 5714 } 5715 5716 /** 5717 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5718 * will forward the intent to the filter's target user. 5719 * Otherwise, returns null. 5720 */ 5721 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5722 String resolvedType, int flags, int sourceUserId) { 5723 int targetUserId = filter.getTargetUserId(); 5724 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5725 resolvedType, flags, targetUserId); 5726 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5727 // If all the matches in the target profile are suspended, return null. 5728 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5729 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5730 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5731 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5732 targetUserId); 5733 } 5734 } 5735 } 5736 return null; 5737 } 5738 5739 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5740 int sourceUserId, int targetUserId) { 5741 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5742 long ident = Binder.clearCallingIdentity(); 5743 boolean targetIsProfile; 5744 try { 5745 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5746 } finally { 5747 Binder.restoreCallingIdentity(ident); 5748 } 5749 String className; 5750 if (targetIsProfile) { 5751 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5752 } else { 5753 className = FORWARD_INTENT_TO_PARENT; 5754 } 5755 ComponentName forwardingActivityComponentName = new ComponentName( 5756 mAndroidApplication.packageName, className); 5757 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5758 sourceUserId); 5759 if (!targetIsProfile) { 5760 forwardingActivityInfo.showUserIcon = targetUserId; 5761 forwardingResolveInfo.noResourceId = true; 5762 } 5763 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5764 forwardingResolveInfo.priority = 0; 5765 forwardingResolveInfo.preferredOrder = 0; 5766 forwardingResolveInfo.match = 0; 5767 forwardingResolveInfo.isDefault = true; 5768 forwardingResolveInfo.filter = filter; 5769 forwardingResolveInfo.targetUserId = targetUserId; 5770 return forwardingResolveInfo; 5771 } 5772 5773 @Override 5774 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5775 Intent[] specifics, String[] specificTypes, Intent intent, 5776 String resolvedType, int flags, int userId) { 5777 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5778 specificTypes, intent, resolvedType, flags, userId)); 5779 } 5780 5781 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5782 Intent[] specifics, String[] specificTypes, Intent intent, 5783 String resolvedType, int flags, int userId) { 5784 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5785 flags = updateFlagsForResolve(flags, userId, intent); 5786 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5787 false /* requireFullPermission */, false /* checkShell */, 5788 "query intent activity options"); 5789 final String resultsAction = intent.getAction(); 5790 5791 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5792 | PackageManager.GET_RESOLVED_FILTER, userId); 5793 5794 if (DEBUG_INTENT_MATCHING) { 5795 Log.v(TAG, "Query " + intent + ": " + results); 5796 } 5797 5798 int specificsPos = 0; 5799 int N; 5800 5801 // todo: note that the algorithm used here is O(N^2). This 5802 // isn't a problem in our current environment, but if we start running 5803 // into situations where we have more than 5 or 10 matches then this 5804 // should probably be changed to something smarter... 5805 5806 // First we go through and resolve each of the specific items 5807 // that were supplied, taking care of removing any corresponding 5808 // duplicate items in the generic resolve list. 5809 if (specifics != null) { 5810 for (int i=0; i<specifics.length; i++) { 5811 final Intent sintent = specifics[i]; 5812 if (sintent == null) { 5813 continue; 5814 } 5815 5816 if (DEBUG_INTENT_MATCHING) { 5817 Log.v(TAG, "Specific #" + i + ": " + sintent); 5818 } 5819 5820 String action = sintent.getAction(); 5821 if (resultsAction != null && resultsAction.equals(action)) { 5822 // If this action was explicitly requested, then don't 5823 // remove things that have it. 5824 action = null; 5825 } 5826 5827 ResolveInfo ri = null; 5828 ActivityInfo ai = null; 5829 5830 ComponentName comp = sintent.getComponent(); 5831 if (comp == null) { 5832 ri = resolveIntent( 5833 sintent, 5834 specificTypes != null ? specificTypes[i] : null, 5835 flags, userId); 5836 if (ri == null) { 5837 continue; 5838 } 5839 if (ri == mResolveInfo) { 5840 // ACK! Must do something better with this. 5841 } 5842 ai = ri.activityInfo; 5843 comp = new ComponentName(ai.applicationInfo.packageName, 5844 ai.name); 5845 } else { 5846 ai = getActivityInfo(comp, flags, userId); 5847 if (ai == null) { 5848 continue; 5849 } 5850 } 5851 5852 // Look for any generic query activities that are duplicates 5853 // of this specific one, and remove them from the results. 5854 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5855 N = results.size(); 5856 int j; 5857 for (j=specificsPos; j<N; j++) { 5858 ResolveInfo sri = results.get(j); 5859 if ((sri.activityInfo.name.equals(comp.getClassName()) 5860 && sri.activityInfo.applicationInfo.packageName.equals( 5861 comp.getPackageName())) 5862 || (action != null && sri.filter.matchAction(action))) { 5863 results.remove(j); 5864 if (DEBUG_INTENT_MATCHING) Log.v( 5865 TAG, "Removing duplicate item from " + j 5866 + " due to specific " + specificsPos); 5867 if (ri == null) { 5868 ri = sri; 5869 } 5870 j--; 5871 N--; 5872 } 5873 } 5874 5875 // Add this specific item to its proper place. 5876 if (ri == null) { 5877 ri = new ResolveInfo(); 5878 ri.activityInfo = ai; 5879 } 5880 results.add(specificsPos, ri); 5881 ri.specificIndex = i; 5882 specificsPos++; 5883 } 5884 } 5885 5886 // Now we go through the remaining generic results and remove any 5887 // duplicate actions that are found here. 5888 N = results.size(); 5889 for (int i=specificsPos; i<N-1; i++) { 5890 final ResolveInfo rii = results.get(i); 5891 if (rii.filter == null) { 5892 continue; 5893 } 5894 5895 // Iterate over all of the actions of this result's intent 5896 // filter... typically this should be just one. 5897 final Iterator<String> it = rii.filter.actionsIterator(); 5898 if (it == null) { 5899 continue; 5900 } 5901 while (it.hasNext()) { 5902 final String action = it.next(); 5903 if (resultsAction != null && resultsAction.equals(action)) { 5904 // If this action was explicitly requested, then don't 5905 // remove things that have it. 5906 continue; 5907 } 5908 for (int j=i+1; j<N; j++) { 5909 final ResolveInfo rij = results.get(j); 5910 if (rij.filter != null && rij.filter.hasAction(action)) { 5911 results.remove(j); 5912 if (DEBUG_INTENT_MATCHING) Log.v( 5913 TAG, "Removing duplicate item from " + j 5914 + " due to action " + action + " at " + i); 5915 j--; 5916 N--; 5917 } 5918 } 5919 } 5920 5921 // If the caller didn't request filter information, drop it now 5922 // so we don't have to marshall/unmarshall it. 5923 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5924 rii.filter = null; 5925 } 5926 } 5927 5928 // Filter out the caller activity if so requested. 5929 if (caller != null) { 5930 N = results.size(); 5931 for (int i=0; i<N; i++) { 5932 ActivityInfo ainfo = results.get(i).activityInfo; 5933 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5934 && caller.getClassName().equals(ainfo.name)) { 5935 results.remove(i); 5936 break; 5937 } 5938 } 5939 } 5940 5941 // If the caller didn't request filter information, 5942 // drop them now so we don't have to 5943 // marshall/unmarshall it. 5944 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5945 N = results.size(); 5946 for (int i=0; i<N; i++) { 5947 results.get(i).filter = null; 5948 } 5949 } 5950 5951 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5952 return results; 5953 } 5954 5955 @Override 5956 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5957 String resolvedType, int flags, int userId) { 5958 return new ParceledListSlice<>( 5959 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5960 } 5961 5962 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5963 String resolvedType, int flags, int userId) { 5964 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5965 flags = updateFlagsForResolve(flags, userId, intent); 5966 ComponentName comp = intent.getComponent(); 5967 if (comp == null) { 5968 if (intent.getSelector() != null) { 5969 intent = intent.getSelector(); 5970 comp = intent.getComponent(); 5971 } 5972 } 5973 if (comp != null) { 5974 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5975 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5976 if (ai != null) { 5977 ResolveInfo ri = new ResolveInfo(); 5978 ri.activityInfo = ai; 5979 list.add(ri); 5980 } 5981 return list; 5982 } 5983 5984 // reader 5985 synchronized (mPackages) { 5986 String pkgName = intent.getPackage(); 5987 if (pkgName == null) { 5988 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5989 } 5990 final PackageParser.Package pkg = mPackages.get(pkgName); 5991 if (pkg != null) { 5992 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5993 userId); 5994 } 5995 return Collections.emptyList(); 5996 } 5997 } 5998 5999 @Override 6000 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6001 if (!sUserManager.exists(userId)) return null; 6002 flags = updateFlagsForResolve(flags, userId, intent); 6003 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6004 if (query != null) { 6005 if (query.size() >= 1) { 6006 // If there is more than one service with the same priority, 6007 // just arbitrarily pick the first one. 6008 return query.get(0); 6009 } 6010 } 6011 return null; 6012 } 6013 6014 @Override 6015 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6016 String resolvedType, int flags, int userId) { 6017 return new ParceledListSlice<>( 6018 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6019 } 6020 6021 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6022 String resolvedType, int flags, int userId) { 6023 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6024 flags = updateFlagsForResolve(flags, userId, intent); 6025 ComponentName comp = intent.getComponent(); 6026 if (comp == null) { 6027 if (intent.getSelector() != null) { 6028 intent = intent.getSelector(); 6029 comp = intent.getComponent(); 6030 } 6031 } 6032 if (comp != null) { 6033 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6034 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6035 if (si != null) { 6036 final ResolveInfo ri = new ResolveInfo(); 6037 ri.serviceInfo = si; 6038 list.add(ri); 6039 } 6040 return list; 6041 } 6042 6043 // reader 6044 synchronized (mPackages) { 6045 String pkgName = intent.getPackage(); 6046 if (pkgName == null) { 6047 return mServices.queryIntent(intent, resolvedType, flags, userId); 6048 } 6049 final PackageParser.Package pkg = mPackages.get(pkgName); 6050 if (pkg != null) { 6051 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6052 userId); 6053 } 6054 return Collections.emptyList(); 6055 } 6056 } 6057 6058 @Override 6059 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6060 String resolvedType, int flags, int userId) { 6061 return new ParceledListSlice<>( 6062 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6063 } 6064 6065 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6066 Intent intent, String resolvedType, int flags, int userId) { 6067 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6068 flags = updateFlagsForResolve(flags, userId, intent); 6069 ComponentName comp = intent.getComponent(); 6070 if (comp == null) { 6071 if (intent.getSelector() != null) { 6072 intent = intent.getSelector(); 6073 comp = intent.getComponent(); 6074 } 6075 } 6076 if (comp != null) { 6077 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6078 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6079 if (pi != null) { 6080 final ResolveInfo ri = new ResolveInfo(); 6081 ri.providerInfo = pi; 6082 list.add(ri); 6083 } 6084 return list; 6085 } 6086 6087 // reader 6088 synchronized (mPackages) { 6089 String pkgName = intent.getPackage(); 6090 if (pkgName == null) { 6091 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6092 } 6093 final PackageParser.Package pkg = mPackages.get(pkgName); 6094 if (pkg != null) { 6095 return mProviders.queryIntentForPackage( 6096 intent, resolvedType, flags, pkg.providers, userId); 6097 } 6098 return Collections.emptyList(); 6099 } 6100 } 6101 6102 @Override 6103 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6104 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6105 flags = updateFlagsForPackage(flags, userId, null); 6106 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6108 true /* requireFullPermission */, false /* checkShell */, 6109 "get installed packages"); 6110 6111 // writer 6112 synchronized (mPackages) { 6113 ArrayList<PackageInfo> list; 6114 if (listUninstalled) { 6115 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6116 for (PackageSetting ps : mSettings.mPackages.values()) { 6117 final PackageInfo pi; 6118 if (ps.pkg != null) { 6119 pi = generatePackageInfo(ps, flags, userId); 6120 } else { 6121 pi = generatePackageInfo(ps, flags, userId); 6122 } 6123 if (pi != null) { 6124 list.add(pi); 6125 } 6126 } 6127 } else { 6128 list = new ArrayList<PackageInfo>(mPackages.size()); 6129 for (PackageParser.Package p : mPackages.values()) { 6130 final PackageInfo pi = 6131 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6132 if (pi != null) { 6133 list.add(pi); 6134 } 6135 } 6136 } 6137 6138 return new ParceledListSlice<PackageInfo>(list); 6139 } 6140 } 6141 6142 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6143 String[] permissions, boolean[] tmp, int flags, int userId) { 6144 int numMatch = 0; 6145 final PermissionsState permissionsState = ps.getPermissionsState(); 6146 for (int i=0; i<permissions.length; i++) { 6147 final String permission = permissions[i]; 6148 if (permissionsState.hasPermission(permission, userId)) { 6149 tmp[i] = true; 6150 numMatch++; 6151 } else { 6152 tmp[i] = false; 6153 } 6154 } 6155 if (numMatch == 0) { 6156 return; 6157 } 6158 final PackageInfo pi; 6159 if (ps.pkg != null) { 6160 pi = generatePackageInfo(ps, flags, userId); 6161 } else { 6162 pi = generatePackageInfo(ps, flags, userId); 6163 } 6164 // The above might return null in cases of uninstalled apps or install-state 6165 // skew across users/profiles. 6166 if (pi != null) { 6167 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6168 if (numMatch == permissions.length) { 6169 pi.requestedPermissions = permissions; 6170 } else { 6171 pi.requestedPermissions = new String[numMatch]; 6172 numMatch = 0; 6173 for (int i=0; i<permissions.length; i++) { 6174 if (tmp[i]) { 6175 pi.requestedPermissions[numMatch] = permissions[i]; 6176 numMatch++; 6177 } 6178 } 6179 } 6180 } 6181 list.add(pi); 6182 } 6183 } 6184 6185 @Override 6186 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6187 String[] permissions, int flags, int userId) { 6188 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6189 flags = updateFlagsForPackage(flags, userId, permissions); 6190 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6191 6192 // writer 6193 synchronized (mPackages) { 6194 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6195 boolean[] tmpBools = new boolean[permissions.length]; 6196 if (listUninstalled) { 6197 for (PackageSetting ps : mSettings.mPackages.values()) { 6198 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6199 } 6200 } else { 6201 for (PackageParser.Package pkg : mPackages.values()) { 6202 PackageSetting ps = (PackageSetting)pkg.mExtras; 6203 if (ps != null) { 6204 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6205 userId); 6206 } 6207 } 6208 } 6209 6210 return new ParceledListSlice<PackageInfo>(list); 6211 } 6212 } 6213 6214 @Override 6215 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6216 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6217 flags = updateFlagsForApplication(flags, userId, null); 6218 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6219 6220 // writer 6221 synchronized (mPackages) { 6222 ArrayList<ApplicationInfo> list; 6223 if (listUninstalled) { 6224 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6225 for (PackageSetting ps : mSettings.mPackages.values()) { 6226 ApplicationInfo ai; 6227 if (ps.pkg != null) { 6228 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6229 ps.readUserState(userId), userId); 6230 } else { 6231 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6232 } 6233 if (ai != null) { 6234 list.add(ai); 6235 } 6236 } 6237 } else { 6238 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6239 for (PackageParser.Package p : mPackages.values()) { 6240 if (p.mExtras != null) { 6241 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6242 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6243 if (ai != null) { 6244 list.add(ai); 6245 } 6246 } 6247 } 6248 } 6249 6250 return new ParceledListSlice<ApplicationInfo>(list); 6251 } 6252 } 6253 6254 @Override 6255 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6256 if (isEphemeralDisabled()) { 6257 return null; 6258 } 6259 6260 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6261 "getEphemeralApplications"); 6262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6263 true /* requireFullPermission */, false /* checkShell */, 6264 "getEphemeralApplications"); 6265 synchronized (mPackages) { 6266 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6267 .getEphemeralApplicationsLPw(userId); 6268 if (ephemeralApps != null) { 6269 return new ParceledListSlice<>(ephemeralApps); 6270 } 6271 } 6272 return null; 6273 } 6274 6275 @Override 6276 public boolean isEphemeralApplication(String packageName, int userId) { 6277 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6278 true /* requireFullPermission */, false /* checkShell */, 6279 "isEphemeral"); 6280 if (isEphemeralDisabled()) { 6281 return false; 6282 } 6283 6284 if (!isCallerSameApp(packageName)) { 6285 return false; 6286 } 6287 synchronized (mPackages) { 6288 PackageParser.Package pkg = mPackages.get(packageName); 6289 if (pkg != null) { 6290 return pkg.applicationInfo.isEphemeralApp(); 6291 } 6292 } 6293 return false; 6294 } 6295 6296 @Override 6297 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6298 if (isEphemeralDisabled()) { 6299 return null; 6300 } 6301 6302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6303 true /* requireFullPermission */, false /* checkShell */, 6304 "getCookie"); 6305 if (!isCallerSameApp(packageName)) { 6306 return null; 6307 } 6308 synchronized (mPackages) { 6309 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6310 packageName, userId); 6311 } 6312 } 6313 6314 @Override 6315 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6316 if (isEphemeralDisabled()) { 6317 return true; 6318 } 6319 6320 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6321 true /* requireFullPermission */, true /* checkShell */, 6322 "setCookie"); 6323 if (!isCallerSameApp(packageName)) { 6324 return false; 6325 } 6326 synchronized (mPackages) { 6327 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6328 packageName, cookie, userId); 6329 } 6330 } 6331 6332 @Override 6333 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6334 if (isEphemeralDisabled()) { 6335 return null; 6336 } 6337 6338 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6339 "getEphemeralApplicationIcon"); 6340 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6341 true /* requireFullPermission */, false /* checkShell */, 6342 "getEphemeralApplicationIcon"); 6343 synchronized (mPackages) { 6344 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6345 packageName, userId); 6346 } 6347 } 6348 6349 private boolean isCallerSameApp(String packageName) { 6350 PackageParser.Package pkg = mPackages.get(packageName); 6351 return pkg != null 6352 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6353 } 6354 6355 @Override 6356 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6357 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6358 } 6359 6360 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6361 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6362 6363 // reader 6364 synchronized (mPackages) { 6365 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6366 final int userId = UserHandle.getCallingUserId(); 6367 while (i.hasNext()) { 6368 final PackageParser.Package p = i.next(); 6369 if (p.applicationInfo == null) continue; 6370 6371 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6372 && !p.applicationInfo.isDirectBootAware(); 6373 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6374 && p.applicationInfo.isDirectBootAware(); 6375 6376 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6377 && (!mSafeMode || isSystemApp(p)) 6378 && (matchesUnaware || matchesAware)) { 6379 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6380 if (ps != null) { 6381 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6382 ps.readUserState(userId), userId); 6383 if (ai != null) { 6384 finalList.add(ai); 6385 } 6386 } 6387 } 6388 } 6389 } 6390 6391 return finalList; 6392 } 6393 6394 @Override 6395 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6396 if (!sUserManager.exists(userId)) return null; 6397 flags = updateFlagsForComponent(flags, userId, name); 6398 // reader 6399 synchronized (mPackages) { 6400 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6401 PackageSetting ps = provider != null 6402 ? mSettings.mPackages.get(provider.owner.packageName) 6403 : null; 6404 return ps != null 6405 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6406 ? PackageParser.generateProviderInfo(provider, flags, 6407 ps.readUserState(userId), userId) 6408 : null; 6409 } 6410 } 6411 6412 /** 6413 * @deprecated 6414 */ 6415 @Deprecated 6416 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6417 // reader 6418 synchronized (mPackages) { 6419 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6420 .entrySet().iterator(); 6421 final int userId = UserHandle.getCallingUserId(); 6422 while (i.hasNext()) { 6423 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6424 PackageParser.Provider p = entry.getValue(); 6425 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6426 6427 if (ps != null && p.syncable 6428 && (!mSafeMode || (p.info.applicationInfo.flags 6429 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6430 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6431 ps.readUserState(userId), userId); 6432 if (info != null) { 6433 outNames.add(entry.getKey()); 6434 outInfo.add(info); 6435 } 6436 } 6437 } 6438 } 6439 } 6440 6441 @Override 6442 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6443 int uid, int flags) { 6444 final int userId = processName != null ? UserHandle.getUserId(uid) 6445 : UserHandle.getCallingUserId(); 6446 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6447 flags = updateFlagsForComponent(flags, userId, processName); 6448 6449 ArrayList<ProviderInfo> finalList = null; 6450 // reader 6451 synchronized (mPackages) { 6452 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6453 while (i.hasNext()) { 6454 final PackageParser.Provider p = i.next(); 6455 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6456 if (ps != null && p.info.authority != null 6457 && (processName == null 6458 || (p.info.processName.equals(processName) 6459 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6460 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6461 if (finalList == null) { 6462 finalList = new ArrayList<ProviderInfo>(3); 6463 } 6464 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6465 ps.readUserState(userId), userId); 6466 if (info != null) { 6467 finalList.add(info); 6468 } 6469 } 6470 } 6471 } 6472 6473 if (finalList != null) { 6474 Collections.sort(finalList, mProviderInitOrderSorter); 6475 return new ParceledListSlice<ProviderInfo>(finalList); 6476 } 6477 6478 return ParceledListSlice.emptyList(); 6479 } 6480 6481 @Override 6482 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6483 // reader 6484 synchronized (mPackages) { 6485 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6486 return PackageParser.generateInstrumentationInfo(i, flags); 6487 } 6488 } 6489 6490 @Override 6491 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6492 String targetPackage, int flags) { 6493 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6494 } 6495 6496 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6497 int flags) { 6498 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6499 6500 // reader 6501 synchronized (mPackages) { 6502 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6503 while (i.hasNext()) { 6504 final PackageParser.Instrumentation p = i.next(); 6505 if (targetPackage == null 6506 || targetPackage.equals(p.info.targetPackage)) { 6507 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6508 flags); 6509 if (ii != null) { 6510 finalList.add(ii); 6511 } 6512 } 6513 } 6514 } 6515 6516 return finalList; 6517 } 6518 6519 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6520 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6521 if (overlays == null) { 6522 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6523 return; 6524 } 6525 for (PackageParser.Package opkg : overlays.values()) { 6526 // Not much to do if idmap fails: we already logged the error 6527 // and we certainly don't want to abort installation of pkg simply 6528 // because an overlay didn't fit properly. For these reasons, 6529 // ignore the return value of createIdmapForPackagePairLI. 6530 createIdmapForPackagePairLI(pkg, opkg); 6531 } 6532 } 6533 6534 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6535 PackageParser.Package opkg) { 6536 if (!opkg.mTrustedOverlay) { 6537 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6538 opkg.baseCodePath + ": overlay not trusted"); 6539 return false; 6540 } 6541 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6542 if (overlaySet == null) { 6543 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6544 opkg.baseCodePath + " but target package has no known overlays"); 6545 return false; 6546 } 6547 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6548 // TODO: generate idmap for split APKs 6549 try { 6550 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6551 } catch (InstallerException e) { 6552 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6553 + opkg.baseCodePath); 6554 return false; 6555 } 6556 PackageParser.Package[] overlayArray = 6557 overlaySet.values().toArray(new PackageParser.Package[0]); 6558 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6559 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6560 return p1.mOverlayPriority - p2.mOverlayPriority; 6561 } 6562 }; 6563 Arrays.sort(overlayArray, cmp); 6564 6565 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6566 int i = 0; 6567 for (PackageParser.Package p : overlayArray) { 6568 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6569 } 6570 return true; 6571 } 6572 6573 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6575 try { 6576 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6577 } finally { 6578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6579 } 6580 } 6581 6582 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6583 final File[] files = dir.listFiles(); 6584 if (ArrayUtils.isEmpty(files)) { 6585 Log.d(TAG, "No files in app dir " + dir); 6586 return; 6587 } 6588 6589 if (DEBUG_PACKAGE_SCANNING) { 6590 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6591 + " flags=0x" + Integer.toHexString(parseFlags)); 6592 } 6593 6594 for (File file : files) { 6595 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6596 && !PackageInstallerService.isStageName(file.getName()); 6597 if (!isPackage) { 6598 // Ignore entries which are not packages 6599 continue; 6600 } 6601 try { 6602 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6603 scanFlags, currentTime, null); 6604 } catch (PackageManagerException e) { 6605 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6606 6607 // Delete invalid userdata apps 6608 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6609 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6610 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6611 removeCodePathLI(file); 6612 } 6613 } 6614 } 6615 } 6616 6617 private static File getSettingsProblemFile() { 6618 File dataDir = Environment.getDataDirectory(); 6619 File systemDir = new File(dataDir, "system"); 6620 File fname = new File(systemDir, "uiderrors.txt"); 6621 return fname; 6622 } 6623 6624 static void reportSettingsProblem(int priority, String msg) { 6625 logCriticalInfo(priority, msg); 6626 } 6627 6628 static void logCriticalInfo(int priority, String msg) { 6629 Slog.println(priority, TAG, msg); 6630 EventLogTags.writePmCriticalInfo(msg); 6631 try { 6632 File fname = getSettingsProblemFile(); 6633 FileOutputStream out = new FileOutputStream(fname, true); 6634 PrintWriter pw = new FastPrintWriter(out); 6635 SimpleDateFormat formatter = new SimpleDateFormat(); 6636 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6637 pw.println(dateString + ": " + msg); 6638 pw.close(); 6639 FileUtils.setPermissions( 6640 fname.toString(), 6641 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6642 -1, -1); 6643 } catch (java.io.IOException e) { 6644 } 6645 } 6646 6647 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6648 if (srcFile.isDirectory()) { 6649 final File baseFile = new File(pkg.baseCodePath); 6650 long maxModifiedTime = baseFile.lastModified(); 6651 if (pkg.splitCodePaths != null) { 6652 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6653 final File splitFile = new File(pkg.splitCodePaths[i]); 6654 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6655 } 6656 } 6657 return maxModifiedTime; 6658 } 6659 return srcFile.lastModified(); 6660 } 6661 6662 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6663 final int policyFlags) throws PackageManagerException { 6664 // When upgrading from pre-N MR1, verify the package time stamp using the package 6665 // directory and not the APK file. 6666 final long lastModifiedTime = mIsPreNMR1Upgrade 6667 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6668 if (ps != null 6669 && ps.codePath.equals(srcFile) 6670 && ps.timeStamp == lastModifiedTime 6671 && !isCompatSignatureUpdateNeeded(pkg) 6672 && !isRecoverSignatureUpdateNeeded(pkg)) { 6673 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6674 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6675 ArraySet<PublicKey> signingKs; 6676 synchronized (mPackages) { 6677 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6678 } 6679 if (ps.signatures.mSignatures != null 6680 && ps.signatures.mSignatures.length != 0 6681 && signingKs != null) { 6682 // Optimization: reuse the existing cached certificates 6683 // if the package appears to be unchanged. 6684 pkg.mSignatures = ps.signatures.mSignatures; 6685 pkg.mSigningKeys = signingKs; 6686 return; 6687 } 6688 6689 Slog.w(TAG, "PackageSetting for " + ps.name 6690 + " is missing signatures. Collecting certs again to recover them."); 6691 } else { 6692 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6693 } 6694 6695 try { 6696 PackageParser.collectCertificates(pkg, policyFlags); 6697 } catch (PackageParserException e) { 6698 throw PackageManagerException.from(e); 6699 } 6700 } 6701 6702 /** 6703 * Traces a package scan. 6704 * @see #scanPackageLI(File, int, int, long, UserHandle) 6705 */ 6706 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6707 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6708 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6709 try { 6710 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6711 } finally { 6712 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6713 } 6714 } 6715 6716 /** 6717 * Scans a package and returns the newly parsed package. 6718 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6719 */ 6720 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6721 long currentTime, UserHandle user) throws PackageManagerException { 6722 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6723 PackageParser pp = new PackageParser(); 6724 pp.setSeparateProcesses(mSeparateProcesses); 6725 pp.setOnlyCoreApps(mOnlyCore); 6726 pp.setDisplayMetrics(mMetrics); 6727 6728 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6729 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6730 } 6731 6732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6733 final PackageParser.Package pkg; 6734 try { 6735 pkg = pp.parsePackage(scanFile, parseFlags); 6736 } catch (PackageParserException e) { 6737 throw PackageManagerException.from(e); 6738 } finally { 6739 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6740 } 6741 6742 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6743 } 6744 6745 /** 6746 * Scans a package and returns the newly parsed package. 6747 * @throws PackageManagerException on a parse error. 6748 */ 6749 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6750 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6751 throws PackageManagerException { 6752 // If the package has children and this is the first dive in the function 6753 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6754 // packages (parent and children) would be successfully scanned before the 6755 // actual scan since scanning mutates internal state and we want to atomically 6756 // install the package and its children. 6757 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6758 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6759 scanFlags |= SCAN_CHECK_ONLY; 6760 } 6761 } else { 6762 scanFlags &= ~SCAN_CHECK_ONLY; 6763 } 6764 6765 // Scan the parent 6766 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6767 scanFlags, currentTime, user); 6768 6769 // Scan the children 6770 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6771 for (int i = 0; i < childCount; i++) { 6772 PackageParser.Package childPackage = pkg.childPackages.get(i); 6773 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6774 currentTime, user); 6775 } 6776 6777 6778 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6779 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6780 } 6781 6782 return scannedPkg; 6783 } 6784 6785 /** 6786 * Scans a package and returns the newly parsed package. 6787 * @throws PackageManagerException on a parse error. 6788 */ 6789 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6790 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6791 throws PackageManagerException { 6792 PackageSetting ps = null; 6793 PackageSetting updatedPkg; 6794 // reader 6795 synchronized (mPackages) { 6796 // Look to see if we already know about this package. 6797 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6798 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6799 // This package has been renamed to its original name. Let's 6800 // use that. 6801 ps = mSettings.peekPackageLPr(oldName); 6802 } 6803 // If there was no original package, see one for the real package name. 6804 if (ps == null) { 6805 ps = mSettings.peekPackageLPr(pkg.packageName); 6806 } 6807 // Check to see if this package could be hiding/updating a system 6808 // package. Must look for it either under the original or real 6809 // package name depending on our state. 6810 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6811 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6812 6813 // If this is a package we don't know about on the system partition, we 6814 // may need to remove disabled child packages on the system partition 6815 // or may need to not add child packages if the parent apk is updated 6816 // on the data partition and no longer defines this child package. 6817 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6818 // If this is a parent package for an updated system app and this system 6819 // app got an OTA update which no longer defines some of the child packages 6820 // we have to prune them from the disabled system packages. 6821 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6822 if (disabledPs != null) { 6823 final int scannedChildCount = (pkg.childPackages != null) 6824 ? pkg.childPackages.size() : 0; 6825 final int disabledChildCount = disabledPs.childPackageNames != null 6826 ? disabledPs.childPackageNames.size() : 0; 6827 for (int i = 0; i < disabledChildCount; i++) { 6828 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6829 boolean disabledPackageAvailable = false; 6830 for (int j = 0; j < scannedChildCount; j++) { 6831 PackageParser.Package childPkg = pkg.childPackages.get(j); 6832 if (childPkg.packageName.equals(disabledChildPackageName)) { 6833 disabledPackageAvailable = true; 6834 break; 6835 } 6836 } 6837 if (!disabledPackageAvailable) { 6838 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6839 } 6840 } 6841 } 6842 } 6843 } 6844 6845 boolean updatedPkgBetter = false; 6846 // First check if this is a system package that may involve an update 6847 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6848 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6849 // it needs to drop FLAG_PRIVILEGED. 6850 if (locationIsPrivileged(scanFile)) { 6851 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6852 } else { 6853 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6854 } 6855 6856 if (ps != null && !ps.codePath.equals(scanFile)) { 6857 // The path has changed from what was last scanned... check the 6858 // version of the new path against what we have stored to determine 6859 // what to do. 6860 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6861 if (pkg.mVersionCode <= ps.versionCode) { 6862 // The system package has been updated and the code path does not match 6863 // Ignore entry. Skip it. 6864 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6865 + " ignored: updated version " + ps.versionCode 6866 + " better than this " + pkg.mVersionCode); 6867 if (!updatedPkg.codePath.equals(scanFile)) { 6868 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6869 + ps.name + " changing from " + updatedPkg.codePathString 6870 + " to " + scanFile); 6871 updatedPkg.codePath = scanFile; 6872 updatedPkg.codePathString = scanFile.toString(); 6873 updatedPkg.resourcePath = scanFile; 6874 updatedPkg.resourcePathString = scanFile.toString(); 6875 } 6876 updatedPkg.pkg = pkg; 6877 updatedPkg.versionCode = pkg.mVersionCode; 6878 6879 // Update the disabled system child packages to point to the package too. 6880 final int childCount = updatedPkg.childPackageNames != null 6881 ? updatedPkg.childPackageNames.size() : 0; 6882 for (int i = 0; i < childCount; i++) { 6883 String childPackageName = updatedPkg.childPackageNames.get(i); 6884 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6885 childPackageName); 6886 if (updatedChildPkg != null) { 6887 updatedChildPkg.pkg = pkg; 6888 updatedChildPkg.versionCode = pkg.mVersionCode; 6889 } 6890 } 6891 6892 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6893 + scanFile + " ignored: updated version " + ps.versionCode 6894 + " better than this " + pkg.mVersionCode); 6895 } else { 6896 // The current app on the system partition is better than 6897 // what we have updated to on the data partition; switch 6898 // back to the system partition version. 6899 // At this point, its safely assumed that package installation for 6900 // apps in system partition will go through. If not there won't be a working 6901 // version of the app 6902 // writer 6903 synchronized (mPackages) { 6904 // Just remove the loaded entries from package lists. 6905 mPackages.remove(ps.name); 6906 } 6907 6908 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6909 + " reverting from " + ps.codePathString 6910 + ": new version " + pkg.mVersionCode 6911 + " better than installed " + ps.versionCode); 6912 6913 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6914 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6915 synchronized (mInstallLock) { 6916 args.cleanUpResourcesLI(); 6917 } 6918 synchronized (mPackages) { 6919 mSettings.enableSystemPackageLPw(ps.name); 6920 } 6921 updatedPkgBetter = true; 6922 } 6923 } 6924 } 6925 6926 if (updatedPkg != null) { 6927 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6928 // initially 6929 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6930 6931 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6932 // flag set initially 6933 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6934 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6935 } 6936 } 6937 6938 // Verify certificates against what was last scanned 6939 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6940 6941 /* 6942 * A new system app appeared, but we already had a non-system one of the 6943 * same name installed earlier. 6944 */ 6945 boolean shouldHideSystemApp = false; 6946 if (updatedPkg == null && ps != null 6947 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6948 /* 6949 * Check to make sure the signatures match first. If they don't, 6950 * wipe the installed application and its data. 6951 */ 6952 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6953 != PackageManager.SIGNATURE_MATCH) { 6954 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6955 + " signatures don't match existing userdata copy; removing"); 6956 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6957 "scanPackageInternalLI")) { 6958 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6959 } 6960 ps = null; 6961 } else { 6962 /* 6963 * If the newly-added system app is an older version than the 6964 * already installed version, hide it. It will be scanned later 6965 * and re-added like an update. 6966 */ 6967 if (pkg.mVersionCode <= ps.versionCode) { 6968 shouldHideSystemApp = true; 6969 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6970 + " but new version " + pkg.mVersionCode + " better than installed " 6971 + ps.versionCode + "; hiding system"); 6972 } else { 6973 /* 6974 * The newly found system app is a newer version that the 6975 * one previously installed. Simply remove the 6976 * already-installed application and replace it with our own 6977 * while keeping the application data. 6978 */ 6979 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6980 + " reverting from " + ps.codePathString + ": new version " 6981 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6982 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6983 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6984 synchronized (mInstallLock) { 6985 args.cleanUpResourcesLI(); 6986 } 6987 } 6988 } 6989 } 6990 6991 // The apk is forward locked (not public) if its code and resources 6992 // are kept in different files. (except for app in either system or 6993 // vendor path). 6994 // TODO grab this value from PackageSettings 6995 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6996 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6997 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6998 } 6999 } 7000 7001 // TODO: extend to support forward-locked splits 7002 String resourcePath = null; 7003 String baseResourcePath = null; 7004 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7005 if (ps != null && ps.resourcePathString != null) { 7006 resourcePath = ps.resourcePathString; 7007 baseResourcePath = ps.resourcePathString; 7008 } else { 7009 // Should not happen at all. Just log an error. 7010 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7011 } 7012 } else { 7013 resourcePath = pkg.codePath; 7014 baseResourcePath = pkg.baseCodePath; 7015 } 7016 7017 // Set application objects path explicitly. 7018 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7019 pkg.setApplicationInfoCodePath(pkg.codePath); 7020 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7021 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7022 pkg.setApplicationInfoResourcePath(resourcePath); 7023 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7024 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7025 7026 // Note that we invoke the following method only if we are about to unpack an application 7027 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7028 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7029 7030 /* 7031 * If the system app should be overridden by a previously installed 7032 * data, hide the system app now and let the /data/app scan pick it up 7033 * again. 7034 */ 7035 if (shouldHideSystemApp) { 7036 synchronized (mPackages) { 7037 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7038 } 7039 } 7040 7041 return scannedPkg; 7042 } 7043 7044 private static String fixProcessName(String defProcessName, 7045 String processName, int uid) { 7046 if (processName == null) { 7047 return defProcessName; 7048 } 7049 return processName; 7050 } 7051 7052 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7053 throws PackageManagerException { 7054 if (pkgSetting.signatures.mSignatures != null) { 7055 // Already existing package. Make sure signatures match 7056 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7057 == PackageManager.SIGNATURE_MATCH; 7058 if (!match) { 7059 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7060 == PackageManager.SIGNATURE_MATCH; 7061 } 7062 if (!match) { 7063 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7064 == PackageManager.SIGNATURE_MATCH; 7065 } 7066 if (!match) { 7067 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7068 + pkg.packageName + " signatures do not match the " 7069 + "previously installed version; ignoring!"); 7070 } 7071 } 7072 7073 // Check for shared user signatures 7074 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7075 // Already existing package. Make sure signatures match 7076 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7077 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7078 if (!match) { 7079 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7080 == PackageManager.SIGNATURE_MATCH; 7081 } 7082 if (!match) { 7083 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7084 == PackageManager.SIGNATURE_MATCH; 7085 } 7086 if (!match) { 7087 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7088 "Package " + pkg.packageName 7089 + " has no signatures that match those in shared user " 7090 + pkgSetting.sharedUser.name + "; ignoring!"); 7091 } 7092 } 7093 } 7094 7095 /** 7096 * Enforces that only the system UID or root's UID can call a method exposed 7097 * via Binder. 7098 * 7099 * @param message used as message if SecurityException is thrown 7100 * @throws SecurityException if the caller is not system or root 7101 */ 7102 private static final void enforceSystemOrRoot(String message) { 7103 final int uid = Binder.getCallingUid(); 7104 if (uid != Process.SYSTEM_UID && uid != 0) { 7105 throw new SecurityException(message); 7106 } 7107 } 7108 7109 @Override 7110 public void performFstrimIfNeeded() { 7111 enforceSystemOrRoot("Only the system can request fstrim"); 7112 7113 // Before everything else, see whether we need to fstrim. 7114 try { 7115 IMountService ms = PackageHelper.getMountService(); 7116 if (ms != null) { 7117 boolean doTrim = false; 7118 final long interval = android.provider.Settings.Global.getLong( 7119 mContext.getContentResolver(), 7120 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7121 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7122 if (interval > 0) { 7123 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7124 if (timeSinceLast > interval) { 7125 doTrim = true; 7126 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7127 + "; running immediately"); 7128 } 7129 } 7130 if (doTrim) { 7131 if (!isFirstBoot()) { 7132 try { 7133 ActivityManagerNative.getDefault().showBootMessage( 7134 mContext.getResources().getString( 7135 R.string.android_upgrading_fstrim), true); 7136 } catch (RemoteException e) { 7137 } 7138 } 7139 ms.runMaintenance(); 7140 } 7141 } else { 7142 Slog.e(TAG, "Mount service unavailable!"); 7143 } 7144 } catch (RemoteException e) { 7145 // Can't happen; MountService is local 7146 } 7147 } 7148 7149 @Override 7150 public void updatePackagesIfNeeded() { 7151 enforceSystemOrRoot("Only the system can request package update"); 7152 7153 // We need to re-extract after an OTA. 7154 boolean causeUpgrade = isUpgrade(); 7155 7156 // First boot or factory reset. 7157 // Note: we also handle devices that are upgrading to N right now as if it is their 7158 // first boot, as they do not have profile data. 7159 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7160 7161 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7162 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7163 7164 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7165 return; 7166 } 7167 7168 List<PackageParser.Package> pkgs; 7169 synchronized (mPackages) { 7170 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7171 } 7172 7173 final long startTime = System.nanoTime(); 7174 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7175 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7176 7177 final int elapsedTimeSeconds = 7178 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7179 7180 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7181 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7182 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7183 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7184 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7185 } 7186 7187 /** 7188 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7189 * containing statistics about the invocation. The array consists of three elements, 7190 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7191 * and {@code numberOfPackagesFailed}. 7192 */ 7193 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7194 String compilerFilter) { 7195 7196 int numberOfPackagesVisited = 0; 7197 int numberOfPackagesOptimized = 0; 7198 int numberOfPackagesSkipped = 0; 7199 int numberOfPackagesFailed = 0; 7200 final int numberOfPackagesToDexopt = pkgs.size(); 7201 7202 for (PackageParser.Package pkg : pkgs) { 7203 numberOfPackagesVisited++; 7204 7205 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7206 if (DEBUG_DEXOPT) { 7207 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7208 } 7209 numberOfPackagesSkipped++; 7210 continue; 7211 } 7212 7213 if (DEBUG_DEXOPT) { 7214 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7215 numberOfPackagesToDexopt + ": " + pkg.packageName); 7216 } 7217 7218 if (showDialog) { 7219 try { 7220 ActivityManagerNative.getDefault().showBootMessage( 7221 mContext.getResources().getString(R.string.android_upgrading_apk, 7222 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7223 } catch (RemoteException e) { 7224 } 7225 } 7226 7227 // If the OTA updates a system app which was previously preopted to a non-preopted state 7228 // the app might end up being verified at runtime. That's because by default the apps 7229 // are verify-profile but for preopted apps there's no profile. 7230 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7231 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7232 // filter (by default interpret-only). 7233 // Note that at this stage unused apps are already filtered. 7234 if (isSystemApp(pkg) && 7235 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7236 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7237 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7238 } 7239 7240 // checkProfiles is false to avoid merging profiles during boot which 7241 // might interfere with background compilation (b/28612421). 7242 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7243 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7244 // trade-off worth doing to save boot time work. 7245 int dexOptStatus = performDexOptTraced(pkg.packageName, 7246 false /* checkProfiles */, 7247 compilerFilter, 7248 false /* force */); 7249 switch (dexOptStatus) { 7250 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7251 numberOfPackagesOptimized++; 7252 break; 7253 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7254 numberOfPackagesSkipped++; 7255 break; 7256 case PackageDexOptimizer.DEX_OPT_FAILED: 7257 numberOfPackagesFailed++; 7258 break; 7259 default: 7260 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7261 break; 7262 } 7263 } 7264 7265 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7266 numberOfPackagesFailed }; 7267 } 7268 7269 @Override 7270 public void notifyPackageUse(String packageName, int reason) { 7271 synchronized (mPackages) { 7272 PackageParser.Package p = mPackages.get(packageName); 7273 if (p == null) { 7274 return; 7275 } 7276 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7277 } 7278 } 7279 7280 // TODO: this is not used nor needed. Delete it. 7281 @Override 7282 public boolean performDexOptIfNeeded(String packageName) { 7283 int dexOptStatus = performDexOptTraced(packageName, 7284 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7285 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7286 } 7287 7288 @Override 7289 public boolean performDexOpt(String packageName, 7290 boolean checkProfiles, int compileReason, boolean force) { 7291 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7292 getCompilerFilterForReason(compileReason), force); 7293 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7294 } 7295 7296 @Override 7297 public boolean performDexOptMode(String packageName, 7298 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7299 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7300 targetCompilerFilter, force); 7301 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7302 } 7303 7304 private int performDexOptTraced(String packageName, 7305 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7306 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7307 try { 7308 return performDexOptInternal(packageName, checkProfiles, 7309 targetCompilerFilter, force); 7310 } finally { 7311 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7312 } 7313 } 7314 7315 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7316 // if the package can now be considered up to date for the given filter. 7317 private int performDexOptInternal(String packageName, 7318 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7319 PackageParser.Package p; 7320 synchronized (mPackages) { 7321 p = mPackages.get(packageName); 7322 if (p == null) { 7323 // Package could not be found. Report failure. 7324 return PackageDexOptimizer.DEX_OPT_FAILED; 7325 } 7326 mPackageUsage.maybeWriteAsync(mPackages); 7327 mCompilerStats.maybeWriteAsync(); 7328 } 7329 long callingId = Binder.clearCallingIdentity(); 7330 try { 7331 synchronized (mInstallLock) { 7332 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7333 targetCompilerFilter, force); 7334 } 7335 } finally { 7336 Binder.restoreCallingIdentity(callingId); 7337 } 7338 } 7339 7340 public ArraySet<String> getOptimizablePackages() { 7341 ArraySet<String> pkgs = new ArraySet<String>(); 7342 synchronized (mPackages) { 7343 for (PackageParser.Package p : mPackages.values()) { 7344 if (PackageDexOptimizer.canOptimizePackage(p)) { 7345 pkgs.add(p.packageName); 7346 } 7347 } 7348 } 7349 return pkgs; 7350 } 7351 7352 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7353 boolean checkProfiles, String targetCompilerFilter, 7354 boolean force) { 7355 // Select the dex optimizer based on the force parameter. 7356 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7357 // allocate an object here. 7358 PackageDexOptimizer pdo = force 7359 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7360 : mPackageDexOptimizer; 7361 7362 // Optimize all dependencies first. Note: we ignore the return value and march on 7363 // on errors. 7364 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7365 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7366 if (!deps.isEmpty()) { 7367 for (PackageParser.Package depPackage : deps) { 7368 // TODO: Analyze and investigate if we (should) profile libraries. 7369 // Currently this will do a full compilation of the library by default. 7370 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7371 false /* checkProfiles */, 7372 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7373 getOrCreateCompilerPackageStats(depPackage)); 7374 } 7375 } 7376 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7377 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7378 } 7379 7380 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7381 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7382 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7383 Set<String> collectedNames = new HashSet<>(); 7384 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7385 7386 retValue.remove(p); 7387 7388 return retValue; 7389 } else { 7390 return Collections.emptyList(); 7391 } 7392 } 7393 7394 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7395 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7396 if (!collectedNames.contains(p.packageName)) { 7397 collectedNames.add(p.packageName); 7398 collected.add(p); 7399 7400 if (p.usesLibraries != null) { 7401 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7402 } 7403 if (p.usesOptionalLibraries != null) { 7404 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7405 collectedNames); 7406 } 7407 } 7408 } 7409 7410 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7411 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7412 for (String libName : libs) { 7413 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7414 if (libPkg != null) { 7415 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7416 } 7417 } 7418 } 7419 7420 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7421 synchronized (mPackages) { 7422 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7423 if (lib != null && lib.apk != null) { 7424 return mPackages.get(lib.apk); 7425 } 7426 } 7427 return null; 7428 } 7429 7430 public void shutdown() { 7431 mPackageUsage.writeNow(mPackages); 7432 mCompilerStats.writeNow(); 7433 } 7434 7435 @Override 7436 public void dumpProfiles(String packageName) { 7437 PackageParser.Package pkg; 7438 synchronized (mPackages) { 7439 pkg = mPackages.get(packageName); 7440 if (pkg == null) { 7441 throw new IllegalArgumentException("Unknown package: " + packageName); 7442 } 7443 } 7444 /* Only the shell, root, or the app user should be able to dump profiles. */ 7445 int callingUid = Binder.getCallingUid(); 7446 if (callingUid != Process.SHELL_UID && 7447 callingUid != Process.ROOT_UID && 7448 callingUid != pkg.applicationInfo.uid) { 7449 throw new SecurityException("dumpProfiles"); 7450 } 7451 7452 synchronized (mInstallLock) { 7453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7454 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7455 try { 7456 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7457 String gid = Integer.toString(sharedGid); 7458 String codePaths = TextUtils.join(";", allCodePaths); 7459 mInstaller.dumpProfiles(gid, packageName, codePaths); 7460 } catch (InstallerException e) { 7461 Slog.w(TAG, "Failed to dump profiles", e); 7462 } 7463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7464 } 7465 } 7466 7467 @Override 7468 public void forceDexOpt(String packageName) { 7469 enforceSystemOrRoot("forceDexOpt"); 7470 7471 PackageParser.Package pkg; 7472 synchronized (mPackages) { 7473 pkg = mPackages.get(packageName); 7474 if (pkg == null) { 7475 throw new IllegalArgumentException("Unknown package: " + packageName); 7476 } 7477 } 7478 7479 synchronized (mInstallLock) { 7480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7481 7482 // Whoever is calling forceDexOpt wants a fully compiled package. 7483 // Don't use profiles since that may cause compilation to be skipped. 7484 final int res = performDexOptInternalWithDependenciesLI(pkg, 7485 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7486 true /* force */); 7487 7488 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7489 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7490 throw new IllegalStateException("Failed to dexopt: " + res); 7491 } 7492 } 7493 } 7494 7495 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7496 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7497 Slog.w(TAG, "Unable to update from " + oldPkg.name 7498 + " to " + newPkg.packageName 7499 + ": old package not in system partition"); 7500 return false; 7501 } else if (mPackages.get(oldPkg.name) != null) { 7502 Slog.w(TAG, "Unable to update from " + oldPkg.name 7503 + " to " + newPkg.packageName 7504 + ": old package still exists"); 7505 return false; 7506 } 7507 return true; 7508 } 7509 7510 void removeCodePathLI(File codePath) { 7511 if (codePath.isDirectory()) { 7512 try { 7513 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7514 } catch (InstallerException e) { 7515 Slog.w(TAG, "Failed to remove code path", e); 7516 } 7517 } else { 7518 codePath.delete(); 7519 } 7520 } 7521 7522 private int[] resolveUserIds(int userId) { 7523 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7524 } 7525 7526 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7527 if (pkg == null) { 7528 Slog.wtf(TAG, "Package was null!", new Throwable()); 7529 return; 7530 } 7531 clearAppDataLeafLIF(pkg, userId, flags); 7532 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7533 for (int i = 0; i < childCount; i++) { 7534 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7535 } 7536 } 7537 7538 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7539 final PackageSetting ps; 7540 synchronized (mPackages) { 7541 ps = mSettings.mPackages.get(pkg.packageName); 7542 } 7543 for (int realUserId : resolveUserIds(userId)) { 7544 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7545 try { 7546 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7547 ceDataInode); 7548 } catch (InstallerException e) { 7549 Slog.w(TAG, String.valueOf(e)); 7550 } 7551 } 7552 } 7553 7554 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7555 if (pkg == null) { 7556 Slog.wtf(TAG, "Package was null!", new Throwable()); 7557 return; 7558 } 7559 destroyAppDataLeafLIF(pkg, userId, flags); 7560 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7561 for (int i = 0; i < childCount; i++) { 7562 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7563 } 7564 } 7565 7566 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7567 final PackageSetting ps; 7568 synchronized (mPackages) { 7569 ps = mSettings.mPackages.get(pkg.packageName); 7570 } 7571 for (int realUserId : resolveUserIds(userId)) { 7572 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7573 try { 7574 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7575 ceDataInode); 7576 } catch (InstallerException e) { 7577 Slog.w(TAG, String.valueOf(e)); 7578 } 7579 } 7580 } 7581 7582 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7583 if (pkg == null) { 7584 Slog.wtf(TAG, "Package was null!", new Throwable()); 7585 return; 7586 } 7587 destroyAppProfilesLeafLIF(pkg); 7588 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7589 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7590 for (int i = 0; i < childCount; i++) { 7591 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7592 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7593 true /* removeBaseMarker */); 7594 } 7595 } 7596 7597 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7598 boolean removeBaseMarker) { 7599 if (pkg.isForwardLocked()) { 7600 return; 7601 } 7602 7603 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7604 try { 7605 path = PackageManagerServiceUtils.realpath(new File(path)); 7606 } catch (IOException e) { 7607 // TODO: Should we return early here ? 7608 Slog.w(TAG, "Failed to get canonical path", e); 7609 continue; 7610 } 7611 7612 final String useMarker = path.replace('/', '@'); 7613 for (int realUserId : resolveUserIds(userId)) { 7614 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7615 if (removeBaseMarker) { 7616 File foreignUseMark = new File(profileDir, useMarker); 7617 if (foreignUseMark.exists()) { 7618 if (!foreignUseMark.delete()) { 7619 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7620 + pkg.packageName); 7621 } 7622 } 7623 } 7624 7625 File[] markers = profileDir.listFiles(); 7626 if (markers != null) { 7627 final String searchString = "@" + pkg.packageName + "@"; 7628 // We also delete all markers that contain the package name we're 7629 // uninstalling. These are associated with secondary dex-files belonging 7630 // to the package. Reconstructing the path of these dex files is messy 7631 // in general. 7632 for (File marker : markers) { 7633 if (marker.getName().indexOf(searchString) > 0) { 7634 if (!marker.delete()) { 7635 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7636 + pkg.packageName); 7637 } 7638 } 7639 } 7640 } 7641 } 7642 } 7643 } 7644 7645 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7646 try { 7647 mInstaller.destroyAppProfiles(pkg.packageName); 7648 } catch (InstallerException e) { 7649 Slog.w(TAG, String.valueOf(e)); 7650 } 7651 } 7652 7653 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7654 if (pkg == null) { 7655 Slog.wtf(TAG, "Package was null!", new Throwable()); 7656 return; 7657 } 7658 clearAppProfilesLeafLIF(pkg); 7659 // We don't remove the base foreign use marker when clearing profiles because 7660 // we will rename it when the app is updated. Unlike the actual profile contents, 7661 // the foreign use marker is good across installs. 7662 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7663 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7664 for (int i = 0; i < childCount; i++) { 7665 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7666 } 7667 } 7668 7669 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7670 try { 7671 mInstaller.clearAppProfiles(pkg.packageName); 7672 } catch (InstallerException e) { 7673 Slog.w(TAG, String.valueOf(e)); 7674 } 7675 } 7676 7677 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7678 long lastUpdateTime) { 7679 // Set parent install/update time 7680 PackageSetting ps = (PackageSetting) pkg.mExtras; 7681 if (ps != null) { 7682 ps.firstInstallTime = firstInstallTime; 7683 ps.lastUpdateTime = lastUpdateTime; 7684 } 7685 // Set children install/update time 7686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7687 for (int i = 0; i < childCount; i++) { 7688 PackageParser.Package childPkg = pkg.childPackages.get(i); 7689 ps = (PackageSetting) childPkg.mExtras; 7690 if (ps != null) { 7691 ps.firstInstallTime = firstInstallTime; 7692 ps.lastUpdateTime = lastUpdateTime; 7693 } 7694 } 7695 } 7696 7697 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7698 PackageParser.Package changingLib) { 7699 if (file.path != null) { 7700 usesLibraryFiles.add(file.path); 7701 return; 7702 } 7703 PackageParser.Package p = mPackages.get(file.apk); 7704 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7705 // If we are doing this while in the middle of updating a library apk, 7706 // then we need to make sure to use that new apk for determining the 7707 // dependencies here. (We haven't yet finished committing the new apk 7708 // to the package manager state.) 7709 if (p == null || p.packageName.equals(changingLib.packageName)) { 7710 p = changingLib; 7711 } 7712 } 7713 if (p != null) { 7714 usesLibraryFiles.addAll(p.getAllCodePaths()); 7715 } 7716 } 7717 7718 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7719 PackageParser.Package changingLib) throws PackageManagerException { 7720 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7721 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7722 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7723 for (int i=0; i<N; i++) { 7724 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7725 if (file == null) { 7726 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7727 "Package " + pkg.packageName + " requires unavailable shared library " 7728 + pkg.usesLibraries.get(i) + "; failing!"); 7729 } 7730 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7731 } 7732 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7733 for (int i=0; i<N; i++) { 7734 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7735 if (file == null) { 7736 Slog.w(TAG, "Package " + pkg.packageName 7737 + " desires unavailable shared library " 7738 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7739 } else { 7740 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7741 } 7742 } 7743 N = usesLibraryFiles.size(); 7744 if (N > 0) { 7745 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7746 } else { 7747 pkg.usesLibraryFiles = null; 7748 } 7749 } 7750 } 7751 7752 private static boolean hasString(List<String> list, List<String> which) { 7753 if (list == null) { 7754 return false; 7755 } 7756 for (int i=list.size()-1; i>=0; i--) { 7757 for (int j=which.size()-1; j>=0; j--) { 7758 if (which.get(j).equals(list.get(i))) { 7759 return true; 7760 } 7761 } 7762 } 7763 return false; 7764 } 7765 7766 private void updateAllSharedLibrariesLPw() { 7767 for (PackageParser.Package pkg : mPackages.values()) { 7768 try { 7769 updateSharedLibrariesLPw(pkg, null); 7770 } catch (PackageManagerException e) { 7771 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7772 } 7773 } 7774 } 7775 7776 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7777 PackageParser.Package changingPkg) { 7778 ArrayList<PackageParser.Package> res = null; 7779 for (PackageParser.Package pkg : mPackages.values()) { 7780 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7781 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7782 if (res == null) { 7783 res = new ArrayList<PackageParser.Package>(); 7784 } 7785 res.add(pkg); 7786 try { 7787 updateSharedLibrariesLPw(pkg, changingPkg); 7788 } catch (PackageManagerException e) { 7789 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7790 } 7791 } 7792 } 7793 return res; 7794 } 7795 7796 /** 7797 * Derive the value of the {@code cpuAbiOverride} based on the provided 7798 * value and an optional stored value from the package settings. 7799 */ 7800 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7801 String cpuAbiOverride = null; 7802 7803 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7804 cpuAbiOverride = null; 7805 } else if (abiOverride != null) { 7806 cpuAbiOverride = abiOverride; 7807 } else if (settings != null) { 7808 cpuAbiOverride = settings.cpuAbiOverrideString; 7809 } 7810 7811 return cpuAbiOverride; 7812 } 7813 7814 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7815 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7816 throws PackageManagerException { 7817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7818 // If the package has children and this is the first dive in the function 7819 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7820 // whether all packages (parent and children) would be successfully scanned 7821 // before the actual scan since scanning mutates internal state and we want 7822 // to atomically install the package and its children. 7823 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7824 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7825 scanFlags |= SCAN_CHECK_ONLY; 7826 } 7827 } else { 7828 scanFlags &= ~SCAN_CHECK_ONLY; 7829 } 7830 7831 final PackageParser.Package scannedPkg; 7832 try { 7833 // Scan the parent 7834 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7835 // Scan the children 7836 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7837 for (int i = 0; i < childCount; i++) { 7838 PackageParser.Package childPkg = pkg.childPackages.get(i); 7839 scanPackageLI(childPkg, policyFlags, 7840 scanFlags, currentTime, user); 7841 } 7842 } finally { 7843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7844 } 7845 7846 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7847 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7848 } 7849 7850 return scannedPkg; 7851 } 7852 7853 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7854 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7855 boolean success = false; 7856 try { 7857 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7858 currentTime, user); 7859 success = true; 7860 return res; 7861 } finally { 7862 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7863 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7864 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7865 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7866 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7867 } 7868 } 7869 } 7870 7871 /** 7872 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7873 */ 7874 private static boolean apkHasCode(String fileName) { 7875 StrictJarFile jarFile = null; 7876 try { 7877 jarFile = new StrictJarFile(fileName, 7878 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7879 return jarFile.findEntry("classes.dex") != null; 7880 } catch (IOException ignore) { 7881 } finally { 7882 try { 7883 if (jarFile != null) { 7884 jarFile.close(); 7885 } 7886 } catch (IOException ignore) {} 7887 } 7888 return false; 7889 } 7890 7891 /** 7892 * Enforces code policy for the package. This ensures that if an APK has 7893 * declared hasCode="true" in its manifest that the APK actually contains 7894 * code. 7895 * 7896 * @throws PackageManagerException If bytecode could not be found when it should exist 7897 */ 7898 private static void enforceCodePolicy(PackageParser.Package pkg) 7899 throws PackageManagerException { 7900 final boolean shouldHaveCode = 7901 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7902 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7903 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7904 "Package " + pkg.baseCodePath + " code is missing"); 7905 } 7906 7907 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7908 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7909 final boolean splitShouldHaveCode = 7910 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7911 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7912 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7913 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7914 } 7915 } 7916 } 7917 } 7918 7919 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7920 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7921 throws PackageManagerException { 7922 final File scanFile = new File(pkg.codePath); 7923 if (pkg.applicationInfo.getCodePath() == null || 7924 pkg.applicationInfo.getResourcePath() == null) { 7925 // Bail out. The resource and code paths haven't been set. 7926 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7927 "Code and resource paths haven't been set correctly"); 7928 } 7929 7930 // Apply policy 7931 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7932 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7933 if (pkg.applicationInfo.isDirectBootAware()) { 7934 // we're direct boot aware; set for all components 7935 for (PackageParser.Service s : pkg.services) { 7936 s.info.encryptionAware = s.info.directBootAware = true; 7937 } 7938 for (PackageParser.Provider p : pkg.providers) { 7939 p.info.encryptionAware = p.info.directBootAware = true; 7940 } 7941 for (PackageParser.Activity a : pkg.activities) { 7942 a.info.encryptionAware = a.info.directBootAware = true; 7943 } 7944 for (PackageParser.Activity r : pkg.receivers) { 7945 r.info.encryptionAware = r.info.directBootAware = true; 7946 } 7947 } 7948 } else { 7949 // Only allow system apps to be flagged as core apps. 7950 pkg.coreApp = false; 7951 // clear flags not applicable to regular apps 7952 pkg.applicationInfo.privateFlags &= 7953 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7954 pkg.applicationInfo.privateFlags &= 7955 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7956 } 7957 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7958 7959 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7960 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7961 } 7962 7963 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7964 enforceCodePolicy(pkg); 7965 } 7966 7967 if (mCustomResolverComponentName != null && 7968 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7969 setUpCustomResolverActivity(pkg); 7970 } 7971 7972 if (pkg.packageName.equals("android")) { 7973 synchronized (mPackages) { 7974 if (mAndroidApplication != null) { 7975 Slog.w(TAG, "*************************************************"); 7976 Slog.w(TAG, "Core android package being redefined. Skipping."); 7977 Slog.w(TAG, " file=" + scanFile); 7978 Slog.w(TAG, "*************************************************"); 7979 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7980 "Core android package being redefined. Skipping."); 7981 } 7982 7983 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7984 // Set up information for our fall-back user intent resolution activity. 7985 mPlatformPackage = pkg; 7986 pkg.mVersionCode = mSdkVersion; 7987 mAndroidApplication = pkg.applicationInfo; 7988 7989 if (!mResolverReplaced) { 7990 mResolveActivity.applicationInfo = mAndroidApplication; 7991 mResolveActivity.name = ResolverActivity.class.getName(); 7992 mResolveActivity.packageName = mAndroidApplication.packageName; 7993 mResolveActivity.processName = "system:ui"; 7994 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7995 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7996 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7997 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7998 mResolveActivity.exported = true; 7999 mResolveActivity.enabled = true; 8000 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8001 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8002 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8003 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8004 | ActivityInfo.CONFIG_ORIENTATION 8005 | ActivityInfo.CONFIG_KEYBOARD 8006 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8007 mResolveInfo.activityInfo = mResolveActivity; 8008 mResolveInfo.priority = 0; 8009 mResolveInfo.preferredOrder = 0; 8010 mResolveInfo.match = 0; 8011 mResolveComponentName = new ComponentName( 8012 mAndroidApplication.packageName, mResolveActivity.name); 8013 } 8014 } 8015 } 8016 } 8017 8018 if (DEBUG_PACKAGE_SCANNING) { 8019 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8020 Log.d(TAG, "Scanning package " + pkg.packageName); 8021 } 8022 8023 synchronized (mPackages) { 8024 if (mPackages.containsKey(pkg.packageName) 8025 || mSharedLibraries.containsKey(pkg.packageName)) { 8026 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8027 "Application package " + pkg.packageName 8028 + " already installed. Skipping duplicate."); 8029 } 8030 8031 // If we're only installing presumed-existing packages, require that the 8032 // scanned APK is both already known and at the path previously established 8033 // for it. Previously unknown packages we pick up normally, but if we have an 8034 // a priori expectation about this package's install presence, enforce it. 8035 // With a singular exception for new system packages. When an OTA contains 8036 // a new system package, we allow the codepath to change from a system location 8037 // to the user-installed location. If we don't allow this change, any newer, 8038 // user-installed version of the application will be ignored. 8039 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8040 if (mExpectingBetter.containsKey(pkg.packageName)) { 8041 logCriticalInfo(Log.WARN, 8042 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8043 } else { 8044 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8045 if (known != null) { 8046 if (DEBUG_PACKAGE_SCANNING) { 8047 Log.d(TAG, "Examining " + pkg.codePath 8048 + " and requiring known paths " + known.codePathString 8049 + " & " + known.resourcePathString); 8050 } 8051 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8052 || !pkg.applicationInfo.getResourcePath().equals( 8053 known.resourcePathString)) { 8054 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8055 "Application package " + pkg.packageName 8056 + " found at " + pkg.applicationInfo.getCodePath() 8057 + " but expected at " + known.codePathString 8058 + "; ignoring."); 8059 } 8060 } 8061 } 8062 } 8063 } 8064 8065 // Initialize package source and resource directories 8066 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8067 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8068 8069 SharedUserSetting suid = null; 8070 PackageSetting pkgSetting = null; 8071 8072 if (!isSystemApp(pkg)) { 8073 // Only system apps can use these features. 8074 pkg.mOriginalPackages = null; 8075 pkg.mRealPackage = null; 8076 pkg.mAdoptPermissions = null; 8077 } 8078 8079 // Getting the package setting may have a side-effect, so if we 8080 // are only checking if scan would succeed, stash a copy of the 8081 // old setting to restore at the end. 8082 PackageSetting nonMutatedPs = null; 8083 8084 // writer 8085 synchronized (mPackages) { 8086 if (pkg.mSharedUserId != null) { 8087 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8088 if (suid == null) { 8089 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8090 "Creating application package " + pkg.packageName 8091 + " for shared user failed"); 8092 } 8093 if (DEBUG_PACKAGE_SCANNING) { 8094 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8095 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8096 + "): packages=" + suid.packages); 8097 } 8098 } 8099 8100 // Check if we are renaming from an original package name. 8101 PackageSetting origPackage = null; 8102 String realName = null; 8103 if (pkg.mOriginalPackages != null) { 8104 // This package may need to be renamed to a previously 8105 // installed name. Let's check on that... 8106 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8107 if (pkg.mOriginalPackages.contains(renamed)) { 8108 // This package had originally been installed as the 8109 // original name, and we have already taken care of 8110 // transitioning to the new one. Just update the new 8111 // one to continue using the old name. 8112 realName = pkg.mRealPackage; 8113 if (!pkg.packageName.equals(renamed)) { 8114 // Callers into this function may have already taken 8115 // care of renaming the package; only do it here if 8116 // it is not already done. 8117 pkg.setPackageName(renamed); 8118 } 8119 8120 } else { 8121 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8122 if ((origPackage = mSettings.peekPackageLPr( 8123 pkg.mOriginalPackages.get(i))) != null) { 8124 // We do have the package already installed under its 8125 // original name... should we use it? 8126 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8127 // New package is not compatible with original. 8128 origPackage = null; 8129 continue; 8130 } else if (origPackage.sharedUser != null) { 8131 // Make sure uid is compatible between packages. 8132 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8133 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8134 + " to " + pkg.packageName + ": old uid " 8135 + origPackage.sharedUser.name 8136 + " differs from " + pkg.mSharedUserId); 8137 origPackage = null; 8138 continue; 8139 } 8140 // TODO: Add case when shared user id is added [b/28144775] 8141 } else { 8142 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8143 + pkg.packageName + " to old name " + origPackage.name); 8144 } 8145 break; 8146 } 8147 } 8148 } 8149 } 8150 8151 if (mTransferedPackages.contains(pkg.packageName)) { 8152 Slog.w(TAG, "Package " + pkg.packageName 8153 + " was transferred to another, but its .apk remains"); 8154 } 8155 8156 // See comments in nonMutatedPs declaration 8157 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8158 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8159 if (foundPs != null) { 8160 nonMutatedPs = new PackageSetting(foundPs); 8161 } 8162 } 8163 8164 // Just create the setting, don't add it yet. For already existing packages 8165 // the PkgSetting exists already and doesn't have to be created. 8166 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8167 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8168 pkg.applicationInfo.primaryCpuAbi, 8169 pkg.applicationInfo.secondaryCpuAbi, 8170 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8171 user, false); 8172 if (pkgSetting == null) { 8173 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8174 "Creating application package " + pkg.packageName + " failed"); 8175 } 8176 8177 if (pkgSetting.origPackage != null) { 8178 // If we are first transitioning from an original package, 8179 // fix up the new package's name now. We need to do this after 8180 // looking up the package under its new name, so getPackageLP 8181 // can take care of fiddling things correctly. 8182 pkg.setPackageName(origPackage.name); 8183 8184 // File a report about this. 8185 String msg = "New package " + pkgSetting.realName 8186 + " renamed to replace old package " + pkgSetting.name; 8187 reportSettingsProblem(Log.WARN, msg); 8188 8189 // Make a note of it. 8190 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8191 mTransferedPackages.add(origPackage.name); 8192 } 8193 8194 // No longer need to retain this. 8195 pkgSetting.origPackage = null; 8196 } 8197 8198 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8199 // Make a note of it. 8200 mTransferedPackages.add(pkg.packageName); 8201 } 8202 8203 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8204 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8205 } 8206 8207 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8208 // Check all shared libraries and map to their actual file path. 8209 // We only do this here for apps not on a system dir, because those 8210 // are the only ones that can fail an install due to this. We 8211 // will take care of the system apps by updating all of their 8212 // library paths after the scan is done. 8213 updateSharedLibrariesLPw(pkg, null); 8214 } 8215 8216 if (mFoundPolicyFile) { 8217 SELinuxMMAC.assignSeinfoValue(pkg); 8218 } 8219 8220 pkg.applicationInfo.uid = pkgSetting.appId; 8221 pkg.mExtras = pkgSetting; 8222 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8223 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8224 // We just determined the app is signed correctly, so bring 8225 // over the latest parsed certs. 8226 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8227 } else { 8228 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8229 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8230 "Package " + pkg.packageName + " upgrade keys do not match the " 8231 + "previously installed version"); 8232 } else { 8233 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8234 String msg = "System package " + pkg.packageName 8235 + " signature changed; retaining data."; 8236 reportSettingsProblem(Log.WARN, msg); 8237 } 8238 } 8239 } else { 8240 try { 8241 verifySignaturesLP(pkgSetting, pkg); 8242 // We just determined the app is signed correctly, so bring 8243 // over the latest parsed certs. 8244 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8245 } catch (PackageManagerException e) { 8246 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8247 throw e; 8248 } 8249 // The signature has changed, but this package is in the system 8250 // image... let's recover! 8251 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8252 // However... if this package is part of a shared user, but it 8253 // doesn't match the signature of the shared user, let's fail. 8254 // What this means is that you can't change the signatures 8255 // associated with an overall shared user, which doesn't seem all 8256 // that unreasonable. 8257 if (pkgSetting.sharedUser != null) { 8258 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8259 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8260 throw new PackageManagerException( 8261 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8262 "Signature mismatch for shared user: " 8263 + pkgSetting.sharedUser); 8264 } 8265 } 8266 // File a report about this. 8267 String msg = "System package " + pkg.packageName 8268 + " signature changed; retaining data."; 8269 reportSettingsProblem(Log.WARN, msg); 8270 } 8271 } 8272 // Verify that this new package doesn't have any content providers 8273 // that conflict with existing packages. Only do this if the 8274 // package isn't already installed, since we don't want to break 8275 // things that are installed. 8276 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8277 final int N = pkg.providers.size(); 8278 int i; 8279 for (i=0; i<N; i++) { 8280 PackageParser.Provider p = pkg.providers.get(i); 8281 if (p.info.authority != null) { 8282 String names[] = p.info.authority.split(";"); 8283 for (int j = 0; j < names.length; j++) { 8284 if (mProvidersByAuthority.containsKey(names[j])) { 8285 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8286 final String otherPackageName = 8287 ((other != null && other.getComponentName() != null) ? 8288 other.getComponentName().getPackageName() : "?"); 8289 throw new PackageManagerException( 8290 INSTALL_FAILED_CONFLICTING_PROVIDER, 8291 "Can't install because provider name " + names[j] 8292 + " (in package " + pkg.applicationInfo.packageName 8293 + ") is already used by " + otherPackageName); 8294 } 8295 } 8296 } 8297 } 8298 } 8299 8300 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8301 // This package wants to adopt ownership of permissions from 8302 // another package. 8303 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8304 final String origName = pkg.mAdoptPermissions.get(i); 8305 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8306 if (orig != null) { 8307 if (verifyPackageUpdateLPr(orig, pkg)) { 8308 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8309 + pkg.packageName); 8310 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8311 } 8312 } 8313 } 8314 } 8315 } 8316 8317 final String pkgName = pkg.packageName; 8318 8319 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8320 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8321 pkg.applicationInfo.processName = fixProcessName( 8322 pkg.applicationInfo.packageName, 8323 pkg.applicationInfo.processName, 8324 pkg.applicationInfo.uid); 8325 8326 if (pkg != mPlatformPackage) { 8327 // Get all of our default paths setup 8328 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8329 } 8330 8331 final String path = scanFile.getPath(); 8332 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8333 8334 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8335 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8336 8337 // Some system apps still use directory structure for native libraries 8338 // in which case we might end up not detecting abi solely based on apk 8339 // structure. Try to detect abi based on directory structure. 8340 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8341 pkg.applicationInfo.primaryCpuAbi == null) { 8342 setBundledAppAbisAndRoots(pkg, pkgSetting); 8343 setNativeLibraryPaths(pkg); 8344 } 8345 8346 } else { 8347 if ((scanFlags & SCAN_MOVE) != 0) { 8348 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8349 // but we already have this packages package info in the PackageSetting. We just 8350 // use that and derive the native library path based on the new codepath. 8351 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8352 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8353 } 8354 8355 // Set native library paths again. For moves, the path will be updated based on the 8356 // ABIs we've determined above. For non-moves, the path will be updated based on the 8357 // ABIs we determined during compilation, but the path will depend on the final 8358 // package path (after the rename away from the stage path). 8359 setNativeLibraryPaths(pkg); 8360 } 8361 8362 // This is a special case for the "system" package, where the ABI is 8363 // dictated by the zygote configuration (and init.rc). We should keep track 8364 // of this ABI so that we can deal with "normal" applications that run under 8365 // the same UID correctly. 8366 if (mPlatformPackage == pkg) { 8367 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8368 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8369 } 8370 8371 // If there's a mismatch between the abi-override in the package setting 8372 // and the abiOverride specified for the install. Warn about this because we 8373 // would've already compiled the app without taking the package setting into 8374 // account. 8375 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8376 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8377 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8378 " for package " + pkg.packageName); 8379 } 8380 } 8381 8382 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8383 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8384 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8385 8386 // Copy the derived override back to the parsed package, so that we can 8387 // update the package settings accordingly. 8388 pkg.cpuAbiOverride = cpuAbiOverride; 8389 8390 if (DEBUG_ABI_SELECTION) { 8391 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8392 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8393 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8394 } 8395 8396 // Push the derived path down into PackageSettings so we know what to 8397 // clean up at uninstall time. 8398 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8399 8400 if (DEBUG_ABI_SELECTION) { 8401 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8402 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8403 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8404 } 8405 8406 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8407 // We don't do this here during boot because we can do it all 8408 // at once after scanning all existing packages. 8409 // 8410 // We also do this *before* we perform dexopt on this package, so that 8411 // we can avoid redundant dexopts, and also to make sure we've got the 8412 // code and package path correct. 8413 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8414 pkg, true /* boot complete */); 8415 } 8416 8417 if (mFactoryTest && pkg.requestedPermissions.contains( 8418 android.Manifest.permission.FACTORY_TEST)) { 8419 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8420 } 8421 8422 if (isSystemApp(pkg)) { 8423 pkgSetting.isOrphaned = true; 8424 } 8425 8426 ArrayList<PackageParser.Package> clientLibPkgs = null; 8427 8428 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8429 if (nonMutatedPs != null) { 8430 synchronized (mPackages) { 8431 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8432 } 8433 } 8434 return pkg; 8435 } 8436 8437 // Only privileged apps and updated privileged apps can add child packages. 8438 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8439 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8440 throw new PackageManagerException("Only privileged apps and updated " 8441 + "privileged apps can add child packages. Ignoring package " 8442 + pkg.packageName); 8443 } 8444 final int childCount = pkg.childPackages.size(); 8445 for (int i = 0; i < childCount; i++) { 8446 PackageParser.Package childPkg = pkg.childPackages.get(i); 8447 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8448 childPkg.packageName)) { 8449 throw new PackageManagerException("Cannot override a child package of " 8450 + "another disabled system app. Ignoring package " + pkg.packageName); 8451 } 8452 } 8453 } 8454 8455 // writer 8456 synchronized (mPackages) { 8457 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8458 // Only system apps can add new shared libraries. 8459 if (pkg.libraryNames != null) { 8460 for (int i=0; i<pkg.libraryNames.size(); i++) { 8461 String name = pkg.libraryNames.get(i); 8462 boolean allowed = false; 8463 if (pkg.isUpdatedSystemApp()) { 8464 // New library entries can only be added through the 8465 // system image. This is important to get rid of a lot 8466 // of nasty edge cases: for example if we allowed a non- 8467 // system update of the app to add a library, then uninstalling 8468 // the update would make the library go away, and assumptions 8469 // we made such as through app install filtering would now 8470 // have allowed apps on the device which aren't compatible 8471 // with it. Better to just have the restriction here, be 8472 // conservative, and create many fewer cases that can negatively 8473 // impact the user experience. 8474 final PackageSetting sysPs = mSettings 8475 .getDisabledSystemPkgLPr(pkg.packageName); 8476 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8477 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8478 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8479 allowed = true; 8480 break; 8481 } 8482 } 8483 } 8484 } else { 8485 allowed = true; 8486 } 8487 if (allowed) { 8488 if (!mSharedLibraries.containsKey(name)) { 8489 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8490 } else if (!name.equals(pkg.packageName)) { 8491 Slog.w(TAG, "Package " + pkg.packageName + " library " 8492 + name + " already exists; skipping"); 8493 } 8494 } else { 8495 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8496 + name + " that is not declared on system image; skipping"); 8497 } 8498 } 8499 if ((scanFlags & SCAN_BOOTING) == 0) { 8500 // If we are not booting, we need to update any applications 8501 // that are clients of our shared library. If we are booting, 8502 // this will all be done once the scan is complete. 8503 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8504 } 8505 } 8506 } 8507 } 8508 8509 if ((scanFlags & SCAN_BOOTING) != 0) { 8510 // No apps can run during boot scan, so they don't need to be frozen 8511 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8512 // Caller asked to not kill app, so it's probably not frozen 8513 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8514 // Caller asked us to ignore frozen check for some reason; they 8515 // probably didn't know the package name 8516 } else { 8517 // We're doing major surgery on this package, so it better be frozen 8518 // right now to keep it from launching 8519 checkPackageFrozen(pkgName); 8520 } 8521 8522 // Also need to kill any apps that are dependent on the library. 8523 if (clientLibPkgs != null) { 8524 for (int i=0; i<clientLibPkgs.size(); i++) { 8525 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8526 killApplication(clientPkg.applicationInfo.packageName, 8527 clientPkg.applicationInfo.uid, "update lib"); 8528 } 8529 } 8530 8531 // Make sure we're not adding any bogus keyset info 8532 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8533 ksms.assertScannedPackageValid(pkg); 8534 8535 // writer 8536 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8537 8538 boolean createIdmapFailed = false; 8539 synchronized (mPackages) { 8540 // We don't expect installation to fail beyond this point 8541 8542 if (pkgSetting.pkg != null) { 8543 // Note that |user| might be null during the initial boot scan. If a codePath 8544 // for an app has changed during a boot scan, it's due to an app update that's 8545 // part of the system partition and marker changes must be applied to all users. 8546 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8547 (user != null) ? user : UserHandle.ALL); 8548 } 8549 8550 // Add the new setting to mSettings 8551 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8552 // Add the new setting to mPackages 8553 mPackages.put(pkg.applicationInfo.packageName, pkg); 8554 // Make sure we don't accidentally delete its data. 8555 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8556 while (iter.hasNext()) { 8557 PackageCleanItem item = iter.next(); 8558 if (pkgName.equals(item.packageName)) { 8559 iter.remove(); 8560 } 8561 } 8562 8563 // Take care of first install / last update times. 8564 if (currentTime != 0) { 8565 if (pkgSetting.firstInstallTime == 0) { 8566 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8567 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8568 pkgSetting.lastUpdateTime = currentTime; 8569 } 8570 } else if (pkgSetting.firstInstallTime == 0) { 8571 // We need *something*. Take time time stamp of the file. 8572 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8573 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8574 if (scanFileTime != pkgSetting.timeStamp) { 8575 // A package on the system image has changed; consider this 8576 // to be an update. 8577 pkgSetting.lastUpdateTime = scanFileTime; 8578 } 8579 } 8580 8581 // Add the package's KeySets to the global KeySetManagerService 8582 ksms.addScannedPackageLPw(pkg); 8583 8584 int N = pkg.providers.size(); 8585 StringBuilder r = null; 8586 int i; 8587 for (i=0; i<N; i++) { 8588 PackageParser.Provider p = pkg.providers.get(i); 8589 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8590 p.info.processName, pkg.applicationInfo.uid); 8591 mProviders.addProvider(p); 8592 p.syncable = p.info.isSyncable; 8593 if (p.info.authority != null) { 8594 String names[] = p.info.authority.split(";"); 8595 p.info.authority = null; 8596 for (int j = 0; j < names.length; j++) { 8597 if (j == 1 && p.syncable) { 8598 // We only want the first authority for a provider to possibly be 8599 // syncable, so if we already added this provider using a different 8600 // authority clear the syncable flag. We copy the provider before 8601 // changing it because the mProviders object contains a reference 8602 // to a provider that we don't want to change. 8603 // Only do this for the second authority since the resulting provider 8604 // object can be the same for all future authorities for this provider. 8605 p = new PackageParser.Provider(p); 8606 p.syncable = false; 8607 } 8608 if (!mProvidersByAuthority.containsKey(names[j])) { 8609 mProvidersByAuthority.put(names[j], p); 8610 if (p.info.authority == null) { 8611 p.info.authority = names[j]; 8612 } else { 8613 p.info.authority = p.info.authority + ";" + names[j]; 8614 } 8615 if (DEBUG_PACKAGE_SCANNING) { 8616 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8617 Log.d(TAG, "Registered content provider: " + names[j] 8618 + ", className = " + p.info.name + ", isSyncable = " 8619 + p.info.isSyncable); 8620 } 8621 } else { 8622 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8623 Slog.w(TAG, "Skipping provider name " + names[j] + 8624 " (in package " + pkg.applicationInfo.packageName + 8625 "): name already used by " 8626 + ((other != null && other.getComponentName() != null) 8627 ? other.getComponentName().getPackageName() : "?")); 8628 } 8629 } 8630 } 8631 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8632 if (r == null) { 8633 r = new StringBuilder(256); 8634 } else { 8635 r.append(' '); 8636 } 8637 r.append(p.info.name); 8638 } 8639 } 8640 if (r != null) { 8641 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8642 } 8643 8644 N = pkg.services.size(); 8645 r = null; 8646 for (i=0; i<N; i++) { 8647 PackageParser.Service s = pkg.services.get(i); 8648 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8649 s.info.processName, pkg.applicationInfo.uid); 8650 mServices.addService(s); 8651 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8652 if (r == null) { 8653 r = new StringBuilder(256); 8654 } else { 8655 r.append(' '); 8656 } 8657 r.append(s.info.name); 8658 } 8659 } 8660 if (r != null) { 8661 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8662 } 8663 8664 N = pkg.receivers.size(); 8665 r = null; 8666 for (i=0; i<N; i++) { 8667 PackageParser.Activity a = pkg.receivers.get(i); 8668 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8669 a.info.processName, pkg.applicationInfo.uid); 8670 mReceivers.addActivity(a, "receiver"); 8671 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8672 if (r == null) { 8673 r = new StringBuilder(256); 8674 } else { 8675 r.append(' '); 8676 } 8677 r.append(a.info.name); 8678 } 8679 } 8680 if (r != null) { 8681 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8682 } 8683 8684 N = pkg.activities.size(); 8685 r = null; 8686 for (i=0; i<N; i++) { 8687 PackageParser.Activity a = pkg.activities.get(i); 8688 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8689 a.info.processName, pkg.applicationInfo.uid); 8690 mActivities.addActivity(a, "activity"); 8691 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8692 if (r == null) { 8693 r = new StringBuilder(256); 8694 } else { 8695 r.append(' '); 8696 } 8697 r.append(a.info.name); 8698 } 8699 } 8700 if (r != null) { 8701 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8702 } 8703 8704 N = pkg.permissionGroups.size(); 8705 r = null; 8706 for (i=0; i<N; i++) { 8707 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8708 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8709 final String curPackageName = cur == null ? null : cur.info.packageName; 8710 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8711 if (cur == null || isPackageUpdate) { 8712 mPermissionGroups.put(pg.info.name, pg); 8713 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8714 if (r == null) { 8715 r = new StringBuilder(256); 8716 } else { 8717 r.append(' '); 8718 } 8719 if (isPackageUpdate) { 8720 r.append("UPD:"); 8721 } 8722 r.append(pg.info.name); 8723 } 8724 } else { 8725 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8726 + pg.info.packageName + " ignored: original from " 8727 + cur.info.packageName); 8728 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8729 if (r == null) { 8730 r = new StringBuilder(256); 8731 } else { 8732 r.append(' '); 8733 } 8734 r.append("DUP:"); 8735 r.append(pg.info.name); 8736 } 8737 } 8738 } 8739 if (r != null) { 8740 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8741 } 8742 8743 N = pkg.permissions.size(); 8744 r = null; 8745 for (i=0; i<N; i++) { 8746 PackageParser.Permission p = pkg.permissions.get(i); 8747 8748 // Assume by default that we did not install this permission into the system. 8749 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8750 8751 // Now that permission groups have a special meaning, we ignore permission 8752 // groups for legacy apps to prevent unexpected behavior. In particular, 8753 // permissions for one app being granted to someone just becase they happen 8754 // to be in a group defined by another app (before this had no implications). 8755 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8756 p.group = mPermissionGroups.get(p.info.group); 8757 // Warn for a permission in an unknown group. 8758 if (p.info.group != null && p.group == null) { 8759 Slog.w(TAG, "Permission " + p.info.name + " from package " 8760 + p.info.packageName + " in an unknown group " + p.info.group); 8761 } 8762 } 8763 8764 ArrayMap<String, BasePermission> permissionMap = 8765 p.tree ? mSettings.mPermissionTrees 8766 : mSettings.mPermissions; 8767 BasePermission bp = permissionMap.get(p.info.name); 8768 8769 // Allow system apps to redefine non-system permissions 8770 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8771 final boolean currentOwnerIsSystem = (bp.perm != null 8772 && isSystemApp(bp.perm.owner)); 8773 if (isSystemApp(p.owner)) { 8774 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8775 // It's a built-in permission and no owner, take ownership now 8776 bp.packageSetting = pkgSetting; 8777 bp.perm = p; 8778 bp.uid = pkg.applicationInfo.uid; 8779 bp.sourcePackage = p.info.packageName; 8780 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8781 } else if (!currentOwnerIsSystem) { 8782 String msg = "New decl " + p.owner + " of permission " 8783 + p.info.name + " is system; overriding " + bp.sourcePackage; 8784 reportSettingsProblem(Log.WARN, msg); 8785 bp = null; 8786 } 8787 } 8788 } 8789 8790 if (bp == null) { 8791 bp = new BasePermission(p.info.name, p.info.packageName, 8792 BasePermission.TYPE_NORMAL); 8793 permissionMap.put(p.info.name, bp); 8794 } 8795 8796 if (bp.perm == null) { 8797 if (bp.sourcePackage == null 8798 || bp.sourcePackage.equals(p.info.packageName)) { 8799 BasePermission tree = findPermissionTreeLP(p.info.name); 8800 if (tree == null 8801 || tree.sourcePackage.equals(p.info.packageName)) { 8802 bp.packageSetting = pkgSetting; 8803 bp.perm = p; 8804 bp.uid = pkg.applicationInfo.uid; 8805 bp.sourcePackage = p.info.packageName; 8806 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8807 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8808 if (r == null) { 8809 r = new StringBuilder(256); 8810 } else { 8811 r.append(' '); 8812 } 8813 r.append(p.info.name); 8814 } 8815 } else { 8816 Slog.w(TAG, "Permission " + p.info.name + " from package " 8817 + p.info.packageName + " ignored: base tree " 8818 + tree.name + " is from package " 8819 + tree.sourcePackage); 8820 } 8821 } else { 8822 Slog.w(TAG, "Permission " + p.info.name + " from package " 8823 + p.info.packageName + " ignored: original from " 8824 + bp.sourcePackage); 8825 } 8826 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8827 if (r == null) { 8828 r = new StringBuilder(256); 8829 } else { 8830 r.append(' '); 8831 } 8832 r.append("DUP:"); 8833 r.append(p.info.name); 8834 } 8835 if (bp.perm == p) { 8836 bp.protectionLevel = p.info.protectionLevel; 8837 } 8838 } 8839 8840 if (r != null) { 8841 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8842 } 8843 8844 N = pkg.instrumentation.size(); 8845 r = null; 8846 for (i=0; i<N; i++) { 8847 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8848 a.info.packageName = pkg.applicationInfo.packageName; 8849 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8850 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8851 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8852 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8853 a.info.dataDir = pkg.applicationInfo.dataDir; 8854 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8855 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8856 8857 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8858 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8859 mInstrumentation.put(a.getComponentName(), a); 8860 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8861 if (r == null) { 8862 r = new StringBuilder(256); 8863 } else { 8864 r.append(' '); 8865 } 8866 r.append(a.info.name); 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8871 } 8872 8873 if (pkg.protectedBroadcasts != null) { 8874 N = pkg.protectedBroadcasts.size(); 8875 for (i=0; i<N; i++) { 8876 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8877 } 8878 } 8879 8880 pkgSetting.setTimeStamp(scanFileTime); 8881 8882 // Create idmap files for pairs of (packages, overlay packages). 8883 // Note: "android", ie framework-res.apk, is handled by native layers. 8884 if (pkg.mOverlayTarget != null) { 8885 // This is an overlay package. 8886 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8887 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8888 mOverlays.put(pkg.mOverlayTarget, 8889 new ArrayMap<String, PackageParser.Package>()); 8890 } 8891 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8892 map.put(pkg.packageName, pkg); 8893 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8894 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8895 createIdmapFailed = true; 8896 } 8897 } 8898 } else if (mOverlays.containsKey(pkg.packageName) && 8899 !pkg.packageName.equals("android")) { 8900 // This is a regular package, with one or more known overlay packages. 8901 createIdmapsForPackageLI(pkg); 8902 } 8903 } 8904 8905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8906 8907 if (createIdmapFailed) { 8908 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8909 "scanPackageLI failed to createIdmap"); 8910 } 8911 return pkg; 8912 } 8913 8914 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8915 PackageParser.Package update, UserHandle user) { 8916 if (existing.applicationInfo == null || update.applicationInfo == null) { 8917 // This isn't due to an app installation. 8918 return; 8919 } 8920 8921 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8922 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8923 8924 // The codePath hasn't changed, so there's nothing for us to do. 8925 if (Objects.equals(oldCodePath, newCodePath)) { 8926 return; 8927 } 8928 8929 File canonicalNewCodePath; 8930 try { 8931 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8932 } catch (IOException e) { 8933 Slog.w(TAG, "Failed to get canonical path.", e); 8934 return; 8935 } 8936 8937 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8938 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8939 // that the last component of the path (i.e, the name) doesn't need canonicalization 8940 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8941 // but may change in the future. Hopefully this function won't exist at that point. 8942 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8943 oldCodePath.getName()); 8944 8945 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8946 // with "@". 8947 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8948 if (!oldMarkerPrefix.endsWith("@")) { 8949 oldMarkerPrefix += "@"; 8950 } 8951 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8952 if (!newMarkerPrefix.endsWith("@")) { 8953 newMarkerPrefix += "@"; 8954 } 8955 8956 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8957 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8958 for (String updatedPath : updatedPaths) { 8959 String updatedPathName = new File(updatedPath).getName(); 8960 markerSuffixes.add(updatedPathName.replace('/', '@')); 8961 } 8962 8963 for (int userId : resolveUserIds(user.getIdentifier())) { 8964 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8965 8966 for (String markerSuffix : markerSuffixes) { 8967 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 8968 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 8969 if (oldForeignUseMark.exists()) { 8970 try { 8971 Os.rename(oldForeignUseMark.getAbsolutePath(), 8972 newForeignUseMark.getAbsolutePath()); 8973 } catch (ErrnoException e) { 8974 Slog.w(TAG, "Failed to rename foreign use marker", e); 8975 oldForeignUseMark.delete(); 8976 } 8977 } 8978 } 8979 } 8980 } 8981 8982 /** 8983 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8984 * is derived purely on the basis of the contents of {@code scanFile} and 8985 * {@code cpuAbiOverride}. 8986 * 8987 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8988 */ 8989 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8990 String cpuAbiOverride, boolean extractLibs) 8991 throws PackageManagerException { 8992 // TODO: We can probably be smarter about this stuff. For installed apps, 8993 // we can calculate this information at install time once and for all. For 8994 // system apps, we can probably assume that this information doesn't change 8995 // after the first boot scan. As things stand, we do lots of unnecessary work. 8996 8997 // Give ourselves some initial paths; we'll come back for another 8998 // pass once we've determined ABI below. 8999 setNativeLibraryPaths(pkg); 9000 9001 // We would never need to extract libs for forward-locked and external packages, 9002 // since the container service will do it for us. We shouldn't attempt to 9003 // extract libs from system app when it was not updated. 9004 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9005 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9006 extractLibs = false; 9007 } 9008 9009 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9010 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9011 9012 NativeLibraryHelper.Handle handle = null; 9013 try { 9014 handle = NativeLibraryHelper.Handle.create(pkg); 9015 // TODO(multiArch): This can be null for apps that didn't go through the 9016 // usual installation process. We can calculate it again, like we 9017 // do during install time. 9018 // 9019 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9020 // unnecessary. 9021 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9022 9023 // Null out the abis so that they can be recalculated. 9024 pkg.applicationInfo.primaryCpuAbi = null; 9025 pkg.applicationInfo.secondaryCpuAbi = null; 9026 if (isMultiArch(pkg.applicationInfo)) { 9027 // Warn if we've set an abiOverride for multi-lib packages.. 9028 // By definition, we need to copy both 32 and 64 bit libraries for 9029 // such packages. 9030 if (pkg.cpuAbiOverride != null 9031 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9032 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9033 } 9034 9035 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9036 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9037 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9038 if (extractLibs) { 9039 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9040 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9041 useIsaSpecificSubdirs); 9042 } else { 9043 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9044 } 9045 } 9046 9047 maybeThrowExceptionForMultiArchCopy( 9048 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9049 9050 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9051 if (extractLibs) { 9052 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9053 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9054 useIsaSpecificSubdirs); 9055 } else { 9056 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9057 } 9058 } 9059 9060 maybeThrowExceptionForMultiArchCopy( 9061 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9062 9063 if (abi64 >= 0) { 9064 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9065 } 9066 9067 if (abi32 >= 0) { 9068 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9069 if (abi64 >= 0) { 9070 if (pkg.use32bitAbi) { 9071 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9072 pkg.applicationInfo.primaryCpuAbi = abi; 9073 } else { 9074 pkg.applicationInfo.secondaryCpuAbi = abi; 9075 } 9076 } else { 9077 pkg.applicationInfo.primaryCpuAbi = abi; 9078 } 9079 } 9080 9081 } else { 9082 String[] abiList = (cpuAbiOverride != null) ? 9083 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9084 9085 // Enable gross and lame hacks for apps that are built with old 9086 // SDK tools. We must scan their APKs for renderscript bitcode and 9087 // not launch them if it's present. Don't bother checking on devices 9088 // that don't have 64 bit support. 9089 boolean needsRenderScriptOverride = false; 9090 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9091 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9092 abiList = Build.SUPPORTED_32_BIT_ABIS; 9093 needsRenderScriptOverride = true; 9094 } 9095 9096 final int copyRet; 9097 if (extractLibs) { 9098 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9099 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9100 } else { 9101 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9102 } 9103 9104 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9105 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9106 "Error unpackaging native libs for app, errorCode=" + copyRet); 9107 } 9108 9109 if (copyRet >= 0) { 9110 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9111 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9112 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9113 } else if (needsRenderScriptOverride) { 9114 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9115 } 9116 } 9117 } catch (IOException ioe) { 9118 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9119 } finally { 9120 IoUtils.closeQuietly(handle); 9121 } 9122 9123 // Now that we've calculated the ABIs and determined if it's an internal app, 9124 // we will go ahead and populate the nativeLibraryPath. 9125 setNativeLibraryPaths(pkg); 9126 } 9127 9128 /** 9129 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9130 * i.e, so that all packages can be run inside a single process if required. 9131 * 9132 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9133 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9134 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9135 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9136 * updating a package that belongs to a shared user. 9137 * 9138 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9139 * adds unnecessary complexity. 9140 */ 9141 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9142 PackageParser.Package scannedPackage, boolean bootComplete) { 9143 String requiredInstructionSet = null; 9144 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9145 requiredInstructionSet = VMRuntime.getInstructionSet( 9146 scannedPackage.applicationInfo.primaryCpuAbi); 9147 } 9148 9149 PackageSetting requirer = null; 9150 for (PackageSetting ps : packagesForUser) { 9151 // If packagesForUser contains scannedPackage, we skip it. This will happen 9152 // when scannedPackage is an update of an existing package. Without this check, 9153 // we will never be able to change the ABI of any package belonging to a shared 9154 // user, even if it's compatible with other packages. 9155 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9156 if (ps.primaryCpuAbiString == null) { 9157 continue; 9158 } 9159 9160 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9161 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9162 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9163 // this but there's not much we can do. 9164 String errorMessage = "Instruction set mismatch, " 9165 + ((requirer == null) ? "[caller]" : requirer) 9166 + " requires " + requiredInstructionSet + " whereas " + ps 9167 + " requires " + instructionSet; 9168 Slog.w(TAG, errorMessage); 9169 } 9170 9171 if (requiredInstructionSet == null) { 9172 requiredInstructionSet = instructionSet; 9173 requirer = ps; 9174 } 9175 } 9176 } 9177 9178 if (requiredInstructionSet != null) { 9179 String adjustedAbi; 9180 if (requirer != null) { 9181 // requirer != null implies that either scannedPackage was null or that scannedPackage 9182 // did not require an ABI, in which case we have to adjust scannedPackage to match 9183 // the ABI of the set (which is the same as requirer's ABI) 9184 adjustedAbi = requirer.primaryCpuAbiString; 9185 if (scannedPackage != null) { 9186 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9187 } 9188 } else { 9189 // requirer == null implies that we're updating all ABIs in the set to 9190 // match scannedPackage. 9191 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9192 } 9193 9194 for (PackageSetting ps : packagesForUser) { 9195 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9196 if (ps.primaryCpuAbiString != null) { 9197 continue; 9198 } 9199 9200 ps.primaryCpuAbiString = adjustedAbi; 9201 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9202 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9203 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9204 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9205 + " (requirer=" 9206 + (requirer == null ? "null" : requirer.pkg.packageName) 9207 + ", scannedPackage=" 9208 + (scannedPackage != null ? scannedPackage.packageName : "null") 9209 + ")"); 9210 try { 9211 mInstaller.rmdex(ps.codePathString, 9212 getDexCodeInstructionSet(getPreferredInstructionSet())); 9213 } catch (InstallerException ignored) { 9214 } 9215 } 9216 } 9217 } 9218 } 9219 } 9220 9221 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9222 synchronized (mPackages) { 9223 mResolverReplaced = true; 9224 // Set up information for custom user intent resolution activity. 9225 mResolveActivity.applicationInfo = pkg.applicationInfo; 9226 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9227 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9228 mResolveActivity.processName = pkg.applicationInfo.packageName; 9229 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9230 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9231 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9232 mResolveActivity.theme = 0; 9233 mResolveActivity.exported = true; 9234 mResolveActivity.enabled = true; 9235 mResolveInfo.activityInfo = mResolveActivity; 9236 mResolveInfo.priority = 0; 9237 mResolveInfo.preferredOrder = 0; 9238 mResolveInfo.match = 0; 9239 mResolveComponentName = mCustomResolverComponentName; 9240 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9241 mResolveComponentName); 9242 } 9243 } 9244 9245 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9246 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9247 9248 // Set up information for ephemeral installer activity 9249 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9250 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9251 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9252 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9253 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9254 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9255 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9256 mEphemeralInstallerActivity.theme = 0; 9257 mEphemeralInstallerActivity.exported = true; 9258 mEphemeralInstallerActivity.enabled = true; 9259 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9260 mEphemeralInstallerInfo.priority = 0; 9261 mEphemeralInstallerInfo.preferredOrder = 1; 9262 mEphemeralInstallerInfo.isDefault = true; 9263 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9264 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9265 9266 if (DEBUG_EPHEMERAL) { 9267 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9268 } 9269 } 9270 9271 private static String calculateBundledApkRoot(final String codePathString) { 9272 final File codePath = new File(codePathString); 9273 final File codeRoot; 9274 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9275 codeRoot = Environment.getRootDirectory(); 9276 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9277 codeRoot = Environment.getOemDirectory(); 9278 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9279 codeRoot = Environment.getVendorDirectory(); 9280 } else { 9281 // Unrecognized code path; take its top real segment as the apk root: 9282 // e.g. /something/app/blah.apk => /something 9283 try { 9284 File f = codePath.getCanonicalFile(); 9285 File parent = f.getParentFile(); // non-null because codePath is a file 9286 File tmp; 9287 while ((tmp = parent.getParentFile()) != null) { 9288 f = parent; 9289 parent = tmp; 9290 } 9291 codeRoot = f; 9292 Slog.w(TAG, "Unrecognized code path " 9293 + codePath + " - using " + codeRoot); 9294 } catch (IOException e) { 9295 // Can't canonicalize the code path -- shenanigans? 9296 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9297 return Environment.getRootDirectory().getPath(); 9298 } 9299 } 9300 return codeRoot.getPath(); 9301 } 9302 9303 /** 9304 * Derive and set the location of native libraries for the given package, 9305 * which varies depending on where and how the package was installed. 9306 */ 9307 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9308 final ApplicationInfo info = pkg.applicationInfo; 9309 final String codePath = pkg.codePath; 9310 final File codeFile = new File(codePath); 9311 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9312 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9313 9314 info.nativeLibraryRootDir = null; 9315 info.nativeLibraryRootRequiresIsa = false; 9316 info.nativeLibraryDir = null; 9317 info.secondaryNativeLibraryDir = null; 9318 9319 if (isApkFile(codeFile)) { 9320 // Monolithic install 9321 if (bundledApp) { 9322 // If "/system/lib64/apkname" exists, assume that is the per-package 9323 // native library directory to use; otherwise use "/system/lib/apkname". 9324 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9325 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9326 getPrimaryInstructionSet(info)); 9327 9328 // This is a bundled system app so choose the path based on the ABI. 9329 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9330 // is just the default path. 9331 final String apkName = deriveCodePathName(codePath); 9332 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9333 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9334 apkName).getAbsolutePath(); 9335 9336 if (info.secondaryCpuAbi != null) { 9337 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9338 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9339 secondaryLibDir, apkName).getAbsolutePath(); 9340 } 9341 } else if (asecApp) { 9342 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9343 .getAbsolutePath(); 9344 } else { 9345 final String apkName = deriveCodePathName(codePath); 9346 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9347 .getAbsolutePath(); 9348 } 9349 9350 info.nativeLibraryRootRequiresIsa = false; 9351 info.nativeLibraryDir = info.nativeLibraryRootDir; 9352 } else { 9353 // Cluster install 9354 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9355 info.nativeLibraryRootRequiresIsa = true; 9356 9357 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9358 getPrimaryInstructionSet(info)).getAbsolutePath(); 9359 9360 if (info.secondaryCpuAbi != null) { 9361 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9362 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9363 } 9364 } 9365 } 9366 9367 /** 9368 * Calculate the abis and roots for a bundled app. These can uniquely 9369 * be determined from the contents of the system partition, i.e whether 9370 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9371 * of this information, and instead assume that the system was built 9372 * sensibly. 9373 */ 9374 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9375 PackageSetting pkgSetting) { 9376 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9377 9378 // If "/system/lib64/apkname" exists, assume that is the per-package 9379 // native library directory to use; otherwise use "/system/lib/apkname". 9380 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9381 setBundledAppAbi(pkg, apkRoot, apkName); 9382 // pkgSetting might be null during rescan following uninstall of updates 9383 // to a bundled app, so accommodate that possibility. The settings in 9384 // that case will be established later from the parsed package. 9385 // 9386 // If the settings aren't null, sync them up with what we've just derived. 9387 // note that apkRoot isn't stored in the package settings. 9388 if (pkgSetting != null) { 9389 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9390 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9391 } 9392 } 9393 9394 /** 9395 * Deduces the ABI of a bundled app and sets the relevant fields on the 9396 * parsed pkg object. 9397 * 9398 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9399 * under which system libraries are installed. 9400 * @param apkName the name of the installed package. 9401 */ 9402 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9403 final File codeFile = new File(pkg.codePath); 9404 9405 final boolean has64BitLibs; 9406 final boolean has32BitLibs; 9407 if (isApkFile(codeFile)) { 9408 // Monolithic install 9409 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9410 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9411 } else { 9412 // Cluster install 9413 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9414 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9415 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9416 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9417 has64BitLibs = (new File(rootDir, isa)).exists(); 9418 } else { 9419 has64BitLibs = false; 9420 } 9421 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9422 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9423 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9424 has32BitLibs = (new File(rootDir, isa)).exists(); 9425 } else { 9426 has32BitLibs = false; 9427 } 9428 } 9429 9430 if (has64BitLibs && !has32BitLibs) { 9431 // The package has 64 bit libs, but not 32 bit libs. Its primary 9432 // ABI should be 64 bit. We can safely assume here that the bundled 9433 // native libraries correspond to the most preferred ABI in the list. 9434 9435 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9436 pkg.applicationInfo.secondaryCpuAbi = null; 9437 } else if (has32BitLibs && !has64BitLibs) { 9438 // The package has 32 bit libs but not 64 bit libs. Its primary 9439 // ABI should be 32 bit. 9440 9441 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9442 pkg.applicationInfo.secondaryCpuAbi = null; 9443 } else if (has32BitLibs && has64BitLibs) { 9444 // The application has both 64 and 32 bit bundled libraries. We check 9445 // here that the app declares multiArch support, and warn if it doesn't. 9446 // 9447 // We will be lenient here and record both ABIs. The primary will be the 9448 // ABI that's higher on the list, i.e, a device that's configured to prefer 9449 // 64 bit apps will see a 64 bit primary ABI, 9450 9451 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9452 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9453 } 9454 9455 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9456 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9457 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9458 } else { 9459 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9460 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9461 } 9462 } else { 9463 pkg.applicationInfo.primaryCpuAbi = null; 9464 pkg.applicationInfo.secondaryCpuAbi = null; 9465 } 9466 } 9467 9468 private void killApplication(String pkgName, int appId, String reason) { 9469 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9470 } 9471 9472 private void killApplication(String pkgName, int appId, int userId, String reason) { 9473 // Request the ActivityManager to kill the process(only for existing packages) 9474 // so that we do not end up in a confused state while the user is still using the older 9475 // version of the application while the new one gets installed. 9476 final long token = Binder.clearCallingIdentity(); 9477 try { 9478 IActivityManager am = ActivityManagerNative.getDefault(); 9479 if (am != null) { 9480 try { 9481 am.killApplication(pkgName, appId, userId, reason); 9482 } catch (RemoteException e) { 9483 } 9484 } 9485 } finally { 9486 Binder.restoreCallingIdentity(token); 9487 } 9488 } 9489 9490 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9491 // Remove the parent package setting 9492 PackageSetting ps = (PackageSetting) pkg.mExtras; 9493 if (ps != null) { 9494 removePackageLI(ps, chatty); 9495 } 9496 // Remove the child package setting 9497 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9498 for (int i = 0; i < childCount; i++) { 9499 PackageParser.Package childPkg = pkg.childPackages.get(i); 9500 ps = (PackageSetting) childPkg.mExtras; 9501 if (ps != null) { 9502 removePackageLI(ps, chatty); 9503 } 9504 } 9505 } 9506 9507 void removePackageLI(PackageSetting ps, boolean chatty) { 9508 if (DEBUG_INSTALL) { 9509 if (chatty) 9510 Log.d(TAG, "Removing package " + ps.name); 9511 } 9512 9513 // writer 9514 synchronized (mPackages) { 9515 mPackages.remove(ps.name); 9516 final PackageParser.Package pkg = ps.pkg; 9517 if (pkg != null) { 9518 cleanPackageDataStructuresLILPw(pkg, chatty); 9519 } 9520 } 9521 } 9522 9523 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9524 if (DEBUG_INSTALL) { 9525 if (chatty) 9526 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9527 } 9528 9529 // writer 9530 synchronized (mPackages) { 9531 // Remove the parent package 9532 mPackages.remove(pkg.applicationInfo.packageName); 9533 cleanPackageDataStructuresLILPw(pkg, chatty); 9534 9535 // Remove the child packages 9536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9537 for (int i = 0; i < childCount; i++) { 9538 PackageParser.Package childPkg = pkg.childPackages.get(i); 9539 mPackages.remove(childPkg.applicationInfo.packageName); 9540 cleanPackageDataStructuresLILPw(childPkg, chatty); 9541 } 9542 } 9543 } 9544 9545 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9546 int N = pkg.providers.size(); 9547 StringBuilder r = null; 9548 int i; 9549 for (i=0; i<N; i++) { 9550 PackageParser.Provider p = pkg.providers.get(i); 9551 mProviders.removeProvider(p); 9552 if (p.info.authority == null) { 9553 9554 /* There was another ContentProvider with this authority when 9555 * this app was installed so this authority is null, 9556 * Ignore it as we don't have to unregister the provider. 9557 */ 9558 continue; 9559 } 9560 String names[] = p.info.authority.split(";"); 9561 for (int j = 0; j < names.length; j++) { 9562 if (mProvidersByAuthority.get(names[j]) == p) { 9563 mProvidersByAuthority.remove(names[j]); 9564 if (DEBUG_REMOVE) { 9565 if (chatty) 9566 Log.d(TAG, "Unregistered content provider: " + names[j] 9567 + ", className = " + p.info.name + ", isSyncable = " 9568 + p.info.isSyncable); 9569 } 9570 } 9571 } 9572 if (DEBUG_REMOVE && chatty) { 9573 if (r == null) { 9574 r = new StringBuilder(256); 9575 } else { 9576 r.append(' '); 9577 } 9578 r.append(p.info.name); 9579 } 9580 } 9581 if (r != null) { 9582 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9583 } 9584 9585 N = pkg.services.size(); 9586 r = null; 9587 for (i=0; i<N; i++) { 9588 PackageParser.Service s = pkg.services.get(i); 9589 mServices.removeService(s); 9590 if (chatty) { 9591 if (r == null) { 9592 r = new StringBuilder(256); 9593 } else { 9594 r.append(' '); 9595 } 9596 r.append(s.info.name); 9597 } 9598 } 9599 if (r != null) { 9600 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9601 } 9602 9603 N = pkg.receivers.size(); 9604 r = null; 9605 for (i=0; i<N; i++) { 9606 PackageParser.Activity a = pkg.receivers.get(i); 9607 mReceivers.removeActivity(a, "receiver"); 9608 if (DEBUG_REMOVE && chatty) { 9609 if (r == null) { 9610 r = new StringBuilder(256); 9611 } else { 9612 r.append(' '); 9613 } 9614 r.append(a.info.name); 9615 } 9616 } 9617 if (r != null) { 9618 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9619 } 9620 9621 N = pkg.activities.size(); 9622 r = null; 9623 for (i=0; i<N; i++) { 9624 PackageParser.Activity a = pkg.activities.get(i); 9625 mActivities.removeActivity(a, "activity"); 9626 if (DEBUG_REMOVE && chatty) { 9627 if (r == null) { 9628 r = new StringBuilder(256); 9629 } else { 9630 r.append(' '); 9631 } 9632 r.append(a.info.name); 9633 } 9634 } 9635 if (r != null) { 9636 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9637 } 9638 9639 N = pkg.permissions.size(); 9640 r = null; 9641 for (i=0; i<N; i++) { 9642 PackageParser.Permission p = pkg.permissions.get(i); 9643 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9644 if (bp == null) { 9645 bp = mSettings.mPermissionTrees.get(p.info.name); 9646 } 9647 if (bp != null && bp.perm == p) { 9648 bp.perm = null; 9649 if (DEBUG_REMOVE && chatty) { 9650 if (r == null) { 9651 r = new StringBuilder(256); 9652 } else { 9653 r.append(' '); 9654 } 9655 r.append(p.info.name); 9656 } 9657 } 9658 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9659 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9660 if (appOpPkgs != null) { 9661 appOpPkgs.remove(pkg.packageName); 9662 } 9663 } 9664 } 9665 if (r != null) { 9666 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9667 } 9668 9669 N = pkg.requestedPermissions.size(); 9670 r = null; 9671 for (i=0; i<N; i++) { 9672 String perm = pkg.requestedPermissions.get(i); 9673 BasePermission bp = mSettings.mPermissions.get(perm); 9674 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9675 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9676 if (appOpPkgs != null) { 9677 appOpPkgs.remove(pkg.packageName); 9678 if (appOpPkgs.isEmpty()) { 9679 mAppOpPermissionPackages.remove(perm); 9680 } 9681 } 9682 } 9683 } 9684 if (r != null) { 9685 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9686 } 9687 9688 N = pkg.instrumentation.size(); 9689 r = null; 9690 for (i=0; i<N; i++) { 9691 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9692 mInstrumentation.remove(a.getComponentName()); 9693 if (DEBUG_REMOVE && chatty) { 9694 if (r == null) { 9695 r = new StringBuilder(256); 9696 } else { 9697 r.append(' '); 9698 } 9699 r.append(a.info.name); 9700 } 9701 } 9702 if (r != null) { 9703 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9704 } 9705 9706 r = null; 9707 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9708 // Only system apps can hold shared libraries. 9709 if (pkg.libraryNames != null) { 9710 for (i=0; i<pkg.libraryNames.size(); i++) { 9711 String name = pkg.libraryNames.get(i); 9712 SharedLibraryEntry cur = mSharedLibraries.get(name); 9713 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9714 mSharedLibraries.remove(name); 9715 if (DEBUG_REMOVE && chatty) { 9716 if (r == null) { 9717 r = new StringBuilder(256); 9718 } else { 9719 r.append(' '); 9720 } 9721 r.append(name); 9722 } 9723 } 9724 } 9725 } 9726 } 9727 if (r != null) { 9728 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9729 } 9730 } 9731 9732 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9733 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9734 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9735 return true; 9736 } 9737 } 9738 return false; 9739 } 9740 9741 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9742 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9743 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9744 9745 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9746 // Update the parent permissions 9747 updatePermissionsLPw(pkg.packageName, pkg, flags); 9748 // Update the child permissions 9749 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9750 for (int i = 0; i < childCount; i++) { 9751 PackageParser.Package childPkg = pkg.childPackages.get(i); 9752 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9753 } 9754 } 9755 9756 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9757 int flags) { 9758 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9759 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9760 } 9761 9762 private void updatePermissionsLPw(String changingPkg, 9763 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9764 // Make sure there are no dangling permission trees. 9765 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9766 while (it.hasNext()) { 9767 final BasePermission bp = it.next(); 9768 if (bp.packageSetting == null) { 9769 // We may not yet have parsed the package, so just see if 9770 // we still know about its settings. 9771 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9772 } 9773 if (bp.packageSetting == null) { 9774 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9775 + " from package " + bp.sourcePackage); 9776 it.remove(); 9777 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9778 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9779 Slog.i(TAG, "Removing old permission tree: " + bp.name 9780 + " from package " + bp.sourcePackage); 9781 flags |= UPDATE_PERMISSIONS_ALL; 9782 it.remove(); 9783 } 9784 } 9785 } 9786 9787 // Make sure all dynamic permissions have been assigned to a package, 9788 // and make sure there are no dangling permissions. 9789 it = mSettings.mPermissions.values().iterator(); 9790 while (it.hasNext()) { 9791 final BasePermission bp = it.next(); 9792 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9793 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9794 + bp.name + " pkg=" + bp.sourcePackage 9795 + " info=" + bp.pendingInfo); 9796 if (bp.packageSetting == null && bp.pendingInfo != null) { 9797 final BasePermission tree = findPermissionTreeLP(bp.name); 9798 if (tree != null && tree.perm != null) { 9799 bp.packageSetting = tree.packageSetting; 9800 bp.perm = new PackageParser.Permission(tree.perm.owner, 9801 new PermissionInfo(bp.pendingInfo)); 9802 bp.perm.info.packageName = tree.perm.info.packageName; 9803 bp.perm.info.name = bp.name; 9804 bp.uid = tree.uid; 9805 } 9806 } 9807 } 9808 if (bp.packageSetting == null) { 9809 // We may not yet have parsed the package, so just see if 9810 // we still know about its settings. 9811 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9812 } 9813 if (bp.packageSetting == null) { 9814 Slog.w(TAG, "Removing dangling permission: " + bp.name 9815 + " from package " + bp.sourcePackage); 9816 it.remove(); 9817 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9818 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9819 Slog.i(TAG, "Removing old permission: " + bp.name 9820 + " from package " + bp.sourcePackage); 9821 flags |= UPDATE_PERMISSIONS_ALL; 9822 it.remove(); 9823 } 9824 } 9825 } 9826 9827 // Now update the permissions for all packages, in particular 9828 // replace the granted permissions of the system packages. 9829 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9830 for (PackageParser.Package pkg : mPackages.values()) { 9831 if (pkg != pkgInfo) { 9832 // Only replace for packages on requested volume 9833 final String volumeUuid = getVolumeUuidForPackage(pkg); 9834 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9835 && Objects.equals(replaceVolumeUuid, volumeUuid); 9836 grantPermissionsLPw(pkg, replace, changingPkg); 9837 } 9838 } 9839 } 9840 9841 if (pkgInfo != null) { 9842 // Only replace for packages on requested volume 9843 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9844 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9845 && Objects.equals(replaceVolumeUuid, volumeUuid); 9846 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9847 } 9848 } 9849 9850 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9851 String packageOfInterest) { 9852 // IMPORTANT: There are two types of permissions: install and runtime. 9853 // Install time permissions are granted when the app is installed to 9854 // all device users and users added in the future. Runtime permissions 9855 // are granted at runtime explicitly to specific users. Normal and signature 9856 // protected permissions are install time permissions. Dangerous permissions 9857 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9858 // otherwise they are runtime permissions. This function does not manage 9859 // runtime permissions except for the case an app targeting Lollipop MR1 9860 // being upgraded to target a newer SDK, in which case dangerous permissions 9861 // are transformed from install time to runtime ones. 9862 9863 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9864 if (ps == null) { 9865 return; 9866 } 9867 9868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9869 9870 PermissionsState permissionsState = ps.getPermissionsState(); 9871 PermissionsState origPermissions = permissionsState; 9872 9873 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9874 9875 boolean runtimePermissionsRevoked = false; 9876 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9877 9878 boolean changedInstallPermission = false; 9879 9880 if (replace) { 9881 ps.installPermissionsFixed = false; 9882 if (!ps.isSharedUser()) { 9883 origPermissions = new PermissionsState(permissionsState); 9884 permissionsState.reset(); 9885 } else { 9886 // We need to know only about runtime permission changes since the 9887 // calling code always writes the install permissions state but 9888 // the runtime ones are written only if changed. The only cases of 9889 // changed runtime permissions here are promotion of an install to 9890 // runtime and revocation of a runtime from a shared user. 9891 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9892 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9893 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9894 runtimePermissionsRevoked = true; 9895 } 9896 } 9897 } 9898 9899 permissionsState.setGlobalGids(mGlobalGids); 9900 9901 final int N = pkg.requestedPermissions.size(); 9902 for (int i=0; i<N; i++) { 9903 final String name = pkg.requestedPermissions.get(i); 9904 final BasePermission bp = mSettings.mPermissions.get(name); 9905 9906 if (DEBUG_INSTALL) { 9907 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9908 } 9909 9910 if (bp == null || bp.packageSetting == null) { 9911 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9912 Slog.w(TAG, "Unknown permission " + name 9913 + " in package " + pkg.packageName); 9914 } 9915 continue; 9916 } 9917 9918 final String perm = bp.name; 9919 boolean allowedSig = false; 9920 int grant = GRANT_DENIED; 9921 9922 // Keep track of app op permissions. 9923 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9924 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9925 if (pkgs == null) { 9926 pkgs = new ArraySet<>(); 9927 mAppOpPermissionPackages.put(bp.name, pkgs); 9928 } 9929 pkgs.add(pkg.packageName); 9930 } 9931 9932 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9933 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9934 >= Build.VERSION_CODES.M; 9935 switch (level) { 9936 case PermissionInfo.PROTECTION_NORMAL: { 9937 // For all apps normal permissions are install time ones. 9938 grant = GRANT_INSTALL; 9939 } break; 9940 9941 case PermissionInfo.PROTECTION_DANGEROUS: { 9942 // If a permission review is required for legacy apps we represent 9943 // their permissions as always granted runtime ones since we need 9944 // to keep the review required permission flag per user while an 9945 // install permission's state is shared across all users. 9946 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9947 // For legacy apps dangerous permissions are install time ones. 9948 grant = GRANT_INSTALL; 9949 } else if (origPermissions.hasInstallPermission(bp.name)) { 9950 // For legacy apps that became modern, install becomes runtime. 9951 grant = GRANT_UPGRADE; 9952 } else if (mPromoteSystemApps 9953 && isSystemApp(ps) 9954 && mExistingSystemPackages.contains(ps.name)) { 9955 // For legacy system apps, install becomes runtime. 9956 // We cannot check hasInstallPermission() for system apps since those 9957 // permissions were granted implicitly and not persisted pre-M. 9958 grant = GRANT_UPGRADE; 9959 } else { 9960 // For modern apps keep runtime permissions unchanged. 9961 grant = GRANT_RUNTIME; 9962 } 9963 } break; 9964 9965 case PermissionInfo.PROTECTION_SIGNATURE: { 9966 // For all apps signature permissions are install time ones. 9967 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9968 if (allowedSig) { 9969 grant = GRANT_INSTALL; 9970 } 9971 } break; 9972 } 9973 9974 if (DEBUG_INSTALL) { 9975 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9976 } 9977 9978 if (grant != GRANT_DENIED) { 9979 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9980 // If this is an existing, non-system package, then 9981 // we can't add any new permissions to it. 9982 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9983 // Except... if this is a permission that was added 9984 // to the platform (note: need to only do this when 9985 // updating the platform). 9986 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9987 grant = GRANT_DENIED; 9988 } 9989 } 9990 } 9991 9992 switch (grant) { 9993 case GRANT_INSTALL: { 9994 // Revoke this as runtime permission to handle the case of 9995 // a runtime permission being downgraded to an install one. 9996 // Also in permission review mode we keep dangerous permissions 9997 // for legacy apps 9998 for (int userId : UserManagerService.getInstance().getUserIds()) { 9999 if (origPermissions.getRuntimePermissionState( 10000 bp.name, userId) != null) { 10001 // Revoke the runtime permission and clear the flags. 10002 origPermissions.revokeRuntimePermission(bp, userId); 10003 origPermissions.updatePermissionFlags(bp, userId, 10004 PackageManager.MASK_PERMISSION_FLAGS, 0); 10005 // If we revoked a permission permission, we have to write. 10006 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10007 changedRuntimePermissionUserIds, userId); 10008 } 10009 } 10010 // Grant an install permission. 10011 if (permissionsState.grantInstallPermission(bp) != 10012 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10013 changedInstallPermission = true; 10014 } 10015 } break; 10016 10017 case GRANT_RUNTIME: { 10018 // Grant previously granted runtime permissions. 10019 for (int userId : UserManagerService.getInstance().getUserIds()) { 10020 PermissionState permissionState = origPermissions 10021 .getRuntimePermissionState(bp.name, userId); 10022 int flags = permissionState != null 10023 ? permissionState.getFlags() : 0; 10024 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10025 if (permissionsState.grantRuntimePermission(bp, userId) == 10026 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10027 // If we cannot put the permission as it was, we have to write. 10028 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10029 changedRuntimePermissionUserIds, userId); 10030 } 10031 // If the app supports runtime permissions no need for a review. 10032 if (Build.PERMISSIONS_REVIEW_REQUIRED 10033 && appSupportsRuntimePermissions 10034 && (flags & PackageManager 10035 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10036 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10037 // Since we changed the flags, we have to write. 10038 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10039 changedRuntimePermissionUserIds, userId); 10040 } 10041 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10042 && !appSupportsRuntimePermissions) { 10043 // For legacy apps that need a permission review, every new 10044 // runtime permission is granted but it is pending a review. 10045 // We also need to review only platform defined runtime 10046 // permissions as these are the only ones the platform knows 10047 // how to disable the API to simulate revocation as legacy 10048 // apps don't expect to run with revoked permissions. 10049 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10050 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10051 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10052 // We changed the flags, hence have to write. 10053 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10054 changedRuntimePermissionUserIds, userId); 10055 } 10056 } 10057 if (permissionsState.grantRuntimePermission(bp, userId) 10058 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10059 // We changed the permission, hence have to write. 10060 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10061 changedRuntimePermissionUserIds, userId); 10062 } 10063 } 10064 // Propagate the permission flags. 10065 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10066 } 10067 } break; 10068 10069 case GRANT_UPGRADE: { 10070 // Grant runtime permissions for a previously held install permission. 10071 PermissionState permissionState = origPermissions 10072 .getInstallPermissionState(bp.name); 10073 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10074 10075 if (origPermissions.revokeInstallPermission(bp) 10076 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10077 // We will be transferring the permission flags, so clear them. 10078 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10079 PackageManager.MASK_PERMISSION_FLAGS, 0); 10080 changedInstallPermission = true; 10081 } 10082 10083 // If the permission is not to be promoted to runtime we ignore it and 10084 // also its other flags as they are not applicable to install permissions. 10085 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10086 for (int userId : currentUserIds) { 10087 if (permissionsState.grantRuntimePermission(bp, userId) != 10088 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10089 // Transfer the permission flags. 10090 permissionsState.updatePermissionFlags(bp, userId, 10091 flags, flags); 10092 // If we granted the permission, we have to write. 10093 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10094 changedRuntimePermissionUserIds, userId); 10095 } 10096 } 10097 } 10098 } break; 10099 10100 default: { 10101 if (packageOfInterest == null 10102 || packageOfInterest.equals(pkg.packageName)) { 10103 Slog.w(TAG, "Not granting permission " + perm 10104 + " to package " + pkg.packageName 10105 + " because it was previously installed without"); 10106 } 10107 } break; 10108 } 10109 } else { 10110 if (permissionsState.revokeInstallPermission(bp) != 10111 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10112 // Also drop the permission flags. 10113 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10114 PackageManager.MASK_PERMISSION_FLAGS, 0); 10115 changedInstallPermission = true; 10116 Slog.i(TAG, "Un-granting permission " + perm 10117 + " from package " + pkg.packageName 10118 + " (protectionLevel=" + bp.protectionLevel 10119 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10120 + ")"); 10121 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10122 // Don't print warning for app op permissions, since it is fine for them 10123 // not to be granted, there is a UI for the user to decide. 10124 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10125 Slog.w(TAG, "Not granting permission " + perm 10126 + " to package " + pkg.packageName 10127 + " (protectionLevel=" + bp.protectionLevel 10128 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10129 + ")"); 10130 } 10131 } 10132 } 10133 } 10134 10135 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10136 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10137 // This is the first that we have heard about this package, so the 10138 // permissions we have now selected are fixed until explicitly 10139 // changed. 10140 ps.installPermissionsFixed = true; 10141 } 10142 10143 // Persist the runtime permissions state for users with changes. If permissions 10144 // were revoked because no app in the shared user declares them we have to 10145 // write synchronously to avoid losing runtime permissions state. 10146 for (int userId : changedRuntimePermissionUserIds) { 10147 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10148 } 10149 10150 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10151 } 10152 10153 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10154 boolean allowed = false; 10155 final int NP = PackageParser.NEW_PERMISSIONS.length; 10156 for (int ip=0; ip<NP; ip++) { 10157 final PackageParser.NewPermissionInfo npi 10158 = PackageParser.NEW_PERMISSIONS[ip]; 10159 if (npi.name.equals(perm) 10160 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10161 allowed = true; 10162 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10163 + pkg.packageName); 10164 break; 10165 } 10166 } 10167 return allowed; 10168 } 10169 10170 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10171 BasePermission bp, PermissionsState origPermissions) { 10172 boolean allowed; 10173 allowed = (compareSignatures( 10174 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10175 == PackageManager.SIGNATURE_MATCH) 10176 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10177 == PackageManager.SIGNATURE_MATCH); 10178 if (!allowed && (bp.protectionLevel 10179 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10180 if (isSystemApp(pkg)) { 10181 // For updated system applications, a system permission 10182 // is granted only if it had been defined by the original application. 10183 if (pkg.isUpdatedSystemApp()) { 10184 final PackageSetting sysPs = mSettings 10185 .getDisabledSystemPkgLPr(pkg.packageName); 10186 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10187 // If the original was granted this permission, we take 10188 // that grant decision as read and propagate it to the 10189 // update. 10190 if (sysPs.isPrivileged()) { 10191 allowed = true; 10192 } 10193 } else { 10194 // The system apk may have been updated with an older 10195 // version of the one on the data partition, but which 10196 // granted a new system permission that it didn't have 10197 // before. In this case we do want to allow the app to 10198 // now get the new permission if the ancestral apk is 10199 // privileged to get it. 10200 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10201 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10202 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10203 allowed = true; 10204 break; 10205 } 10206 } 10207 } 10208 // Also if a privileged parent package on the system image or any of 10209 // its children requested a privileged permission, the updated child 10210 // packages can also get the permission. 10211 if (pkg.parentPackage != null) { 10212 final PackageSetting disabledSysParentPs = mSettings 10213 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10214 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10215 && disabledSysParentPs.isPrivileged()) { 10216 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10217 allowed = true; 10218 } else if (disabledSysParentPs.pkg.childPackages != null) { 10219 final int count = disabledSysParentPs.pkg.childPackages.size(); 10220 for (int i = 0; i < count; i++) { 10221 PackageParser.Package disabledSysChildPkg = 10222 disabledSysParentPs.pkg.childPackages.get(i); 10223 if (isPackageRequestingPermission(disabledSysChildPkg, 10224 perm)) { 10225 allowed = true; 10226 break; 10227 } 10228 } 10229 } 10230 } 10231 } 10232 } 10233 } else { 10234 allowed = isPrivilegedApp(pkg); 10235 } 10236 } 10237 } 10238 if (!allowed) { 10239 if (!allowed && (bp.protectionLevel 10240 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10241 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10242 // If this was a previously normal/dangerous permission that got moved 10243 // to a system permission as part of the runtime permission redesign, then 10244 // we still want to blindly grant it to old apps. 10245 allowed = true; 10246 } 10247 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10248 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10249 // If this permission is to be granted to the system installer and 10250 // this app is an installer, then it gets the permission. 10251 allowed = true; 10252 } 10253 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10254 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10255 // If this permission is to be granted to the system verifier and 10256 // this app is a verifier, then it gets the permission. 10257 allowed = true; 10258 } 10259 if (!allowed && (bp.protectionLevel 10260 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10261 && isSystemApp(pkg)) { 10262 // Any pre-installed system app is allowed to get this permission. 10263 allowed = true; 10264 } 10265 if (!allowed && (bp.protectionLevel 10266 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10267 // For development permissions, a development permission 10268 // is granted only if it was already granted. 10269 allowed = origPermissions.hasInstallPermission(perm); 10270 } 10271 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10272 && pkg.packageName.equals(mSetupWizardPackage)) { 10273 // If this permission is to be granted to the system setup wizard and 10274 // this app is a setup wizard, then it gets the permission. 10275 allowed = true; 10276 } 10277 } 10278 return allowed; 10279 } 10280 10281 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10282 final int permCount = pkg.requestedPermissions.size(); 10283 for (int j = 0; j < permCount; j++) { 10284 String requestedPermission = pkg.requestedPermissions.get(j); 10285 if (permission.equals(requestedPermission)) { 10286 return true; 10287 } 10288 } 10289 return false; 10290 } 10291 10292 final class ActivityIntentResolver 10293 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10294 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10295 boolean defaultOnly, int userId) { 10296 if (!sUserManager.exists(userId)) return null; 10297 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10298 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10299 } 10300 10301 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10302 int userId) { 10303 if (!sUserManager.exists(userId)) return null; 10304 mFlags = flags; 10305 return super.queryIntent(intent, resolvedType, 10306 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10307 } 10308 10309 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10310 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10311 if (!sUserManager.exists(userId)) return null; 10312 if (packageActivities == null) { 10313 return null; 10314 } 10315 mFlags = flags; 10316 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10317 final int N = packageActivities.size(); 10318 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10319 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10320 10321 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10322 for (int i = 0; i < N; ++i) { 10323 intentFilters = packageActivities.get(i).intents; 10324 if (intentFilters != null && intentFilters.size() > 0) { 10325 PackageParser.ActivityIntentInfo[] array = 10326 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10327 intentFilters.toArray(array); 10328 listCut.add(array); 10329 } 10330 } 10331 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10332 } 10333 10334 /** 10335 * Finds a privileged activity that matches the specified activity names. 10336 */ 10337 private PackageParser.Activity findMatchingActivity( 10338 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10339 for (PackageParser.Activity sysActivity : activityList) { 10340 if (sysActivity.info.name.equals(activityInfo.name)) { 10341 return sysActivity; 10342 } 10343 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10344 return sysActivity; 10345 } 10346 if (sysActivity.info.targetActivity != null) { 10347 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10348 return sysActivity; 10349 } 10350 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10351 return sysActivity; 10352 } 10353 } 10354 } 10355 return null; 10356 } 10357 10358 public class IterGenerator<E> { 10359 public Iterator<E> generate(ActivityIntentInfo info) { 10360 return null; 10361 } 10362 } 10363 10364 public class ActionIterGenerator extends IterGenerator<String> { 10365 @Override 10366 public Iterator<String> generate(ActivityIntentInfo info) { 10367 return info.actionsIterator(); 10368 } 10369 } 10370 10371 public class CategoriesIterGenerator extends IterGenerator<String> { 10372 @Override 10373 public Iterator<String> generate(ActivityIntentInfo info) { 10374 return info.categoriesIterator(); 10375 } 10376 } 10377 10378 public class SchemesIterGenerator extends IterGenerator<String> { 10379 @Override 10380 public Iterator<String> generate(ActivityIntentInfo info) { 10381 return info.schemesIterator(); 10382 } 10383 } 10384 10385 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10386 @Override 10387 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10388 return info.authoritiesIterator(); 10389 } 10390 } 10391 10392 /** 10393 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10394 * MODIFIED. Do not pass in a list that should not be changed. 10395 */ 10396 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10397 IterGenerator<T> generator, Iterator<T> searchIterator) { 10398 // loop through the set of actions; every one must be found in the intent filter 10399 while (searchIterator.hasNext()) { 10400 // we must have at least one filter in the list to consider a match 10401 if (intentList.size() == 0) { 10402 break; 10403 } 10404 10405 final T searchAction = searchIterator.next(); 10406 10407 // loop through the set of intent filters 10408 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10409 while (intentIter.hasNext()) { 10410 final ActivityIntentInfo intentInfo = intentIter.next(); 10411 boolean selectionFound = false; 10412 10413 // loop through the intent filter's selection criteria; at least one 10414 // of them must match the searched criteria 10415 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10416 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10417 final T intentSelection = intentSelectionIter.next(); 10418 if (intentSelection != null && intentSelection.equals(searchAction)) { 10419 selectionFound = true; 10420 break; 10421 } 10422 } 10423 10424 // the selection criteria wasn't found in this filter's set; this filter 10425 // is not a potential match 10426 if (!selectionFound) { 10427 intentIter.remove(); 10428 } 10429 } 10430 } 10431 } 10432 10433 private boolean isProtectedAction(ActivityIntentInfo filter) { 10434 final Iterator<String> actionsIter = filter.actionsIterator(); 10435 while (actionsIter != null && actionsIter.hasNext()) { 10436 final String filterAction = actionsIter.next(); 10437 if (PROTECTED_ACTIONS.contains(filterAction)) { 10438 return true; 10439 } 10440 } 10441 return false; 10442 } 10443 10444 /** 10445 * Adjusts the priority of the given intent filter according to policy. 10446 * <p> 10447 * <ul> 10448 * <li>The priority for non privileged applications is capped to '0'</li> 10449 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10450 * <li>The priority for unbundled updates to privileged applications is capped to the 10451 * priority defined on the system partition</li> 10452 * </ul> 10453 * <p> 10454 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10455 * allowed to obtain any priority on any action. 10456 */ 10457 private void adjustPriority( 10458 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10459 // nothing to do; priority is fine as-is 10460 if (intent.getPriority() <= 0) { 10461 return; 10462 } 10463 10464 final ActivityInfo activityInfo = intent.activity.info; 10465 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10466 10467 final boolean privilegedApp = 10468 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10469 if (!privilegedApp) { 10470 // non-privileged applications can never define a priority >0 10471 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10472 + " package: " + applicationInfo.packageName 10473 + " activity: " + intent.activity.className 10474 + " origPrio: " + intent.getPriority()); 10475 intent.setPriority(0); 10476 return; 10477 } 10478 10479 if (systemActivities == null) { 10480 // the system package is not disabled; we're parsing the system partition 10481 if (isProtectedAction(intent)) { 10482 if (mDeferProtectedFilters) { 10483 // We can't deal with these just yet. No component should ever obtain a 10484 // >0 priority for a protected actions, with ONE exception -- the setup 10485 // wizard. The setup wizard, however, cannot be known until we're able to 10486 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10487 // until all intent filters have been processed. Chicken, meet egg. 10488 // Let the filter temporarily have a high priority and rectify the 10489 // priorities after all system packages have been scanned. 10490 mProtectedFilters.add(intent); 10491 if (DEBUG_FILTERS) { 10492 Slog.i(TAG, "Protected action; save for later;" 10493 + " package: " + applicationInfo.packageName 10494 + " activity: " + intent.activity.className 10495 + " origPrio: " + intent.getPriority()); 10496 } 10497 return; 10498 } else { 10499 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10500 Slog.i(TAG, "No setup wizard;" 10501 + " All protected intents capped to priority 0"); 10502 } 10503 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10504 if (DEBUG_FILTERS) { 10505 Slog.i(TAG, "Found setup wizard;" 10506 + " allow priority " + intent.getPriority() + ";" 10507 + " package: " + intent.activity.info.packageName 10508 + " activity: " + intent.activity.className 10509 + " priority: " + intent.getPriority()); 10510 } 10511 // setup wizard gets whatever it wants 10512 return; 10513 } 10514 Slog.w(TAG, "Protected action; cap priority to 0;" 10515 + " package: " + intent.activity.info.packageName 10516 + " activity: " + intent.activity.className 10517 + " origPrio: " + intent.getPriority()); 10518 intent.setPriority(0); 10519 return; 10520 } 10521 } 10522 // privileged apps on the system image get whatever priority they request 10523 return; 10524 } 10525 10526 // privileged app unbundled update ... try to find the same activity 10527 final PackageParser.Activity foundActivity = 10528 findMatchingActivity(systemActivities, activityInfo); 10529 if (foundActivity == null) { 10530 // this is a new activity; it cannot obtain >0 priority 10531 if (DEBUG_FILTERS) { 10532 Slog.i(TAG, "New activity; cap priority to 0;" 10533 + " package: " + applicationInfo.packageName 10534 + " activity: " + intent.activity.className 10535 + " origPrio: " + intent.getPriority()); 10536 } 10537 intent.setPriority(0); 10538 return; 10539 } 10540 10541 // found activity, now check for filter equivalence 10542 10543 // a shallow copy is enough; we modify the list, not its contents 10544 final List<ActivityIntentInfo> intentListCopy = 10545 new ArrayList<>(foundActivity.intents); 10546 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10547 10548 // find matching action subsets 10549 final Iterator<String> actionsIterator = intent.actionsIterator(); 10550 if (actionsIterator != null) { 10551 getIntentListSubset( 10552 intentListCopy, new ActionIterGenerator(), actionsIterator); 10553 if (intentListCopy.size() == 0) { 10554 // no more intents to match; we're not equivalent 10555 if (DEBUG_FILTERS) { 10556 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10557 + " package: " + applicationInfo.packageName 10558 + " activity: " + intent.activity.className 10559 + " origPrio: " + intent.getPriority()); 10560 } 10561 intent.setPriority(0); 10562 return; 10563 } 10564 } 10565 10566 // find matching category subsets 10567 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10568 if (categoriesIterator != null) { 10569 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10570 categoriesIterator); 10571 if (intentListCopy.size() == 0) { 10572 // no more intents to match; we're not equivalent 10573 if (DEBUG_FILTERS) { 10574 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10575 + " package: " + applicationInfo.packageName 10576 + " activity: " + intent.activity.className 10577 + " origPrio: " + intent.getPriority()); 10578 } 10579 intent.setPriority(0); 10580 return; 10581 } 10582 } 10583 10584 // find matching schemes subsets 10585 final Iterator<String> schemesIterator = intent.schemesIterator(); 10586 if (schemesIterator != null) { 10587 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10588 schemesIterator); 10589 if (intentListCopy.size() == 0) { 10590 // no more intents to match; we're not equivalent 10591 if (DEBUG_FILTERS) { 10592 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10593 + " package: " + applicationInfo.packageName 10594 + " activity: " + intent.activity.className 10595 + " origPrio: " + intent.getPriority()); 10596 } 10597 intent.setPriority(0); 10598 return; 10599 } 10600 } 10601 10602 // find matching authorities subsets 10603 final Iterator<IntentFilter.AuthorityEntry> 10604 authoritiesIterator = intent.authoritiesIterator(); 10605 if (authoritiesIterator != null) { 10606 getIntentListSubset(intentListCopy, 10607 new AuthoritiesIterGenerator(), 10608 authoritiesIterator); 10609 if (intentListCopy.size() == 0) { 10610 // no more intents to match; we're not equivalent 10611 if (DEBUG_FILTERS) { 10612 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10613 + " package: " + applicationInfo.packageName 10614 + " activity: " + intent.activity.className 10615 + " origPrio: " + intent.getPriority()); 10616 } 10617 intent.setPriority(0); 10618 return; 10619 } 10620 } 10621 10622 // we found matching filter(s); app gets the max priority of all intents 10623 int cappedPriority = 0; 10624 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10625 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10626 } 10627 if (intent.getPriority() > cappedPriority) { 10628 if (DEBUG_FILTERS) { 10629 Slog.i(TAG, "Found matching filter(s);" 10630 + " cap priority to " + cappedPriority + ";" 10631 + " package: " + applicationInfo.packageName 10632 + " activity: " + intent.activity.className 10633 + " origPrio: " + intent.getPriority()); 10634 } 10635 intent.setPriority(cappedPriority); 10636 return; 10637 } 10638 // all this for nothing; the requested priority was <= what was on the system 10639 } 10640 10641 public final void addActivity(PackageParser.Activity a, String type) { 10642 mActivities.put(a.getComponentName(), a); 10643 if (DEBUG_SHOW_INFO) 10644 Log.v( 10645 TAG, " " + type + " " + 10646 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10647 if (DEBUG_SHOW_INFO) 10648 Log.v(TAG, " Class=" + a.info.name); 10649 final int NI = a.intents.size(); 10650 for (int j=0; j<NI; j++) { 10651 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10652 if ("activity".equals(type)) { 10653 final PackageSetting ps = 10654 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10655 final List<PackageParser.Activity> systemActivities = 10656 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10657 adjustPriority(systemActivities, intent); 10658 } 10659 if (DEBUG_SHOW_INFO) { 10660 Log.v(TAG, " IntentFilter:"); 10661 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10662 } 10663 if (!intent.debugCheck()) { 10664 Log.w(TAG, "==> For Activity " + a.info.name); 10665 } 10666 addFilter(intent); 10667 } 10668 } 10669 10670 public final void removeActivity(PackageParser.Activity a, String type) { 10671 mActivities.remove(a.getComponentName()); 10672 if (DEBUG_SHOW_INFO) { 10673 Log.v(TAG, " " + type + " " 10674 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10675 : a.info.name) + ":"); 10676 Log.v(TAG, " Class=" + a.info.name); 10677 } 10678 final int NI = a.intents.size(); 10679 for (int j=0; j<NI; j++) { 10680 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10681 if (DEBUG_SHOW_INFO) { 10682 Log.v(TAG, " IntentFilter:"); 10683 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10684 } 10685 removeFilter(intent); 10686 } 10687 } 10688 10689 @Override 10690 protected boolean allowFilterResult( 10691 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10692 ActivityInfo filterAi = filter.activity.info; 10693 for (int i=dest.size()-1; i>=0; i--) { 10694 ActivityInfo destAi = dest.get(i).activityInfo; 10695 if (destAi.name == filterAi.name 10696 && destAi.packageName == filterAi.packageName) { 10697 return false; 10698 } 10699 } 10700 return true; 10701 } 10702 10703 @Override 10704 protected ActivityIntentInfo[] newArray(int size) { 10705 return new ActivityIntentInfo[size]; 10706 } 10707 10708 @Override 10709 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10710 if (!sUserManager.exists(userId)) return true; 10711 PackageParser.Package p = filter.activity.owner; 10712 if (p != null) { 10713 PackageSetting ps = (PackageSetting)p.mExtras; 10714 if (ps != null) { 10715 // System apps are never considered stopped for purposes of 10716 // filtering, because there may be no way for the user to 10717 // actually re-launch them. 10718 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10719 && ps.getStopped(userId); 10720 } 10721 } 10722 return false; 10723 } 10724 10725 @Override 10726 protected boolean isPackageForFilter(String packageName, 10727 PackageParser.ActivityIntentInfo info) { 10728 return packageName.equals(info.activity.owner.packageName); 10729 } 10730 10731 @Override 10732 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10733 int match, int userId) { 10734 if (!sUserManager.exists(userId)) return null; 10735 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10736 return null; 10737 } 10738 final PackageParser.Activity activity = info.activity; 10739 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10740 if (ps == null) { 10741 return null; 10742 } 10743 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10744 ps.readUserState(userId), userId); 10745 if (ai == null) { 10746 return null; 10747 } 10748 final ResolveInfo res = new ResolveInfo(); 10749 res.activityInfo = ai; 10750 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10751 res.filter = info; 10752 } 10753 if (info != null) { 10754 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10755 } 10756 res.priority = info.getPriority(); 10757 res.preferredOrder = activity.owner.mPreferredOrder; 10758 //System.out.println("Result: " + res.activityInfo.className + 10759 // " = " + res.priority); 10760 res.match = match; 10761 res.isDefault = info.hasDefault; 10762 res.labelRes = info.labelRes; 10763 res.nonLocalizedLabel = info.nonLocalizedLabel; 10764 if (userNeedsBadging(userId)) { 10765 res.noResourceId = true; 10766 } else { 10767 res.icon = info.icon; 10768 } 10769 res.iconResourceId = info.icon; 10770 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10771 return res; 10772 } 10773 10774 @Override 10775 protected void sortResults(List<ResolveInfo> results) { 10776 Collections.sort(results, mResolvePrioritySorter); 10777 } 10778 10779 @Override 10780 protected void dumpFilter(PrintWriter out, String prefix, 10781 PackageParser.ActivityIntentInfo filter) { 10782 out.print(prefix); out.print( 10783 Integer.toHexString(System.identityHashCode(filter.activity))); 10784 out.print(' '); 10785 filter.activity.printComponentShortName(out); 10786 out.print(" filter "); 10787 out.println(Integer.toHexString(System.identityHashCode(filter))); 10788 } 10789 10790 @Override 10791 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10792 return filter.activity; 10793 } 10794 10795 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10796 PackageParser.Activity activity = (PackageParser.Activity)label; 10797 out.print(prefix); out.print( 10798 Integer.toHexString(System.identityHashCode(activity))); 10799 out.print(' '); 10800 activity.printComponentShortName(out); 10801 if (count > 1) { 10802 out.print(" ("); out.print(count); out.print(" filters)"); 10803 } 10804 out.println(); 10805 } 10806 10807 // Keys are String (activity class name), values are Activity. 10808 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10809 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10810 private int mFlags; 10811 } 10812 10813 private final class ServiceIntentResolver 10814 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10816 boolean defaultOnly, int userId) { 10817 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10818 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10819 } 10820 10821 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10822 int userId) { 10823 if (!sUserManager.exists(userId)) return null; 10824 mFlags = flags; 10825 return super.queryIntent(intent, resolvedType, 10826 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10827 } 10828 10829 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10830 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10831 if (!sUserManager.exists(userId)) return null; 10832 if (packageServices == null) { 10833 return null; 10834 } 10835 mFlags = flags; 10836 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10837 final int N = packageServices.size(); 10838 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10839 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10840 10841 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10842 for (int i = 0; i < N; ++i) { 10843 intentFilters = packageServices.get(i).intents; 10844 if (intentFilters != null && intentFilters.size() > 0) { 10845 PackageParser.ServiceIntentInfo[] array = 10846 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10847 intentFilters.toArray(array); 10848 listCut.add(array); 10849 } 10850 } 10851 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10852 } 10853 10854 public final void addService(PackageParser.Service s) { 10855 mServices.put(s.getComponentName(), s); 10856 if (DEBUG_SHOW_INFO) { 10857 Log.v(TAG, " " 10858 + (s.info.nonLocalizedLabel != null 10859 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10860 Log.v(TAG, " Class=" + s.info.name); 10861 } 10862 final int NI = s.intents.size(); 10863 int j; 10864 for (j=0; j<NI; j++) { 10865 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10866 if (DEBUG_SHOW_INFO) { 10867 Log.v(TAG, " IntentFilter:"); 10868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10869 } 10870 if (!intent.debugCheck()) { 10871 Log.w(TAG, "==> For Service " + s.info.name); 10872 } 10873 addFilter(intent); 10874 } 10875 } 10876 10877 public final void removeService(PackageParser.Service s) { 10878 mServices.remove(s.getComponentName()); 10879 if (DEBUG_SHOW_INFO) { 10880 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10881 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10882 Log.v(TAG, " Class=" + s.info.name); 10883 } 10884 final int NI = s.intents.size(); 10885 int j; 10886 for (j=0; j<NI; j++) { 10887 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10888 if (DEBUG_SHOW_INFO) { 10889 Log.v(TAG, " IntentFilter:"); 10890 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10891 } 10892 removeFilter(intent); 10893 } 10894 } 10895 10896 @Override 10897 protected boolean allowFilterResult( 10898 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10899 ServiceInfo filterSi = filter.service.info; 10900 for (int i=dest.size()-1; i>=0; i--) { 10901 ServiceInfo destAi = dest.get(i).serviceInfo; 10902 if (destAi.name == filterSi.name 10903 && destAi.packageName == filterSi.packageName) { 10904 return false; 10905 } 10906 } 10907 return true; 10908 } 10909 10910 @Override 10911 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10912 return new PackageParser.ServiceIntentInfo[size]; 10913 } 10914 10915 @Override 10916 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10917 if (!sUserManager.exists(userId)) return true; 10918 PackageParser.Package p = filter.service.owner; 10919 if (p != null) { 10920 PackageSetting ps = (PackageSetting)p.mExtras; 10921 if (ps != null) { 10922 // System apps are never considered stopped for purposes of 10923 // filtering, because there may be no way for the user to 10924 // actually re-launch them. 10925 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10926 && ps.getStopped(userId); 10927 } 10928 } 10929 return false; 10930 } 10931 10932 @Override 10933 protected boolean isPackageForFilter(String packageName, 10934 PackageParser.ServiceIntentInfo info) { 10935 return packageName.equals(info.service.owner.packageName); 10936 } 10937 10938 @Override 10939 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10940 int match, int userId) { 10941 if (!sUserManager.exists(userId)) return null; 10942 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10943 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10944 return null; 10945 } 10946 final PackageParser.Service service = info.service; 10947 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10948 if (ps == null) { 10949 return null; 10950 } 10951 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10952 ps.readUserState(userId), userId); 10953 if (si == null) { 10954 return null; 10955 } 10956 final ResolveInfo res = new ResolveInfo(); 10957 res.serviceInfo = si; 10958 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10959 res.filter = filter; 10960 } 10961 res.priority = info.getPriority(); 10962 res.preferredOrder = service.owner.mPreferredOrder; 10963 res.match = match; 10964 res.isDefault = info.hasDefault; 10965 res.labelRes = info.labelRes; 10966 res.nonLocalizedLabel = info.nonLocalizedLabel; 10967 res.icon = info.icon; 10968 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10969 return res; 10970 } 10971 10972 @Override 10973 protected void sortResults(List<ResolveInfo> results) { 10974 Collections.sort(results, mResolvePrioritySorter); 10975 } 10976 10977 @Override 10978 protected void dumpFilter(PrintWriter out, String prefix, 10979 PackageParser.ServiceIntentInfo filter) { 10980 out.print(prefix); out.print( 10981 Integer.toHexString(System.identityHashCode(filter.service))); 10982 out.print(' '); 10983 filter.service.printComponentShortName(out); 10984 out.print(" filter "); 10985 out.println(Integer.toHexString(System.identityHashCode(filter))); 10986 } 10987 10988 @Override 10989 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10990 return filter.service; 10991 } 10992 10993 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10994 PackageParser.Service service = (PackageParser.Service)label; 10995 out.print(prefix); out.print( 10996 Integer.toHexString(System.identityHashCode(service))); 10997 out.print(' '); 10998 service.printComponentShortName(out); 10999 if (count > 1) { 11000 out.print(" ("); out.print(count); out.print(" filters)"); 11001 } 11002 out.println(); 11003 } 11004 11005// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11006// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11007// final List<ResolveInfo> retList = Lists.newArrayList(); 11008// while (i.hasNext()) { 11009// final ResolveInfo resolveInfo = (ResolveInfo) i; 11010// if (isEnabledLP(resolveInfo.serviceInfo)) { 11011// retList.add(resolveInfo); 11012// } 11013// } 11014// return retList; 11015// } 11016 11017 // Keys are String (activity class name), values are Activity. 11018 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11019 = new ArrayMap<ComponentName, PackageParser.Service>(); 11020 private int mFlags; 11021 }; 11022 11023 private final class ProviderIntentResolver 11024 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11026 boolean defaultOnly, int userId) { 11027 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11028 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11029 } 11030 11031 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11032 int userId) { 11033 if (!sUserManager.exists(userId)) 11034 return null; 11035 mFlags = flags; 11036 return super.queryIntent(intent, resolvedType, 11037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11038 } 11039 11040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11041 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11042 if (!sUserManager.exists(userId)) 11043 return null; 11044 if (packageProviders == null) { 11045 return null; 11046 } 11047 mFlags = flags; 11048 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11049 final int N = packageProviders.size(); 11050 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11051 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11052 11053 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11054 for (int i = 0; i < N; ++i) { 11055 intentFilters = packageProviders.get(i).intents; 11056 if (intentFilters != null && intentFilters.size() > 0) { 11057 PackageParser.ProviderIntentInfo[] array = 11058 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11059 intentFilters.toArray(array); 11060 listCut.add(array); 11061 } 11062 } 11063 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11064 } 11065 11066 public final void addProvider(PackageParser.Provider p) { 11067 if (mProviders.containsKey(p.getComponentName())) { 11068 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11069 return; 11070 } 11071 11072 mProviders.put(p.getComponentName(), p); 11073 if (DEBUG_SHOW_INFO) { 11074 Log.v(TAG, " " 11075 + (p.info.nonLocalizedLabel != null 11076 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11077 Log.v(TAG, " Class=" + p.info.name); 11078 } 11079 final int NI = p.intents.size(); 11080 int j; 11081 for (j = 0; j < NI; j++) { 11082 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11083 if (DEBUG_SHOW_INFO) { 11084 Log.v(TAG, " IntentFilter:"); 11085 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11086 } 11087 if (!intent.debugCheck()) { 11088 Log.w(TAG, "==> For Provider " + p.info.name); 11089 } 11090 addFilter(intent); 11091 } 11092 } 11093 11094 public final void removeProvider(PackageParser.Provider p) { 11095 mProviders.remove(p.getComponentName()); 11096 if (DEBUG_SHOW_INFO) { 11097 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11098 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11099 Log.v(TAG, " Class=" + p.info.name); 11100 } 11101 final int NI = p.intents.size(); 11102 int j; 11103 for (j = 0; j < NI; j++) { 11104 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11105 if (DEBUG_SHOW_INFO) { 11106 Log.v(TAG, " IntentFilter:"); 11107 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11108 } 11109 removeFilter(intent); 11110 } 11111 } 11112 11113 @Override 11114 protected boolean allowFilterResult( 11115 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11116 ProviderInfo filterPi = filter.provider.info; 11117 for (int i = dest.size() - 1; i >= 0; i--) { 11118 ProviderInfo destPi = dest.get(i).providerInfo; 11119 if (destPi.name == filterPi.name 11120 && destPi.packageName == filterPi.packageName) { 11121 return false; 11122 } 11123 } 11124 return true; 11125 } 11126 11127 @Override 11128 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11129 return new PackageParser.ProviderIntentInfo[size]; 11130 } 11131 11132 @Override 11133 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11134 if (!sUserManager.exists(userId)) 11135 return true; 11136 PackageParser.Package p = filter.provider.owner; 11137 if (p != null) { 11138 PackageSetting ps = (PackageSetting) p.mExtras; 11139 if (ps != null) { 11140 // System apps are never considered stopped for purposes of 11141 // filtering, because there may be no way for the user to 11142 // actually re-launch them. 11143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11144 && ps.getStopped(userId); 11145 } 11146 } 11147 return false; 11148 } 11149 11150 @Override 11151 protected boolean isPackageForFilter(String packageName, 11152 PackageParser.ProviderIntentInfo info) { 11153 return packageName.equals(info.provider.owner.packageName); 11154 } 11155 11156 @Override 11157 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11158 int match, int userId) { 11159 if (!sUserManager.exists(userId)) 11160 return null; 11161 final PackageParser.ProviderIntentInfo info = filter; 11162 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11163 return null; 11164 } 11165 final PackageParser.Provider provider = info.provider; 11166 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11167 if (ps == null) { 11168 return null; 11169 } 11170 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11171 ps.readUserState(userId), userId); 11172 if (pi == null) { 11173 return null; 11174 } 11175 final ResolveInfo res = new ResolveInfo(); 11176 res.providerInfo = pi; 11177 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11178 res.filter = filter; 11179 } 11180 res.priority = info.getPriority(); 11181 res.preferredOrder = provider.owner.mPreferredOrder; 11182 res.match = match; 11183 res.isDefault = info.hasDefault; 11184 res.labelRes = info.labelRes; 11185 res.nonLocalizedLabel = info.nonLocalizedLabel; 11186 res.icon = info.icon; 11187 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11188 return res; 11189 } 11190 11191 @Override 11192 protected void sortResults(List<ResolveInfo> results) { 11193 Collections.sort(results, mResolvePrioritySorter); 11194 } 11195 11196 @Override 11197 protected void dumpFilter(PrintWriter out, String prefix, 11198 PackageParser.ProviderIntentInfo filter) { 11199 out.print(prefix); 11200 out.print( 11201 Integer.toHexString(System.identityHashCode(filter.provider))); 11202 out.print(' '); 11203 filter.provider.printComponentShortName(out); 11204 out.print(" filter "); 11205 out.println(Integer.toHexString(System.identityHashCode(filter))); 11206 } 11207 11208 @Override 11209 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11210 return filter.provider; 11211 } 11212 11213 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11214 PackageParser.Provider provider = (PackageParser.Provider)label; 11215 out.print(prefix); out.print( 11216 Integer.toHexString(System.identityHashCode(provider))); 11217 out.print(' '); 11218 provider.printComponentShortName(out); 11219 if (count > 1) { 11220 out.print(" ("); out.print(count); out.print(" filters)"); 11221 } 11222 out.println(); 11223 } 11224 11225 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11226 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11227 private int mFlags; 11228 } 11229 11230 private static final class EphemeralIntentResolver 11231 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11232 @Override 11233 protected EphemeralResolveIntentInfo[] newArray(int size) { 11234 return new EphemeralResolveIntentInfo[size]; 11235 } 11236 11237 @Override 11238 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11239 return true; 11240 } 11241 11242 @Override 11243 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11244 int userId) { 11245 if (!sUserManager.exists(userId)) { 11246 return null; 11247 } 11248 return info.getEphemeralResolveInfo(); 11249 } 11250 } 11251 11252 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11253 new Comparator<ResolveInfo>() { 11254 public int compare(ResolveInfo r1, ResolveInfo r2) { 11255 int v1 = r1.priority; 11256 int v2 = r2.priority; 11257 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11258 if (v1 != v2) { 11259 return (v1 > v2) ? -1 : 1; 11260 } 11261 v1 = r1.preferredOrder; 11262 v2 = r2.preferredOrder; 11263 if (v1 != v2) { 11264 return (v1 > v2) ? -1 : 1; 11265 } 11266 if (r1.isDefault != r2.isDefault) { 11267 return r1.isDefault ? -1 : 1; 11268 } 11269 v1 = r1.match; 11270 v2 = r2.match; 11271 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11272 if (v1 != v2) { 11273 return (v1 > v2) ? -1 : 1; 11274 } 11275 if (r1.system != r2.system) { 11276 return r1.system ? -1 : 1; 11277 } 11278 if (r1.activityInfo != null) { 11279 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11280 } 11281 if (r1.serviceInfo != null) { 11282 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11283 } 11284 if (r1.providerInfo != null) { 11285 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11286 } 11287 return 0; 11288 } 11289 }; 11290 11291 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11292 new Comparator<ProviderInfo>() { 11293 public int compare(ProviderInfo p1, ProviderInfo p2) { 11294 final int v1 = p1.initOrder; 11295 final int v2 = p2.initOrder; 11296 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11297 } 11298 }; 11299 11300 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11301 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11302 final int[] userIds) { 11303 mHandler.post(new Runnable() { 11304 @Override 11305 public void run() { 11306 try { 11307 final IActivityManager am = ActivityManagerNative.getDefault(); 11308 if (am == null) return; 11309 final int[] resolvedUserIds; 11310 if (userIds == null) { 11311 resolvedUserIds = am.getRunningUserIds(); 11312 } else { 11313 resolvedUserIds = userIds; 11314 } 11315 for (int id : resolvedUserIds) { 11316 final Intent intent = new Intent(action, 11317 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11318 if (extras != null) { 11319 intent.putExtras(extras); 11320 } 11321 if (targetPkg != null) { 11322 intent.setPackage(targetPkg); 11323 } 11324 // Modify the UID when posting to other users 11325 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11326 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11327 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11328 intent.putExtra(Intent.EXTRA_UID, uid); 11329 } 11330 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11331 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11332 if (DEBUG_BROADCASTS) { 11333 RuntimeException here = new RuntimeException("here"); 11334 here.fillInStackTrace(); 11335 Slog.d(TAG, "Sending to user " + id + ": " 11336 + intent.toShortString(false, true, false, false) 11337 + " " + intent.getExtras(), here); 11338 } 11339 am.broadcastIntent(null, intent, null, finishedReceiver, 11340 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11341 null, finishedReceiver != null, false, id); 11342 } 11343 } catch (RemoteException ex) { 11344 } 11345 } 11346 }); 11347 } 11348 11349 /** 11350 * Check if the external storage media is available. This is true if there 11351 * is a mounted external storage medium or if the external storage is 11352 * emulated. 11353 */ 11354 private boolean isExternalMediaAvailable() { 11355 return mMediaMounted || Environment.isExternalStorageEmulated(); 11356 } 11357 11358 @Override 11359 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11360 // writer 11361 synchronized (mPackages) { 11362 if (!isExternalMediaAvailable()) { 11363 // If the external storage is no longer mounted at this point, 11364 // the caller may not have been able to delete all of this 11365 // packages files and can not delete any more. Bail. 11366 return null; 11367 } 11368 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11369 if (lastPackage != null) { 11370 pkgs.remove(lastPackage); 11371 } 11372 if (pkgs.size() > 0) { 11373 return pkgs.get(0); 11374 } 11375 } 11376 return null; 11377 } 11378 11379 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11380 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11381 userId, andCode ? 1 : 0, packageName); 11382 if (mSystemReady) { 11383 msg.sendToTarget(); 11384 } else { 11385 if (mPostSystemReadyMessages == null) { 11386 mPostSystemReadyMessages = new ArrayList<>(); 11387 } 11388 mPostSystemReadyMessages.add(msg); 11389 } 11390 } 11391 11392 void startCleaningPackages() { 11393 // reader 11394 if (!isExternalMediaAvailable()) { 11395 return; 11396 } 11397 synchronized (mPackages) { 11398 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11399 return; 11400 } 11401 } 11402 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11403 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11404 IActivityManager am = ActivityManagerNative.getDefault(); 11405 if (am != null) { 11406 try { 11407 am.startService(null, intent, null, mContext.getOpPackageName(), 11408 UserHandle.USER_SYSTEM); 11409 } catch (RemoteException e) { 11410 } 11411 } 11412 } 11413 11414 @Override 11415 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11416 int installFlags, String installerPackageName, int userId) { 11417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11418 11419 final int callingUid = Binder.getCallingUid(); 11420 enforceCrossUserPermission(callingUid, userId, 11421 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11422 11423 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11424 try { 11425 if (observer != null) { 11426 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11427 } 11428 } catch (RemoteException re) { 11429 } 11430 return; 11431 } 11432 11433 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11434 installFlags |= PackageManager.INSTALL_FROM_ADB; 11435 11436 } else { 11437 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11438 // about installerPackageName. 11439 11440 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11441 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11442 } 11443 11444 UserHandle user; 11445 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11446 user = UserHandle.ALL; 11447 } else { 11448 user = new UserHandle(userId); 11449 } 11450 11451 // Only system components can circumvent runtime permissions when installing. 11452 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11453 && mContext.checkCallingOrSelfPermission(Manifest.permission 11454 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11455 throw new SecurityException("You need the " 11456 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11457 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11458 } 11459 11460 final File originFile = new File(originPath); 11461 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11462 11463 final Message msg = mHandler.obtainMessage(INIT_COPY); 11464 final VerificationInfo verificationInfo = new VerificationInfo( 11465 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11466 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11467 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11468 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11469 null /*certificates*/); 11470 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11471 msg.obj = params; 11472 11473 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11474 System.identityHashCode(msg.obj)); 11475 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11476 System.identityHashCode(msg.obj)); 11477 11478 mHandler.sendMessage(msg); 11479 } 11480 11481 void installStage(String packageName, File stagedDir, String stagedCid, 11482 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11483 String installerPackageName, int installerUid, UserHandle user, 11484 Certificate[][] certificates) { 11485 if (DEBUG_EPHEMERAL) { 11486 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11487 Slog.d(TAG, "Ephemeral install of " + packageName); 11488 } 11489 } 11490 final VerificationInfo verificationInfo = new VerificationInfo( 11491 sessionParams.originatingUri, sessionParams.referrerUri, 11492 sessionParams.originatingUid, installerUid); 11493 11494 final OriginInfo origin; 11495 if (stagedDir != null) { 11496 origin = OriginInfo.fromStagedFile(stagedDir); 11497 } else { 11498 origin = OriginInfo.fromStagedContainer(stagedCid); 11499 } 11500 11501 final Message msg = mHandler.obtainMessage(INIT_COPY); 11502 final InstallParams params = new InstallParams(origin, null, observer, 11503 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11504 verificationInfo, user, sessionParams.abiOverride, 11505 sessionParams.grantedRuntimePermissions, certificates); 11506 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11507 msg.obj = params; 11508 11509 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11510 System.identityHashCode(msg.obj)); 11511 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11512 System.identityHashCode(msg.obj)); 11513 11514 mHandler.sendMessage(msg); 11515 } 11516 11517 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11518 int userId) { 11519 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11520 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11521 } 11522 11523 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11524 int appId, int userId) { 11525 Bundle extras = new Bundle(1); 11526 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11527 11528 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11529 packageName, extras, 0, null, null, new int[] {userId}); 11530 try { 11531 IActivityManager am = ActivityManagerNative.getDefault(); 11532 if (isSystem && am.isUserRunning(userId, 0)) { 11533 // The just-installed/enabled app is bundled on the system, so presumed 11534 // to be able to run automatically without needing an explicit launch. 11535 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11536 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11537 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11538 .setPackage(packageName); 11539 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11540 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11541 } 11542 } catch (RemoteException e) { 11543 // shouldn't happen 11544 Slog.w(TAG, "Unable to bootstrap installed package", e); 11545 } 11546 } 11547 11548 @Override 11549 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11550 int userId) { 11551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11552 PackageSetting pkgSetting; 11553 final int uid = Binder.getCallingUid(); 11554 enforceCrossUserPermission(uid, userId, 11555 true /* requireFullPermission */, true /* checkShell */, 11556 "setApplicationHiddenSetting for user " + userId); 11557 11558 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11559 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11560 return false; 11561 } 11562 11563 long callingId = Binder.clearCallingIdentity(); 11564 try { 11565 boolean sendAdded = false; 11566 boolean sendRemoved = false; 11567 // writer 11568 synchronized (mPackages) { 11569 pkgSetting = mSettings.mPackages.get(packageName); 11570 if (pkgSetting == null) { 11571 return false; 11572 } 11573 // Do not allow "android" is being disabled 11574 if ("android".equals(packageName)) { 11575 Slog.w(TAG, "Cannot hide package: android"); 11576 return false; 11577 } 11578 // Only allow protected packages to hide themselves. 11579 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11580 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11581 Slog.w(TAG, "Not hiding protected package: " + packageName); 11582 return false; 11583 } 11584 11585 if (pkgSetting.getHidden(userId) != hidden) { 11586 pkgSetting.setHidden(hidden, userId); 11587 mSettings.writePackageRestrictionsLPr(userId); 11588 if (hidden) { 11589 sendRemoved = true; 11590 } else { 11591 sendAdded = true; 11592 } 11593 } 11594 } 11595 if (sendAdded) { 11596 sendPackageAddedForUser(packageName, pkgSetting, userId); 11597 return true; 11598 } 11599 if (sendRemoved) { 11600 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11601 "hiding pkg"); 11602 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11603 return true; 11604 } 11605 } finally { 11606 Binder.restoreCallingIdentity(callingId); 11607 } 11608 return false; 11609 } 11610 11611 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11612 int userId) { 11613 final PackageRemovedInfo info = new PackageRemovedInfo(); 11614 info.removedPackage = packageName; 11615 info.removedUsers = new int[] {userId}; 11616 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11617 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11618 } 11619 11620 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11621 if (pkgList.length > 0) { 11622 Bundle extras = new Bundle(1); 11623 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11624 11625 sendPackageBroadcast( 11626 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11627 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11628 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11629 new int[] {userId}); 11630 } 11631 } 11632 11633 /** 11634 * Returns true if application is not found or there was an error. Otherwise it returns 11635 * the hidden state of the package for the given user. 11636 */ 11637 @Override 11638 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11640 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11641 true /* requireFullPermission */, false /* checkShell */, 11642 "getApplicationHidden for user " + userId); 11643 PackageSetting pkgSetting; 11644 long callingId = Binder.clearCallingIdentity(); 11645 try { 11646 // writer 11647 synchronized (mPackages) { 11648 pkgSetting = mSettings.mPackages.get(packageName); 11649 if (pkgSetting == null) { 11650 return true; 11651 } 11652 return pkgSetting.getHidden(userId); 11653 } 11654 } finally { 11655 Binder.restoreCallingIdentity(callingId); 11656 } 11657 } 11658 11659 /** 11660 * @hide 11661 */ 11662 @Override 11663 public int installExistingPackageAsUser(String packageName, int userId) { 11664 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11665 null); 11666 PackageSetting pkgSetting; 11667 final int uid = Binder.getCallingUid(); 11668 enforceCrossUserPermission(uid, userId, 11669 true /* requireFullPermission */, true /* checkShell */, 11670 "installExistingPackage for user " + userId); 11671 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11672 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11673 } 11674 11675 long callingId = Binder.clearCallingIdentity(); 11676 try { 11677 boolean installed = false; 11678 11679 // writer 11680 synchronized (mPackages) { 11681 pkgSetting = mSettings.mPackages.get(packageName); 11682 if (pkgSetting == null) { 11683 return PackageManager.INSTALL_FAILED_INVALID_URI; 11684 } 11685 if (!pkgSetting.getInstalled(userId)) { 11686 pkgSetting.setInstalled(true, userId); 11687 pkgSetting.setHidden(false, userId); 11688 mSettings.writePackageRestrictionsLPr(userId); 11689 installed = true; 11690 } 11691 } 11692 11693 if (installed) { 11694 if (pkgSetting.pkg != null) { 11695 synchronized (mInstallLock) { 11696 // We don't need to freeze for a brand new install 11697 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11698 } 11699 } 11700 sendPackageAddedForUser(packageName, pkgSetting, userId); 11701 } 11702 } finally { 11703 Binder.restoreCallingIdentity(callingId); 11704 } 11705 11706 return PackageManager.INSTALL_SUCCEEDED; 11707 } 11708 11709 boolean isUserRestricted(int userId, String restrictionKey) { 11710 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11711 if (restrictions.getBoolean(restrictionKey, false)) { 11712 Log.w(TAG, "User is restricted: " + restrictionKey); 11713 return true; 11714 } 11715 return false; 11716 } 11717 11718 @Override 11719 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11720 int userId) { 11721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11722 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11723 true /* requireFullPermission */, true /* checkShell */, 11724 "setPackagesSuspended for user " + userId); 11725 11726 if (ArrayUtils.isEmpty(packageNames)) { 11727 return packageNames; 11728 } 11729 11730 // List of package names for whom the suspended state has changed. 11731 List<String> changedPackages = new ArrayList<>(packageNames.length); 11732 // List of package names for whom the suspended state is not set as requested in this 11733 // method. 11734 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11735 long callingId = Binder.clearCallingIdentity(); 11736 try { 11737 for (int i = 0; i < packageNames.length; i++) { 11738 String packageName = packageNames[i]; 11739 boolean changed = false; 11740 final int appId; 11741 synchronized (mPackages) { 11742 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11743 if (pkgSetting == null) { 11744 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11745 + "\". Skipping suspending/un-suspending."); 11746 unactionedPackages.add(packageName); 11747 continue; 11748 } 11749 appId = pkgSetting.appId; 11750 if (pkgSetting.getSuspended(userId) != suspended) { 11751 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11752 unactionedPackages.add(packageName); 11753 continue; 11754 } 11755 pkgSetting.setSuspended(suspended, userId); 11756 mSettings.writePackageRestrictionsLPr(userId); 11757 changed = true; 11758 changedPackages.add(packageName); 11759 } 11760 } 11761 11762 if (changed && suspended) { 11763 killApplication(packageName, UserHandle.getUid(userId, appId), 11764 "suspending package"); 11765 } 11766 } 11767 } finally { 11768 Binder.restoreCallingIdentity(callingId); 11769 } 11770 11771 if (!changedPackages.isEmpty()) { 11772 sendPackagesSuspendedForUser(changedPackages.toArray( 11773 new String[changedPackages.size()]), userId, suspended); 11774 } 11775 11776 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11777 } 11778 11779 @Override 11780 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11781 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11782 true /* requireFullPermission */, false /* checkShell */, 11783 "isPackageSuspendedForUser for user " + userId); 11784 synchronized (mPackages) { 11785 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11786 if (pkgSetting == null) { 11787 throw new IllegalArgumentException("Unknown target package: " + packageName); 11788 } 11789 return pkgSetting.getSuspended(userId); 11790 } 11791 } 11792 11793 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11794 if (isPackageDeviceAdmin(packageName, userId)) { 11795 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11796 + "\": has an active device admin"); 11797 return false; 11798 } 11799 11800 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11801 if (packageName.equals(activeLauncherPackageName)) { 11802 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11803 + "\": contains the active launcher"); 11804 return false; 11805 } 11806 11807 if (packageName.equals(mRequiredInstallerPackage)) { 11808 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11809 + "\": required for package installation"); 11810 return false; 11811 } 11812 11813 if (packageName.equals(mRequiredVerifierPackage)) { 11814 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11815 + "\": required for package verification"); 11816 return false; 11817 } 11818 11819 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11820 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11821 + "\": is the default dialer"); 11822 return false; 11823 } 11824 11825 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11826 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11827 + "\": protected package"); 11828 return false; 11829 } 11830 11831 return true; 11832 } 11833 11834 private String getActiveLauncherPackageName(int userId) { 11835 Intent intent = new Intent(Intent.ACTION_MAIN); 11836 intent.addCategory(Intent.CATEGORY_HOME); 11837 ResolveInfo resolveInfo = resolveIntent( 11838 intent, 11839 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11840 PackageManager.MATCH_DEFAULT_ONLY, 11841 userId); 11842 11843 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11844 } 11845 11846 private String getDefaultDialerPackageName(int userId) { 11847 synchronized (mPackages) { 11848 return mSettings.getDefaultDialerPackageNameLPw(userId); 11849 } 11850 } 11851 11852 @Override 11853 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11854 mContext.enforceCallingOrSelfPermission( 11855 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11856 "Only package verification agents can verify applications"); 11857 11858 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11859 final PackageVerificationResponse response = new PackageVerificationResponse( 11860 verificationCode, Binder.getCallingUid()); 11861 msg.arg1 = id; 11862 msg.obj = response; 11863 mHandler.sendMessage(msg); 11864 } 11865 11866 @Override 11867 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11868 long millisecondsToDelay) { 11869 mContext.enforceCallingOrSelfPermission( 11870 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11871 "Only package verification agents can extend verification timeouts"); 11872 11873 final PackageVerificationState state = mPendingVerification.get(id); 11874 final PackageVerificationResponse response = new PackageVerificationResponse( 11875 verificationCodeAtTimeout, Binder.getCallingUid()); 11876 11877 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11878 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11879 } 11880 if (millisecondsToDelay < 0) { 11881 millisecondsToDelay = 0; 11882 } 11883 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11884 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11885 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11886 } 11887 11888 if ((state != null) && !state.timeoutExtended()) { 11889 state.extendTimeout(); 11890 11891 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11892 msg.arg1 = id; 11893 msg.obj = response; 11894 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11895 } 11896 } 11897 11898 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11899 int verificationCode, UserHandle user) { 11900 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11901 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11902 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11903 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11904 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11905 11906 mContext.sendBroadcastAsUser(intent, user, 11907 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11908 } 11909 11910 private ComponentName matchComponentForVerifier(String packageName, 11911 List<ResolveInfo> receivers) { 11912 ActivityInfo targetReceiver = null; 11913 11914 final int NR = receivers.size(); 11915 for (int i = 0; i < NR; i++) { 11916 final ResolveInfo info = receivers.get(i); 11917 if (info.activityInfo == null) { 11918 continue; 11919 } 11920 11921 if (packageName.equals(info.activityInfo.packageName)) { 11922 targetReceiver = info.activityInfo; 11923 break; 11924 } 11925 } 11926 11927 if (targetReceiver == null) { 11928 return null; 11929 } 11930 11931 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11932 } 11933 11934 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11935 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11936 if (pkgInfo.verifiers.length == 0) { 11937 return null; 11938 } 11939 11940 final int N = pkgInfo.verifiers.length; 11941 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11942 for (int i = 0; i < N; i++) { 11943 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11944 11945 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11946 receivers); 11947 if (comp == null) { 11948 continue; 11949 } 11950 11951 final int verifierUid = getUidForVerifier(verifierInfo); 11952 if (verifierUid == -1) { 11953 continue; 11954 } 11955 11956 if (DEBUG_VERIFY) { 11957 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11958 + " with the correct signature"); 11959 } 11960 sufficientVerifiers.add(comp); 11961 verificationState.addSufficientVerifier(verifierUid); 11962 } 11963 11964 return sufficientVerifiers; 11965 } 11966 11967 private int getUidForVerifier(VerifierInfo verifierInfo) { 11968 synchronized (mPackages) { 11969 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11970 if (pkg == null) { 11971 return -1; 11972 } else if (pkg.mSignatures.length != 1) { 11973 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11974 + " has more than one signature; ignoring"); 11975 return -1; 11976 } 11977 11978 /* 11979 * If the public key of the package's signature does not match 11980 * our expected public key, then this is a different package and 11981 * we should skip. 11982 */ 11983 11984 final byte[] expectedPublicKey; 11985 try { 11986 final Signature verifierSig = pkg.mSignatures[0]; 11987 final PublicKey publicKey = verifierSig.getPublicKey(); 11988 expectedPublicKey = publicKey.getEncoded(); 11989 } catch (CertificateException e) { 11990 return -1; 11991 } 11992 11993 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11994 11995 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11996 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11997 + " does not have the expected public key; ignoring"); 11998 return -1; 11999 } 12000 12001 return pkg.applicationInfo.uid; 12002 } 12003 } 12004 12005 @Override 12006 public void finishPackageInstall(int token, boolean didLaunch) { 12007 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12008 12009 if (DEBUG_INSTALL) { 12010 Slog.v(TAG, "BM finishing package install for " + token); 12011 } 12012 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12013 12014 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12015 mHandler.sendMessage(msg); 12016 } 12017 12018 /** 12019 * Get the verification agent timeout. 12020 * 12021 * @return verification timeout in milliseconds 12022 */ 12023 private long getVerificationTimeout() { 12024 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12025 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12026 DEFAULT_VERIFICATION_TIMEOUT); 12027 } 12028 12029 /** 12030 * Get the default verification agent response code. 12031 * 12032 * @return default verification response code 12033 */ 12034 private int getDefaultVerificationResponse() { 12035 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12036 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12037 DEFAULT_VERIFICATION_RESPONSE); 12038 } 12039 12040 /** 12041 * Check whether or not package verification has been enabled. 12042 * 12043 * @return true if verification should be performed 12044 */ 12045 private boolean isVerificationEnabled(int userId, int installFlags) { 12046 if (!DEFAULT_VERIFY_ENABLE) { 12047 return false; 12048 } 12049 // Ephemeral apps don't get the full verification treatment 12050 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12051 if (DEBUG_EPHEMERAL) { 12052 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12053 } 12054 return false; 12055 } 12056 12057 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12058 12059 // Check if installing from ADB 12060 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12061 // Do not run verification in a test harness environment 12062 if (ActivityManager.isRunningInTestHarness()) { 12063 return false; 12064 } 12065 if (ensureVerifyAppsEnabled) { 12066 return true; 12067 } 12068 // Check if the developer does not want package verification for ADB installs 12069 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12070 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12071 return false; 12072 } 12073 } 12074 12075 if (ensureVerifyAppsEnabled) { 12076 return true; 12077 } 12078 12079 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12080 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12081 } 12082 12083 @Override 12084 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12085 throws RemoteException { 12086 mContext.enforceCallingOrSelfPermission( 12087 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12088 "Only intentfilter verification agents can verify applications"); 12089 12090 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12091 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12092 Binder.getCallingUid(), verificationCode, failedDomains); 12093 msg.arg1 = id; 12094 msg.obj = response; 12095 mHandler.sendMessage(msg); 12096 } 12097 12098 @Override 12099 public int getIntentVerificationStatus(String packageName, int userId) { 12100 synchronized (mPackages) { 12101 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12102 } 12103 } 12104 12105 @Override 12106 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12107 mContext.enforceCallingOrSelfPermission( 12108 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12109 12110 boolean result = false; 12111 synchronized (mPackages) { 12112 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12113 } 12114 if (result) { 12115 scheduleWritePackageRestrictionsLocked(userId); 12116 } 12117 return result; 12118 } 12119 12120 @Override 12121 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12122 String packageName) { 12123 synchronized (mPackages) { 12124 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12125 } 12126 } 12127 12128 @Override 12129 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12130 if (TextUtils.isEmpty(packageName)) { 12131 return ParceledListSlice.emptyList(); 12132 } 12133 synchronized (mPackages) { 12134 PackageParser.Package pkg = mPackages.get(packageName); 12135 if (pkg == null || pkg.activities == null) { 12136 return ParceledListSlice.emptyList(); 12137 } 12138 final int count = pkg.activities.size(); 12139 ArrayList<IntentFilter> result = new ArrayList<>(); 12140 for (int n=0; n<count; n++) { 12141 PackageParser.Activity activity = pkg.activities.get(n); 12142 if (activity.intents != null && activity.intents.size() > 0) { 12143 result.addAll(activity.intents); 12144 } 12145 } 12146 return new ParceledListSlice<>(result); 12147 } 12148 } 12149 12150 @Override 12151 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12152 mContext.enforceCallingOrSelfPermission( 12153 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12154 12155 synchronized (mPackages) { 12156 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12157 if (packageName != null) { 12158 result |= updateIntentVerificationStatus(packageName, 12159 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12160 userId); 12161 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12162 packageName, userId); 12163 } 12164 return result; 12165 } 12166 } 12167 12168 @Override 12169 public String getDefaultBrowserPackageName(int userId) { 12170 synchronized (mPackages) { 12171 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12172 } 12173 } 12174 12175 /** 12176 * Get the "allow unknown sources" setting. 12177 * 12178 * @return the current "allow unknown sources" setting 12179 */ 12180 private int getUnknownSourcesSettings() { 12181 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12182 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12183 -1); 12184 } 12185 12186 @Override 12187 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12188 final int uid = Binder.getCallingUid(); 12189 // writer 12190 synchronized (mPackages) { 12191 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12192 if (targetPackageSetting == null) { 12193 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12194 } 12195 12196 PackageSetting installerPackageSetting; 12197 if (installerPackageName != null) { 12198 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12199 if (installerPackageSetting == null) { 12200 throw new IllegalArgumentException("Unknown installer package: " 12201 + installerPackageName); 12202 } 12203 } else { 12204 installerPackageSetting = null; 12205 } 12206 12207 Signature[] callerSignature; 12208 Object obj = mSettings.getUserIdLPr(uid); 12209 if (obj != null) { 12210 if (obj instanceof SharedUserSetting) { 12211 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12212 } else if (obj instanceof PackageSetting) { 12213 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12214 } else { 12215 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12216 } 12217 } else { 12218 throw new SecurityException("Unknown calling UID: " + uid); 12219 } 12220 12221 // Verify: can't set installerPackageName to a package that is 12222 // not signed with the same cert as the caller. 12223 if (installerPackageSetting != null) { 12224 if (compareSignatures(callerSignature, 12225 installerPackageSetting.signatures.mSignatures) 12226 != PackageManager.SIGNATURE_MATCH) { 12227 throw new SecurityException( 12228 "Caller does not have same cert as new installer package " 12229 + installerPackageName); 12230 } 12231 } 12232 12233 // Verify: if target already has an installer package, it must 12234 // be signed with the same cert as the caller. 12235 if (targetPackageSetting.installerPackageName != null) { 12236 PackageSetting setting = mSettings.mPackages.get( 12237 targetPackageSetting.installerPackageName); 12238 // If the currently set package isn't valid, then it's always 12239 // okay to change it. 12240 if (setting != null) { 12241 if (compareSignatures(callerSignature, 12242 setting.signatures.mSignatures) 12243 != PackageManager.SIGNATURE_MATCH) { 12244 throw new SecurityException( 12245 "Caller does not have same cert as old installer package " 12246 + targetPackageSetting.installerPackageName); 12247 } 12248 } 12249 } 12250 12251 // Okay! 12252 targetPackageSetting.installerPackageName = installerPackageName; 12253 if (installerPackageName != null) { 12254 mSettings.mInstallerPackages.add(installerPackageName); 12255 } 12256 scheduleWriteSettingsLocked(); 12257 } 12258 } 12259 12260 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12261 // Queue up an async operation since the package installation may take a little while. 12262 mHandler.post(new Runnable() { 12263 public void run() { 12264 mHandler.removeCallbacks(this); 12265 // Result object to be returned 12266 PackageInstalledInfo res = new PackageInstalledInfo(); 12267 res.setReturnCode(currentStatus); 12268 res.uid = -1; 12269 res.pkg = null; 12270 res.removedInfo = null; 12271 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12272 args.doPreInstall(res.returnCode); 12273 synchronized (mInstallLock) { 12274 installPackageTracedLI(args, res); 12275 } 12276 args.doPostInstall(res.returnCode, res.uid); 12277 } 12278 12279 // A restore should be performed at this point if (a) the install 12280 // succeeded, (b) the operation is not an update, and (c) the new 12281 // package has not opted out of backup participation. 12282 final boolean update = res.removedInfo != null 12283 && res.removedInfo.removedPackage != null; 12284 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12285 boolean doRestore = !update 12286 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12287 12288 // Set up the post-install work request bookkeeping. This will be used 12289 // and cleaned up by the post-install event handling regardless of whether 12290 // there's a restore pass performed. Token values are >= 1. 12291 int token; 12292 if (mNextInstallToken < 0) mNextInstallToken = 1; 12293 token = mNextInstallToken++; 12294 12295 PostInstallData data = new PostInstallData(args, res); 12296 mRunningInstalls.put(token, data); 12297 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12298 12299 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12300 // Pass responsibility to the Backup Manager. It will perform a 12301 // restore if appropriate, then pass responsibility back to the 12302 // Package Manager to run the post-install observer callbacks 12303 // and broadcasts. 12304 IBackupManager bm = IBackupManager.Stub.asInterface( 12305 ServiceManager.getService(Context.BACKUP_SERVICE)); 12306 if (bm != null) { 12307 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12308 + " to BM for possible restore"); 12309 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12310 try { 12311 // TODO: http://b/22388012 12312 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12313 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12314 } else { 12315 doRestore = false; 12316 } 12317 } catch (RemoteException e) { 12318 // can't happen; the backup manager is local 12319 } catch (Exception e) { 12320 Slog.e(TAG, "Exception trying to enqueue restore", e); 12321 doRestore = false; 12322 } 12323 } else { 12324 Slog.e(TAG, "Backup Manager not found!"); 12325 doRestore = false; 12326 } 12327 } 12328 12329 if (!doRestore) { 12330 // No restore possible, or the Backup Manager was mysteriously not 12331 // available -- just fire the post-install work request directly. 12332 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12333 12334 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12335 12336 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12337 mHandler.sendMessage(msg); 12338 } 12339 } 12340 }); 12341 } 12342 12343 /** 12344 * Callback from PackageSettings whenever an app is first transitioned out of the 12345 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12346 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12347 * here whether the app is the target of an ongoing install, and only send the 12348 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12349 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12350 * handling. 12351 */ 12352 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12353 // Serialize this with the rest of the install-process message chain. In the 12354 // restore-at-install case, this Runnable will necessarily run before the 12355 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12356 // are coherent. In the non-restore case, the app has already completed install 12357 // and been launched through some other means, so it is not in a problematic 12358 // state for observers to see the FIRST_LAUNCH signal. 12359 mHandler.post(new Runnable() { 12360 @Override 12361 public void run() { 12362 for (int i = 0; i < mRunningInstalls.size(); i++) { 12363 final PostInstallData data = mRunningInstalls.valueAt(i); 12364 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12365 continue; 12366 } 12367 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12368 // right package; but is it for the right user? 12369 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12370 if (userId == data.res.newUsers[uIndex]) { 12371 if (DEBUG_BACKUP) { 12372 Slog.i(TAG, "Package " + pkgName 12373 + " being restored so deferring FIRST_LAUNCH"); 12374 } 12375 return; 12376 } 12377 } 12378 } 12379 } 12380 // didn't find it, so not being restored 12381 if (DEBUG_BACKUP) { 12382 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12383 } 12384 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12385 } 12386 }); 12387 } 12388 12389 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12390 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12391 installerPkg, null, userIds); 12392 } 12393 12394 private abstract class HandlerParams { 12395 private static final int MAX_RETRIES = 4; 12396 12397 /** 12398 * Number of times startCopy() has been attempted and had a non-fatal 12399 * error. 12400 */ 12401 private int mRetries = 0; 12402 12403 /** User handle for the user requesting the information or installation. */ 12404 private final UserHandle mUser; 12405 String traceMethod; 12406 int traceCookie; 12407 12408 HandlerParams(UserHandle user) { 12409 mUser = user; 12410 } 12411 12412 UserHandle getUser() { 12413 return mUser; 12414 } 12415 12416 HandlerParams setTraceMethod(String traceMethod) { 12417 this.traceMethod = traceMethod; 12418 return this; 12419 } 12420 12421 HandlerParams setTraceCookie(int traceCookie) { 12422 this.traceCookie = traceCookie; 12423 return this; 12424 } 12425 12426 final boolean startCopy() { 12427 boolean res; 12428 try { 12429 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12430 12431 if (++mRetries > MAX_RETRIES) { 12432 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12433 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12434 handleServiceError(); 12435 return false; 12436 } else { 12437 handleStartCopy(); 12438 res = true; 12439 } 12440 } catch (RemoteException e) { 12441 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12442 mHandler.sendEmptyMessage(MCS_RECONNECT); 12443 res = false; 12444 } 12445 handleReturnCode(); 12446 return res; 12447 } 12448 12449 final void serviceError() { 12450 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12451 handleServiceError(); 12452 handleReturnCode(); 12453 } 12454 12455 abstract void handleStartCopy() throws RemoteException; 12456 abstract void handleServiceError(); 12457 abstract void handleReturnCode(); 12458 } 12459 12460 class MeasureParams extends HandlerParams { 12461 private final PackageStats mStats; 12462 private boolean mSuccess; 12463 12464 private final IPackageStatsObserver mObserver; 12465 12466 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12467 super(new UserHandle(stats.userHandle)); 12468 mObserver = observer; 12469 mStats = stats; 12470 } 12471 12472 @Override 12473 public String toString() { 12474 return "MeasureParams{" 12475 + Integer.toHexString(System.identityHashCode(this)) 12476 + " " + mStats.packageName + "}"; 12477 } 12478 12479 @Override 12480 void handleStartCopy() throws RemoteException { 12481 synchronized (mInstallLock) { 12482 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12483 } 12484 12485 if (mSuccess) { 12486 boolean mounted = false; 12487 try { 12488 final String status = Environment.getExternalStorageState(); 12489 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12490 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12491 } catch (Exception e) { 12492 } 12493 12494 if (mounted) { 12495 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12496 12497 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12498 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12499 12500 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12501 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12502 12503 // Always subtract cache size, since it's a subdirectory 12504 mStats.externalDataSize -= mStats.externalCacheSize; 12505 12506 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12507 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12508 12509 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12510 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12511 } 12512 } 12513 } 12514 12515 @Override 12516 void handleReturnCode() { 12517 if (mObserver != null) { 12518 try { 12519 mObserver.onGetStatsCompleted(mStats, mSuccess); 12520 } catch (RemoteException e) { 12521 Slog.i(TAG, "Observer no longer exists."); 12522 } 12523 } 12524 } 12525 12526 @Override 12527 void handleServiceError() { 12528 Slog.e(TAG, "Could not measure application " + mStats.packageName 12529 + " external storage"); 12530 } 12531 } 12532 12533 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12534 throws RemoteException { 12535 long result = 0; 12536 for (File path : paths) { 12537 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12538 } 12539 return result; 12540 } 12541 12542 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12543 for (File path : paths) { 12544 try { 12545 mcs.clearDirectory(path.getAbsolutePath()); 12546 } catch (RemoteException e) { 12547 } 12548 } 12549 } 12550 12551 static class OriginInfo { 12552 /** 12553 * Location where install is coming from, before it has been 12554 * copied/renamed into place. This could be a single monolithic APK 12555 * file, or a cluster directory. This location may be untrusted. 12556 */ 12557 final File file; 12558 final String cid; 12559 12560 /** 12561 * Flag indicating that {@link #file} or {@link #cid} has already been 12562 * staged, meaning downstream users don't need to defensively copy the 12563 * contents. 12564 */ 12565 final boolean staged; 12566 12567 /** 12568 * Flag indicating that {@link #file} or {@link #cid} is an already 12569 * installed app that is being moved. 12570 */ 12571 final boolean existing; 12572 12573 final String resolvedPath; 12574 final File resolvedFile; 12575 12576 static OriginInfo fromNothing() { 12577 return new OriginInfo(null, null, false, false); 12578 } 12579 12580 static OriginInfo fromUntrustedFile(File file) { 12581 return new OriginInfo(file, null, false, false); 12582 } 12583 12584 static OriginInfo fromExistingFile(File file) { 12585 return new OriginInfo(file, null, false, true); 12586 } 12587 12588 static OriginInfo fromStagedFile(File file) { 12589 return new OriginInfo(file, null, true, false); 12590 } 12591 12592 static OriginInfo fromStagedContainer(String cid) { 12593 return new OriginInfo(null, cid, true, false); 12594 } 12595 12596 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12597 this.file = file; 12598 this.cid = cid; 12599 this.staged = staged; 12600 this.existing = existing; 12601 12602 if (cid != null) { 12603 resolvedPath = PackageHelper.getSdDir(cid); 12604 resolvedFile = new File(resolvedPath); 12605 } else if (file != null) { 12606 resolvedPath = file.getAbsolutePath(); 12607 resolvedFile = file; 12608 } else { 12609 resolvedPath = null; 12610 resolvedFile = null; 12611 } 12612 } 12613 } 12614 12615 static class MoveInfo { 12616 final int moveId; 12617 final String fromUuid; 12618 final String toUuid; 12619 final String packageName; 12620 final String dataAppName; 12621 final int appId; 12622 final String seinfo; 12623 final int targetSdkVersion; 12624 12625 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12626 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12627 this.moveId = moveId; 12628 this.fromUuid = fromUuid; 12629 this.toUuid = toUuid; 12630 this.packageName = packageName; 12631 this.dataAppName = dataAppName; 12632 this.appId = appId; 12633 this.seinfo = seinfo; 12634 this.targetSdkVersion = targetSdkVersion; 12635 } 12636 } 12637 12638 static class VerificationInfo { 12639 /** A constant used to indicate that a uid value is not present. */ 12640 public static final int NO_UID = -1; 12641 12642 /** URI referencing where the package was downloaded from. */ 12643 final Uri originatingUri; 12644 12645 /** HTTP referrer URI associated with the originatingURI. */ 12646 final Uri referrer; 12647 12648 /** UID of the application that the install request originated from. */ 12649 final int originatingUid; 12650 12651 /** UID of application requesting the install */ 12652 final int installerUid; 12653 12654 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12655 this.originatingUri = originatingUri; 12656 this.referrer = referrer; 12657 this.originatingUid = originatingUid; 12658 this.installerUid = installerUid; 12659 } 12660 } 12661 12662 class InstallParams extends HandlerParams { 12663 final OriginInfo origin; 12664 final MoveInfo move; 12665 final IPackageInstallObserver2 observer; 12666 int installFlags; 12667 final String installerPackageName; 12668 final String volumeUuid; 12669 private InstallArgs mArgs; 12670 private int mRet; 12671 final String packageAbiOverride; 12672 final String[] grantedRuntimePermissions; 12673 final VerificationInfo verificationInfo; 12674 final Certificate[][] certificates; 12675 12676 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12677 int installFlags, String installerPackageName, String volumeUuid, 12678 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12679 String[] grantedPermissions, Certificate[][] certificates) { 12680 super(user); 12681 this.origin = origin; 12682 this.move = move; 12683 this.observer = observer; 12684 this.installFlags = installFlags; 12685 this.installerPackageName = installerPackageName; 12686 this.volumeUuid = volumeUuid; 12687 this.verificationInfo = verificationInfo; 12688 this.packageAbiOverride = packageAbiOverride; 12689 this.grantedRuntimePermissions = grantedPermissions; 12690 this.certificates = certificates; 12691 } 12692 12693 @Override 12694 public String toString() { 12695 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12696 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12697 } 12698 12699 private int installLocationPolicy(PackageInfoLite pkgLite) { 12700 String packageName = pkgLite.packageName; 12701 int installLocation = pkgLite.installLocation; 12702 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12703 // reader 12704 synchronized (mPackages) { 12705 // Currently installed package which the new package is attempting to replace or 12706 // null if no such package is installed. 12707 PackageParser.Package installedPkg = mPackages.get(packageName); 12708 // Package which currently owns the data which the new package will own if installed. 12709 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12710 // will be null whereas dataOwnerPkg will contain information about the package 12711 // which was uninstalled while keeping its data. 12712 PackageParser.Package dataOwnerPkg = installedPkg; 12713 if (dataOwnerPkg == null) { 12714 PackageSetting ps = mSettings.mPackages.get(packageName); 12715 if (ps != null) { 12716 dataOwnerPkg = ps.pkg; 12717 } 12718 } 12719 12720 if (dataOwnerPkg != null) { 12721 // If installed, the package will get access to data left on the device by its 12722 // predecessor. As a security measure, this is permited only if this is not a 12723 // version downgrade or if the predecessor package is marked as debuggable and 12724 // a downgrade is explicitly requested. 12725 // 12726 // On debuggable platform builds, downgrades are permitted even for 12727 // non-debuggable packages to make testing easier. Debuggable platform builds do 12728 // not offer security guarantees and thus it's OK to disable some security 12729 // mechanisms to make debugging/testing easier on those builds. However, even on 12730 // debuggable builds downgrades of packages are permitted only if requested via 12731 // installFlags. This is because we aim to keep the behavior of debuggable 12732 // platform builds as close as possible to the behavior of non-debuggable 12733 // platform builds. 12734 final boolean downgradeRequested = 12735 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12736 final boolean packageDebuggable = 12737 (dataOwnerPkg.applicationInfo.flags 12738 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12739 final boolean downgradePermitted = 12740 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12741 if (!downgradePermitted) { 12742 try { 12743 checkDowngrade(dataOwnerPkg, pkgLite); 12744 } catch (PackageManagerException e) { 12745 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12746 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12747 } 12748 } 12749 } 12750 12751 if (installedPkg != null) { 12752 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12753 // Check for updated system application. 12754 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12755 if (onSd) { 12756 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12757 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12758 } 12759 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12760 } else { 12761 if (onSd) { 12762 // Install flag overrides everything. 12763 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12764 } 12765 // If current upgrade specifies particular preference 12766 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12767 // Application explicitly specified internal. 12768 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12769 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12770 // App explictly prefers external. Let policy decide 12771 } else { 12772 // Prefer previous location 12773 if (isExternal(installedPkg)) { 12774 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12775 } 12776 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12777 } 12778 } 12779 } else { 12780 // Invalid install. Return error code 12781 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12782 } 12783 } 12784 } 12785 // All the special cases have been taken care of. 12786 // Return result based on recommended install location. 12787 if (onSd) { 12788 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12789 } 12790 return pkgLite.recommendedInstallLocation; 12791 } 12792 12793 /* 12794 * Invoke remote method to get package information and install 12795 * location values. Override install location based on default 12796 * policy if needed and then create install arguments based 12797 * on the install location. 12798 */ 12799 public void handleStartCopy() throws RemoteException { 12800 int ret = PackageManager.INSTALL_SUCCEEDED; 12801 12802 // If we're already staged, we've firmly committed to an install location 12803 if (origin.staged) { 12804 if (origin.file != null) { 12805 installFlags |= PackageManager.INSTALL_INTERNAL; 12806 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12807 } else if (origin.cid != null) { 12808 installFlags |= PackageManager.INSTALL_EXTERNAL; 12809 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12810 } else { 12811 throw new IllegalStateException("Invalid stage location"); 12812 } 12813 } 12814 12815 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12816 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12817 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12818 PackageInfoLite pkgLite = null; 12819 12820 if (onInt && onSd) { 12821 // Check if both bits are set. 12822 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12823 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12824 } else if (onSd && ephemeral) { 12825 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12826 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12827 } else { 12828 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12829 packageAbiOverride); 12830 12831 if (DEBUG_EPHEMERAL && ephemeral) { 12832 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12833 } 12834 12835 /* 12836 * If we have too little free space, try to free cache 12837 * before giving up. 12838 */ 12839 if (!origin.staged && pkgLite.recommendedInstallLocation 12840 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12841 // TODO: focus freeing disk space on the target device 12842 final StorageManager storage = StorageManager.from(mContext); 12843 final long lowThreshold = storage.getStorageLowBytes( 12844 Environment.getDataDirectory()); 12845 12846 final long sizeBytes = mContainerService.calculateInstalledSize( 12847 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12848 12849 try { 12850 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12851 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12852 installFlags, packageAbiOverride); 12853 } catch (InstallerException e) { 12854 Slog.w(TAG, "Failed to free cache", e); 12855 } 12856 12857 /* 12858 * The cache free must have deleted the file we 12859 * downloaded to install. 12860 * 12861 * TODO: fix the "freeCache" call to not delete 12862 * the file we care about. 12863 */ 12864 if (pkgLite.recommendedInstallLocation 12865 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12866 pkgLite.recommendedInstallLocation 12867 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12868 } 12869 } 12870 } 12871 12872 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12873 int loc = pkgLite.recommendedInstallLocation; 12874 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12875 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12876 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12877 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12878 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12879 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12880 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12881 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12882 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12883 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12884 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12885 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12886 } else { 12887 // Override with defaults if needed. 12888 loc = installLocationPolicy(pkgLite); 12889 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12890 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12891 } else if (!onSd && !onInt) { 12892 // Override install location with flags 12893 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12894 // Set the flag to install on external media. 12895 installFlags |= PackageManager.INSTALL_EXTERNAL; 12896 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12897 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12898 if (DEBUG_EPHEMERAL) { 12899 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12900 } 12901 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12902 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12903 |PackageManager.INSTALL_INTERNAL); 12904 } else { 12905 // Make sure the flag for installing on external 12906 // media is unset 12907 installFlags |= PackageManager.INSTALL_INTERNAL; 12908 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12909 } 12910 } 12911 } 12912 } 12913 12914 final InstallArgs args = createInstallArgs(this); 12915 mArgs = args; 12916 12917 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12918 // TODO: http://b/22976637 12919 // Apps installed for "all" users use the device owner to verify the app 12920 UserHandle verifierUser = getUser(); 12921 if (verifierUser == UserHandle.ALL) { 12922 verifierUser = UserHandle.SYSTEM; 12923 } 12924 12925 /* 12926 * Determine if we have any installed package verifiers. If we 12927 * do, then we'll defer to them to verify the packages. 12928 */ 12929 final int requiredUid = mRequiredVerifierPackage == null ? -1 12930 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12931 verifierUser.getIdentifier()); 12932 if (!origin.existing && requiredUid != -1 12933 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12934 final Intent verification = new Intent( 12935 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12936 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12937 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12938 PACKAGE_MIME_TYPE); 12939 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12940 12941 // Query all live verifiers based on current user state 12942 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12943 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12944 12945 if (DEBUG_VERIFY) { 12946 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12947 + verification.toString() + " with " + pkgLite.verifiers.length 12948 + " optional verifiers"); 12949 } 12950 12951 final int verificationId = mPendingVerificationToken++; 12952 12953 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12954 12955 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12956 installerPackageName); 12957 12958 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12959 installFlags); 12960 12961 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12962 pkgLite.packageName); 12963 12964 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12965 pkgLite.versionCode); 12966 12967 if (verificationInfo != null) { 12968 if (verificationInfo.originatingUri != null) { 12969 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12970 verificationInfo.originatingUri); 12971 } 12972 if (verificationInfo.referrer != null) { 12973 verification.putExtra(Intent.EXTRA_REFERRER, 12974 verificationInfo.referrer); 12975 } 12976 if (verificationInfo.originatingUid >= 0) { 12977 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12978 verificationInfo.originatingUid); 12979 } 12980 if (verificationInfo.installerUid >= 0) { 12981 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12982 verificationInfo.installerUid); 12983 } 12984 } 12985 12986 final PackageVerificationState verificationState = new PackageVerificationState( 12987 requiredUid, args); 12988 12989 mPendingVerification.append(verificationId, verificationState); 12990 12991 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12992 receivers, verificationState); 12993 12994 /* 12995 * If any sufficient verifiers were listed in the package 12996 * manifest, attempt to ask them. 12997 */ 12998 if (sufficientVerifiers != null) { 12999 final int N = sufficientVerifiers.size(); 13000 if (N == 0) { 13001 Slog.i(TAG, "Additional verifiers required, but none installed."); 13002 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13003 } else { 13004 for (int i = 0; i < N; i++) { 13005 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13006 13007 final Intent sufficientIntent = new Intent(verification); 13008 sufficientIntent.setComponent(verifierComponent); 13009 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13010 } 13011 } 13012 } 13013 13014 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13015 mRequiredVerifierPackage, receivers); 13016 if (ret == PackageManager.INSTALL_SUCCEEDED 13017 && mRequiredVerifierPackage != null) { 13018 Trace.asyncTraceBegin( 13019 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13020 /* 13021 * Send the intent to the required verification agent, 13022 * but only start the verification timeout after the 13023 * target BroadcastReceivers have run. 13024 */ 13025 verification.setComponent(requiredVerifierComponent); 13026 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13027 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13028 new BroadcastReceiver() { 13029 @Override 13030 public void onReceive(Context context, Intent intent) { 13031 final Message msg = mHandler 13032 .obtainMessage(CHECK_PENDING_VERIFICATION); 13033 msg.arg1 = verificationId; 13034 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13035 } 13036 }, null, 0, null, null); 13037 13038 /* 13039 * We don't want the copy to proceed until verification 13040 * succeeds, so null out this field. 13041 */ 13042 mArgs = null; 13043 } 13044 } else { 13045 /* 13046 * No package verification is enabled, so immediately start 13047 * the remote call to initiate copy using temporary file. 13048 */ 13049 ret = args.copyApk(mContainerService, true); 13050 } 13051 } 13052 13053 mRet = ret; 13054 } 13055 13056 @Override 13057 void handleReturnCode() { 13058 // If mArgs is null, then MCS couldn't be reached. When it 13059 // reconnects, it will try again to install. At that point, this 13060 // will succeed. 13061 if (mArgs != null) { 13062 processPendingInstall(mArgs, mRet); 13063 } 13064 } 13065 13066 @Override 13067 void handleServiceError() { 13068 mArgs = createInstallArgs(this); 13069 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13070 } 13071 13072 public boolean isForwardLocked() { 13073 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13074 } 13075 } 13076 13077 /** 13078 * Used during creation of InstallArgs 13079 * 13080 * @param installFlags package installation flags 13081 * @return true if should be installed on external storage 13082 */ 13083 private static boolean installOnExternalAsec(int installFlags) { 13084 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13085 return false; 13086 } 13087 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13088 return true; 13089 } 13090 return false; 13091 } 13092 13093 /** 13094 * Used during creation of InstallArgs 13095 * 13096 * @param installFlags package installation flags 13097 * @return true if should be installed as forward locked 13098 */ 13099 private static boolean installForwardLocked(int installFlags) { 13100 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13101 } 13102 13103 private InstallArgs createInstallArgs(InstallParams params) { 13104 if (params.move != null) { 13105 return new MoveInstallArgs(params); 13106 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13107 return new AsecInstallArgs(params); 13108 } else { 13109 return new FileInstallArgs(params); 13110 } 13111 } 13112 13113 /** 13114 * Create args that describe an existing installed package. Typically used 13115 * when cleaning up old installs, or used as a move source. 13116 */ 13117 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13118 String resourcePath, String[] instructionSets) { 13119 final boolean isInAsec; 13120 if (installOnExternalAsec(installFlags)) { 13121 /* Apps on SD card are always in ASEC containers. */ 13122 isInAsec = true; 13123 } else if (installForwardLocked(installFlags) 13124 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13125 /* 13126 * Forward-locked apps are only in ASEC containers if they're the 13127 * new style 13128 */ 13129 isInAsec = true; 13130 } else { 13131 isInAsec = false; 13132 } 13133 13134 if (isInAsec) { 13135 return new AsecInstallArgs(codePath, instructionSets, 13136 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13137 } else { 13138 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13139 } 13140 } 13141 13142 static abstract class InstallArgs { 13143 /** @see InstallParams#origin */ 13144 final OriginInfo origin; 13145 /** @see InstallParams#move */ 13146 final MoveInfo move; 13147 13148 final IPackageInstallObserver2 observer; 13149 // Always refers to PackageManager flags only 13150 final int installFlags; 13151 final String installerPackageName; 13152 final String volumeUuid; 13153 final UserHandle user; 13154 final String abiOverride; 13155 final String[] installGrantPermissions; 13156 /** If non-null, drop an async trace when the install completes */ 13157 final String traceMethod; 13158 final int traceCookie; 13159 final Certificate[][] certificates; 13160 13161 // The list of instruction sets supported by this app. This is currently 13162 // only used during the rmdex() phase to clean up resources. We can get rid of this 13163 // if we move dex files under the common app path. 13164 /* nullable */ String[] instructionSets; 13165 13166 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13167 int installFlags, String installerPackageName, String volumeUuid, 13168 UserHandle user, String[] instructionSets, 13169 String abiOverride, String[] installGrantPermissions, 13170 String traceMethod, int traceCookie, Certificate[][] certificates) { 13171 this.origin = origin; 13172 this.move = move; 13173 this.installFlags = installFlags; 13174 this.observer = observer; 13175 this.installerPackageName = installerPackageName; 13176 this.volumeUuid = volumeUuid; 13177 this.user = user; 13178 this.instructionSets = instructionSets; 13179 this.abiOverride = abiOverride; 13180 this.installGrantPermissions = installGrantPermissions; 13181 this.traceMethod = traceMethod; 13182 this.traceCookie = traceCookie; 13183 this.certificates = certificates; 13184 } 13185 13186 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13187 abstract int doPreInstall(int status); 13188 13189 /** 13190 * Rename package into final resting place. All paths on the given 13191 * scanned package should be updated to reflect the rename. 13192 */ 13193 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13194 abstract int doPostInstall(int status, int uid); 13195 13196 /** @see PackageSettingBase#codePathString */ 13197 abstract String getCodePath(); 13198 /** @see PackageSettingBase#resourcePathString */ 13199 abstract String getResourcePath(); 13200 13201 // Need installer lock especially for dex file removal. 13202 abstract void cleanUpResourcesLI(); 13203 abstract boolean doPostDeleteLI(boolean delete); 13204 13205 /** 13206 * Called before the source arguments are copied. This is used mostly 13207 * for MoveParams when it needs to read the source file to put it in the 13208 * destination. 13209 */ 13210 int doPreCopy() { 13211 return PackageManager.INSTALL_SUCCEEDED; 13212 } 13213 13214 /** 13215 * Called after the source arguments are copied. This is used mostly for 13216 * MoveParams when it needs to read the source file to put it in the 13217 * destination. 13218 */ 13219 int doPostCopy(int uid) { 13220 return PackageManager.INSTALL_SUCCEEDED; 13221 } 13222 13223 protected boolean isFwdLocked() { 13224 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13225 } 13226 13227 protected boolean isExternalAsec() { 13228 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13229 } 13230 13231 protected boolean isEphemeral() { 13232 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13233 } 13234 13235 UserHandle getUser() { 13236 return user; 13237 } 13238 } 13239 13240 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13241 if (!allCodePaths.isEmpty()) { 13242 if (instructionSets == null) { 13243 throw new IllegalStateException("instructionSet == null"); 13244 } 13245 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13246 for (String codePath : allCodePaths) { 13247 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13248 try { 13249 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13250 } catch (InstallerException ignored) { 13251 } 13252 } 13253 } 13254 } 13255 } 13256 13257 /** 13258 * Logic to handle installation of non-ASEC applications, including copying 13259 * and renaming logic. 13260 */ 13261 class FileInstallArgs extends InstallArgs { 13262 private File codeFile; 13263 private File resourceFile; 13264 13265 // Example topology: 13266 // /data/app/com.example/base.apk 13267 // /data/app/com.example/split_foo.apk 13268 // /data/app/com.example/lib/arm/libfoo.so 13269 // /data/app/com.example/lib/arm64/libfoo.so 13270 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13271 13272 /** New install */ 13273 FileInstallArgs(InstallParams params) { 13274 super(params.origin, params.move, params.observer, params.installFlags, 13275 params.installerPackageName, params.volumeUuid, 13276 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13277 params.grantedRuntimePermissions, 13278 params.traceMethod, params.traceCookie, params.certificates); 13279 if (isFwdLocked()) { 13280 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13281 } 13282 } 13283 13284 /** Existing install */ 13285 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13286 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13287 null, null, null, 0, null /*certificates*/); 13288 this.codeFile = (codePath != null) ? new File(codePath) : null; 13289 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13290 } 13291 13292 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13294 try { 13295 return doCopyApk(imcs, temp); 13296 } finally { 13297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13298 } 13299 } 13300 13301 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13302 if (origin.staged) { 13303 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13304 codeFile = origin.file; 13305 resourceFile = origin.file; 13306 return PackageManager.INSTALL_SUCCEEDED; 13307 } 13308 13309 try { 13310 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13311 final File tempDir = 13312 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13313 codeFile = tempDir; 13314 resourceFile = tempDir; 13315 } catch (IOException e) { 13316 Slog.w(TAG, "Failed to create copy file: " + e); 13317 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13318 } 13319 13320 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13321 @Override 13322 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13323 if (!FileUtils.isValidExtFilename(name)) { 13324 throw new IllegalArgumentException("Invalid filename: " + name); 13325 } 13326 try { 13327 final File file = new File(codeFile, name); 13328 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13329 O_RDWR | O_CREAT, 0644); 13330 Os.chmod(file.getAbsolutePath(), 0644); 13331 return new ParcelFileDescriptor(fd); 13332 } catch (ErrnoException e) { 13333 throw new RemoteException("Failed to open: " + e.getMessage()); 13334 } 13335 } 13336 }; 13337 13338 int ret = PackageManager.INSTALL_SUCCEEDED; 13339 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13340 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13341 Slog.e(TAG, "Failed to copy package"); 13342 return ret; 13343 } 13344 13345 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13346 NativeLibraryHelper.Handle handle = null; 13347 try { 13348 handle = NativeLibraryHelper.Handle.create(codeFile); 13349 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13350 abiOverride); 13351 } catch (IOException e) { 13352 Slog.e(TAG, "Copying native libraries failed", e); 13353 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13354 } finally { 13355 IoUtils.closeQuietly(handle); 13356 } 13357 13358 return ret; 13359 } 13360 13361 int doPreInstall(int status) { 13362 if (status != PackageManager.INSTALL_SUCCEEDED) { 13363 cleanUp(); 13364 } 13365 return status; 13366 } 13367 13368 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13369 if (status != PackageManager.INSTALL_SUCCEEDED) { 13370 cleanUp(); 13371 return false; 13372 } 13373 13374 final File targetDir = codeFile.getParentFile(); 13375 final File beforeCodeFile = codeFile; 13376 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13377 13378 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13379 try { 13380 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13381 } catch (ErrnoException e) { 13382 Slog.w(TAG, "Failed to rename", e); 13383 return false; 13384 } 13385 13386 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13387 Slog.w(TAG, "Failed to restorecon"); 13388 return false; 13389 } 13390 13391 // Reflect the rename internally 13392 codeFile = afterCodeFile; 13393 resourceFile = afterCodeFile; 13394 13395 // Reflect the rename in scanned details 13396 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13397 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13398 afterCodeFile, pkg.baseCodePath)); 13399 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13400 afterCodeFile, pkg.splitCodePaths)); 13401 13402 // Reflect the rename in app info 13403 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13404 pkg.setApplicationInfoCodePath(pkg.codePath); 13405 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13406 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13407 pkg.setApplicationInfoResourcePath(pkg.codePath); 13408 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13409 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13410 13411 return true; 13412 } 13413 13414 int doPostInstall(int status, int uid) { 13415 if (status != PackageManager.INSTALL_SUCCEEDED) { 13416 cleanUp(); 13417 } 13418 return status; 13419 } 13420 13421 @Override 13422 String getCodePath() { 13423 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13424 } 13425 13426 @Override 13427 String getResourcePath() { 13428 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13429 } 13430 13431 private boolean cleanUp() { 13432 if (codeFile == null || !codeFile.exists()) { 13433 return false; 13434 } 13435 13436 removeCodePathLI(codeFile); 13437 13438 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13439 resourceFile.delete(); 13440 } 13441 13442 return true; 13443 } 13444 13445 void cleanUpResourcesLI() { 13446 // Try enumerating all code paths before deleting 13447 List<String> allCodePaths = Collections.EMPTY_LIST; 13448 if (codeFile != null && codeFile.exists()) { 13449 try { 13450 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13451 allCodePaths = pkg.getAllCodePaths(); 13452 } catch (PackageParserException e) { 13453 // Ignored; we tried our best 13454 } 13455 } 13456 13457 cleanUp(); 13458 removeDexFiles(allCodePaths, instructionSets); 13459 } 13460 13461 boolean doPostDeleteLI(boolean delete) { 13462 // XXX err, shouldn't we respect the delete flag? 13463 cleanUpResourcesLI(); 13464 return true; 13465 } 13466 } 13467 13468 private boolean isAsecExternal(String cid) { 13469 final String asecPath = PackageHelper.getSdFilesystem(cid); 13470 return !asecPath.startsWith(mAsecInternalPath); 13471 } 13472 13473 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13474 PackageManagerException { 13475 if (copyRet < 0) { 13476 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13477 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13478 throw new PackageManagerException(copyRet, message); 13479 } 13480 } 13481 } 13482 13483 /** 13484 * Extract the MountService "container ID" from the full code path of an 13485 * .apk. 13486 */ 13487 static String cidFromCodePath(String fullCodePath) { 13488 int eidx = fullCodePath.lastIndexOf("/"); 13489 String subStr1 = fullCodePath.substring(0, eidx); 13490 int sidx = subStr1.lastIndexOf("/"); 13491 return subStr1.substring(sidx+1, eidx); 13492 } 13493 13494 /** 13495 * Logic to handle installation of ASEC applications, including copying and 13496 * renaming logic. 13497 */ 13498 class AsecInstallArgs extends InstallArgs { 13499 static final String RES_FILE_NAME = "pkg.apk"; 13500 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13501 13502 String cid; 13503 String packagePath; 13504 String resourcePath; 13505 13506 /** New install */ 13507 AsecInstallArgs(InstallParams params) { 13508 super(params.origin, params.move, params.observer, params.installFlags, 13509 params.installerPackageName, params.volumeUuid, 13510 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13511 params.grantedRuntimePermissions, 13512 params.traceMethod, params.traceCookie, params.certificates); 13513 } 13514 13515 /** Existing install */ 13516 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13517 boolean isExternal, boolean isForwardLocked) { 13518 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13519 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13520 instructionSets, null, null, null, 0, null /*certificates*/); 13521 // Hackily pretend we're still looking at a full code path 13522 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13523 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13524 } 13525 13526 // Extract cid from fullCodePath 13527 int eidx = fullCodePath.lastIndexOf("/"); 13528 String subStr1 = fullCodePath.substring(0, eidx); 13529 int sidx = subStr1.lastIndexOf("/"); 13530 cid = subStr1.substring(sidx+1, eidx); 13531 setMountPath(subStr1); 13532 } 13533 13534 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13535 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13536 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13537 instructionSets, null, null, null, 0, null /*certificates*/); 13538 this.cid = cid; 13539 setMountPath(PackageHelper.getSdDir(cid)); 13540 } 13541 13542 void createCopyFile() { 13543 cid = mInstallerService.allocateExternalStageCidLegacy(); 13544 } 13545 13546 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13547 if (origin.staged && origin.cid != null) { 13548 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13549 cid = origin.cid; 13550 setMountPath(PackageHelper.getSdDir(cid)); 13551 return PackageManager.INSTALL_SUCCEEDED; 13552 } 13553 13554 if (temp) { 13555 createCopyFile(); 13556 } else { 13557 /* 13558 * Pre-emptively destroy the container since it's destroyed if 13559 * copying fails due to it existing anyway. 13560 */ 13561 PackageHelper.destroySdDir(cid); 13562 } 13563 13564 final String newMountPath = imcs.copyPackageToContainer( 13565 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13566 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13567 13568 if (newMountPath != null) { 13569 setMountPath(newMountPath); 13570 return PackageManager.INSTALL_SUCCEEDED; 13571 } else { 13572 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13573 } 13574 } 13575 13576 @Override 13577 String getCodePath() { 13578 return packagePath; 13579 } 13580 13581 @Override 13582 String getResourcePath() { 13583 return resourcePath; 13584 } 13585 13586 int doPreInstall(int status) { 13587 if (status != PackageManager.INSTALL_SUCCEEDED) { 13588 // Destroy container 13589 PackageHelper.destroySdDir(cid); 13590 } else { 13591 boolean mounted = PackageHelper.isContainerMounted(cid); 13592 if (!mounted) { 13593 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13594 Process.SYSTEM_UID); 13595 if (newMountPath != null) { 13596 setMountPath(newMountPath); 13597 } else { 13598 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13599 } 13600 } 13601 } 13602 return status; 13603 } 13604 13605 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13606 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13607 String newMountPath = null; 13608 if (PackageHelper.isContainerMounted(cid)) { 13609 // Unmount the container 13610 if (!PackageHelper.unMountSdDir(cid)) { 13611 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13612 return false; 13613 } 13614 } 13615 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13616 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13617 " which might be stale. Will try to clean up."); 13618 // Clean up the stale container and proceed to recreate. 13619 if (!PackageHelper.destroySdDir(newCacheId)) { 13620 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13621 return false; 13622 } 13623 // Successfully cleaned up stale container. Try to rename again. 13624 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13625 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13626 + " inspite of cleaning it up."); 13627 return false; 13628 } 13629 } 13630 if (!PackageHelper.isContainerMounted(newCacheId)) { 13631 Slog.w(TAG, "Mounting container " + newCacheId); 13632 newMountPath = PackageHelper.mountSdDir(newCacheId, 13633 getEncryptKey(), Process.SYSTEM_UID); 13634 } else { 13635 newMountPath = PackageHelper.getSdDir(newCacheId); 13636 } 13637 if (newMountPath == null) { 13638 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13639 return false; 13640 } 13641 Log.i(TAG, "Succesfully renamed " + cid + 13642 " to " + newCacheId + 13643 " at new path: " + newMountPath); 13644 cid = newCacheId; 13645 13646 final File beforeCodeFile = new File(packagePath); 13647 setMountPath(newMountPath); 13648 final File afterCodeFile = new File(packagePath); 13649 13650 // Reflect the rename in scanned details 13651 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13652 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13653 afterCodeFile, pkg.baseCodePath)); 13654 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13655 afterCodeFile, pkg.splitCodePaths)); 13656 13657 // Reflect the rename in app info 13658 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13659 pkg.setApplicationInfoCodePath(pkg.codePath); 13660 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13661 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13662 pkg.setApplicationInfoResourcePath(pkg.codePath); 13663 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13664 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13665 13666 return true; 13667 } 13668 13669 private void setMountPath(String mountPath) { 13670 final File mountFile = new File(mountPath); 13671 13672 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13673 if (monolithicFile.exists()) { 13674 packagePath = monolithicFile.getAbsolutePath(); 13675 if (isFwdLocked()) { 13676 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13677 } else { 13678 resourcePath = packagePath; 13679 } 13680 } else { 13681 packagePath = mountFile.getAbsolutePath(); 13682 resourcePath = packagePath; 13683 } 13684 } 13685 13686 int doPostInstall(int status, int uid) { 13687 if (status != PackageManager.INSTALL_SUCCEEDED) { 13688 cleanUp(); 13689 } else { 13690 final int groupOwner; 13691 final String protectedFile; 13692 if (isFwdLocked()) { 13693 groupOwner = UserHandle.getSharedAppGid(uid); 13694 protectedFile = RES_FILE_NAME; 13695 } else { 13696 groupOwner = -1; 13697 protectedFile = null; 13698 } 13699 13700 if (uid < Process.FIRST_APPLICATION_UID 13701 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13702 Slog.e(TAG, "Failed to finalize " + cid); 13703 PackageHelper.destroySdDir(cid); 13704 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13705 } 13706 13707 boolean mounted = PackageHelper.isContainerMounted(cid); 13708 if (!mounted) { 13709 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13710 } 13711 } 13712 return status; 13713 } 13714 13715 private void cleanUp() { 13716 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13717 13718 // Destroy secure container 13719 PackageHelper.destroySdDir(cid); 13720 } 13721 13722 private List<String> getAllCodePaths() { 13723 final File codeFile = new File(getCodePath()); 13724 if (codeFile != null && codeFile.exists()) { 13725 try { 13726 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13727 return pkg.getAllCodePaths(); 13728 } catch (PackageParserException e) { 13729 // Ignored; we tried our best 13730 } 13731 } 13732 return Collections.EMPTY_LIST; 13733 } 13734 13735 void cleanUpResourcesLI() { 13736 // Enumerate all code paths before deleting 13737 cleanUpResourcesLI(getAllCodePaths()); 13738 } 13739 13740 private void cleanUpResourcesLI(List<String> allCodePaths) { 13741 cleanUp(); 13742 removeDexFiles(allCodePaths, instructionSets); 13743 } 13744 13745 String getPackageName() { 13746 return getAsecPackageName(cid); 13747 } 13748 13749 boolean doPostDeleteLI(boolean delete) { 13750 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13751 final List<String> allCodePaths = getAllCodePaths(); 13752 boolean mounted = PackageHelper.isContainerMounted(cid); 13753 if (mounted) { 13754 // Unmount first 13755 if (PackageHelper.unMountSdDir(cid)) { 13756 mounted = false; 13757 } 13758 } 13759 if (!mounted && delete) { 13760 cleanUpResourcesLI(allCodePaths); 13761 } 13762 return !mounted; 13763 } 13764 13765 @Override 13766 int doPreCopy() { 13767 if (isFwdLocked()) { 13768 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13769 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13770 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13771 } 13772 } 13773 13774 return PackageManager.INSTALL_SUCCEEDED; 13775 } 13776 13777 @Override 13778 int doPostCopy(int uid) { 13779 if (isFwdLocked()) { 13780 if (uid < Process.FIRST_APPLICATION_UID 13781 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13782 RES_FILE_NAME)) { 13783 Slog.e(TAG, "Failed to finalize " + cid); 13784 PackageHelper.destroySdDir(cid); 13785 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13786 } 13787 } 13788 13789 return PackageManager.INSTALL_SUCCEEDED; 13790 } 13791 } 13792 13793 /** 13794 * Logic to handle movement of existing installed applications. 13795 */ 13796 class MoveInstallArgs extends InstallArgs { 13797 private File codeFile; 13798 private File resourceFile; 13799 13800 /** New install */ 13801 MoveInstallArgs(InstallParams params) { 13802 super(params.origin, params.move, params.observer, params.installFlags, 13803 params.installerPackageName, params.volumeUuid, 13804 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13805 params.grantedRuntimePermissions, 13806 params.traceMethod, params.traceCookie, params.certificates); 13807 } 13808 13809 int copyApk(IMediaContainerService imcs, boolean temp) { 13810 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13811 + move.fromUuid + " to " + move.toUuid); 13812 synchronized (mInstaller) { 13813 try { 13814 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13815 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13816 } catch (InstallerException e) { 13817 Slog.w(TAG, "Failed to move app", e); 13818 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13819 } 13820 } 13821 13822 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13823 resourceFile = codeFile; 13824 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13825 13826 return PackageManager.INSTALL_SUCCEEDED; 13827 } 13828 13829 int doPreInstall(int status) { 13830 if (status != PackageManager.INSTALL_SUCCEEDED) { 13831 cleanUp(move.toUuid); 13832 } 13833 return status; 13834 } 13835 13836 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13837 if (status != PackageManager.INSTALL_SUCCEEDED) { 13838 cleanUp(move.toUuid); 13839 return false; 13840 } 13841 13842 // Reflect the move in app info 13843 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13844 pkg.setApplicationInfoCodePath(pkg.codePath); 13845 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13846 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13847 pkg.setApplicationInfoResourcePath(pkg.codePath); 13848 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13849 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13850 13851 return true; 13852 } 13853 13854 int doPostInstall(int status, int uid) { 13855 if (status == PackageManager.INSTALL_SUCCEEDED) { 13856 cleanUp(move.fromUuid); 13857 } else { 13858 cleanUp(move.toUuid); 13859 } 13860 return status; 13861 } 13862 13863 @Override 13864 String getCodePath() { 13865 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13866 } 13867 13868 @Override 13869 String getResourcePath() { 13870 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13871 } 13872 13873 private boolean cleanUp(String volumeUuid) { 13874 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13875 move.dataAppName); 13876 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13877 final int[] userIds = sUserManager.getUserIds(); 13878 synchronized (mInstallLock) { 13879 // Clean up both app data and code 13880 // All package moves are frozen until finished 13881 for (int userId : userIds) { 13882 try { 13883 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13884 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13885 } catch (InstallerException e) { 13886 Slog.w(TAG, String.valueOf(e)); 13887 } 13888 } 13889 removeCodePathLI(codeFile); 13890 } 13891 return true; 13892 } 13893 13894 void cleanUpResourcesLI() { 13895 throw new UnsupportedOperationException(); 13896 } 13897 13898 boolean doPostDeleteLI(boolean delete) { 13899 throw new UnsupportedOperationException(); 13900 } 13901 } 13902 13903 static String getAsecPackageName(String packageCid) { 13904 int idx = packageCid.lastIndexOf("-"); 13905 if (idx == -1) { 13906 return packageCid; 13907 } 13908 return packageCid.substring(0, idx); 13909 } 13910 13911 // Utility method used to create code paths based on package name and available index. 13912 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13913 String idxStr = ""; 13914 int idx = 1; 13915 // Fall back to default value of idx=1 if prefix is not 13916 // part of oldCodePath 13917 if (oldCodePath != null) { 13918 String subStr = oldCodePath; 13919 // Drop the suffix right away 13920 if (suffix != null && subStr.endsWith(suffix)) { 13921 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13922 } 13923 // If oldCodePath already contains prefix find out the 13924 // ending index to either increment or decrement. 13925 int sidx = subStr.lastIndexOf(prefix); 13926 if (sidx != -1) { 13927 subStr = subStr.substring(sidx + prefix.length()); 13928 if (subStr != null) { 13929 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13930 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13931 } 13932 try { 13933 idx = Integer.parseInt(subStr); 13934 if (idx <= 1) { 13935 idx++; 13936 } else { 13937 idx--; 13938 } 13939 } catch(NumberFormatException e) { 13940 } 13941 } 13942 } 13943 } 13944 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13945 return prefix + idxStr; 13946 } 13947 13948 private File getNextCodePath(File targetDir, String packageName) { 13949 int suffix = 1; 13950 File result; 13951 do { 13952 result = new File(targetDir, packageName + "-" + suffix); 13953 suffix++; 13954 } while (result.exists()); 13955 return result; 13956 } 13957 13958 // Utility method that returns the relative package path with respect 13959 // to the installation directory. Like say for /data/data/com.test-1.apk 13960 // string com.test-1 is returned. 13961 static String deriveCodePathName(String codePath) { 13962 if (codePath == null) { 13963 return null; 13964 } 13965 final File codeFile = new File(codePath); 13966 final String name = codeFile.getName(); 13967 if (codeFile.isDirectory()) { 13968 return name; 13969 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13970 final int lastDot = name.lastIndexOf('.'); 13971 return name.substring(0, lastDot); 13972 } else { 13973 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13974 return null; 13975 } 13976 } 13977 13978 static class PackageInstalledInfo { 13979 String name; 13980 int uid; 13981 // The set of users that originally had this package installed. 13982 int[] origUsers; 13983 // The set of users that now have this package installed. 13984 int[] newUsers; 13985 PackageParser.Package pkg; 13986 int returnCode; 13987 String returnMsg; 13988 PackageRemovedInfo removedInfo; 13989 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13990 13991 public void setError(int code, String msg) { 13992 setReturnCode(code); 13993 setReturnMessage(msg); 13994 Slog.w(TAG, msg); 13995 } 13996 13997 public void setError(String msg, PackageParserException e) { 13998 setReturnCode(e.error); 13999 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14000 Slog.w(TAG, msg, e); 14001 } 14002 14003 public void setError(String msg, PackageManagerException e) { 14004 returnCode = e.error; 14005 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14006 Slog.w(TAG, msg, e); 14007 } 14008 14009 public void setReturnCode(int returnCode) { 14010 this.returnCode = returnCode; 14011 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14012 for (int i = 0; i < childCount; i++) { 14013 addedChildPackages.valueAt(i).returnCode = returnCode; 14014 } 14015 } 14016 14017 private void setReturnMessage(String returnMsg) { 14018 this.returnMsg = returnMsg; 14019 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14020 for (int i = 0; i < childCount; i++) { 14021 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14022 } 14023 } 14024 14025 // In some error cases we want to convey more info back to the observer 14026 String origPackage; 14027 String origPermission; 14028 } 14029 14030 /* 14031 * Install a non-existing package. 14032 */ 14033 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14034 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14035 PackageInstalledInfo res) { 14036 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14037 14038 // Remember this for later, in case we need to rollback this install 14039 String pkgName = pkg.packageName; 14040 14041 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14042 14043 synchronized(mPackages) { 14044 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14045 // A package with the same name is already installed, though 14046 // it has been renamed to an older name. The package we 14047 // are trying to install should be installed as an update to 14048 // the existing one, but that has not been requested, so bail. 14049 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14050 + " without first uninstalling package running as " 14051 + mSettings.mRenamedPackages.get(pkgName)); 14052 return; 14053 } 14054 if (mPackages.containsKey(pkgName)) { 14055 // Don't allow installation over an existing package with the same name. 14056 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14057 + " without first uninstalling."); 14058 return; 14059 } 14060 } 14061 14062 try { 14063 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14064 System.currentTimeMillis(), user); 14065 14066 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14067 14068 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14069 prepareAppDataAfterInstallLIF(newPackage); 14070 14071 } else { 14072 // Remove package from internal structures, but keep around any 14073 // data that might have already existed 14074 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14075 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14076 } 14077 } catch (PackageManagerException e) { 14078 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14079 } 14080 14081 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14082 } 14083 14084 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14085 // Can't rotate keys during boot or if sharedUser. 14086 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14087 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14088 return false; 14089 } 14090 // app is using upgradeKeySets; make sure all are valid 14091 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14092 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14093 for (int i = 0; i < upgradeKeySets.length; i++) { 14094 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14095 Slog.wtf(TAG, "Package " 14096 + (oldPs.name != null ? oldPs.name : "<null>") 14097 + " contains upgrade-key-set reference to unknown key-set: " 14098 + upgradeKeySets[i] 14099 + " reverting to signatures check."); 14100 return false; 14101 } 14102 } 14103 return true; 14104 } 14105 14106 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14107 // Upgrade keysets are being used. Determine if new package has a superset of the 14108 // required keys. 14109 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14110 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14111 for (int i = 0; i < upgradeKeySets.length; i++) { 14112 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14113 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14114 return true; 14115 } 14116 } 14117 return false; 14118 } 14119 14120 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14121 try (DigestInputStream digestStream = 14122 new DigestInputStream(new FileInputStream(file), digest)) { 14123 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14124 } 14125 } 14126 14127 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14128 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14129 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14130 14131 final PackageParser.Package oldPackage; 14132 final String pkgName = pkg.packageName; 14133 final int[] allUsers; 14134 final int[] installedUsers; 14135 14136 synchronized(mPackages) { 14137 oldPackage = mPackages.get(pkgName); 14138 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14139 14140 // don't allow upgrade to target a release SDK from a pre-release SDK 14141 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14142 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14143 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14144 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14145 if (oldTargetsPreRelease 14146 && !newTargetsPreRelease 14147 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14148 Slog.w(TAG, "Can't install package targeting released sdk"); 14149 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14150 return; 14151 } 14152 14153 // don't allow an upgrade from full to ephemeral 14154 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14155 if (isEphemeral && !oldIsEphemeral) { 14156 // can't downgrade from full to ephemeral 14157 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14158 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14159 return; 14160 } 14161 14162 // verify signatures are valid 14163 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14164 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14165 if (!checkUpgradeKeySetLP(ps, pkg)) { 14166 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14167 "New package not signed by keys specified by upgrade-keysets: " 14168 + pkgName); 14169 return; 14170 } 14171 } else { 14172 // default to original signature matching 14173 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14174 != PackageManager.SIGNATURE_MATCH) { 14175 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14176 "New package has a different signature: " + pkgName); 14177 return; 14178 } 14179 } 14180 14181 // don't allow a system upgrade unless the upgrade hash matches 14182 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14183 byte[] digestBytes = null; 14184 try { 14185 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14186 updateDigest(digest, new File(pkg.baseCodePath)); 14187 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14188 for (String path : pkg.splitCodePaths) { 14189 updateDigest(digest, new File(path)); 14190 } 14191 } 14192 digestBytes = digest.digest(); 14193 } catch (NoSuchAlgorithmException | IOException e) { 14194 res.setError(INSTALL_FAILED_INVALID_APK, 14195 "Could not compute hash: " + pkgName); 14196 return; 14197 } 14198 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14199 res.setError(INSTALL_FAILED_INVALID_APK, 14200 "New package fails restrict-update check: " + pkgName); 14201 return; 14202 } 14203 // retain upgrade restriction 14204 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14205 } 14206 14207 // Check for shared user id changes 14208 String invalidPackageName = 14209 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14210 if (invalidPackageName != null) { 14211 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14212 "Package " + invalidPackageName + " tried to change user " 14213 + oldPackage.mSharedUserId); 14214 return; 14215 } 14216 14217 // In case of rollback, remember per-user/profile install state 14218 allUsers = sUserManager.getUserIds(); 14219 installedUsers = ps.queryInstalledUsers(allUsers, true); 14220 } 14221 14222 // Update what is removed 14223 res.removedInfo = new PackageRemovedInfo(); 14224 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14225 res.removedInfo.removedPackage = oldPackage.packageName; 14226 res.removedInfo.isUpdate = true; 14227 res.removedInfo.origUsers = installedUsers; 14228 final int childCount = (oldPackage.childPackages != null) 14229 ? oldPackage.childPackages.size() : 0; 14230 for (int i = 0; i < childCount; i++) { 14231 boolean childPackageUpdated = false; 14232 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14233 if (res.addedChildPackages != null) { 14234 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14235 if (childRes != null) { 14236 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14237 childRes.removedInfo.removedPackage = childPkg.packageName; 14238 childRes.removedInfo.isUpdate = true; 14239 childPackageUpdated = true; 14240 } 14241 } 14242 if (!childPackageUpdated) { 14243 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14244 childRemovedRes.removedPackage = childPkg.packageName; 14245 childRemovedRes.isUpdate = false; 14246 childRemovedRes.dataRemoved = true; 14247 synchronized (mPackages) { 14248 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14249 if (childPs != null) { 14250 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14251 } 14252 } 14253 if (res.removedInfo.removedChildPackages == null) { 14254 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14255 } 14256 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14257 } 14258 } 14259 14260 boolean sysPkg = (isSystemApp(oldPackage)); 14261 if (sysPkg) { 14262 // Set the system/privileged flags as needed 14263 final boolean privileged = 14264 (oldPackage.applicationInfo.privateFlags 14265 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14266 final int systemPolicyFlags = policyFlags 14267 | PackageParser.PARSE_IS_SYSTEM 14268 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14269 14270 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14271 user, allUsers, installerPackageName, res); 14272 } else { 14273 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14274 user, allUsers, installerPackageName, res); 14275 } 14276 } 14277 14278 public List<String> getPreviousCodePaths(String packageName) { 14279 final PackageSetting ps = mSettings.mPackages.get(packageName); 14280 final List<String> result = new ArrayList<String>(); 14281 if (ps != null && ps.oldCodePaths != null) { 14282 result.addAll(ps.oldCodePaths); 14283 } 14284 return result; 14285 } 14286 14287 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14288 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14289 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14290 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14291 + deletedPackage); 14292 14293 String pkgName = deletedPackage.packageName; 14294 boolean deletedPkg = true; 14295 boolean addedPkg = false; 14296 boolean updatedSettings = false; 14297 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14298 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14299 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14300 14301 final long origUpdateTime = (pkg.mExtras != null) 14302 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14303 14304 // First delete the existing package while retaining the data directory 14305 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14306 res.removedInfo, true, pkg)) { 14307 // If the existing package wasn't successfully deleted 14308 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14309 deletedPkg = false; 14310 } else { 14311 // Successfully deleted the old package; proceed with replace. 14312 14313 // If deleted package lived in a container, give users a chance to 14314 // relinquish resources before killing. 14315 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14316 if (DEBUG_INSTALL) { 14317 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14318 } 14319 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14320 final ArrayList<String> pkgList = new ArrayList<String>(1); 14321 pkgList.add(deletedPackage.applicationInfo.packageName); 14322 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14323 } 14324 14325 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14326 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14327 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14328 14329 try { 14330 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14331 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14332 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14333 14334 // Update the in-memory copy of the previous code paths. 14335 PackageSetting ps = mSettings.mPackages.get(pkgName); 14336 if (!killApp) { 14337 if (ps.oldCodePaths == null) { 14338 ps.oldCodePaths = new ArraySet<>(); 14339 } 14340 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14341 if (deletedPackage.splitCodePaths != null) { 14342 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14343 } 14344 } else { 14345 ps.oldCodePaths = null; 14346 } 14347 if (ps.childPackageNames != null) { 14348 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14349 final String childPkgName = ps.childPackageNames.get(i); 14350 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14351 childPs.oldCodePaths = ps.oldCodePaths; 14352 } 14353 } 14354 prepareAppDataAfterInstallLIF(newPackage); 14355 addedPkg = true; 14356 } catch (PackageManagerException e) { 14357 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14358 } 14359 } 14360 14361 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14362 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14363 14364 // Revert all internal state mutations and added folders for the failed install 14365 if (addedPkg) { 14366 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14367 res.removedInfo, true, null); 14368 } 14369 14370 // Restore the old package 14371 if (deletedPkg) { 14372 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14373 File restoreFile = new File(deletedPackage.codePath); 14374 // Parse old package 14375 boolean oldExternal = isExternal(deletedPackage); 14376 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14377 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14378 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14379 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14380 try { 14381 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14382 null); 14383 } catch (PackageManagerException e) { 14384 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14385 + e.getMessage()); 14386 return; 14387 } 14388 14389 synchronized (mPackages) { 14390 // Ensure the installer package name up to date 14391 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14392 14393 // Update permissions for restored package 14394 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14395 14396 mSettings.writeLPr(); 14397 } 14398 14399 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14400 } 14401 } else { 14402 synchronized (mPackages) { 14403 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14404 if (ps != null) { 14405 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14406 if (res.removedInfo.removedChildPackages != null) { 14407 final int childCount = res.removedInfo.removedChildPackages.size(); 14408 // Iterate in reverse as we may modify the collection 14409 for (int i = childCount - 1; i >= 0; i--) { 14410 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14411 if (res.addedChildPackages.containsKey(childPackageName)) { 14412 res.removedInfo.removedChildPackages.removeAt(i); 14413 } else { 14414 PackageRemovedInfo childInfo = res.removedInfo 14415 .removedChildPackages.valueAt(i); 14416 childInfo.removedForAllUsers = mPackages.get( 14417 childInfo.removedPackage) == null; 14418 } 14419 } 14420 } 14421 } 14422 } 14423 } 14424 } 14425 14426 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14427 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14428 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14429 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14430 + ", old=" + deletedPackage); 14431 14432 final boolean disabledSystem; 14433 14434 // Remove existing system package 14435 removePackageLI(deletedPackage, true); 14436 14437 synchronized (mPackages) { 14438 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14439 } 14440 if (!disabledSystem) { 14441 // We didn't need to disable the .apk as a current system package, 14442 // which means we are replacing another update that is already 14443 // installed. We need to make sure to delete the older one's .apk. 14444 res.removedInfo.args = createInstallArgsForExisting(0, 14445 deletedPackage.applicationInfo.getCodePath(), 14446 deletedPackage.applicationInfo.getResourcePath(), 14447 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14448 } else { 14449 res.removedInfo.args = null; 14450 } 14451 14452 // Successfully disabled the old package. Now proceed with re-installation 14453 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14454 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14455 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14456 14457 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14458 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14459 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14460 14461 PackageParser.Package newPackage = null; 14462 try { 14463 // Add the package to the internal data structures 14464 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14465 14466 // Set the update and install times 14467 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14468 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14469 System.currentTimeMillis()); 14470 14471 // Update the package dynamic state if succeeded 14472 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14473 // Now that the install succeeded make sure we remove data 14474 // directories for any child package the update removed. 14475 final int deletedChildCount = (deletedPackage.childPackages != null) 14476 ? deletedPackage.childPackages.size() : 0; 14477 final int newChildCount = (newPackage.childPackages != null) 14478 ? newPackage.childPackages.size() : 0; 14479 for (int i = 0; i < deletedChildCount; i++) { 14480 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14481 boolean childPackageDeleted = true; 14482 for (int j = 0; j < newChildCount; j++) { 14483 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14484 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14485 childPackageDeleted = false; 14486 break; 14487 } 14488 } 14489 if (childPackageDeleted) { 14490 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14491 deletedChildPkg.packageName); 14492 if (ps != null && res.removedInfo.removedChildPackages != null) { 14493 PackageRemovedInfo removedChildRes = res.removedInfo 14494 .removedChildPackages.get(deletedChildPkg.packageName); 14495 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14496 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14497 } 14498 } 14499 } 14500 14501 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14502 prepareAppDataAfterInstallLIF(newPackage); 14503 } 14504 } catch (PackageManagerException e) { 14505 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14506 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14507 } 14508 14509 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14510 // Re installation failed. Restore old information 14511 // Remove new pkg information 14512 if (newPackage != null) { 14513 removeInstalledPackageLI(newPackage, true); 14514 } 14515 // Add back the old system package 14516 try { 14517 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14518 } catch (PackageManagerException e) { 14519 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14520 } 14521 14522 synchronized (mPackages) { 14523 if (disabledSystem) { 14524 enableSystemPackageLPw(deletedPackage); 14525 } 14526 14527 // Ensure the installer package name up to date 14528 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14529 14530 // Update permissions for restored package 14531 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14532 14533 mSettings.writeLPr(); 14534 } 14535 14536 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14537 + " after failed upgrade"); 14538 } 14539 } 14540 14541 /** 14542 * Checks whether the parent or any of the child packages have a change shared 14543 * user. For a package to be a valid update the shred users of the parent and 14544 * the children should match. We may later support changing child shared users. 14545 * @param oldPkg The updated package. 14546 * @param newPkg The update package. 14547 * @return The shared user that change between the versions. 14548 */ 14549 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14550 PackageParser.Package newPkg) { 14551 // Check parent shared user 14552 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14553 return newPkg.packageName; 14554 } 14555 // Check child shared users 14556 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14557 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14558 for (int i = 0; i < newChildCount; i++) { 14559 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14560 // If this child was present, did it have the same shared user? 14561 for (int j = 0; j < oldChildCount; j++) { 14562 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14563 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14564 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14565 return newChildPkg.packageName; 14566 } 14567 } 14568 } 14569 return null; 14570 } 14571 14572 private void removeNativeBinariesLI(PackageSetting ps) { 14573 // Remove the lib path for the parent package 14574 if (ps != null) { 14575 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14576 // Remove the lib path for the child packages 14577 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14578 for (int i = 0; i < childCount; i++) { 14579 PackageSetting childPs = null; 14580 synchronized (mPackages) { 14581 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14582 } 14583 if (childPs != null) { 14584 NativeLibraryHelper.removeNativeBinariesLI(childPs 14585 .legacyNativeLibraryPathString); 14586 } 14587 } 14588 } 14589 } 14590 14591 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14592 // Enable the parent package 14593 mSettings.enableSystemPackageLPw(pkg.packageName); 14594 // Enable the child packages 14595 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14596 for (int i = 0; i < childCount; i++) { 14597 PackageParser.Package childPkg = pkg.childPackages.get(i); 14598 mSettings.enableSystemPackageLPw(childPkg.packageName); 14599 } 14600 } 14601 14602 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14603 PackageParser.Package newPkg) { 14604 // Disable the parent package (parent always replaced) 14605 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14606 // Disable the child packages 14607 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14608 for (int i = 0; i < childCount; i++) { 14609 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14610 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14611 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14612 } 14613 return disabled; 14614 } 14615 14616 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14617 String installerPackageName) { 14618 // Enable the parent package 14619 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14620 // Enable the child packages 14621 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14622 for (int i = 0; i < childCount; i++) { 14623 PackageParser.Package childPkg = pkg.childPackages.get(i); 14624 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14625 } 14626 } 14627 14628 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14629 // Collect all used permissions in the UID 14630 ArraySet<String> usedPermissions = new ArraySet<>(); 14631 final int packageCount = su.packages.size(); 14632 for (int i = 0; i < packageCount; i++) { 14633 PackageSetting ps = su.packages.valueAt(i); 14634 if (ps.pkg == null) { 14635 continue; 14636 } 14637 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14638 for (int j = 0; j < requestedPermCount; j++) { 14639 String permission = ps.pkg.requestedPermissions.get(j); 14640 BasePermission bp = mSettings.mPermissions.get(permission); 14641 if (bp != null) { 14642 usedPermissions.add(permission); 14643 } 14644 } 14645 } 14646 14647 PermissionsState permissionsState = su.getPermissionsState(); 14648 // Prune install permissions 14649 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14650 final int installPermCount = installPermStates.size(); 14651 for (int i = installPermCount - 1; i >= 0; i--) { 14652 PermissionState permissionState = installPermStates.get(i); 14653 if (!usedPermissions.contains(permissionState.getName())) { 14654 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14655 if (bp != null) { 14656 permissionsState.revokeInstallPermission(bp); 14657 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14658 PackageManager.MASK_PERMISSION_FLAGS, 0); 14659 } 14660 } 14661 } 14662 14663 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14664 14665 // Prune runtime permissions 14666 for (int userId : allUserIds) { 14667 List<PermissionState> runtimePermStates = permissionsState 14668 .getRuntimePermissionStates(userId); 14669 final int runtimePermCount = runtimePermStates.size(); 14670 for (int i = runtimePermCount - 1; i >= 0; i--) { 14671 PermissionState permissionState = runtimePermStates.get(i); 14672 if (!usedPermissions.contains(permissionState.getName())) { 14673 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14674 if (bp != null) { 14675 permissionsState.revokeRuntimePermission(bp, userId); 14676 permissionsState.updatePermissionFlags(bp, userId, 14677 PackageManager.MASK_PERMISSION_FLAGS, 0); 14678 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14679 runtimePermissionChangedUserIds, userId); 14680 } 14681 } 14682 } 14683 } 14684 14685 return runtimePermissionChangedUserIds; 14686 } 14687 14688 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14689 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14690 // Update the parent package setting 14691 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14692 res, user); 14693 // Update the child packages setting 14694 final int childCount = (newPackage.childPackages != null) 14695 ? newPackage.childPackages.size() : 0; 14696 for (int i = 0; i < childCount; i++) { 14697 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14698 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14699 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14700 childRes.origUsers, childRes, user); 14701 } 14702 } 14703 14704 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14705 String installerPackageName, int[] allUsers, int[] installedForUsers, 14706 PackageInstalledInfo res, UserHandle user) { 14707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14708 14709 String pkgName = newPackage.packageName; 14710 synchronized (mPackages) { 14711 //write settings. the installStatus will be incomplete at this stage. 14712 //note that the new package setting would have already been 14713 //added to mPackages. It hasn't been persisted yet. 14714 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14716 mSettings.writeLPr(); 14717 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14718 } 14719 14720 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14721 synchronized (mPackages) { 14722 updatePermissionsLPw(newPackage.packageName, newPackage, 14723 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14724 ? UPDATE_PERMISSIONS_ALL : 0)); 14725 // For system-bundled packages, we assume that installing an upgraded version 14726 // of the package implies that the user actually wants to run that new code, 14727 // so we enable the package. 14728 PackageSetting ps = mSettings.mPackages.get(pkgName); 14729 final int userId = user.getIdentifier(); 14730 if (ps != null) { 14731 if (isSystemApp(newPackage)) { 14732 if (DEBUG_INSTALL) { 14733 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14734 } 14735 // Enable system package for requested users 14736 if (res.origUsers != null) { 14737 for (int origUserId : res.origUsers) { 14738 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14739 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14740 origUserId, installerPackageName); 14741 } 14742 } 14743 } 14744 // Also convey the prior install/uninstall state 14745 if (allUsers != null && installedForUsers != null) { 14746 for (int currentUserId : allUsers) { 14747 final boolean installed = ArrayUtils.contains( 14748 installedForUsers, currentUserId); 14749 if (DEBUG_INSTALL) { 14750 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14751 } 14752 ps.setInstalled(installed, currentUserId); 14753 } 14754 // these install state changes will be persisted in the 14755 // upcoming call to mSettings.writeLPr(). 14756 } 14757 } 14758 // It's implied that when a user requests installation, they want the app to be 14759 // installed and enabled. 14760 if (userId != UserHandle.USER_ALL) { 14761 ps.setInstalled(true, userId); 14762 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14763 } 14764 } 14765 res.name = pkgName; 14766 res.uid = newPackage.applicationInfo.uid; 14767 res.pkg = newPackage; 14768 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14769 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14770 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14771 //to update install status 14772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14773 mSettings.writeLPr(); 14774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14775 } 14776 14777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14778 } 14779 14780 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14781 try { 14782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14783 installPackageLI(args, res); 14784 } finally { 14785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14786 } 14787 } 14788 14789 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14790 final int installFlags = args.installFlags; 14791 final String installerPackageName = args.installerPackageName; 14792 final String volumeUuid = args.volumeUuid; 14793 final File tmpPackageFile = new File(args.getCodePath()); 14794 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14795 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14796 || (args.volumeUuid != null)); 14797 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14798 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14799 boolean replace = false; 14800 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14801 if (args.move != null) { 14802 // moving a complete application; perform an initial scan on the new install location 14803 scanFlags |= SCAN_INITIAL; 14804 } 14805 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14806 scanFlags |= SCAN_DONT_KILL_APP; 14807 } 14808 14809 // Result object to be returned 14810 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14811 14812 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14813 14814 // Sanity check 14815 if (ephemeral && (forwardLocked || onExternal)) { 14816 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14817 + " external=" + onExternal); 14818 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14819 return; 14820 } 14821 14822 // Retrieve PackageSettings and parse package 14823 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14824 | PackageParser.PARSE_ENFORCE_CODE 14825 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14826 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14827 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14828 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14829 PackageParser pp = new PackageParser(); 14830 pp.setSeparateProcesses(mSeparateProcesses); 14831 pp.setDisplayMetrics(mMetrics); 14832 14833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14834 final PackageParser.Package pkg; 14835 try { 14836 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14837 } catch (PackageParserException e) { 14838 res.setError("Failed parse during installPackageLI", e); 14839 return; 14840 } finally { 14841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14842 } 14843 14844 // If we are installing a clustered package add results for the children 14845 if (pkg.childPackages != null) { 14846 synchronized (mPackages) { 14847 final int childCount = pkg.childPackages.size(); 14848 for (int i = 0; i < childCount; i++) { 14849 PackageParser.Package childPkg = pkg.childPackages.get(i); 14850 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14851 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14852 childRes.pkg = childPkg; 14853 childRes.name = childPkg.packageName; 14854 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14855 if (childPs != null) { 14856 childRes.origUsers = childPs.queryInstalledUsers( 14857 sUserManager.getUserIds(), true); 14858 } 14859 if ((mPackages.containsKey(childPkg.packageName))) { 14860 childRes.removedInfo = new PackageRemovedInfo(); 14861 childRes.removedInfo.removedPackage = childPkg.packageName; 14862 } 14863 if (res.addedChildPackages == null) { 14864 res.addedChildPackages = new ArrayMap<>(); 14865 } 14866 res.addedChildPackages.put(childPkg.packageName, childRes); 14867 } 14868 } 14869 } 14870 14871 // If package doesn't declare API override, mark that we have an install 14872 // time CPU ABI override. 14873 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14874 pkg.cpuAbiOverride = args.abiOverride; 14875 } 14876 14877 String pkgName = res.name = pkg.packageName; 14878 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14879 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14880 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14881 return; 14882 } 14883 } 14884 14885 try { 14886 // either use what we've been given or parse directly from the APK 14887 if (args.certificates != null) { 14888 try { 14889 PackageParser.populateCertificates(pkg, args.certificates); 14890 } catch (PackageParserException e) { 14891 // there was something wrong with the certificates we were given; 14892 // try to pull them from the APK 14893 PackageParser.collectCertificates(pkg, parseFlags); 14894 } 14895 } else { 14896 PackageParser.collectCertificates(pkg, parseFlags); 14897 } 14898 } catch (PackageParserException e) { 14899 res.setError("Failed collect during installPackageLI", e); 14900 return; 14901 } 14902 14903 // Get rid of all references to package scan path via parser. 14904 pp = null; 14905 String oldCodePath = null; 14906 boolean systemApp = false; 14907 synchronized (mPackages) { 14908 // Check if installing already existing package 14909 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14910 String oldName = mSettings.mRenamedPackages.get(pkgName); 14911 if (pkg.mOriginalPackages != null 14912 && pkg.mOriginalPackages.contains(oldName) 14913 && mPackages.containsKey(oldName)) { 14914 // This package is derived from an original package, 14915 // and this device has been updating from that original 14916 // name. We must continue using the original name, so 14917 // rename the new package here. 14918 pkg.setPackageName(oldName); 14919 pkgName = pkg.packageName; 14920 replace = true; 14921 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14922 + oldName + " pkgName=" + pkgName); 14923 } else if (mPackages.containsKey(pkgName)) { 14924 // This package, under its official name, already exists 14925 // on the device; we should replace it. 14926 replace = true; 14927 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14928 } 14929 14930 // Child packages are installed through the parent package 14931 if (pkg.parentPackage != null) { 14932 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14933 "Package " + pkg.packageName + " is child of package " 14934 + pkg.parentPackage.parentPackage + ". Child packages " 14935 + "can be updated only through the parent package."); 14936 return; 14937 } 14938 14939 if (replace) { 14940 // Prevent apps opting out from runtime permissions 14941 PackageParser.Package oldPackage = mPackages.get(pkgName); 14942 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14943 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14944 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14945 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14946 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14947 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14948 + " doesn't support runtime permissions but the old" 14949 + " target SDK " + oldTargetSdk + " does."); 14950 return; 14951 } 14952 14953 // Prevent installing of child packages 14954 if (oldPackage.parentPackage != null) { 14955 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14956 "Package " + pkg.packageName + " is child of package " 14957 + oldPackage.parentPackage + ". Child packages " 14958 + "can be updated only through the parent package."); 14959 return; 14960 } 14961 } 14962 } 14963 14964 PackageSetting ps = mSettings.mPackages.get(pkgName); 14965 if (ps != null) { 14966 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14967 14968 // Quick sanity check that we're signed correctly if updating; 14969 // we'll check this again later when scanning, but we want to 14970 // bail early here before tripping over redefined permissions. 14971 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14972 if (!checkUpgradeKeySetLP(ps, pkg)) { 14973 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14974 + pkg.packageName + " upgrade keys do not match the " 14975 + "previously installed version"); 14976 return; 14977 } 14978 } else { 14979 try { 14980 verifySignaturesLP(ps, pkg); 14981 } catch (PackageManagerException e) { 14982 res.setError(e.error, e.getMessage()); 14983 return; 14984 } 14985 } 14986 14987 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14988 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14989 systemApp = (ps.pkg.applicationInfo.flags & 14990 ApplicationInfo.FLAG_SYSTEM) != 0; 14991 } 14992 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14993 } 14994 14995 // Check whether the newly-scanned package wants to define an already-defined perm 14996 int N = pkg.permissions.size(); 14997 for (int i = N-1; i >= 0; i--) { 14998 PackageParser.Permission perm = pkg.permissions.get(i); 14999 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15000 if (bp != null) { 15001 // If the defining package is signed with our cert, it's okay. This 15002 // also includes the "updating the same package" case, of course. 15003 // "updating same package" could also involve key-rotation. 15004 final boolean sigsOk; 15005 if (bp.sourcePackage.equals(pkg.packageName) 15006 && (bp.packageSetting instanceof PackageSetting) 15007 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15008 scanFlags))) { 15009 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15010 } else { 15011 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15012 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15013 } 15014 if (!sigsOk) { 15015 // If the owning package is the system itself, we log but allow 15016 // install to proceed; we fail the install on all other permission 15017 // redefinitions. 15018 if (!bp.sourcePackage.equals("android")) { 15019 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15020 + pkg.packageName + " attempting to redeclare permission " 15021 + perm.info.name + " already owned by " + bp.sourcePackage); 15022 res.origPermission = perm.info.name; 15023 res.origPackage = bp.sourcePackage; 15024 return; 15025 } else { 15026 Slog.w(TAG, "Package " + pkg.packageName 15027 + " attempting to redeclare system permission " 15028 + perm.info.name + "; ignoring new declaration"); 15029 pkg.permissions.remove(i); 15030 } 15031 } 15032 } 15033 } 15034 } 15035 15036 if (systemApp) { 15037 if (onExternal) { 15038 // Abort update; system app can't be replaced with app on sdcard 15039 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15040 "Cannot install updates to system apps on sdcard"); 15041 return; 15042 } else if (ephemeral) { 15043 // Abort update; system app can't be replaced with an ephemeral app 15044 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15045 "Cannot update a system app with an ephemeral app"); 15046 return; 15047 } 15048 } 15049 15050 if (args.move != null) { 15051 // We did an in-place move, so dex is ready to roll 15052 scanFlags |= SCAN_NO_DEX; 15053 scanFlags |= SCAN_MOVE; 15054 15055 synchronized (mPackages) { 15056 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15057 if (ps == null) { 15058 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15059 "Missing settings for moved package " + pkgName); 15060 } 15061 15062 // We moved the entire application as-is, so bring over the 15063 // previously derived ABI information. 15064 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15065 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15066 } 15067 15068 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15069 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15070 scanFlags |= SCAN_NO_DEX; 15071 15072 try { 15073 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15074 args.abiOverride : pkg.cpuAbiOverride); 15075 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15076 true /* extract libs */); 15077 } catch (PackageManagerException pme) { 15078 Slog.e(TAG, "Error deriving application ABI", pme); 15079 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15080 return; 15081 } 15082 15083 // Shared libraries for the package need to be updated. 15084 synchronized (mPackages) { 15085 try { 15086 updateSharedLibrariesLPw(pkg, null); 15087 } catch (PackageManagerException e) { 15088 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15089 } 15090 } 15091 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15092 // Do not run PackageDexOptimizer through the local performDexOpt 15093 // method because `pkg` may not be in `mPackages` yet. 15094 // 15095 // Also, don't fail application installs if the dexopt step fails. 15096 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15097 null /* instructionSets */, false /* checkProfiles */, 15098 getCompilerFilterForReason(REASON_INSTALL), 15099 getOrCreateCompilerPackageStats(pkg)); 15100 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15101 15102 // Notify BackgroundDexOptService that the package has been changed. 15103 // If this is an update of a package which used to fail to compile, 15104 // BDOS will remove it from its blacklist. 15105 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15106 } 15107 15108 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15109 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15110 return; 15111 } 15112 15113 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15114 15115 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15116 "installPackageLI")) { 15117 if (replace) { 15118 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15119 installerPackageName, res); 15120 } else { 15121 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15122 args.user, installerPackageName, volumeUuid, res); 15123 } 15124 } 15125 synchronized (mPackages) { 15126 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15127 if (ps != null) { 15128 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15129 } 15130 15131 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15132 for (int i = 0; i < childCount; i++) { 15133 PackageParser.Package childPkg = pkg.childPackages.get(i); 15134 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15135 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15136 if (childPs != null) { 15137 childRes.newUsers = childPs.queryInstalledUsers( 15138 sUserManager.getUserIds(), true); 15139 } 15140 } 15141 } 15142 } 15143 15144 private void startIntentFilterVerifications(int userId, boolean replacing, 15145 PackageParser.Package pkg) { 15146 if (mIntentFilterVerifierComponent == null) { 15147 Slog.w(TAG, "No IntentFilter verification will not be done as " 15148 + "there is no IntentFilterVerifier available!"); 15149 return; 15150 } 15151 15152 final int verifierUid = getPackageUid( 15153 mIntentFilterVerifierComponent.getPackageName(), 15154 MATCH_DEBUG_TRIAGED_MISSING, 15155 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15156 15157 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15158 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15159 mHandler.sendMessage(msg); 15160 15161 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15162 for (int i = 0; i < childCount; i++) { 15163 PackageParser.Package childPkg = pkg.childPackages.get(i); 15164 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15165 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15166 mHandler.sendMessage(msg); 15167 } 15168 } 15169 15170 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15171 PackageParser.Package pkg) { 15172 int size = pkg.activities.size(); 15173 if (size == 0) { 15174 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15175 "No activity, so no need to verify any IntentFilter!"); 15176 return; 15177 } 15178 15179 final boolean hasDomainURLs = hasDomainURLs(pkg); 15180 if (!hasDomainURLs) { 15181 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15182 "No domain URLs, so no need to verify any IntentFilter!"); 15183 return; 15184 } 15185 15186 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15187 + " if any IntentFilter from the " + size 15188 + " Activities needs verification ..."); 15189 15190 int count = 0; 15191 final String packageName = pkg.packageName; 15192 15193 synchronized (mPackages) { 15194 // If this is a new install and we see that we've already run verification for this 15195 // package, we have nothing to do: it means the state was restored from backup. 15196 if (!replacing) { 15197 IntentFilterVerificationInfo ivi = 15198 mSettings.getIntentFilterVerificationLPr(packageName); 15199 if (ivi != null) { 15200 if (DEBUG_DOMAIN_VERIFICATION) { 15201 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15202 + ivi.getStatusString()); 15203 } 15204 return; 15205 } 15206 } 15207 15208 // If any filters need to be verified, then all need to be. 15209 boolean needToVerify = false; 15210 for (PackageParser.Activity a : pkg.activities) { 15211 for (ActivityIntentInfo filter : a.intents) { 15212 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15213 if (DEBUG_DOMAIN_VERIFICATION) { 15214 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15215 } 15216 needToVerify = true; 15217 break; 15218 } 15219 } 15220 } 15221 15222 if (needToVerify) { 15223 final int verificationId = mIntentFilterVerificationToken++; 15224 for (PackageParser.Activity a : pkg.activities) { 15225 for (ActivityIntentInfo filter : a.intents) { 15226 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15227 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15228 "Verification needed for IntentFilter:" + filter.toString()); 15229 mIntentFilterVerifier.addOneIntentFilterVerification( 15230 verifierUid, userId, verificationId, filter, packageName); 15231 count++; 15232 } 15233 } 15234 } 15235 } 15236 } 15237 15238 if (count > 0) { 15239 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15240 + " IntentFilter verification" + (count > 1 ? "s" : "") 15241 + " for userId:" + userId); 15242 mIntentFilterVerifier.startVerifications(userId); 15243 } else { 15244 if (DEBUG_DOMAIN_VERIFICATION) { 15245 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15246 } 15247 } 15248 } 15249 15250 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15251 final ComponentName cn = filter.activity.getComponentName(); 15252 final String packageName = cn.getPackageName(); 15253 15254 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15255 packageName); 15256 if (ivi == null) { 15257 return true; 15258 } 15259 int status = ivi.getStatus(); 15260 switch (status) { 15261 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15262 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15263 return true; 15264 15265 default: 15266 // Nothing to do 15267 return false; 15268 } 15269 } 15270 15271 private static boolean isMultiArch(ApplicationInfo info) { 15272 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15273 } 15274 15275 private static boolean isExternal(PackageParser.Package pkg) { 15276 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15277 } 15278 15279 private static boolean isExternal(PackageSetting ps) { 15280 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15281 } 15282 15283 private static boolean isEphemeral(PackageParser.Package pkg) { 15284 return pkg.applicationInfo.isEphemeralApp(); 15285 } 15286 15287 private static boolean isEphemeral(PackageSetting ps) { 15288 return ps.pkg != null && isEphemeral(ps.pkg); 15289 } 15290 15291 private static boolean isSystemApp(PackageParser.Package pkg) { 15292 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15293 } 15294 15295 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15296 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15297 } 15298 15299 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15300 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15301 } 15302 15303 private static boolean isSystemApp(PackageSetting ps) { 15304 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15305 } 15306 15307 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15308 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15309 } 15310 15311 private int packageFlagsToInstallFlags(PackageSetting ps) { 15312 int installFlags = 0; 15313 if (isEphemeral(ps)) { 15314 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15315 } 15316 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15317 // This existing package was an external ASEC install when we have 15318 // the external flag without a UUID 15319 installFlags |= PackageManager.INSTALL_EXTERNAL; 15320 } 15321 if (ps.isForwardLocked()) { 15322 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15323 } 15324 return installFlags; 15325 } 15326 15327 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15328 if (isExternal(pkg)) { 15329 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15330 return StorageManager.UUID_PRIMARY_PHYSICAL; 15331 } else { 15332 return pkg.volumeUuid; 15333 } 15334 } else { 15335 return StorageManager.UUID_PRIVATE_INTERNAL; 15336 } 15337 } 15338 15339 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15340 if (isExternal(pkg)) { 15341 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15342 return mSettings.getExternalVersion(); 15343 } else { 15344 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15345 } 15346 } else { 15347 return mSettings.getInternalVersion(); 15348 } 15349 } 15350 15351 private void deleteTempPackageFiles() { 15352 final FilenameFilter filter = new FilenameFilter() { 15353 public boolean accept(File dir, String name) { 15354 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15355 } 15356 }; 15357 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15358 file.delete(); 15359 } 15360 } 15361 15362 @Override 15363 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15364 int flags) { 15365 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15366 flags); 15367 } 15368 15369 @Override 15370 public void deletePackage(final String packageName, 15371 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15372 mContext.enforceCallingOrSelfPermission( 15373 android.Manifest.permission.DELETE_PACKAGES, null); 15374 Preconditions.checkNotNull(packageName); 15375 Preconditions.checkNotNull(observer); 15376 final int uid = Binder.getCallingUid(); 15377 if (uid != Process.SHELL_UID && uid != Process.ROOT_UID && uid != Process.SYSTEM_UID 15378 && uid != getPackageUid(mRequiredInstallerPackage, 0, UserHandle.getUserId(uid)) 15379 && !isOrphaned(packageName) 15380 && !isCallerSameAsInstaller(uid, packageName)) { 15381 try { 15382 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15383 intent.setData(Uri.fromParts("package", packageName, null)); 15384 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15385 observer.onUserActionRequired(intent); 15386 } catch (RemoteException re) { 15387 } 15388 return; 15389 } 15390 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15391 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15392 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15393 mContext.enforceCallingOrSelfPermission( 15394 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15395 "deletePackage for user " + userId); 15396 } 15397 15398 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15399 try { 15400 observer.onPackageDeleted(packageName, 15401 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15402 } catch (RemoteException re) { 15403 } 15404 return; 15405 } 15406 15407 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15408 try { 15409 observer.onPackageDeleted(packageName, 15410 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15411 } catch (RemoteException re) { 15412 } 15413 return; 15414 } 15415 15416 if (DEBUG_REMOVE) { 15417 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15418 + " deleteAllUsers: " + deleteAllUsers ); 15419 } 15420 // Queue up an async operation since the package deletion may take a little while. 15421 mHandler.post(new Runnable() { 15422 public void run() { 15423 mHandler.removeCallbacks(this); 15424 int returnCode; 15425 if (!deleteAllUsers) { 15426 returnCode = deletePackageX(packageName, userId, deleteFlags); 15427 } else { 15428 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15429 // If nobody is blocking uninstall, proceed with delete for all users 15430 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15431 returnCode = deletePackageX(packageName, userId, deleteFlags); 15432 } else { 15433 // Otherwise uninstall individually for users with blockUninstalls=false 15434 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15435 for (int userId : users) { 15436 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15437 returnCode = deletePackageX(packageName, userId, userFlags); 15438 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15439 Slog.w(TAG, "Package delete failed for user " + userId 15440 + ", returnCode " + returnCode); 15441 } 15442 } 15443 } 15444 // The app has only been marked uninstalled for certain users. 15445 // We still need to report that delete was blocked 15446 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15447 } 15448 } 15449 try { 15450 observer.onPackageDeleted(packageName, returnCode, null); 15451 } catch (RemoteException e) { 15452 Log.i(TAG, "Observer no longer exists."); 15453 } //end catch 15454 } //end run 15455 }); 15456 } 15457 15458 private boolean isCallerSameAsInstaller(int callingUid, String pkgName) { 15459 final int installerPkgUid = getPackageUid(getInstallerPackageName(pkgName), 15460 0 /* flags */, UserHandle.getUserId(callingUid)); 15461 return installerPkgUid == callingUid; 15462 } 15463 15464 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15465 int[] result = EMPTY_INT_ARRAY; 15466 for (int userId : userIds) { 15467 if (getBlockUninstallForUser(packageName, userId)) { 15468 result = ArrayUtils.appendInt(result, userId); 15469 } 15470 } 15471 return result; 15472 } 15473 15474 @Override 15475 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15476 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15477 } 15478 15479 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15480 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15481 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15482 try { 15483 if (dpm != null) { 15484 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15485 /* callingUserOnly =*/ false); 15486 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15487 : deviceOwnerComponentName.getPackageName(); 15488 // Does the package contains the device owner? 15489 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15490 // this check is probably not needed, since DO should be registered as a device 15491 // admin on some user too. (Original bug for this: b/17657954) 15492 if (packageName.equals(deviceOwnerPackageName)) { 15493 return true; 15494 } 15495 // Does it contain a device admin for any user? 15496 int[] users; 15497 if (userId == UserHandle.USER_ALL) { 15498 users = sUserManager.getUserIds(); 15499 } else { 15500 users = new int[]{userId}; 15501 } 15502 for (int i = 0; i < users.length; ++i) { 15503 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15504 return true; 15505 } 15506 } 15507 } 15508 } catch (RemoteException e) { 15509 } 15510 return false; 15511 } 15512 15513 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15514 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15515 } 15516 15517 /** 15518 * This method is an internal method that could be get invoked either 15519 * to delete an installed package or to clean up a failed installation. 15520 * After deleting an installed package, a broadcast is sent to notify any 15521 * listeners that the package has been removed. For cleaning up a failed 15522 * installation, the broadcast is not necessary since the package's 15523 * installation wouldn't have sent the initial broadcast either 15524 * The key steps in deleting a package are 15525 * deleting the package information in internal structures like mPackages, 15526 * deleting the packages base directories through installd 15527 * updating mSettings to reflect current status 15528 * persisting settings for later use 15529 * sending a broadcast if necessary 15530 */ 15531 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15532 final PackageRemovedInfo info = new PackageRemovedInfo(); 15533 final boolean res; 15534 15535 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15536 ? UserHandle.USER_ALL : userId; 15537 15538 if (isPackageDeviceAdmin(packageName, removeUser)) { 15539 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15540 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15541 } 15542 15543 PackageSetting uninstalledPs = null; 15544 15545 // for the uninstall-updates case and restricted profiles, remember the per- 15546 // user handle installed state 15547 int[] allUsers; 15548 synchronized (mPackages) { 15549 uninstalledPs = mSettings.mPackages.get(packageName); 15550 if (uninstalledPs == null) { 15551 Slog.w(TAG, "Not removing non-existent package " + packageName); 15552 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15553 } 15554 allUsers = sUserManager.getUserIds(); 15555 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15556 } 15557 15558 final int freezeUser; 15559 if (isUpdatedSystemApp(uninstalledPs) 15560 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15561 // We're downgrading a system app, which will apply to all users, so 15562 // freeze them all during the downgrade 15563 freezeUser = UserHandle.USER_ALL; 15564 } else { 15565 freezeUser = removeUser; 15566 } 15567 15568 synchronized (mInstallLock) { 15569 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15570 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15571 deleteFlags, "deletePackageX")) { 15572 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15573 deleteFlags | REMOVE_CHATTY, info, true, null); 15574 } 15575 synchronized (mPackages) { 15576 if (res) { 15577 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15578 } 15579 } 15580 } 15581 15582 if (res) { 15583 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15584 info.sendPackageRemovedBroadcasts(killApp); 15585 info.sendSystemPackageUpdatedBroadcasts(); 15586 info.sendSystemPackageAppearedBroadcasts(); 15587 } 15588 // Force a gc here. 15589 Runtime.getRuntime().gc(); 15590 // Delete the resources here after sending the broadcast to let 15591 // other processes clean up before deleting resources. 15592 if (info.args != null) { 15593 synchronized (mInstallLock) { 15594 info.args.doPostDeleteLI(true); 15595 } 15596 } 15597 15598 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15599 } 15600 15601 class PackageRemovedInfo { 15602 String removedPackage; 15603 int uid = -1; 15604 int removedAppId = -1; 15605 int[] origUsers; 15606 int[] removedUsers = null; 15607 boolean isRemovedPackageSystemUpdate = false; 15608 boolean isUpdate; 15609 boolean dataRemoved; 15610 boolean removedForAllUsers; 15611 // Clean up resources deleted packages. 15612 InstallArgs args = null; 15613 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15614 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15615 15616 void sendPackageRemovedBroadcasts(boolean killApp) { 15617 sendPackageRemovedBroadcastInternal(killApp); 15618 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15619 for (int i = 0; i < childCount; i++) { 15620 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15621 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15622 } 15623 } 15624 15625 void sendSystemPackageUpdatedBroadcasts() { 15626 if (isRemovedPackageSystemUpdate) { 15627 sendSystemPackageUpdatedBroadcastsInternal(); 15628 final int childCount = (removedChildPackages != null) 15629 ? removedChildPackages.size() : 0; 15630 for (int i = 0; i < childCount; i++) { 15631 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15632 if (childInfo.isRemovedPackageSystemUpdate) { 15633 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15634 } 15635 } 15636 } 15637 } 15638 15639 void sendSystemPackageAppearedBroadcasts() { 15640 final int packageCount = (appearedChildPackages != null) 15641 ? appearedChildPackages.size() : 0; 15642 for (int i = 0; i < packageCount; i++) { 15643 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15644 for (int userId : installedInfo.newUsers) { 15645 sendPackageAddedForUser(installedInfo.name, true, 15646 UserHandle.getAppId(installedInfo.uid), userId); 15647 } 15648 } 15649 } 15650 15651 private void sendSystemPackageUpdatedBroadcastsInternal() { 15652 Bundle extras = new Bundle(2); 15653 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15654 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15655 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15656 extras, 0, null, null, null); 15657 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15658 extras, 0, null, null, null); 15659 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15660 null, 0, removedPackage, null, null); 15661 } 15662 15663 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15664 Bundle extras = new Bundle(2); 15665 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15666 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15667 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15668 if (isUpdate || isRemovedPackageSystemUpdate) { 15669 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15670 } 15671 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15672 if (removedPackage != null) { 15673 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15674 extras, 0, null, null, removedUsers); 15675 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15676 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15677 removedPackage, extras, 0, null, null, removedUsers); 15678 } 15679 } 15680 if (removedAppId >= 0) { 15681 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15682 removedUsers); 15683 } 15684 } 15685 } 15686 15687 /* 15688 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15689 * flag is not set, the data directory is removed as well. 15690 * make sure this flag is set for partially installed apps. If not its meaningless to 15691 * delete a partially installed application. 15692 */ 15693 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15694 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15695 String packageName = ps.name; 15696 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15697 // Retrieve object to delete permissions for shared user later on 15698 final PackageParser.Package deletedPkg; 15699 final PackageSetting deletedPs; 15700 // reader 15701 synchronized (mPackages) { 15702 deletedPkg = mPackages.get(packageName); 15703 deletedPs = mSettings.mPackages.get(packageName); 15704 if (outInfo != null) { 15705 outInfo.removedPackage = packageName; 15706 outInfo.removedUsers = deletedPs != null 15707 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15708 : null; 15709 } 15710 } 15711 15712 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15713 15714 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15715 final PackageParser.Package resolvedPkg; 15716 if (deletedPkg != null) { 15717 resolvedPkg = deletedPkg; 15718 } else { 15719 // We don't have a parsed package when it lives on an ejected 15720 // adopted storage device, so fake something together 15721 resolvedPkg = new PackageParser.Package(ps.name); 15722 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15723 } 15724 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15725 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15726 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15727 if (outInfo != null) { 15728 outInfo.dataRemoved = true; 15729 } 15730 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15731 } 15732 15733 // writer 15734 synchronized (mPackages) { 15735 if (deletedPs != null) { 15736 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15737 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15738 clearDefaultBrowserIfNeeded(packageName); 15739 if (outInfo != null) { 15740 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15741 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15742 } 15743 updatePermissionsLPw(deletedPs.name, null, 0); 15744 if (deletedPs.sharedUser != null) { 15745 // Remove permissions associated with package. Since runtime 15746 // permissions are per user we have to kill the removed package 15747 // or packages running under the shared user of the removed 15748 // package if revoking the permissions requested only by the removed 15749 // package is successful and this causes a change in gids. 15750 for (int userId : UserManagerService.getInstance().getUserIds()) { 15751 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15752 userId); 15753 if (userIdToKill == UserHandle.USER_ALL 15754 || userIdToKill >= UserHandle.USER_SYSTEM) { 15755 // If gids changed for this user, kill all affected packages. 15756 mHandler.post(new Runnable() { 15757 @Override 15758 public void run() { 15759 // This has to happen with no lock held. 15760 killApplication(deletedPs.name, deletedPs.appId, 15761 KILL_APP_REASON_GIDS_CHANGED); 15762 } 15763 }); 15764 break; 15765 } 15766 } 15767 } 15768 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15769 } 15770 // make sure to preserve per-user disabled state if this removal was just 15771 // a downgrade of a system app to the factory package 15772 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15773 if (DEBUG_REMOVE) { 15774 Slog.d(TAG, "Propagating install state across downgrade"); 15775 } 15776 for (int userId : allUserHandles) { 15777 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15778 if (DEBUG_REMOVE) { 15779 Slog.d(TAG, " user " + userId + " => " + installed); 15780 } 15781 ps.setInstalled(installed, userId); 15782 } 15783 } 15784 } 15785 // can downgrade to reader 15786 if (writeSettings) { 15787 // Save settings now 15788 mSettings.writeLPr(); 15789 } 15790 } 15791 if (outInfo != null) { 15792 // A user ID was deleted here. Go through all users and remove it 15793 // from KeyStore. 15794 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15795 } 15796 } 15797 15798 static boolean locationIsPrivileged(File path) { 15799 try { 15800 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15801 .getCanonicalPath(); 15802 return path.getCanonicalPath().startsWith(privilegedAppDir); 15803 } catch (IOException e) { 15804 Slog.e(TAG, "Unable to access code path " + path); 15805 } 15806 return false; 15807 } 15808 15809 /* 15810 * Tries to delete system package. 15811 */ 15812 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15813 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15814 boolean writeSettings) { 15815 if (deletedPs.parentPackageName != null) { 15816 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15817 return false; 15818 } 15819 15820 final boolean applyUserRestrictions 15821 = (allUserHandles != null) && (outInfo.origUsers != null); 15822 final PackageSetting disabledPs; 15823 // Confirm if the system package has been updated 15824 // An updated system app can be deleted. This will also have to restore 15825 // the system pkg from system partition 15826 // reader 15827 synchronized (mPackages) { 15828 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15829 } 15830 15831 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15832 + " disabledPs=" + disabledPs); 15833 15834 if (disabledPs == null) { 15835 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15836 return false; 15837 } else if (DEBUG_REMOVE) { 15838 Slog.d(TAG, "Deleting system pkg from data partition"); 15839 } 15840 15841 if (DEBUG_REMOVE) { 15842 if (applyUserRestrictions) { 15843 Slog.d(TAG, "Remembering install states:"); 15844 for (int userId : allUserHandles) { 15845 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15846 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15847 } 15848 } 15849 } 15850 15851 // Delete the updated package 15852 outInfo.isRemovedPackageSystemUpdate = true; 15853 if (outInfo.removedChildPackages != null) { 15854 final int childCount = (deletedPs.childPackageNames != null) 15855 ? deletedPs.childPackageNames.size() : 0; 15856 for (int i = 0; i < childCount; i++) { 15857 String childPackageName = deletedPs.childPackageNames.get(i); 15858 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15859 .contains(childPackageName)) { 15860 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15861 childPackageName); 15862 if (childInfo != null) { 15863 childInfo.isRemovedPackageSystemUpdate = true; 15864 } 15865 } 15866 } 15867 } 15868 15869 if (disabledPs.versionCode < deletedPs.versionCode) { 15870 // Delete data for downgrades 15871 flags &= ~PackageManager.DELETE_KEEP_DATA; 15872 } else { 15873 // Preserve data by setting flag 15874 flags |= PackageManager.DELETE_KEEP_DATA; 15875 } 15876 15877 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15878 outInfo, writeSettings, disabledPs.pkg); 15879 if (!ret) { 15880 return false; 15881 } 15882 15883 // writer 15884 synchronized (mPackages) { 15885 // Reinstate the old system package 15886 enableSystemPackageLPw(disabledPs.pkg); 15887 // Remove any native libraries from the upgraded package. 15888 removeNativeBinariesLI(deletedPs); 15889 } 15890 15891 // Install the system package 15892 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15893 int parseFlags = mDefParseFlags 15894 | PackageParser.PARSE_MUST_BE_APK 15895 | PackageParser.PARSE_IS_SYSTEM 15896 | PackageParser.PARSE_IS_SYSTEM_DIR; 15897 if (locationIsPrivileged(disabledPs.codePath)) { 15898 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15899 } 15900 15901 final PackageParser.Package newPkg; 15902 try { 15903 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15904 } catch (PackageManagerException e) { 15905 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15906 + e.getMessage()); 15907 return false; 15908 } 15909 try { 15910 // update shared libraries for the newly re-installed system package 15911 updateSharedLibrariesLPw(newPkg, null); 15912 } catch (PackageManagerException e) { 15913 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 15914 } 15915 15916 prepareAppDataAfterInstallLIF(newPkg); 15917 15918 // writer 15919 synchronized (mPackages) { 15920 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15921 15922 // Propagate the permissions state as we do not want to drop on the floor 15923 // runtime permissions. The update permissions method below will take 15924 // care of removing obsolete permissions and grant install permissions. 15925 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15926 updatePermissionsLPw(newPkg.packageName, newPkg, 15927 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15928 15929 if (applyUserRestrictions) { 15930 if (DEBUG_REMOVE) { 15931 Slog.d(TAG, "Propagating install state across reinstall"); 15932 } 15933 for (int userId : allUserHandles) { 15934 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15935 if (DEBUG_REMOVE) { 15936 Slog.d(TAG, " user " + userId + " => " + installed); 15937 } 15938 ps.setInstalled(installed, userId); 15939 15940 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15941 } 15942 // Regardless of writeSettings we need to ensure that this restriction 15943 // state propagation is persisted 15944 mSettings.writeAllUsersPackageRestrictionsLPr(); 15945 } 15946 // can downgrade to reader here 15947 if (writeSettings) { 15948 mSettings.writeLPr(); 15949 } 15950 } 15951 return true; 15952 } 15953 15954 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15955 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15956 PackageRemovedInfo outInfo, boolean writeSettings, 15957 PackageParser.Package replacingPackage) { 15958 synchronized (mPackages) { 15959 if (outInfo != null) { 15960 outInfo.uid = ps.appId; 15961 } 15962 15963 if (outInfo != null && outInfo.removedChildPackages != null) { 15964 final int childCount = (ps.childPackageNames != null) 15965 ? ps.childPackageNames.size() : 0; 15966 for (int i = 0; i < childCount; i++) { 15967 String childPackageName = ps.childPackageNames.get(i); 15968 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15969 if (childPs == null) { 15970 return false; 15971 } 15972 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15973 childPackageName); 15974 if (childInfo != null) { 15975 childInfo.uid = childPs.appId; 15976 } 15977 } 15978 } 15979 } 15980 15981 // Delete package data from internal structures and also remove data if flag is set 15982 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15983 15984 // Delete the child packages data 15985 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15986 for (int i = 0; i < childCount; i++) { 15987 PackageSetting childPs; 15988 synchronized (mPackages) { 15989 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15990 } 15991 if (childPs != null) { 15992 PackageRemovedInfo childOutInfo = (outInfo != null 15993 && outInfo.removedChildPackages != null) 15994 ? outInfo.removedChildPackages.get(childPs.name) : null; 15995 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15996 && (replacingPackage != null 15997 && !replacingPackage.hasChildPackage(childPs.name)) 15998 ? flags & ~DELETE_KEEP_DATA : flags; 15999 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16000 deleteFlags, writeSettings); 16001 } 16002 } 16003 16004 // Delete application code and resources only for parent packages 16005 if (ps.parentPackageName == null) { 16006 if (deleteCodeAndResources && (outInfo != null)) { 16007 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16008 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16009 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16010 } 16011 } 16012 16013 return true; 16014 } 16015 16016 @Override 16017 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16018 int userId) { 16019 mContext.enforceCallingOrSelfPermission( 16020 android.Manifest.permission.DELETE_PACKAGES, null); 16021 synchronized (mPackages) { 16022 PackageSetting ps = mSettings.mPackages.get(packageName); 16023 if (ps == null) { 16024 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16025 return false; 16026 } 16027 if (!ps.getInstalled(userId)) { 16028 // Can't block uninstall for an app that is not installed or enabled. 16029 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16030 return false; 16031 } 16032 ps.setBlockUninstall(blockUninstall, userId); 16033 mSettings.writePackageRestrictionsLPr(userId); 16034 } 16035 return true; 16036 } 16037 16038 @Override 16039 public boolean getBlockUninstallForUser(String packageName, int userId) { 16040 synchronized (mPackages) { 16041 PackageSetting ps = mSettings.mPackages.get(packageName); 16042 if (ps == null) { 16043 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16044 return false; 16045 } 16046 return ps.getBlockUninstall(userId); 16047 } 16048 } 16049 16050 @Override 16051 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16052 int callingUid = Binder.getCallingUid(); 16053 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16054 throw new SecurityException( 16055 "setRequiredForSystemUser can only be run by the system or root"); 16056 } 16057 synchronized (mPackages) { 16058 PackageSetting ps = mSettings.mPackages.get(packageName); 16059 if (ps == null) { 16060 Log.w(TAG, "Package doesn't exist: " + packageName); 16061 return false; 16062 } 16063 if (systemUserApp) { 16064 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16065 } else { 16066 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16067 } 16068 mSettings.writeLPr(); 16069 } 16070 return true; 16071 } 16072 16073 /* 16074 * This method handles package deletion in general 16075 */ 16076 private boolean deletePackageLIF(String packageName, UserHandle user, 16077 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16078 PackageRemovedInfo outInfo, boolean writeSettings, 16079 PackageParser.Package replacingPackage) { 16080 if (packageName == null) { 16081 Slog.w(TAG, "Attempt to delete null packageName."); 16082 return false; 16083 } 16084 16085 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16086 16087 PackageSetting ps; 16088 16089 synchronized (mPackages) { 16090 ps = mSettings.mPackages.get(packageName); 16091 if (ps == null) { 16092 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16093 return false; 16094 } 16095 16096 if (ps.parentPackageName != null && (!isSystemApp(ps) 16097 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16098 if (DEBUG_REMOVE) { 16099 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16100 + ((user == null) ? UserHandle.USER_ALL : user)); 16101 } 16102 final int removedUserId = (user != null) ? user.getIdentifier() 16103 : UserHandle.USER_ALL; 16104 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16105 return false; 16106 } 16107 markPackageUninstalledForUserLPw(ps, user); 16108 scheduleWritePackageRestrictionsLocked(user); 16109 return true; 16110 } 16111 } 16112 16113 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16114 && user.getIdentifier() != UserHandle.USER_ALL)) { 16115 // The caller is asking that the package only be deleted for a single 16116 // user. To do this, we just mark its uninstalled state and delete 16117 // its data. If this is a system app, we only allow this to happen if 16118 // they have set the special DELETE_SYSTEM_APP which requests different 16119 // semantics than normal for uninstalling system apps. 16120 markPackageUninstalledForUserLPw(ps, user); 16121 16122 if (!isSystemApp(ps)) { 16123 // Do not uninstall the APK if an app should be cached 16124 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16125 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16126 // Other user still have this package installed, so all 16127 // we need to do is clear this user's data and save that 16128 // it is uninstalled. 16129 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16130 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16131 return false; 16132 } 16133 scheduleWritePackageRestrictionsLocked(user); 16134 return true; 16135 } else { 16136 // We need to set it back to 'installed' so the uninstall 16137 // broadcasts will be sent correctly. 16138 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16139 ps.setInstalled(true, user.getIdentifier()); 16140 } 16141 } else { 16142 // This is a system app, so we assume that the 16143 // other users still have this package installed, so all 16144 // we need to do is clear this user's data and save that 16145 // it is uninstalled. 16146 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16147 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16148 return false; 16149 } 16150 scheduleWritePackageRestrictionsLocked(user); 16151 return true; 16152 } 16153 } 16154 16155 // If we are deleting a composite package for all users, keep track 16156 // of result for each child. 16157 if (ps.childPackageNames != null && outInfo != null) { 16158 synchronized (mPackages) { 16159 final int childCount = ps.childPackageNames.size(); 16160 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16161 for (int i = 0; i < childCount; i++) { 16162 String childPackageName = ps.childPackageNames.get(i); 16163 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16164 childInfo.removedPackage = childPackageName; 16165 outInfo.removedChildPackages.put(childPackageName, childInfo); 16166 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16167 if (childPs != null) { 16168 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16169 } 16170 } 16171 } 16172 } 16173 16174 boolean ret = false; 16175 if (isSystemApp(ps)) { 16176 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16177 // When an updated system application is deleted we delete the existing resources 16178 // as well and fall back to existing code in system partition 16179 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16180 } else { 16181 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16182 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16183 outInfo, writeSettings, replacingPackage); 16184 } 16185 16186 // Take a note whether we deleted the package for all users 16187 if (outInfo != null) { 16188 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16189 if (outInfo.removedChildPackages != null) { 16190 synchronized (mPackages) { 16191 final int childCount = outInfo.removedChildPackages.size(); 16192 for (int i = 0; i < childCount; i++) { 16193 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16194 if (childInfo != null) { 16195 childInfo.removedForAllUsers = mPackages.get( 16196 childInfo.removedPackage) == null; 16197 } 16198 } 16199 } 16200 } 16201 // If we uninstalled an update to a system app there may be some 16202 // child packages that appeared as they are declared in the system 16203 // app but were not declared in the update. 16204 if (isSystemApp(ps)) { 16205 synchronized (mPackages) { 16206 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16207 final int childCount = (updatedPs.childPackageNames != null) 16208 ? updatedPs.childPackageNames.size() : 0; 16209 for (int i = 0; i < childCount; i++) { 16210 String childPackageName = updatedPs.childPackageNames.get(i); 16211 if (outInfo.removedChildPackages == null 16212 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16213 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16214 if (childPs == null) { 16215 continue; 16216 } 16217 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16218 installRes.name = childPackageName; 16219 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16220 installRes.pkg = mPackages.get(childPackageName); 16221 installRes.uid = childPs.pkg.applicationInfo.uid; 16222 if (outInfo.appearedChildPackages == null) { 16223 outInfo.appearedChildPackages = new ArrayMap<>(); 16224 } 16225 outInfo.appearedChildPackages.put(childPackageName, installRes); 16226 } 16227 } 16228 } 16229 } 16230 } 16231 16232 return ret; 16233 } 16234 16235 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16236 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16237 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16238 for (int nextUserId : userIds) { 16239 if (DEBUG_REMOVE) { 16240 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16241 } 16242 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16243 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16244 false /*hidden*/, false /*suspended*/, null, null, null, 16245 false /*blockUninstall*/, 16246 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16247 } 16248 } 16249 16250 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16251 PackageRemovedInfo outInfo) { 16252 final PackageParser.Package pkg; 16253 synchronized (mPackages) { 16254 pkg = mPackages.get(ps.name); 16255 } 16256 16257 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16258 : new int[] {userId}; 16259 for (int nextUserId : userIds) { 16260 if (DEBUG_REMOVE) { 16261 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16262 + nextUserId); 16263 } 16264 16265 destroyAppDataLIF(pkg, userId, 16266 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16267 destroyAppProfilesLIF(pkg, userId); 16268 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16269 schedulePackageCleaning(ps.name, nextUserId, false); 16270 synchronized (mPackages) { 16271 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16272 scheduleWritePackageRestrictionsLocked(nextUserId); 16273 } 16274 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16275 } 16276 } 16277 16278 if (outInfo != null) { 16279 outInfo.removedPackage = ps.name; 16280 outInfo.removedAppId = ps.appId; 16281 outInfo.removedUsers = userIds; 16282 } 16283 16284 return true; 16285 } 16286 16287 private final class ClearStorageConnection implements ServiceConnection { 16288 IMediaContainerService mContainerService; 16289 16290 @Override 16291 public void onServiceConnected(ComponentName name, IBinder service) { 16292 synchronized (this) { 16293 mContainerService = IMediaContainerService.Stub.asInterface(service); 16294 notifyAll(); 16295 } 16296 } 16297 16298 @Override 16299 public void onServiceDisconnected(ComponentName name) { 16300 } 16301 } 16302 16303 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16304 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16305 16306 final boolean mounted; 16307 if (Environment.isExternalStorageEmulated()) { 16308 mounted = true; 16309 } else { 16310 final String status = Environment.getExternalStorageState(); 16311 16312 mounted = status.equals(Environment.MEDIA_MOUNTED) 16313 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16314 } 16315 16316 if (!mounted) { 16317 return; 16318 } 16319 16320 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16321 int[] users; 16322 if (userId == UserHandle.USER_ALL) { 16323 users = sUserManager.getUserIds(); 16324 } else { 16325 users = new int[] { userId }; 16326 } 16327 final ClearStorageConnection conn = new ClearStorageConnection(); 16328 if (mContext.bindServiceAsUser( 16329 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16330 try { 16331 for (int curUser : users) { 16332 long timeout = SystemClock.uptimeMillis() + 5000; 16333 synchronized (conn) { 16334 long now; 16335 while (conn.mContainerService == null && 16336 (now = SystemClock.uptimeMillis()) < timeout) { 16337 try { 16338 conn.wait(timeout - now); 16339 } catch (InterruptedException e) { 16340 } 16341 } 16342 } 16343 if (conn.mContainerService == null) { 16344 return; 16345 } 16346 16347 final UserEnvironment userEnv = new UserEnvironment(curUser); 16348 clearDirectory(conn.mContainerService, 16349 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16350 if (allData) { 16351 clearDirectory(conn.mContainerService, 16352 userEnv.buildExternalStorageAppDataDirs(packageName)); 16353 clearDirectory(conn.mContainerService, 16354 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16355 } 16356 } 16357 } finally { 16358 mContext.unbindService(conn); 16359 } 16360 } 16361 } 16362 16363 @Override 16364 public void clearApplicationProfileData(String packageName) { 16365 enforceSystemOrRoot("Only the system can clear all profile data"); 16366 16367 final PackageParser.Package pkg; 16368 synchronized (mPackages) { 16369 pkg = mPackages.get(packageName); 16370 } 16371 16372 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16373 synchronized (mInstallLock) { 16374 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16375 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16376 true /* removeBaseMarker */); 16377 } 16378 } 16379 } 16380 16381 @Override 16382 public void clearApplicationUserData(final String packageName, 16383 final IPackageDataObserver observer, final int userId) { 16384 mContext.enforceCallingOrSelfPermission( 16385 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16386 16387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16388 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16389 16390 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16391 throw new SecurityException("Cannot clear data for a protected package: " 16392 + packageName); 16393 } 16394 // Queue up an async operation since the package deletion may take a little while. 16395 mHandler.post(new Runnable() { 16396 public void run() { 16397 mHandler.removeCallbacks(this); 16398 final boolean succeeded; 16399 try (PackageFreezer freezer = freezePackage(packageName, 16400 "clearApplicationUserData")) { 16401 synchronized (mInstallLock) { 16402 succeeded = clearApplicationUserDataLIF(packageName, userId); 16403 } 16404 clearExternalStorageDataSync(packageName, userId, true); 16405 } 16406 if (succeeded) { 16407 // invoke DeviceStorageMonitor's update method to clear any notifications 16408 DeviceStorageMonitorInternal dsm = LocalServices 16409 .getService(DeviceStorageMonitorInternal.class); 16410 if (dsm != null) { 16411 dsm.checkMemory(); 16412 } 16413 } 16414 if(observer != null) { 16415 try { 16416 observer.onRemoveCompleted(packageName, succeeded); 16417 } catch (RemoteException e) { 16418 Log.i(TAG, "Observer no longer exists."); 16419 } 16420 } //end if observer 16421 } //end run 16422 }); 16423 } 16424 16425 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16426 if (packageName == null) { 16427 Slog.w(TAG, "Attempt to delete null packageName."); 16428 return false; 16429 } 16430 16431 // Try finding details about the requested package 16432 PackageParser.Package pkg; 16433 synchronized (mPackages) { 16434 pkg = mPackages.get(packageName); 16435 if (pkg == null) { 16436 final PackageSetting ps = mSettings.mPackages.get(packageName); 16437 if (ps != null) { 16438 pkg = ps.pkg; 16439 } 16440 } 16441 16442 if (pkg == null) { 16443 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16444 return false; 16445 } 16446 16447 PackageSetting ps = (PackageSetting) pkg.mExtras; 16448 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16449 } 16450 16451 clearAppDataLIF(pkg, userId, 16452 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16453 16454 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16455 removeKeystoreDataIfNeeded(userId, appId); 16456 16457 UserManagerInternal umInternal = getUserManagerInternal(); 16458 final int flags; 16459 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16460 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16461 } else if (umInternal.isUserRunning(userId)) { 16462 flags = StorageManager.FLAG_STORAGE_DE; 16463 } else { 16464 flags = 0; 16465 } 16466 prepareAppDataContentsLIF(pkg, userId, flags); 16467 16468 return true; 16469 } 16470 16471 /** 16472 * Reverts user permission state changes (permissions and flags) in 16473 * all packages for a given user. 16474 * 16475 * @param userId The device user for which to do a reset. 16476 */ 16477 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16478 final int packageCount = mPackages.size(); 16479 for (int i = 0; i < packageCount; i++) { 16480 PackageParser.Package pkg = mPackages.valueAt(i); 16481 PackageSetting ps = (PackageSetting) pkg.mExtras; 16482 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16483 } 16484 } 16485 16486 private void resetNetworkPolicies(int userId) { 16487 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16488 } 16489 16490 /** 16491 * Reverts user permission state changes (permissions and flags). 16492 * 16493 * @param ps The package for which to reset. 16494 * @param userId The device user for which to do a reset. 16495 */ 16496 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16497 final PackageSetting ps, final int userId) { 16498 if (ps.pkg == null) { 16499 return; 16500 } 16501 16502 // These are flags that can change base on user actions. 16503 final int userSettableMask = FLAG_PERMISSION_USER_SET 16504 | FLAG_PERMISSION_USER_FIXED 16505 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16506 | FLAG_PERMISSION_REVIEW_REQUIRED; 16507 16508 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16509 | FLAG_PERMISSION_POLICY_FIXED; 16510 16511 boolean writeInstallPermissions = false; 16512 boolean writeRuntimePermissions = false; 16513 16514 final int permissionCount = ps.pkg.requestedPermissions.size(); 16515 for (int i = 0; i < permissionCount; i++) { 16516 String permission = ps.pkg.requestedPermissions.get(i); 16517 16518 BasePermission bp = mSettings.mPermissions.get(permission); 16519 if (bp == null) { 16520 continue; 16521 } 16522 16523 // If shared user we just reset the state to which only this app contributed. 16524 if (ps.sharedUser != null) { 16525 boolean used = false; 16526 final int packageCount = ps.sharedUser.packages.size(); 16527 for (int j = 0; j < packageCount; j++) { 16528 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16529 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16530 && pkg.pkg.requestedPermissions.contains(permission)) { 16531 used = true; 16532 break; 16533 } 16534 } 16535 if (used) { 16536 continue; 16537 } 16538 } 16539 16540 PermissionsState permissionsState = ps.getPermissionsState(); 16541 16542 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16543 16544 // Always clear the user settable flags. 16545 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16546 bp.name) != null; 16547 // If permission review is enabled and this is a legacy app, mark the 16548 // permission as requiring a review as this is the initial state. 16549 int flags = 0; 16550 if (Build.PERMISSIONS_REVIEW_REQUIRED 16551 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16552 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16553 } 16554 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16555 if (hasInstallState) { 16556 writeInstallPermissions = true; 16557 } else { 16558 writeRuntimePermissions = true; 16559 } 16560 } 16561 16562 // Below is only runtime permission handling. 16563 if (!bp.isRuntime()) { 16564 continue; 16565 } 16566 16567 // Never clobber system or policy. 16568 if ((oldFlags & policyOrSystemFlags) != 0) { 16569 continue; 16570 } 16571 16572 // If this permission was granted by default, make sure it is. 16573 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16574 if (permissionsState.grantRuntimePermission(bp, userId) 16575 != PERMISSION_OPERATION_FAILURE) { 16576 writeRuntimePermissions = true; 16577 } 16578 // If permission review is enabled the permissions for a legacy apps 16579 // are represented as constantly granted runtime ones, so don't revoke. 16580 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16581 // Otherwise, reset the permission. 16582 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16583 switch (revokeResult) { 16584 case PERMISSION_OPERATION_SUCCESS: 16585 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16586 writeRuntimePermissions = true; 16587 final int appId = ps.appId; 16588 mHandler.post(new Runnable() { 16589 @Override 16590 public void run() { 16591 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16592 } 16593 }); 16594 } break; 16595 } 16596 } 16597 } 16598 16599 // Synchronously write as we are taking permissions away. 16600 if (writeRuntimePermissions) { 16601 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16602 } 16603 16604 // Synchronously write as we are taking permissions away. 16605 if (writeInstallPermissions) { 16606 mSettings.writeLPr(); 16607 } 16608 } 16609 16610 /** 16611 * Remove entries from the keystore daemon. Will only remove it if the 16612 * {@code appId} is valid. 16613 */ 16614 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16615 if (appId < 0) { 16616 return; 16617 } 16618 16619 final KeyStore keyStore = KeyStore.getInstance(); 16620 if (keyStore != null) { 16621 if (userId == UserHandle.USER_ALL) { 16622 for (final int individual : sUserManager.getUserIds()) { 16623 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16624 } 16625 } else { 16626 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16627 } 16628 } else { 16629 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16630 } 16631 } 16632 16633 @Override 16634 public void deleteApplicationCacheFiles(final String packageName, 16635 final IPackageDataObserver observer) { 16636 final int userId = UserHandle.getCallingUserId(); 16637 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16638 } 16639 16640 @Override 16641 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16642 final IPackageDataObserver observer) { 16643 mContext.enforceCallingOrSelfPermission( 16644 android.Manifest.permission.DELETE_CACHE_FILES, null); 16645 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16646 /* requireFullPermission= */ true, /* checkShell= */ false, 16647 "delete application cache files"); 16648 16649 final PackageParser.Package pkg; 16650 synchronized (mPackages) { 16651 pkg = mPackages.get(packageName); 16652 } 16653 16654 // Queue up an async operation since the package deletion may take a little while. 16655 mHandler.post(new Runnable() { 16656 public void run() { 16657 synchronized (mInstallLock) { 16658 final int flags = StorageManager.FLAG_STORAGE_DE 16659 | StorageManager.FLAG_STORAGE_CE; 16660 // We're only clearing cache files, so we don't care if the 16661 // app is unfrozen and still able to run 16662 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16663 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16664 } 16665 clearExternalStorageDataSync(packageName, userId, false); 16666 if (observer != null) { 16667 try { 16668 observer.onRemoveCompleted(packageName, true); 16669 } catch (RemoteException e) { 16670 Log.i(TAG, "Observer no longer exists."); 16671 } 16672 } 16673 } 16674 }); 16675 } 16676 16677 @Override 16678 public void getPackageSizeInfo(final String packageName, int userHandle, 16679 final IPackageStatsObserver observer) { 16680 mContext.enforceCallingOrSelfPermission( 16681 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16682 if (packageName == null) { 16683 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16684 } 16685 16686 PackageStats stats = new PackageStats(packageName, userHandle); 16687 16688 /* 16689 * Queue up an async operation since the package measurement may take a 16690 * little while. 16691 */ 16692 Message msg = mHandler.obtainMessage(INIT_COPY); 16693 msg.obj = new MeasureParams(stats, observer); 16694 mHandler.sendMessage(msg); 16695 } 16696 16697 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16698 final PackageSetting ps; 16699 synchronized (mPackages) { 16700 ps = mSettings.mPackages.get(packageName); 16701 if (ps == null) { 16702 Slog.w(TAG, "Failed to find settings for " + packageName); 16703 return false; 16704 } 16705 } 16706 try { 16707 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16708 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16709 ps.getCeDataInode(userId), ps.codePathString, stats); 16710 } catch (InstallerException e) { 16711 Slog.w(TAG, String.valueOf(e)); 16712 return false; 16713 } 16714 16715 // For now, ignore code size of packages on system partition 16716 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16717 stats.codeSize = 0; 16718 } 16719 16720 return true; 16721 } 16722 16723 private int getUidTargetSdkVersionLockedLPr(int uid) { 16724 Object obj = mSettings.getUserIdLPr(uid); 16725 if (obj instanceof SharedUserSetting) { 16726 final SharedUserSetting sus = (SharedUserSetting) obj; 16727 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16728 final Iterator<PackageSetting> it = sus.packages.iterator(); 16729 while (it.hasNext()) { 16730 final PackageSetting ps = it.next(); 16731 if (ps.pkg != null) { 16732 int v = ps.pkg.applicationInfo.targetSdkVersion; 16733 if (v < vers) vers = v; 16734 } 16735 } 16736 return vers; 16737 } else if (obj instanceof PackageSetting) { 16738 final PackageSetting ps = (PackageSetting) obj; 16739 if (ps.pkg != null) { 16740 return ps.pkg.applicationInfo.targetSdkVersion; 16741 } 16742 } 16743 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16744 } 16745 16746 @Override 16747 public void addPreferredActivity(IntentFilter filter, int match, 16748 ComponentName[] set, ComponentName activity, int userId) { 16749 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16750 "Adding preferred"); 16751 } 16752 16753 private void addPreferredActivityInternal(IntentFilter filter, int match, 16754 ComponentName[] set, ComponentName activity, boolean always, int userId, 16755 String opname) { 16756 // writer 16757 int callingUid = Binder.getCallingUid(); 16758 enforceCrossUserPermission(callingUid, userId, 16759 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16760 if (filter.countActions() == 0) { 16761 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16762 return; 16763 } 16764 synchronized (mPackages) { 16765 if (mContext.checkCallingOrSelfPermission( 16766 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16767 != PackageManager.PERMISSION_GRANTED) { 16768 if (getUidTargetSdkVersionLockedLPr(callingUid) 16769 < Build.VERSION_CODES.FROYO) { 16770 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16771 + callingUid); 16772 return; 16773 } 16774 mContext.enforceCallingOrSelfPermission( 16775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16776 } 16777 16778 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16779 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16780 + userId + ":"); 16781 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16782 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16783 scheduleWritePackageRestrictionsLocked(userId); 16784 postPreferredActivityChangedBroadcast(userId); 16785 } 16786 } 16787 16788 private void postPreferredActivityChangedBroadcast(int userId) { 16789 mHandler.post(() -> { 16790 final IActivityManager am = ActivityManagerNative.getDefault(); 16791 if (am == null) { 16792 return; 16793 } 16794 16795 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16796 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16797 try { 16798 am.broadcastIntent(null, intent, null, null, 16799 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16800 null, false, false, userId); 16801 } catch (RemoteException e) { 16802 } 16803 }); 16804 } 16805 16806 @Override 16807 public void replacePreferredActivity(IntentFilter filter, int match, 16808 ComponentName[] set, ComponentName activity, int userId) { 16809 if (filter.countActions() != 1) { 16810 throw new IllegalArgumentException( 16811 "replacePreferredActivity expects filter to have only 1 action."); 16812 } 16813 if (filter.countDataAuthorities() != 0 16814 || filter.countDataPaths() != 0 16815 || filter.countDataSchemes() > 1 16816 || filter.countDataTypes() != 0) { 16817 throw new IllegalArgumentException( 16818 "replacePreferredActivity expects filter to have no data authorities, " + 16819 "paths, or types; and at most one scheme."); 16820 } 16821 16822 final int callingUid = Binder.getCallingUid(); 16823 enforceCrossUserPermission(callingUid, userId, 16824 true /* requireFullPermission */, false /* checkShell */, 16825 "replace preferred activity"); 16826 synchronized (mPackages) { 16827 if (mContext.checkCallingOrSelfPermission( 16828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16829 != PackageManager.PERMISSION_GRANTED) { 16830 if (getUidTargetSdkVersionLockedLPr(callingUid) 16831 < Build.VERSION_CODES.FROYO) { 16832 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16833 + Binder.getCallingUid()); 16834 return; 16835 } 16836 mContext.enforceCallingOrSelfPermission( 16837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16838 } 16839 16840 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16841 if (pir != null) { 16842 // Get all of the existing entries that exactly match this filter. 16843 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16844 if (existing != null && existing.size() == 1) { 16845 PreferredActivity cur = existing.get(0); 16846 if (DEBUG_PREFERRED) { 16847 Slog.i(TAG, "Checking replace of preferred:"); 16848 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16849 if (!cur.mPref.mAlways) { 16850 Slog.i(TAG, " -- CUR; not mAlways!"); 16851 } else { 16852 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16853 Slog.i(TAG, " -- CUR: mSet=" 16854 + Arrays.toString(cur.mPref.mSetComponents)); 16855 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16856 Slog.i(TAG, " -- NEW: mMatch=" 16857 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16858 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16859 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16860 } 16861 } 16862 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16863 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16864 && cur.mPref.sameSet(set)) { 16865 // Setting the preferred activity to what it happens to be already 16866 if (DEBUG_PREFERRED) { 16867 Slog.i(TAG, "Replacing with same preferred activity " 16868 + cur.mPref.mShortComponent + " for user " 16869 + userId + ":"); 16870 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16871 } 16872 return; 16873 } 16874 } 16875 16876 if (existing != null) { 16877 if (DEBUG_PREFERRED) { 16878 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16879 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16880 } 16881 for (int i = 0; i < existing.size(); i++) { 16882 PreferredActivity pa = existing.get(i); 16883 if (DEBUG_PREFERRED) { 16884 Slog.i(TAG, "Removing existing preferred activity " 16885 + pa.mPref.mComponent + ":"); 16886 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16887 } 16888 pir.removeFilter(pa); 16889 } 16890 } 16891 } 16892 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16893 "Replacing preferred"); 16894 } 16895 } 16896 16897 @Override 16898 public void clearPackagePreferredActivities(String packageName) { 16899 final int uid = Binder.getCallingUid(); 16900 // writer 16901 synchronized (mPackages) { 16902 PackageParser.Package pkg = mPackages.get(packageName); 16903 if (pkg == null || pkg.applicationInfo.uid != uid) { 16904 if (mContext.checkCallingOrSelfPermission( 16905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16906 != PackageManager.PERMISSION_GRANTED) { 16907 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16908 < Build.VERSION_CODES.FROYO) { 16909 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16910 + Binder.getCallingUid()); 16911 return; 16912 } 16913 mContext.enforceCallingOrSelfPermission( 16914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16915 } 16916 } 16917 16918 int user = UserHandle.getCallingUserId(); 16919 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16920 scheduleWritePackageRestrictionsLocked(user); 16921 } 16922 } 16923 } 16924 16925 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16926 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16927 ArrayList<PreferredActivity> removed = null; 16928 boolean changed = false; 16929 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16930 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16931 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16932 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16933 continue; 16934 } 16935 Iterator<PreferredActivity> it = pir.filterIterator(); 16936 while (it.hasNext()) { 16937 PreferredActivity pa = it.next(); 16938 // Mark entry for removal only if it matches the package name 16939 // and the entry is of type "always". 16940 if (packageName == null || 16941 (pa.mPref.mComponent.getPackageName().equals(packageName) 16942 && pa.mPref.mAlways)) { 16943 if (removed == null) { 16944 removed = new ArrayList<PreferredActivity>(); 16945 } 16946 removed.add(pa); 16947 } 16948 } 16949 if (removed != null) { 16950 for (int j=0; j<removed.size(); j++) { 16951 PreferredActivity pa = removed.get(j); 16952 pir.removeFilter(pa); 16953 } 16954 changed = true; 16955 } 16956 } 16957 if (changed) { 16958 postPreferredActivityChangedBroadcast(userId); 16959 } 16960 return changed; 16961 } 16962 16963 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16964 private void clearIntentFilterVerificationsLPw(int userId) { 16965 final int packageCount = mPackages.size(); 16966 for (int i = 0; i < packageCount; i++) { 16967 PackageParser.Package pkg = mPackages.valueAt(i); 16968 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16969 } 16970 } 16971 16972 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16973 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16974 if (userId == UserHandle.USER_ALL) { 16975 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16976 sUserManager.getUserIds())) { 16977 for (int oneUserId : sUserManager.getUserIds()) { 16978 scheduleWritePackageRestrictionsLocked(oneUserId); 16979 } 16980 } 16981 } else { 16982 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16983 scheduleWritePackageRestrictionsLocked(userId); 16984 } 16985 } 16986 } 16987 16988 void clearDefaultBrowserIfNeeded(String packageName) { 16989 for (int oneUserId : sUserManager.getUserIds()) { 16990 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16991 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16992 if (packageName.equals(defaultBrowserPackageName)) { 16993 setDefaultBrowserPackageName(null, oneUserId); 16994 } 16995 } 16996 } 16997 16998 @Override 16999 public void resetApplicationPreferences(int userId) { 17000 mContext.enforceCallingOrSelfPermission( 17001 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17002 final long identity = Binder.clearCallingIdentity(); 17003 // writer 17004 try { 17005 synchronized (mPackages) { 17006 clearPackagePreferredActivitiesLPw(null, userId); 17007 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17008 // TODO: We have to reset the default SMS and Phone. This requires 17009 // significant refactoring to keep all default apps in the package 17010 // manager (cleaner but more work) or have the services provide 17011 // callbacks to the package manager to request a default app reset. 17012 applyFactoryDefaultBrowserLPw(userId); 17013 clearIntentFilterVerificationsLPw(userId); 17014 primeDomainVerificationsLPw(userId); 17015 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17016 scheduleWritePackageRestrictionsLocked(userId); 17017 } 17018 resetNetworkPolicies(userId); 17019 } finally { 17020 Binder.restoreCallingIdentity(identity); 17021 } 17022 } 17023 17024 @Override 17025 public int getPreferredActivities(List<IntentFilter> outFilters, 17026 List<ComponentName> outActivities, String packageName) { 17027 17028 int num = 0; 17029 final int userId = UserHandle.getCallingUserId(); 17030 // reader 17031 synchronized (mPackages) { 17032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17033 if (pir != null) { 17034 final Iterator<PreferredActivity> it = pir.filterIterator(); 17035 while (it.hasNext()) { 17036 final PreferredActivity pa = it.next(); 17037 if (packageName == null 17038 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17039 && pa.mPref.mAlways)) { 17040 if (outFilters != null) { 17041 outFilters.add(new IntentFilter(pa)); 17042 } 17043 if (outActivities != null) { 17044 outActivities.add(pa.mPref.mComponent); 17045 } 17046 } 17047 } 17048 } 17049 } 17050 17051 return num; 17052 } 17053 17054 @Override 17055 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17056 int userId) { 17057 int callingUid = Binder.getCallingUid(); 17058 if (callingUid != Process.SYSTEM_UID) { 17059 throw new SecurityException( 17060 "addPersistentPreferredActivity can only be run by the system"); 17061 } 17062 if (filter.countActions() == 0) { 17063 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17064 return; 17065 } 17066 synchronized (mPackages) { 17067 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17068 ":"); 17069 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17070 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17071 new PersistentPreferredActivity(filter, activity)); 17072 scheduleWritePackageRestrictionsLocked(userId); 17073 postPreferredActivityChangedBroadcast(userId); 17074 } 17075 } 17076 17077 @Override 17078 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17079 int callingUid = Binder.getCallingUid(); 17080 if (callingUid != Process.SYSTEM_UID) { 17081 throw new SecurityException( 17082 "clearPackagePersistentPreferredActivities can only be run by the system"); 17083 } 17084 ArrayList<PersistentPreferredActivity> removed = null; 17085 boolean changed = false; 17086 synchronized (mPackages) { 17087 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17088 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17089 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17090 .valueAt(i); 17091 if (userId != thisUserId) { 17092 continue; 17093 } 17094 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17095 while (it.hasNext()) { 17096 PersistentPreferredActivity ppa = it.next(); 17097 // Mark entry for removal only if it matches the package name. 17098 if (ppa.mComponent.getPackageName().equals(packageName)) { 17099 if (removed == null) { 17100 removed = new ArrayList<PersistentPreferredActivity>(); 17101 } 17102 removed.add(ppa); 17103 } 17104 } 17105 if (removed != null) { 17106 for (int j=0; j<removed.size(); j++) { 17107 PersistentPreferredActivity ppa = removed.get(j); 17108 ppir.removeFilter(ppa); 17109 } 17110 changed = true; 17111 } 17112 } 17113 17114 if (changed) { 17115 scheduleWritePackageRestrictionsLocked(userId); 17116 postPreferredActivityChangedBroadcast(userId); 17117 } 17118 } 17119 } 17120 17121 /** 17122 * Common machinery for picking apart a restored XML blob and passing 17123 * it to a caller-supplied functor to be applied to the running system. 17124 */ 17125 private void restoreFromXml(XmlPullParser parser, int userId, 17126 String expectedStartTag, BlobXmlRestorer functor) 17127 throws IOException, XmlPullParserException { 17128 int type; 17129 while ((type = parser.next()) != XmlPullParser.START_TAG 17130 && type != XmlPullParser.END_DOCUMENT) { 17131 } 17132 if (type != XmlPullParser.START_TAG) { 17133 // oops didn't find a start tag?! 17134 if (DEBUG_BACKUP) { 17135 Slog.e(TAG, "Didn't find start tag during restore"); 17136 } 17137 return; 17138 } 17139Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17140 // this is supposed to be TAG_PREFERRED_BACKUP 17141 if (!expectedStartTag.equals(parser.getName())) { 17142 if (DEBUG_BACKUP) { 17143 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17144 } 17145 return; 17146 } 17147 17148 // skip interfering stuff, then we're aligned with the backing implementation 17149 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17150Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17151 functor.apply(parser, userId); 17152 } 17153 17154 private interface BlobXmlRestorer { 17155 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17156 } 17157 17158 /** 17159 * Non-Binder method, support for the backup/restore mechanism: write the 17160 * full set of preferred activities in its canonical XML format. Returns the 17161 * XML output as a byte array, or null if there is none. 17162 */ 17163 @Override 17164 public byte[] getPreferredActivityBackup(int userId) { 17165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17166 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17167 } 17168 17169 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17170 try { 17171 final XmlSerializer serializer = new FastXmlSerializer(); 17172 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17173 serializer.startDocument(null, true); 17174 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17175 17176 synchronized (mPackages) { 17177 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17178 } 17179 17180 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17181 serializer.endDocument(); 17182 serializer.flush(); 17183 } catch (Exception e) { 17184 if (DEBUG_BACKUP) { 17185 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17186 } 17187 return null; 17188 } 17189 17190 return dataStream.toByteArray(); 17191 } 17192 17193 @Override 17194 public void restorePreferredActivities(byte[] backup, int userId) { 17195 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17196 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17197 } 17198 17199 try { 17200 final XmlPullParser parser = Xml.newPullParser(); 17201 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17202 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17203 new BlobXmlRestorer() { 17204 @Override 17205 public void apply(XmlPullParser parser, int userId) 17206 throws XmlPullParserException, IOException { 17207 synchronized (mPackages) { 17208 mSettings.readPreferredActivitiesLPw(parser, userId); 17209 } 17210 } 17211 } ); 17212 } catch (Exception e) { 17213 if (DEBUG_BACKUP) { 17214 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17215 } 17216 } 17217 } 17218 17219 /** 17220 * Non-Binder method, support for the backup/restore mechanism: write the 17221 * default browser (etc) settings in its canonical XML format. Returns the default 17222 * browser XML representation as a byte array, or null if there is none. 17223 */ 17224 @Override 17225 public byte[] getDefaultAppsBackup(int userId) { 17226 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17227 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17228 } 17229 17230 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17231 try { 17232 final XmlSerializer serializer = new FastXmlSerializer(); 17233 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17234 serializer.startDocument(null, true); 17235 serializer.startTag(null, TAG_DEFAULT_APPS); 17236 17237 synchronized (mPackages) { 17238 mSettings.writeDefaultAppsLPr(serializer, userId); 17239 } 17240 17241 serializer.endTag(null, TAG_DEFAULT_APPS); 17242 serializer.endDocument(); 17243 serializer.flush(); 17244 } catch (Exception e) { 17245 if (DEBUG_BACKUP) { 17246 Slog.e(TAG, "Unable to write default apps for backup", e); 17247 } 17248 return null; 17249 } 17250 17251 return dataStream.toByteArray(); 17252 } 17253 17254 @Override 17255 public void restoreDefaultApps(byte[] backup, int userId) { 17256 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17257 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17258 } 17259 17260 try { 17261 final XmlPullParser parser = Xml.newPullParser(); 17262 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17263 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17264 new BlobXmlRestorer() { 17265 @Override 17266 public void apply(XmlPullParser parser, int userId) 17267 throws XmlPullParserException, IOException { 17268 synchronized (mPackages) { 17269 mSettings.readDefaultAppsLPw(parser, userId); 17270 } 17271 } 17272 } ); 17273 } catch (Exception e) { 17274 if (DEBUG_BACKUP) { 17275 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17276 } 17277 } 17278 } 17279 17280 @Override 17281 public byte[] getIntentFilterVerificationBackup(int userId) { 17282 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17283 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17284 } 17285 17286 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17287 try { 17288 final XmlSerializer serializer = new FastXmlSerializer(); 17289 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17290 serializer.startDocument(null, true); 17291 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17292 17293 synchronized (mPackages) { 17294 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17295 } 17296 17297 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17298 serializer.endDocument(); 17299 serializer.flush(); 17300 } catch (Exception e) { 17301 if (DEBUG_BACKUP) { 17302 Slog.e(TAG, "Unable to write default apps for backup", e); 17303 } 17304 return null; 17305 } 17306 17307 return dataStream.toByteArray(); 17308 } 17309 17310 @Override 17311 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17313 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17314 } 17315 17316 try { 17317 final XmlPullParser parser = Xml.newPullParser(); 17318 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17319 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17320 new BlobXmlRestorer() { 17321 @Override 17322 public void apply(XmlPullParser parser, int userId) 17323 throws XmlPullParserException, IOException { 17324 synchronized (mPackages) { 17325 mSettings.readAllDomainVerificationsLPr(parser, userId); 17326 mSettings.writeLPr(); 17327 } 17328 } 17329 } ); 17330 } catch (Exception e) { 17331 if (DEBUG_BACKUP) { 17332 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17333 } 17334 } 17335 } 17336 17337 @Override 17338 public byte[] getPermissionGrantBackup(int userId) { 17339 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17340 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17341 } 17342 17343 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17344 try { 17345 final XmlSerializer serializer = new FastXmlSerializer(); 17346 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17347 serializer.startDocument(null, true); 17348 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17349 17350 synchronized (mPackages) { 17351 serializeRuntimePermissionGrantsLPr(serializer, userId); 17352 } 17353 17354 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17355 serializer.endDocument(); 17356 serializer.flush(); 17357 } catch (Exception e) { 17358 if (DEBUG_BACKUP) { 17359 Slog.e(TAG, "Unable to write default apps for backup", e); 17360 } 17361 return null; 17362 } 17363 17364 return dataStream.toByteArray(); 17365 } 17366 17367 @Override 17368 public void restorePermissionGrants(byte[] backup, int userId) { 17369 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17370 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17371 } 17372 17373 try { 17374 final XmlPullParser parser = Xml.newPullParser(); 17375 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17376 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17377 new BlobXmlRestorer() { 17378 @Override 17379 public void apply(XmlPullParser parser, int userId) 17380 throws XmlPullParserException, IOException { 17381 synchronized (mPackages) { 17382 processRestoredPermissionGrantsLPr(parser, userId); 17383 } 17384 } 17385 } ); 17386 } catch (Exception e) { 17387 if (DEBUG_BACKUP) { 17388 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17389 } 17390 } 17391 } 17392 17393 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17394 throws IOException { 17395 serializer.startTag(null, TAG_ALL_GRANTS); 17396 17397 final int N = mSettings.mPackages.size(); 17398 for (int i = 0; i < N; i++) { 17399 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17400 boolean pkgGrantsKnown = false; 17401 17402 PermissionsState packagePerms = ps.getPermissionsState(); 17403 17404 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17405 final int grantFlags = state.getFlags(); 17406 // only look at grants that are not system/policy fixed 17407 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17408 final boolean isGranted = state.isGranted(); 17409 // And only back up the user-twiddled state bits 17410 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17411 final String packageName = mSettings.mPackages.keyAt(i); 17412 if (!pkgGrantsKnown) { 17413 serializer.startTag(null, TAG_GRANT); 17414 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17415 pkgGrantsKnown = true; 17416 } 17417 17418 final boolean userSet = 17419 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17420 final boolean userFixed = 17421 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17422 final boolean revoke = 17423 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17424 17425 serializer.startTag(null, TAG_PERMISSION); 17426 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17427 if (isGranted) { 17428 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17429 } 17430 if (userSet) { 17431 serializer.attribute(null, ATTR_USER_SET, "true"); 17432 } 17433 if (userFixed) { 17434 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17435 } 17436 if (revoke) { 17437 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17438 } 17439 serializer.endTag(null, TAG_PERMISSION); 17440 } 17441 } 17442 } 17443 17444 if (pkgGrantsKnown) { 17445 serializer.endTag(null, TAG_GRANT); 17446 } 17447 } 17448 17449 serializer.endTag(null, TAG_ALL_GRANTS); 17450 } 17451 17452 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17453 throws XmlPullParserException, IOException { 17454 String pkgName = null; 17455 int outerDepth = parser.getDepth(); 17456 int type; 17457 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17458 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17459 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17460 continue; 17461 } 17462 17463 final String tagName = parser.getName(); 17464 if (tagName.equals(TAG_GRANT)) { 17465 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17466 if (DEBUG_BACKUP) { 17467 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17468 } 17469 } else if (tagName.equals(TAG_PERMISSION)) { 17470 17471 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17472 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17473 17474 int newFlagSet = 0; 17475 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17476 newFlagSet |= FLAG_PERMISSION_USER_SET; 17477 } 17478 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17479 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17480 } 17481 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17482 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17483 } 17484 if (DEBUG_BACKUP) { 17485 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17486 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17487 } 17488 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17489 if (ps != null) { 17490 // Already installed so we apply the grant immediately 17491 if (DEBUG_BACKUP) { 17492 Slog.v(TAG, " + already installed; applying"); 17493 } 17494 PermissionsState perms = ps.getPermissionsState(); 17495 BasePermission bp = mSettings.mPermissions.get(permName); 17496 if (bp != null) { 17497 if (isGranted) { 17498 perms.grantRuntimePermission(bp, userId); 17499 } 17500 if (newFlagSet != 0) { 17501 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17502 } 17503 } 17504 } else { 17505 // Need to wait for post-restore install to apply the grant 17506 if (DEBUG_BACKUP) { 17507 Slog.v(TAG, " - not yet installed; saving for later"); 17508 } 17509 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17510 isGranted, newFlagSet, userId); 17511 } 17512 } else { 17513 PackageManagerService.reportSettingsProblem(Log.WARN, 17514 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17515 XmlUtils.skipCurrentTag(parser); 17516 } 17517 } 17518 17519 scheduleWriteSettingsLocked(); 17520 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17521 } 17522 17523 @Override 17524 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17525 int sourceUserId, int targetUserId, int flags) { 17526 mContext.enforceCallingOrSelfPermission( 17527 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17528 int callingUid = Binder.getCallingUid(); 17529 enforceOwnerRights(ownerPackage, callingUid); 17530 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17531 if (intentFilter.countActions() == 0) { 17532 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17533 return; 17534 } 17535 synchronized (mPackages) { 17536 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17537 ownerPackage, targetUserId, flags); 17538 CrossProfileIntentResolver resolver = 17539 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17540 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17541 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17542 if (existing != null) { 17543 int size = existing.size(); 17544 for (int i = 0; i < size; i++) { 17545 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17546 return; 17547 } 17548 } 17549 } 17550 resolver.addFilter(newFilter); 17551 scheduleWritePackageRestrictionsLocked(sourceUserId); 17552 } 17553 } 17554 17555 @Override 17556 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17557 mContext.enforceCallingOrSelfPermission( 17558 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17559 int callingUid = Binder.getCallingUid(); 17560 enforceOwnerRights(ownerPackage, callingUid); 17561 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17562 synchronized (mPackages) { 17563 CrossProfileIntentResolver resolver = 17564 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17565 ArraySet<CrossProfileIntentFilter> set = 17566 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17567 for (CrossProfileIntentFilter filter : set) { 17568 if (filter.getOwnerPackage().equals(ownerPackage)) { 17569 resolver.removeFilter(filter); 17570 } 17571 } 17572 scheduleWritePackageRestrictionsLocked(sourceUserId); 17573 } 17574 } 17575 17576 // Enforcing that callingUid is owning pkg on userId 17577 private void enforceOwnerRights(String pkg, int callingUid) { 17578 // The system owns everything. 17579 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17580 return; 17581 } 17582 int callingUserId = UserHandle.getUserId(callingUid); 17583 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17584 if (pi == null) { 17585 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17586 + callingUserId); 17587 } 17588 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17589 throw new SecurityException("Calling uid " + callingUid 17590 + " does not own package " + pkg); 17591 } 17592 } 17593 17594 @Override 17595 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17596 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17597 } 17598 17599 private Intent getHomeIntent() { 17600 Intent intent = new Intent(Intent.ACTION_MAIN); 17601 intent.addCategory(Intent.CATEGORY_HOME); 17602 intent.addCategory(Intent.CATEGORY_DEFAULT); 17603 return intent; 17604 } 17605 17606 private IntentFilter getHomeFilter() { 17607 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17608 filter.addCategory(Intent.CATEGORY_HOME); 17609 filter.addCategory(Intent.CATEGORY_DEFAULT); 17610 return filter; 17611 } 17612 17613 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17614 int userId) { 17615 Intent intent = getHomeIntent(); 17616 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17617 PackageManager.GET_META_DATA, userId); 17618 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17619 true, false, false, userId); 17620 17621 allHomeCandidates.clear(); 17622 if (list != null) { 17623 for (ResolveInfo ri : list) { 17624 allHomeCandidates.add(ri); 17625 } 17626 } 17627 return (preferred == null || preferred.activityInfo == null) 17628 ? null 17629 : new ComponentName(preferred.activityInfo.packageName, 17630 preferred.activityInfo.name); 17631 } 17632 17633 @Override 17634 public void setHomeActivity(ComponentName comp, int userId) { 17635 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17636 getHomeActivitiesAsUser(homeActivities, userId); 17637 17638 boolean found = false; 17639 17640 final int size = homeActivities.size(); 17641 final ComponentName[] set = new ComponentName[size]; 17642 for (int i = 0; i < size; i++) { 17643 final ResolveInfo candidate = homeActivities.get(i); 17644 final ActivityInfo info = candidate.activityInfo; 17645 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17646 set[i] = activityName; 17647 if (!found && activityName.equals(comp)) { 17648 found = true; 17649 } 17650 } 17651 if (!found) { 17652 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17653 + userId); 17654 } 17655 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17656 set, comp, userId); 17657 } 17658 17659 private @Nullable String getSetupWizardPackageName() { 17660 final Intent intent = new Intent(Intent.ACTION_MAIN); 17661 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17662 17663 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17664 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17665 | MATCH_DISABLED_COMPONENTS, 17666 UserHandle.myUserId()); 17667 if (matches.size() == 1) { 17668 return matches.get(0).getComponentInfo().packageName; 17669 } else { 17670 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17671 + ": matches=" + matches); 17672 return null; 17673 } 17674 } 17675 17676 @Override 17677 public void setApplicationEnabledSetting(String appPackageName, 17678 int newState, int flags, int userId, String callingPackage) { 17679 if (!sUserManager.exists(userId)) return; 17680 if (callingPackage == null) { 17681 callingPackage = Integer.toString(Binder.getCallingUid()); 17682 } 17683 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17684 } 17685 17686 @Override 17687 public void setComponentEnabledSetting(ComponentName componentName, 17688 int newState, int flags, int userId) { 17689 if (!sUserManager.exists(userId)) return; 17690 setEnabledSetting(componentName.getPackageName(), 17691 componentName.getClassName(), newState, flags, userId, null); 17692 } 17693 17694 private void setEnabledSetting(final String packageName, String className, int newState, 17695 final int flags, int userId, String callingPackage) { 17696 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17697 || newState == COMPONENT_ENABLED_STATE_ENABLED 17698 || newState == COMPONENT_ENABLED_STATE_DISABLED 17699 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17700 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17701 throw new IllegalArgumentException("Invalid new component state: " 17702 + newState); 17703 } 17704 PackageSetting pkgSetting; 17705 final int uid = Binder.getCallingUid(); 17706 final int permission; 17707 if (uid == Process.SYSTEM_UID) { 17708 permission = PackageManager.PERMISSION_GRANTED; 17709 } else { 17710 permission = mContext.checkCallingOrSelfPermission( 17711 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17712 } 17713 enforceCrossUserPermission(uid, userId, 17714 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17715 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17716 boolean sendNow = false; 17717 boolean isApp = (className == null); 17718 String componentName = isApp ? packageName : className; 17719 int packageUid = -1; 17720 ArrayList<String> components; 17721 17722 // writer 17723 synchronized (mPackages) { 17724 pkgSetting = mSettings.mPackages.get(packageName); 17725 if (pkgSetting == null) { 17726 if (className == null) { 17727 throw new IllegalArgumentException("Unknown package: " + packageName); 17728 } 17729 throw new IllegalArgumentException( 17730 "Unknown component: " + packageName + "/" + className); 17731 } 17732 } 17733 17734 // Limit who can change which apps 17735 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17736 // Don't allow apps that don't have permission to modify other apps 17737 if (!allowedByPermission) { 17738 throw new SecurityException( 17739 "Permission Denial: attempt to change component state from pid=" 17740 + Binder.getCallingPid() 17741 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17742 } 17743 // Don't allow changing protected packages. 17744 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17745 throw new SecurityException("Cannot disable a protected package: " + packageName); 17746 } 17747 } 17748 17749 synchronized (mPackages) { 17750 if (uid == Process.SHELL_UID) { 17751 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17752 int oldState = pkgSetting.getEnabled(userId); 17753 if (className == null 17754 && 17755 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17756 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17757 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17758 && 17759 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17760 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17761 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17762 // ok 17763 } else { 17764 throw new SecurityException( 17765 "Shell cannot change component state for " + packageName + "/" 17766 + className + " to " + newState); 17767 } 17768 } 17769 if (className == null) { 17770 // We're dealing with an application/package level state change 17771 if (pkgSetting.getEnabled(userId) == newState) { 17772 // Nothing to do 17773 return; 17774 } 17775 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17776 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17777 // Don't care about who enables an app. 17778 callingPackage = null; 17779 } 17780 pkgSetting.setEnabled(newState, userId, callingPackage); 17781 // pkgSetting.pkg.mSetEnabled = newState; 17782 } else { 17783 // We're dealing with a component level state change 17784 // First, verify that this is a valid class name. 17785 PackageParser.Package pkg = pkgSetting.pkg; 17786 if (pkg == null || !pkg.hasComponentClassName(className)) { 17787 if (pkg != null && 17788 pkg.applicationInfo.targetSdkVersion >= 17789 Build.VERSION_CODES.JELLY_BEAN) { 17790 throw new IllegalArgumentException("Component class " + className 17791 + " does not exist in " + packageName); 17792 } else { 17793 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17794 + className + " does not exist in " + packageName); 17795 } 17796 } 17797 switch (newState) { 17798 case COMPONENT_ENABLED_STATE_ENABLED: 17799 if (!pkgSetting.enableComponentLPw(className, userId)) { 17800 return; 17801 } 17802 break; 17803 case COMPONENT_ENABLED_STATE_DISABLED: 17804 if (!pkgSetting.disableComponentLPw(className, userId)) { 17805 return; 17806 } 17807 break; 17808 case COMPONENT_ENABLED_STATE_DEFAULT: 17809 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17810 return; 17811 } 17812 break; 17813 default: 17814 Slog.e(TAG, "Invalid new component state: " + newState); 17815 return; 17816 } 17817 } 17818 scheduleWritePackageRestrictionsLocked(userId); 17819 components = mPendingBroadcasts.get(userId, packageName); 17820 final boolean newPackage = components == null; 17821 if (newPackage) { 17822 components = new ArrayList<String>(); 17823 } 17824 if (!components.contains(componentName)) { 17825 components.add(componentName); 17826 } 17827 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17828 sendNow = true; 17829 // Purge entry from pending broadcast list if another one exists already 17830 // since we are sending one right away. 17831 mPendingBroadcasts.remove(userId, packageName); 17832 } else { 17833 if (newPackage) { 17834 mPendingBroadcasts.put(userId, packageName, components); 17835 } 17836 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17837 // Schedule a message 17838 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17839 } 17840 } 17841 } 17842 17843 long callingId = Binder.clearCallingIdentity(); 17844 try { 17845 if (sendNow) { 17846 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17847 sendPackageChangedBroadcast(packageName, 17848 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17849 } 17850 } finally { 17851 Binder.restoreCallingIdentity(callingId); 17852 } 17853 } 17854 17855 @Override 17856 public void flushPackageRestrictionsAsUser(int userId) { 17857 if (!sUserManager.exists(userId)) { 17858 return; 17859 } 17860 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17861 false /* checkShell */, "flushPackageRestrictions"); 17862 synchronized (mPackages) { 17863 mSettings.writePackageRestrictionsLPr(userId); 17864 mDirtyUsers.remove(userId); 17865 if (mDirtyUsers.isEmpty()) { 17866 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17867 } 17868 } 17869 } 17870 17871 private void sendPackageChangedBroadcast(String packageName, 17872 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17873 if (DEBUG_INSTALL) 17874 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17875 + componentNames); 17876 Bundle extras = new Bundle(4); 17877 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17878 String nameList[] = new String[componentNames.size()]; 17879 componentNames.toArray(nameList); 17880 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17881 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17882 extras.putInt(Intent.EXTRA_UID, packageUid); 17883 // If this is not reporting a change of the overall package, then only send it 17884 // to registered receivers. We don't want to launch a swath of apps for every 17885 // little component state change. 17886 final int flags = !componentNames.contains(packageName) 17887 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17888 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17889 new int[] {UserHandle.getUserId(packageUid)}); 17890 } 17891 17892 @Override 17893 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17894 if (!sUserManager.exists(userId)) return; 17895 final int uid = Binder.getCallingUid(); 17896 final int permission = mContext.checkCallingOrSelfPermission( 17897 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17898 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17899 enforceCrossUserPermission(uid, userId, 17900 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17901 // writer 17902 synchronized (mPackages) { 17903 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17904 allowedByPermission, uid, userId)) { 17905 scheduleWritePackageRestrictionsLocked(userId); 17906 } 17907 } 17908 } 17909 17910 @Override 17911 public String getInstallerPackageName(String packageName) { 17912 // reader 17913 synchronized (mPackages) { 17914 return mSettings.getInstallerPackageNameLPr(packageName); 17915 } 17916 } 17917 17918 public boolean isOrphaned(String packageName) { 17919 // reader 17920 synchronized (mPackages) { 17921 return mSettings.isOrphaned(packageName); 17922 } 17923 } 17924 17925 @Override 17926 public int getApplicationEnabledSetting(String packageName, int userId) { 17927 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17928 int uid = Binder.getCallingUid(); 17929 enforceCrossUserPermission(uid, userId, 17930 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17931 // reader 17932 synchronized (mPackages) { 17933 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17934 } 17935 } 17936 17937 @Override 17938 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17939 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17940 int uid = Binder.getCallingUid(); 17941 enforceCrossUserPermission(uid, userId, 17942 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17943 // reader 17944 synchronized (mPackages) { 17945 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17946 } 17947 } 17948 17949 @Override 17950 public void enterSafeMode() { 17951 enforceSystemOrRoot("Only the system can request entering safe mode"); 17952 17953 if (!mSystemReady) { 17954 mSafeMode = true; 17955 } 17956 } 17957 17958 @Override 17959 public void systemReady() { 17960 mSystemReady = true; 17961 17962 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 17963 // disabled after already being started. 17964 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 17965 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 17966 17967 // Read the compatibilty setting when the system is ready. 17968 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17969 mContext.getContentResolver(), 17970 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17971 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17972 if (DEBUG_SETTINGS) { 17973 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17974 } 17975 17976 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17977 17978 synchronized (mPackages) { 17979 // Verify that all of the preferred activity components actually 17980 // exist. It is possible for applications to be updated and at 17981 // that point remove a previously declared activity component that 17982 // had been set as a preferred activity. We try to clean this up 17983 // the next time we encounter that preferred activity, but it is 17984 // possible for the user flow to never be able to return to that 17985 // situation so here we do a sanity check to make sure we haven't 17986 // left any junk around. 17987 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17988 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17989 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17990 removed.clear(); 17991 for (PreferredActivity pa : pir.filterSet()) { 17992 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17993 removed.add(pa); 17994 } 17995 } 17996 if (removed.size() > 0) { 17997 for (int r=0; r<removed.size(); r++) { 17998 PreferredActivity pa = removed.get(r); 17999 Slog.w(TAG, "Removing dangling preferred activity: " 18000 + pa.mPref.mComponent); 18001 pir.removeFilter(pa); 18002 } 18003 mSettings.writePackageRestrictionsLPr( 18004 mSettings.mPreferredActivities.keyAt(i)); 18005 } 18006 } 18007 18008 for (int userId : UserManagerService.getInstance().getUserIds()) { 18009 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18010 grantPermissionsUserIds = ArrayUtils.appendInt( 18011 grantPermissionsUserIds, userId); 18012 } 18013 } 18014 } 18015 sUserManager.systemReady(); 18016 18017 // If we upgraded grant all default permissions before kicking off. 18018 for (int userId : grantPermissionsUserIds) { 18019 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18020 } 18021 18022 // If we did not grant default permissions, we preload from this the 18023 // default permission exceptions lazily to ensure we don't hit the 18024 // disk on a new user creation. 18025 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18026 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18027 } 18028 18029 // Kick off any messages waiting for system ready 18030 if (mPostSystemReadyMessages != null) { 18031 for (Message msg : mPostSystemReadyMessages) { 18032 msg.sendToTarget(); 18033 } 18034 mPostSystemReadyMessages = null; 18035 } 18036 18037 // Watch for external volumes that come and go over time 18038 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18039 storage.registerListener(mStorageListener); 18040 18041 mInstallerService.systemReady(); 18042 mPackageDexOptimizer.systemReady(); 18043 18044 MountServiceInternal mountServiceInternal = LocalServices.getService( 18045 MountServiceInternal.class); 18046 mountServiceInternal.addExternalStoragePolicy( 18047 new MountServiceInternal.ExternalStorageMountPolicy() { 18048 @Override 18049 public int getMountMode(int uid, String packageName) { 18050 if (Process.isIsolated(uid)) { 18051 return Zygote.MOUNT_EXTERNAL_NONE; 18052 } 18053 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18054 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18055 } 18056 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18057 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18058 } 18059 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18060 return Zygote.MOUNT_EXTERNAL_READ; 18061 } 18062 return Zygote.MOUNT_EXTERNAL_WRITE; 18063 } 18064 18065 @Override 18066 public boolean hasExternalStorage(int uid, String packageName) { 18067 return true; 18068 } 18069 }); 18070 18071 // Now that we're mostly running, clean up stale users and apps 18072 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18073 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18074 } 18075 18076 @Override 18077 public boolean isSafeMode() { 18078 return mSafeMode; 18079 } 18080 18081 @Override 18082 public boolean hasSystemUidErrors() { 18083 return mHasSystemUidErrors; 18084 } 18085 18086 static String arrayToString(int[] array) { 18087 StringBuffer buf = new StringBuffer(128); 18088 buf.append('['); 18089 if (array != null) { 18090 for (int i=0; i<array.length; i++) { 18091 if (i > 0) buf.append(", "); 18092 buf.append(array[i]); 18093 } 18094 } 18095 buf.append(']'); 18096 return buf.toString(); 18097 } 18098 18099 static class DumpState { 18100 public static final int DUMP_LIBS = 1 << 0; 18101 public static final int DUMP_FEATURES = 1 << 1; 18102 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18103 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18104 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18105 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18106 public static final int DUMP_PERMISSIONS = 1 << 6; 18107 public static final int DUMP_PACKAGES = 1 << 7; 18108 public static final int DUMP_SHARED_USERS = 1 << 8; 18109 public static final int DUMP_MESSAGES = 1 << 9; 18110 public static final int DUMP_PROVIDERS = 1 << 10; 18111 public static final int DUMP_VERIFIERS = 1 << 11; 18112 public static final int DUMP_PREFERRED = 1 << 12; 18113 public static final int DUMP_PREFERRED_XML = 1 << 13; 18114 public static final int DUMP_KEYSETS = 1 << 14; 18115 public static final int DUMP_VERSION = 1 << 15; 18116 public static final int DUMP_INSTALLS = 1 << 16; 18117 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18118 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18119 public static final int DUMP_FROZEN = 1 << 19; 18120 public static final int DUMP_DEXOPT = 1 << 20; 18121 public static final int DUMP_COMPILER_STATS = 1 << 21; 18122 18123 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18124 18125 private int mTypes; 18126 18127 private int mOptions; 18128 18129 private boolean mTitlePrinted; 18130 18131 private SharedUserSetting mSharedUser; 18132 18133 public boolean isDumping(int type) { 18134 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18135 return true; 18136 } 18137 18138 return (mTypes & type) != 0; 18139 } 18140 18141 public void setDump(int type) { 18142 mTypes |= type; 18143 } 18144 18145 public boolean isOptionEnabled(int option) { 18146 return (mOptions & option) != 0; 18147 } 18148 18149 public void setOptionEnabled(int option) { 18150 mOptions |= option; 18151 } 18152 18153 public boolean onTitlePrinted() { 18154 final boolean printed = mTitlePrinted; 18155 mTitlePrinted = true; 18156 return printed; 18157 } 18158 18159 public boolean getTitlePrinted() { 18160 return mTitlePrinted; 18161 } 18162 18163 public void setTitlePrinted(boolean enabled) { 18164 mTitlePrinted = enabled; 18165 } 18166 18167 public SharedUserSetting getSharedUser() { 18168 return mSharedUser; 18169 } 18170 18171 public void setSharedUser(SharedUserSetting user) { 18172 mSharedUser = user; 18173 } 18174 } 18175 18176 @Override 18177 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18178 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18179 (new PackageManagerShellCommand(this)).exec( 18180 this, in, out, err, args, resultReceiver); 18181 } 18182 18183 @Override 18184 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18185 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18186 != PackageManager.PERMISSION_GRANTED) { 18187 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18188 + Binder.getCallingPid() 18189 + ", uid=" + Binder.getCallingUid() 18190 + " without permission " 18191 + android.Manifest.permission.DUMP); 18192 return; 18193 } 18194 18195 DumpState dumpState = new DumpState(); 18196 boolean fullPreferred = false; 18197 boolean checkin = false; 18198 18199 String packageName = null; 18200 ArraySet<String> permissionNames = null; 18201 18202 int opti = 0; 18203 while (opti < args.length) { 18204 String opt = args[opti]; 18205 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18206 break; 18207 } 18208 opti++; 18209 18210 if ("-a".equals(opt)) { 18211 // Right now we only know how to print all. 18212 } else if ("-h".equals(opt)) { 18213 pw.println("Package manager dump options:"); 18214 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18215 pw.println(" --checkin: dump for a checkin"); 18216 pw.println(" -f: print details of intent filters"); 18217 pw.println(" -h: print this help"); 18218 pw.println(" cmd may be one of:"); 18219 pw.println(" l[ibraries]: list known shared libraries"); 18220 pw.println(" f[eatures]: list device features"); 18221 pw.println(" k[eysets]: print known keysets"); 18222 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18223 pw.println(" perm[issions]: dump permissions"); 18224 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18225 pw.println(" pref[erred]: print preferred package settings"); 18226 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18227 pw.println(" prov[iders]: dump content providers"); 18228 pw.println(" p[ackages]: dump installed packages"); 18229 pw.println(" s[hared-users]: dump shared user IDs"); 18230 pw.println(" m[essages]: print collected runtime messages"); 18231 pw.println(" v[erifiers]: print package verifier info"); 18232 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18233 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18234 pw.println(" version: print database version info"); 18235 pw.println(" write: write current settings now"); 18236 pw.println(" installs: details about install sessions"); 18237 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18238 pw.println(" dexopt: dump dexopt state"); 18239 pw.println(" compiler-stats: dump compiler statistics"); 18240 pw.println(" <package.name>: info about given package"); 18241 return; 18242 } else if ("--checkin".equals(opt)) { 18243 checkin = true; 18244 } else if ("-f".equals(opt)) { 18245 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18246 } else { 18247 pw.println("Unknown argument: " + opt + "; use -h for help"); 18248 } 18249 } 18250 18251 // Is the caller requesting to dump a particular piece of data? 18252 if (opti < args.length) { 18253 String cmd = args[opti]; 18254 opti++; 18255 // Is this a package name? 18256 if ("android".equals(cmd) || cmd.contains(".")) { 18257 packageName = cmd; 18258 // When dumping a single package, we always dump all of its 18259 // filter information since the amount of data will be reasonable. 18260 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18261 } else if ("check-permission".equals(cmd)) { 18262 if (opti >= args.length) { 18263 pw.println("Error: check-permission missing permission argument"); 18264 return; 18265 } 18266 String perm = args[opti]; 18267 opti++; 18268 if (opti >= args.length) { 18269 pw.println("Error: check-permission missing package argument"); 18270 return; 18271 } 18272 String pkg = args[opti]; 18273 opti++; 18274 int user = UserHandle.getUserId(Binder.getCallingUid()); 18275 if (opti < args.length) { 18276 try { 18277 user = Integer.parseInt(args[opti]); 18278 } catch (NumberFormatException e) { 18279 pw.println("Error: check-permission user argument is not a number: " 18280 + args[opti]); 18281 return; 18282 } 18283 } 18284 pw.println(checkPermission(perm, pkg, user)); 18285 return; 18286 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18287 dumpState.setDump(DumpState.DUMP_LIBS); 18288 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18289 dumpState.setDump(DumpState.DUMP_FEATURES); 18290 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18291 if (opti >= args.length) { 18292 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18293 | DumpState.DUMP_SERVICE_RESOLVERS 18294 | DumpState.DUMP_RECEIVER_RESOLVERS 18295 | DumpState.DUMP_CONTENT_RESOLVERS); 18296 } else { 18297 while (opti < args.length) { 18298 String name = args[opti]; 18299 if ("a".equals(name) || "activity".equals(name)) { 18300 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18301 } else if ("s".equals(name) || "service".equals(name)) { 18302 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18303 } else if ("r".equals(name) || "receiver".equals(name)) { 18304 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18305 } else if ("c".equals(name) || "content".equals(name)) { 18306 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18307 } else { 18308 pw.println("Error: unknown resolver table type: " + name); 18309 return; 18310 } 18311 opti++; 18312 } 18313 } 18314 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18315 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18316 } else if ("permission".equals(cmd)) { 18317 if (opti >= args.length) { 18318 pw.println("Error: permission requires permission name"); 18319 return; 18320 } 18321 permissionNames = new ArraySet<>(); 18322 while (opti < args.length) { 18323 permissionNames.add(args[opti]); 18324 opti++; 18325 } 18326 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18327 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18328 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18329 dumpState.setDump(DumpState.DUMP_PREFERRED); 18330 } else if ("preferred-xml".equals(cmd)) { 18331 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18332 if (opti < args.length && "--full".equals(args[opti])) { 18333 fullPreferred = true; 18334 opti++; 18335 } 18336 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18337 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18338 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18339 dumpState.setDump(DumpState.DUMP_PACKAGES); 18340 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18341 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18342 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18343 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18344 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18345 dumpState.setDump(DumpState.DUMP_MESSAGES); 18346 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18347 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18348 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18349 || "intent-filter-verifiers".equals(cmd)) { 18350 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18351 } else if ("version".equals(cmd)) { 18352 dumpState.setDump(DumpState.DUMP_VERSION); 18353 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18354 dumpState.setDump(DumpState.DUMP_KEYSETS); 18355 } else if ("installs".equals(cmd)) { 18356 dumpState.setDump(DumpState.DUMP_INSTALLS); 18357 } else if ("frozen".equals(cmd)) { 18358 dumpState.setDump(DumpState.DUMP_FROZEN); 18359 } else if ("dexopt".equals(cmd)) { 18360 dumpState.setDump(DumpState.DUMP_DEXOPT); 18361 } else if ("compiler-stats".equals(cmd)) { 18362 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18363 } else if ("write".equals(cmd)) { 18364 synchronized (mPackages) { 18365 mSettings.writeLPr(); 18366 pw.println("Settings written."); 18367 return; 18368 } 18369 } 18370 } 18371 18372 if (checkin) { 18373 pw.println("vers,1"); 18374 } 18375 18376 // reader 18377 synchronized (mPackages) { 18378 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18379 if (!checkin) { 18380 if (dumpState.onTitlePrinted()) 18381 pw.println(); 18382 pw.println("Database versions:"); 18383 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18384 } 18385 } 18386 18387 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18388 if (!checkin) { 18389 if (dumpState.onTitlePrinted()) 18390 pw.println(); 18391 pw.println("Verifiers:"); 18392 pw.print(" Required: "); 18393 pw.print(mRequiredVerifierPackage); 18394 pw.print(" (uid="); 18395 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18396 UserHandle.USER_SYSTEM)); 18397 pw.println(")"); 18398 } else if (mRequiredVerifierPackage != null) { 18399 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18400 pw.print(","); 18401 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18402 UserHandle.USER_SYSTEM)); 18403 } 18404 } 18405 18406 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18407 packageName == null) { 18408 if (mIntentFilterVerifierComponent != null) { 18409 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18410 if (!checkin) { 18411 if (dumpState.onTitlePrinted()) 18412 pw.println(); 18413 pw.println("Intent Filter Verifier:"); 18414 pw.print(" Using: "); 18415 pw.print(verifierPackageName); 18416 pw.print(" (uid="); 18417 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18418 UserHandle.USER_SYSTEM)); 18419 pw.println(")"); 18420 } else if (verifierPackageName != null) { 18421 pw.print("ifv,"); pw.print(verifierPackageName); 18422 pw.print(","); 18423 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18424 UserHandle.USER_SYSTEM)); 18425 } 18426 } else { 18427 pw.println(); 18428 pw.println("No Intent Filter Verifier available!"); 18429 } 18430 } 18431 18432 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18433 boolean printedHeader = false; 18434 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18435 while (it.hasNext()) { 18436 String name = it.next(); 18437 SharedLibraryEntry ent = mSharedLibraries.get(name); 18438 if (!checkin) { 18439 if (!printedHeader) { 18440 if (dumpState.onTitlePrinted()) 18441 pw.println(); 18442 pw.println("Libraries:"); 18443 printedHeader = true; 18444 } 18445 pw.print(" "); 18446 } else { 18447 pw.print("lib,"); 18448 } 18449 pw.print(name); 18450 if (!checkin) { 18451 pw.print(" -> "); 18452 } 18453 if (ent.path != null) { 18454 if (!checkin) { 18455 pw.print("(jar) "); 18456 pw.print(ent.path); 18457 } else { 18458 pw.print(",jar,"); 18459 pw.print(ent.path); 18460 } 18461 } else { 18462 if (!checkin) { 18463 pw.print("(apk) "); 18464 pw.print(ent.apk); 18465 } else { 18466 pw.print(",apk,"); 18467 pw.print(ent.apk); 18468 } 18469 } 18470 pw.println(); 18471 } 18472 } 18473 18474 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18475 if (dumpState.onTitlePrinted()) 18476 pw.println(); 18477 if (!checkin) { 18478 pw.println("Features:"); 18479 } 18480 18481 for (FeatureInfo feat : mAvailableFeatures.values()) { 18482 if (checkin) { 18483 pw.print("feat,"); 18484 pw.print(feat.name); 18485 pw.print(","); 18486 pw.println(feat.version); 18487 } else { 18488 pw.print(" "); 18489 pw.print(feat.name); 18490 if (feat.version > 0) { 18491 pw.print(" version="); 18492 pw.print(feat.version); 18493 } 18494 pw.println(); 18495 } 18496 } 18497 } 18498 18499 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18500 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18501 : "Activity Resolver Table:", " ", packageName, 18502 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18503 dumpState.setTitlePrinted(true); 18504 } 18505 } 18506 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18507 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18508 : "Receiver Resolver Table:", " ", packageName, 18509 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18510 dumpState.setTitlePrinted(true); 18511 } 18512 } 18513 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18514 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18515 : "Service Resolver Table:", " ", packageName, 18516 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18517 dumpState.setTitlePrinted(true); 18518 } 18519 } 18520 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18521 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18522 : "Provider Resolver Table:", " ", packageName, 18523 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18524 dumpState.setTitlePrinted(true); 18525 } 18526 } 18527 18528 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18529 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18530 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18531 int user = mSettings.mPreferredActivities.keyAt(i); 18532 if (pir.dump(pw, 18533 dumpState.getTitlePrinted() 18534 ? "\nPreferred Activities User " + user + ":" 18535 : "Preferred Activities User " + user + ":", " ", 18536 packageName, true, false)) { 18537 dumpState.setTitlePrinted(true); 18538 } 18539 } 18540 } 18541 18542 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18543 pw.flush(); 18544 FileOutputStream fout = new FileOutputStream(fd); 18545 BufferedOutputStream str = new BufferedOutputStream(fout); 18546 XmlSerializer serializer = new FastXmlSerializer(); 18547 try { 18548 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18549 serializer.startDocument(null, true); 18550 serializer.setFeature( 18551 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18552 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18553 serializer.endDocument(); 18554 serializer.flush(); 18555 } catch (IllegalArgumentException e) { 18556 pw.println("Failed writing: " + e); 18557 } catch (IllegalStateException e) { 18558 pw.println("Failed writing: " + e); 18559 } catch (IOException e) { 18560 pw.println("Failed writing: " + e); 18561 } 18562 } 18563 18564 if (!checkin 18565 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18566 && packageName == null) { 18567 pw.println(); 18568 int count = mSettings.mPackages.size(); 18569 if (count == 0) { 18570 pw.println("No applications!"); 18571 pw.println(); 18572 } else { 18573 final String prefix = " "; 18574 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18575 if (allPackageSettings.size() == 0) { 18576 pw.println("No domain preferred apps!"); 18577 pw.println(); 18578 } else { 18579 pw.println("App verification status:"); 18580 pw.println(); 18581 count = 0; 18582 for (PackageSetting ps : allPackageSettings) { 18583 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18584 if (ivi == null || ivi.getPackageName() == null) continue; 18585 pw.println(prefix + "Package: " + ivi.getPackageName()); 18586 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18587 pw.println(prefix + "Status: " + ivi.getStatusString()); 18588 pw.println(); 18589 count++; 18590 } 18591 if (count == 0) { 18592 pw.println(prefix + "No app verification established."); 18593 pw.println(); 18594 } 18595 for (int userId : sUserManager.getUserIds()) { 18596 pw.println("App linkages for user " + userId + ":"); 18597 pw.println(); 18598 count = 0; 18599 for (PackageSetting ps : allPackageSettings) { 18600 final long status = ps.getDomainVerificationStatusForUser(userId); 18601 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18602 continue; 18603 } 18604 pw.println(prefix + "Package: " + ps.name); 18605 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18606 String statusStr = IntentFilterVerificationInfo. 18607 getStatusStringFromValue(status); 18608 pw.println(prefix + "Status: " + statusStr); 18609 pw.println(); 18610 count++; 18611 } 18612 if (count == 0) { 18613 pw.println(prefix + "No configured app linkages."); 18614 pw.println(); 18615 } 18616 } 18617 } 18618 } 18619 } 18620 18621 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18622 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18623 if (packageName == null && permissionNames == null) { 18624 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18625 if (iperm == 0) { 18626 if (dumpState.onTitlePrinted()) 18627 pw.println(); 18628 pw.println("AppOp Permissions:"); 18629 } 18630 pw.print(" AppOp Permission "); 18631 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18632 pw.println(":"); 18633 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18634 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18635 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18636 } 18637 } 18638 } 18639 } 18640 18641 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18642 boolean printedSomething = false; 18643 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18644 if (packageName != null && !packageName.equals(p.info.packageName)) { 18645 continue; 18646 } 18647 if (!printedSomething) { 18648 if (dumpState.onTitlePrinted()) 18649 pw.println(); 18650 pw.println("Registered ContentProviders:"); 18651 printedSomething = true; 18652 } 18653 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18654 pw.print(" "); pw.println(p.toString()); 18655 } 18656 printedSomething = false; 18657 for (Map.Entry<String, PackageParser.Provider> entry : 18658 mProvidersByAuthority.entrySet()) { 18659 PackageParser.Provider p = entry.getValue(); 18660 if (packageName != null && !packageName.equals(p.info.packageName)) { 18661 continue; 18662 } 18663 if (!printedSomething) { 18664 if (dumpState.onTitlePrinted()) 18665 pw.println(); 18666 pw.println("ContentProvider Authorities:"); 18667 printedSomething = true; 18668 } 18669 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18670 pw.print(" "); pw.println(p.toString()); 18671 if (p.info != null && p.info.applicationInfo != null) { 18672 final String appInfo = p.info.applicationInfo.toString(); 18673 pw.print(" applicationInfo="); pw.println(appInfo); 18674 } 18675 } 18676 } 18677 18678 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18679 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18680 } 18681 18682 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18683 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18684 } 18685 18686 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18687 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18688 } 18689 18690 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18691 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18692 } 18693 18694 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18695 // XXX should handle packageName != null by dumping only install data that 18696 // the given package is involved with. 18697 if (dumpState.onTitlePrinted()) pw.println(); 18698 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18699 } 18700 18701 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18702 // XXX should handle packageName != null by dumping only install data that 18703 // the given package is involved with. 18704 if (dumpState.onTitlePrinted()) pw.println(); 18705 18706 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18707 ipw.println(); 18708 ipw.println("Frozen packages:"); 18709 ipw.increaseIndent(); 18710 if (mFrozenPackages.size() == 0) { 18711 ipw.println("(none)"); 18712 } else { 18713 for (int i = 0; i < mFrozenPackages.size(); i++) { 18714 ipw.println(mFrozenPackages.valueAt(i)); 18715 } 18716 } 18717 ipw.decreaseIndent(); 18718 } 18719 18720 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18721 if (dumpState.onTitlePrinted()) pw.println(); 18722 dumpDexoptStateLPr(pw, packageName); 18723 } 18724 18725 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18726 if (dumpState.onTitlePrinted()) pw.println(); 18727 dumpCompilerStatsLPr(pw, packageName); 18728 } 18729 18730 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18731 if (dumpState.onTitlePrinted()) pw.println(); 18732 mSettings.dumpReadMessagesLPr(pw, dumpState); 18733 18734 pw.println(); 18735 pw.println("Package warning messages:"); 18736 BufferedReader in = null; 18737 String line = null; 18738 try { 18739 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18740 while ((line = in.readLine()) != null) { 18741 if (line.contains("ignored: updated version")) continue; 18742 pw.println(line); 18743 } 18744 } catch (IOException ignored) { 18745 } finally { 18746 IoUtils.closeQuietly(in); 18747 } 18748 } 18749 18750 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18751 BufferedReader in = null; 18752 String line = null; 18753 try { 18754 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18755 while ((line = in.readLine()) != null) { 18756 if (line.contains("ignored: updated version")) continue; 18757 pw.print("msg,"); 18758 pw.println(line); 18759 } 18760 } catch (IOException ignored) { 18761 } finally { 18762 IoUtils.closeQuietly(in); 18763 } 18764 } 18765 } 18766 } 18767 18768 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18769 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18770 ipw.println(); 18771 ipw.println("Dexopt state:"); 18772 ipw.increaseIndent(); 18773 Collection<PackageParser.Package> packages = null; 18774 if (packageName != null) { 18775 PackageParser.Package targetPackage = mPackages.get(packageName); 18776 if (targetPackage != null) { 18777 packages = Collections.singletonList(targetPackage); 18778 } else { 18779 ipw.println("Unable to find package: " + packageName); 18780 return; 18781 } 18782 } else { 18783 packages = mPackages.values(); 18784 } 18785 18786 for (PackageParser.Package pkg : packages) { 18787 ipw.println("[" + pkg.packageName + "]"); 18788 ipw.increaseIndent(); 18789 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18790 ipw.decreaseIndent(); 18791 } 18792 } 18793 18794 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18795 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18796 ipw.println(); 18797 ipw.println("Compiler stats:"); 18798 ipw.increaseIndent(); 18799 Collection<PackageParser.Package> packages = null; 18800 if (packageName != null) { 18801 PackageParser.Package targetPackage = mPackages.get(packageName); 18802 if (targetPackage != null) { 18803 packages = Collections.singletonList(targetPackage); 18804 } else { 18805 ipw.println("Unable to find package: " + packageName); 18806 return; 18807 } 18808 } else { 18809 packages = mPackages.values(); 18810 } 18811 18812 for (PackageParser.Package pkg : packages) { 18813 ipw.println("[" + pkg.packageName + "]"); 18814 ipw.increaseIndent(); 18815 18816 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18817 if (stats == null) { 18818 ipw.println("(No recorded stats)"); 18819 } else { 18820 stats.dump(ipw); 18821 } 18822 ipw.decreaseIndent(); 18823 } 18824 } 18825 18826 private String dumpDomainString(String packageName) { 18827 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18828 .getList(); 18829 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18830 18831 ArraySet<String> result = new ArraySet<>(); 18832 if (iviList.size() > 0) { 18833 for (IntentFilterVerificationInfo ivi : iviList) { 18834 for (String host : ivi.getDomains()) { 18835 result.add(host); 18836 } 18837 } 18838 } 18839 if (filters != null && filters.size() > 0) { 18840 for (IntentFilter filter : filters) { 18841 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18842 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18843 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18844 result.addAll(filter.getHostsList()); 18845 } 18846 } 18847 } 18848 18849 StringBuilder sb = new StringBuilder(result.size() * 16); 18850 for (String domain : result) { 18851 if (sb.length() > 0) sb.append(" "); 18852 sb.append(domain); 18853 } 18854 return sb.toString(); 18855 } 18856 18857 // ------- apps on sdcard specific code ------- 18858 static final boolean DEBUG_SD_INSTALL = false; 18859 18860 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18861 18862 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18863 18864 private boolean mMediaMounted = false; 18865 18866 static String getEncryptKey() { 18867 try { 18868 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18869 SD_ENCRYPTION_KEYSTORE_NAME); 18870 if (sdEncKey == null) { 18871 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18872 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18873 if (sdEncKey == null) { 18874 Slog.e(TAG, "Failed to create encryption keys"); 18875 return null; 18876 } 18877 } 18878 return sdEncKey; 18879 } catch (NoSuchAlgorithmException nsae) { 18880 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18881 return null; 18882 } catch (IOException ioe) { 18883 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18884 return null; 18885 } 18886 } 18887 18888 /* 18889 * Update media status on PackageManager. 18890 */ 18891 @Override 18892 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18893 int callingUid = Binder.getCallingUid(); 18894 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18895 throw new SecurityException("Media status can only be updated by the system"); 18896 } 18897 // reader; this apparently protects mMediaMounted, but should probably 18898 // be a different lock in that case. 18899 synchronized (mPackages) { 18900 Log.i(TAG, "Updating external media status from " 18901 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18902 + (mediaStatus ? "mounted" : "unmounted")); 18903 if (DEBUG_SD_INSTALL) 18904 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18905 + ", mMediaMounted=" + mMediaMounted); 18906 if (mediaStatus == mMediaMounted) { 18907 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18908 : 0, -1); 18909 mHandler.sendMessage(msg); 18910 return; 18911 } 18912 mMediaMounted = mediaStatus; 18913 } 18914 // Queue up an async operation since the package installation may take a 18915 // little while. 18916 mHandler.post(new Runnable() { 18917 public void run() { 18918 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18919 } 18920 }); 18921 } 18922 18923 /** 18924 * Called by MountService when the initial ASECs to scan are available. 18925 * Should block until all the ASEC containers are finished being scanned. 18926 */ 18927 public void scanAvailableAsecs() { 18928 updateExternalMediaStatusInner(true, false, false); 18929 } 18930 18931 /* 18932 * Collect information of applications on external media, map them against 18933 * existing containers and update information based on current mount status. 18934 * Please note that we always have to report status if reportStatus has been 18935 * set to true especially when unloading packages. 18936 */ 18937 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18938 boolean externalStorage) { 18939 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18940 int[] uidArr = EmptyArray.INT; 18941 18942 final String[] list = PackageHelper.getSecureContainerList(); 18943 if (ArrayUtils.isEmpty(list)) { 18944 Log.i(TAG, "No secure containers found"); 18945 } else { 18946 // Process list of secure containers and categorize them 18947 // as active or stale based on their package internal state. 18948 18949 // reader 18950 synchronized (mPackages) { 18951 for (String cid : list) { 18952 // Leave stages untouched for now; installer service owns them 18953 if (PackageInstallerService.isStageName(cid)) continue; 18954 18955 if (DEBUG_SD_INSTALL) 18956 Log.i(TAG, "Processing container " + cid); 18957 String pkgName = getAsecPackageName(cid); 18958 if (pkgName == null) { 18959 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18960 continue; 18961 } 18962 if (DEBUG_SD_INSTALL) 18963 Log.i(TAG, "Looking for pkg : " + pkgName); 18964 18965 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18966 if (ps == null) { 18967 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18968 continue; 18969 } 18970 18971 /* 18972 * Skip packages that are not external if we're unmounting 18973 * external storage. 18974 */ 18975 if (externalStorage && !isMounted && !isExternal(ps)) { 18976 continue; 18977 } 18978 18979 final AsecInstallArgs args = new AsecInstallArgs(cid, 18980 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18981 // The package status is changed only if the code path 18982 // matches between settings and the container id. 18983 if (ps.codePathString != null 18984 && ps.codePathString.startsWith(args.getCodePath())) { 18985 if (DEBUG_SD_INSTALL) { 18986 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18987 + " at code path: " + ps.codePathString); 18988 } 18989 18990 // We do have a valid package installed on sdcard 18991 processCids.put(args, ps.codePathString); 18992 final int uid = ps.appId; 18993 if (uid != -1) { 18994 uidArr = ArrayUtils.appendInt(uidArr, uid); 18995 } 18996 } else { 18997 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18998 + ps.codePathString); 18999 } 19000 } 19001 } 19002 19003 Arrays.sort(uidArr); 19004 } 19005 19006 // Process packages with valid entries. 19007 if (isMounted) { 19008 if (DEBUG_SD_INSTALL) 19009 Log.i(TAG, "Loading packages"); 19010 loadMediaPackages(processCids, uidArr, externalStorage); 19011 startCleaningPackages(); 19012 mInstallerService.onSecureContainersAvailable(); 19013 } else { 19014 if (DEBUG_SD_INSTALL) 19015 Log.i(TAG, "Unloading packages"); 19016 unloadMediaPackages(processCids, uidArr, reportStatus); 19017 } 19018 } 19019 19020 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19021 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19022 final int size = infos.size(); 19023 final String[] packageNames = new String[size]; 19024 final int[] packageUids = new int[size]; 19025 for (int i = 0; i < size; i++) { 19026 final ApplicationInfo info = infos.get(i); 19027 packageNames[i] = info.packageName; 19028 packageUids[i] = info.uid; 19029 } 19030 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19031 finishedReceiver); 19032 } 19033 19034 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19035 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19036 sendResourcesChangedBroadcast(mediaStatus, replacing, 19037 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19038 } 19039 19040 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19041 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19042 int size = pkgList.length; 19043 if (size > 0) { 19044 // Send broadcasts here 19045 Bundle extras = new Bundle(); 19046 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19047 if (uidArr != null) { 19048 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19049 } 19050 if (replacing) { 19051 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19052 } 19053 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19054 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19055 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19056 } 19057 } 19058 19059 /* 19060 * Look at potentially valid container ids from processCids If package 19061 * information doesn't match the one on record or package scanning fails, 19062 * the cid is added to list of removeCids. We currently don't delete stale 19063 * containers. 19064 */ 19065 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19066 boolean externalStorage) { 19067 ArrayList<String> pkgList = new ArrayList<String>(); 19068 Set<AsecInstallArgs> keys = processCids.keySet(); 19069 19070 for (AsecInstallArgs args : keys) { 19071 String codePath = processCids.get(args); 19072 if (DEBUG_SD_INSTALL) 19073 Log.i(TAG, "Loading container : " + args.cid); 19074 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19075 try { 19076 // Make sure there are no container errors first. 19077 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19078 Slog.e(TAG, "Failed to mount cid : " + args.cid 19079 + " when installing from sdcard"); 19080 continue; 19081 } 19082 // Check code path here. 19083 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19084 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19085 + " does not match one in settings " + codePath); 19086 continue; 19087 } 19088 // Parse package 19089 int parseFlags = mDefParseFlags; 19090 if (args.isExternalAsec()) { 19091 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19092 } 19093 if (args.isFwdLocked()) { 19094 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19095 } 19096 19097 synchronized (mInstallLock) { 19098 PackageParser.Package pkg = null; 19099 try { 19100 // Sadly we don't know the package name yet to freeze it 19101 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19102 SCAN_IGNORE_FROZEN, 0, null); 19103 } catch (PackageManagerException e) { 19104 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19105 } 19106 // Scan the package 19107 if (pkg != null) { 19108 /* 19109 * TODO why is the lock being held? doPostInstall is 19110 * called in other places without the lock. This needs 19111 * to be straightened out. 19112 */ 19113 // writer 19114 synchronized (mPackages) { 19115 retCode = PackageManager.INSTALL_SUCCEEDED; 19116 pkgList.add(pkg.packageName); 19117 // Post process args 19118 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19119 pkg.applicationInfo.uid); 19120 } 19121 } else { 19122 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19123 } 19124 } 19125 19126 } finally { 19127 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19128 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19129 } 19130 } 19131 } 19132 // writer 19133 synchronized (mPackages) { 19134 // If the platform SDK has changed since the last time we booted, 19135 // we need to re-grant app permission to catch any new ones that 19136 // appear. This is really a hack, and means that apps can in some 19137 // cases get permissions that the user didn't initially explicitly 19138 // allow... it would be nice to have some better way to handle 19139 // this situation. 19140 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19141 : mSettings.getInternalVersion(); 19142 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19143 : StorageManager.UUID_PRIVATE_INTERNAL; 19144 19145 int updateFlags = UPDATE_PERMISSIONS_ALL; 19146 if (ver.sdkVersion != mSdkVersion) { 19147 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19148 + mSdkVersion + "; regranting permissions for external"); 19149 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19150 } 19151 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19152 19153 // Yay, everything is now upgraded 19154 ver.forceCurrent(); 19155 19156 // can downgrade to reader 19157 // Persist settings 19158 mSettings.writeLPr(); 19159 } 19160 // Send a broadcast to let everyone know we are done processing 19161 if (pkgList.size() > 0) { 19162 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19163 } 19164 } 19165 19166 /* 19167 * Utility method to unload a list of specified containers 19168 */ 19169 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19170 // Just unmount all valid containers. 19171 for (AsecInstallArgs arg : cidArgs) { 19172 synchronized (mInstallLock) { 19173 arg.doPostDeleteLI(false); 19174 } 19175 } 19176 } 19177 19178 /* 19179 * Unload packages mounted on external media. This involves deleting package 19180 * data from internal structures, sending broadcasts about disabled packages, 19181 * gc'ing to free up references, unmounting all secure containers 19182 * corresponding to packages on external media, and posting a 19183 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19184 * that we always have to post this message if status has been requested no 19185 * matter what. 19186 */ 19187 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19188 final boolean reportStatus) { 19189 if (DEBUG_SD_INSTALL) 19190 Log.i(TAG, "unloading media packages"); 19191 ArrayList<String> pkgList = new ArrayList<String>(); 19192 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19193 final Set<AsecInstallArgs> keys = processCids.keySet(); 19194 for (AsecInstallArgs args : keys) { 19195 String pkgName = args.getPackageName(); 19196 if (DEBUG_SD_INSTALL) 19197 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19198 // Delete package internally 19199 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19200 synchronized (mInstallLock) { 19201 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19202 final boolean res; 19203 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19204 "unloadMediaPackages")) { 19205 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19206 null); 19207 } 19208 if (res) { 19209 pkgList.add(pkgName); 19210 } else { 19211 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19212 failedList.add(args); 19213 } 19214 } 19215 } 19216 19217 // reader 19218 synchronized (mPackages) { 19219 // We didn't update the settings after removing each package; 19220 // write them now for all packages. 19221 mSettings.writeLPr(); 19222 } 19223 19224 // We have to absolutely send UPDATED_MEDIA_STATUS only 19225 // after confirming that all the receivers processed the ordered 19226 // broadcast when packages get disabled, force a gc to clean things up. 19227 // and unload all the containers. 19228 if (pkgList.size() > 0) { 19229 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19230 new IIntentReceiver.Stub() { 19231 public void performReceive(Intent intent, int resultCode, String data, 19232 Bundle extras, boolean ordered, boolean sticky, 19233 int sendingUser) throws RemoteException { 19234 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19235 reportStatus ? 1 : 0, 1, keys); 19236 mHandler.sendMessage(msg); 19237 } 19238 }); 19239 } else { 19240 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19241 keys); 19242 mHandler.sendMessage(msg); 19243 } 19244 } 19245 19246 private void loadPrivatePackages(final VolumeInfo vol) { 19247 mHandler.post(new Runnable() { 19248 @Override 19249 public void run() { 19250 loadPrivatePackagesInner(vol); 19251 } 19252 }); 19253 } 19254 19255 private void loadPrivatePackagesInner(VolumeInfo vol) { 19256 final String volumeUuid = vol.fsUuid; 19257 if (TextUtils.isEmpty(volumeUuid)) { 19258 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19259 return; 19260 } 19261 19262 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19263 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19264 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19265 19266 final VersionInfo ver; 19267 final List<PackageSetting> packages; 19268 synchronized (mPackages) { 19269 ver = mSettings.findOrCreateVersion(volumeUuid); 19270 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19271 } 19272 19273 for (PackageSetting ps : packages) { 19274 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19275 synchronized (mInstallLock) { 19276 final PackageParser.Package pkg; 19277 try { 19278 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19279 loaded.add(pkg.applicationInfo); 19280 19281 } catch (PackageManagerException e) { 19282 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19283 } 19284 19285 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19286 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19287 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19288 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19289 } 19290 } 19291 } 19292 19293 // Reconcile app data for all started/unlocked users 19294 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19295 final UserManager um = mContext.getSystemService(UserManager.class); 19296 UserManagerInternal umInternal = getUserManagerInternal(); 19297 for (UserInfo user : um.getUsers()) { 19298 final int flags; 19299 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19300 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19301 } else if (umInternal.isUserRunning(user.id)) { 19302 flags = StorageManager.FLAG_STORAGE_DE; 19303 } else { 19304 continue; 19305 } 19306 19307 try { 19308 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19309 synchronized (mInstallLock) { 19310 reconcileAppsDataLI(volumeUuid, user.id, flags); 19311 } 19312 } catch (IllegalStateException e) { 19313 // Device was probably ejected, and we'll process that event momentarily 19314 Slog.w(TAG, "Failed to prepare storage: " + e); 19315 } 19316 } 19317 19318 synchronized (mPackages) { 19319 int updateFlags = UPDATE_PERMISSIONS_ALL; 19320 if (ver.sdkVersion != mSdkVersion) { 19321 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19322 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19323 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19324 } 19325 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19326 19327 // Yay, everything is now upgraded 19328 ver.forceCurrent(); 19329 19330 mSettings.writeLPr(); 19331 } 19332 19333 for (PackageFreezer freezer : freezers) { 19334 freezer.close(); 19335 } 19336 19337 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19338 sendResourcesChangedBroadcast(true, false, loaded, null); 19339 } 19340 19341 private void unloadPrivatePackages(final VolumeInfo vol) { 19342 mHandler.post(new Runnable() { 19343 @Override 19344 public void run() { 19345 unloadPrivatePackagesInner(vol); 19346 } 19347 }); 19348 } 19349 19350 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19351 final String volumeUuid = vol.fsUuid; 19352 if (TextUtils.isEmpty(volumeUuid)) { 19353 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19354 return; 19355 } 19356 19357 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19358 synchronized (mInstallLock) { 19359 synchronized (mPackages) { 19360 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19361 for (PackageSetting ps : packages) { 19362 if (ps.pkg == null) continue; 19363 19364 final ApplicationInfo info = ps.pkg.applicationInfo; 19365 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19366 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19367 19368 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19369 "unloadPrivatePackagesInner")) { 19370 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19371 false, null)) { 19372 unloaded.add(info); 19373 } else { 19374 Slog.w(TAG, "Failed to unload " + ps.codePath); 19375 } 19376 } 19377 19378 // Try very hard to release any references to this package 19379 // so we don't risk the system server being killed due to 19380 // open FDs 19381 AttributeCache.instance().removePackage(ps.name); 19382 } 19383 19384 mSettings.writeLPr(); 19385 } 19386 } 19387 19388 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19389 sendResourcesChangedBroadcast(false, false, unloaded, null); 19390 19391 // Try very hard to release any references to this path so we don't risk 19392 // the system server being killed due to open FDs 19393 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19394 19395 for (int i = 0; i < 3; i++) { 19396 System.gc(); 19397 System.runFinalization(); 19398 } 19399 } 19400 19401 /** 19402 * Prepare storage areas for given user on all mounted devices. 19403 */ 19404 void prepareUserData(int userId, int userSerial, int flags) { 19405 synchronized (mInstallLock) { 19406 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19407 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19408 final String volumeUuid = vol.getFsUuid(); 19409 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19410 } 19411 } 19412 } 19413 19414 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19415 boolean allowRecover) { 19416 // Prepare storage and verify that serial numbers are consistent; if 19417 // there's a mismatch we need to destroy to avoid leaking data 19418 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19419 try { 19420 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19421 19422 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19423 UserManagerService.enforceSerialNumber( 19424 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19425 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19426 UserManagerService.enforceSerialNumber( 19427 Environment.getDataSystemDeDirectory(userId), userSerial); 19428 } 19429 } 19430 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19431 UserManagerService.enforceSerialNumber( 19432 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19433 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19434 UserManagerService.enforceSerialNumber( 19435 Environment.getDataSystemCeDirectory(userId), userSerial); 19436 } 19437 } 19438 19439 synchronized (mInstallLock) { 19440 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19441 } 19442 } catch (Exception e) { 19443 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19444 + " because we failed to prepare: " + e); 19445 destroyUserDataLI(volumeUuid, userId, 19446 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19447 19448 if (allowRecover) { 19449 // Try one last time; if we fail again we're really in trouble 19450 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19451 } 19452 } 19453 } 19454 19455 /** 19456 * Destroy storage areas for given user on all mounted devices. 19457 */ 19458 void destroyUserData(int userId, int flags) { 19459 synchronized (mInstallLock) { 19460 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19461 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19462 final String volumeUuid = vol.getFsUuid(); 19463 destroyUserDataLI(volumeUuid, userId, flags); 19464 } 19465 } 19466 } 19467 19468 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19469 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19470 try { 19471 // Clean up app data, profile data, and media data 19472 mInstaller.destroyUserData(volumeUuid, userId, flags); 19473 19474 // Clean up system data 19475 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19476 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19477 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19478 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19479 } 19480 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19481 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19482 } 19483 } 19484 19485 // Data with special labels is now gone, so finish the job 19486 storage.destroyUserStorage(volumeUuid, userId, flags); 19487 19488 } catch (Exception e) { 19489 logCriticalInfo(Log.WARN, 19490 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19491 } 19492 } 19493 19494 /** 19495 * Examine all users present on given mounted volume, and destroy data 19496 * belonging to users that are no longer valid, or whose user ID has been 19497 * recycled. 19498 */ 19499 private void reconcileUsers(String volumeUuid) { 19500 final List<File> files = new ArrayList<>(); 19501 Collections.addAll(files, FileUtils 19502 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19503 Collections.addAll(files, FileUtils 19504 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19505 Collections.addAll(files, FileUtils 19506 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19507 Collections.addAll(files, FileUtils 19508 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19509 for (File file : files) { 19510 if (!file.isDirectory()) continue; 19511 19512 final int userId; 19513 final UserInfo info; 19514 try { 19515 userId = Integer.parseInt(file.getName()); 19516 info = sUserManager.getUserInfo(userId); 19517 } catch (NumberFormatException e) { 19518 Slog.w(TAG, "Invalid user directory " + file); 19519 continue; 19520 } 19521 19522 boolean destroyUser = false; 19523 if (info == null) { 19524 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19525 + " because no matching user was found"); 19526 destroyUser = true; 19527 } else if (!mOnlyCore) { 19528 try { 19529 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19530 } catch (IOException e) { 19531 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19532 + " because we failed to enforce serial number: " + e); 19533 destroyUser = true; 19534 } 19535 } 19536 19537 if (destroyUser) { 19538 synchronized (mInstallLock) { 19539 destroyUserDataLI(volumeUuid, userId, 19540 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19541 } 19542 } 19543 } 19544 } 19545 19546 private void assertPackageKnown(String volumeUuid, String packageName) 19547 throws PackageManagerException { 19548 synchronized (mPackages) { 19549 final PackageSetting ps = mSettings.mPackages.get(packageName); 19550 if (ps == null) { 19551 throw new PackageManagerException("Package " + packageName + " is unknown"); 19552 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19553 throw new PackageManagerException( 19554 "Package " + packageName + " found on unknown volume " + volumeUuid 19555 + "; expected volume " + ps.volumeUuid); 19556 } 19557 } 19558 } 19559 19560 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19561 throws PackageManagerException { 19562 synchronized (mPackages) { 19563 final PackageSetting ps = mSettings.mPackages.get(packageName); 19564 if (ps == null) { 19565 throw new PackageManagerException("Package " + packageName + " is unknown"); 19566 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19567 throw new PackageManagerException( 19568 "Package " + packageName + " found on unknown volume " + volumeUuid 19569 + "; expected volume " + ps.volumeUuid); 19570 } else if (!ps.getInstalled(userId)) { 19571 throw new PackageManagerException( 19572 "Package " + packageName + " not installed for user " + userId); 19573 } 19574 } 19575 } 19576 19577 /** 19578 * Examine all apps present on given mounted volume, and destroy apps that 19579 * aren't expected, either due to uninstallation or reinstallation on 19580 * another volume. 19581 */ 19582 private void reconcileApps(String volumeUuid) { 19583 final File[] files = FileUtils 19584 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19585 for (File file : files) { 19586 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19587 && !PackageInstallerService.isStageName(file.getName()); 19588 if (!isPackage) { 19589 // Ignore entries which are not packages 19590 continue; 19591 } 19592 19593 try { 19594 final PackageLite pkg = PackageParser.parsePackageLite(file, 19595 PackageParser.PARSE_MUST_BE_APK); 19596 assertPackageKnown(volumeUuid, pkg.packageName); 19597 19598 } catch (PackageParserException | PackageManagerException e) { 19599 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19600 synchronized (mInstallLock) { 19601 removeCodePathLI(file); 19602 } 19603 } 19604 } 19605 } 19606 19607 /** 19608 * Reconcile all app data for the given user. 19609 * <p> 19610 * Verifies that directories exist and that ownership and labeling is 19611 * correct for all installed apps on all mounted volumes. 19612 */ 19613 void reconcileAppsData(int userId, int flags) { 19614 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19615 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19616 final String volumeUuid = vol.getFsUuid(); 19617 synchronized (mInstallLock) { 19618 reconcileAppsDataLI(volumeUuid, userId, flags); 19619 } 19620 } 19621 } 19622 19623 /** 19624 * Reconcile all app data on given mounted volume. 19625 * <p> 19626 * Destroys app data that isn't expected, either due to uninstallation or 19627 * reinstallation on another volume. 19628 * <p> 19629 * Verifies that directories exist and that ownership and labeling is 19630 * correct for all installed apps. 19631 */ 19632 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19633 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19634 + Integer.toHexString(flags)); 19635 19636 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19637 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19638 19639 boolean restoreconNeeded = false; 19640 19641 // First look for stale data that doesn't belong, and check if things 19642 // have changed since we did our last restorecon 19643 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19644 if (StorageManager.isFileEncryptedNativeOrEmulated() 19645 && !StorageManager.isUserKeyUnlocked(userId)) { 19646 throw new RuntimeException( 19647 "Yikes, someone asked us to reconcile CE storage while " + userId 19648 + " was still locked; this would have caused massive data loss!"); 19649 } 19650 19651 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19652 19653 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19654 for (File file : files) { 19655 final String packageName = file.getName(); 19656 try { 19657 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19658 } catch (PackageManagerException e) { 19659 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19660 try { 19661 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19662 StorageManager.FLAG_STORAGE_CE, 0); 19663 } catch (InstallerException e2) { 19664 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19665 } 19666 } 19667 } 19668 } 19669 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19670 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19671 19672 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19673 for (File file : files) { 19674 final String packageName = file.getName(); 19675 try { 19676 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19677 } catch (PackageManagerException e) { 19678 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19679 try { 19680 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19681 StorageManager.FLAG_STORAGE_DE, 0); 19682 } catch (InstallerException e2) { 19683 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19684 } 19685 } 19686 } 19687 } 19688 19689 // Ensure that data directories are ready to roll for all packages 19690 // installed for this volume and user 19691 final List<PackageSetting> packages; 19692 synchronized (mPackages) { 19693 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19694 } 19695 int preparedCount = 0; 19696 for (PackageSetting ps : packages) { 19697 final String packageName = ps.name; 19698 if (ps.pkg == null) { 19699 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19700 // TODO: might be due to legacy ASEC apps; we should circle back 19701 // and reconcile again once they're scanned 19702 continue; 19703 } 19704 19705 if (ps.getInstalled(userId)) { 19706 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19707 19708 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19709 // We may have just shuffled around app data directories, so 19710 // prepare them one more time 19711 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19712 } 19713 19714 preparedCount++; 19715 } 19716 } 19717 19718 if (restoreconNeeded) { 19719 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19720 SELinuxMMAC.setRestoreconDone(ceDir); 19721 } 19722 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19723 SELinuxMMAC.setRestoreconDone(deDir); 19724 } 19725 } 19726 19727 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19728 + " packages; restoreconNeeded was " + restoreconNeeded); 19729 } 19730 19731 /** 19732 * Prepare app data for the given app just after it was installed or 19733 * upgraded. This method carefully only touches users that it's installed 19734 * for, and it forces a restorecon to handle any seinfo changes. 19735 * <p> 19736 * Verifies that directories exist and that ownership and labeling is 19737 * correct for all installed apps. If there is an ownership mismatch, it 19738 * will try recovering system apps by wiping data; third-party app data is 19739 * left intact. 19740 * <p> 19741 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19742 */ 19743 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19744 final PackageSetting ps; 19745 synchronized (mPackages) { 19746 ps = mSettings.mPackages.get(pkg.packageName); 19747 mSettings.writeKernelMappingLPr(ps); 19748 } 19749 19750 final UserManager um = mContext.getSystemService(UserManager.class); 19751 UserManagerInternal umInternal = getUserManagerInternal(); 19752 for (UserInfo user : um.getUsers()) { 19753 final int flags; 19754 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19755 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19756 } else if (umInternal.isUserRunning(user.id)) { 19757 flags = StorageManager.FLAG_STORAGE_DE; 19758 } else { 19759 continue; 19760 } 19761 19762 if (ps.getInstalled(user.id)) { 19763 // Whenever an app changes, force a restorecon of its data 19764 // TODO: when user data is locked, mark that we're still dirty 19765 prepareAppDataLIF(pkg, user.id, flags, true); 19766 } 19767 } 19768 } 19769 19770 /** 19771 * Prepare app data for the given app. 19772 * <p> 19773 * Verifies that directories exist and that ownership and labeling is 19774 * correct for all installed apps. If there is an ownership mismatch, this 19775 * will try recovering system apps by wiping data; third-party app data is 19776 * left intact. 19777 */ 19778 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19779 boolean restoreconNeeded) { 19780 if (pkg == null) { 19781 Slog.wtf(TAG, "Package was null!", new Throwable()); 19782 return; 19783 } 19784 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19785 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19786 for (int i = 0; i < childCount; i++) { 19787 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19788 } 19789 } 19790 19791 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19792 boolean restoreconNeeded) { 19793 if (DEBUG_APP_DATA) { 19794 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19795 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19796 } 19797 19798 final String volumeUuid = pkg.volumeUuid; 19799 final String packageName = pkg.packageName; 19800 final ApplicationInfo app = pkg.applicationInfo; 19801 final int appId = UserHandle.getAppId(app.uid); 19802 19803 Preconditions.checkNotNull(app.seinfo); 19804 19805 try { 19806 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19807 appId, app.seinfo, app.targetSdkVersion); 19808 } catch (InstallerException e) { 19809 if (app.isSystemApp()) { 19810 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19811 + ", but trying to recover: " + e); 19812 destroyAppDataLeafLIF(pkg, userId, flags); 19813 try { 19814 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19815 appId, app.seinfo, app.targetSdkVersion); 19816 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19817 } catch (InstallerException e2) { 19818 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19819 } 19820 } else { 19821 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19822 } 19823 } 19824 19825 if (restoreconNeeded) { 19826 try { 19827 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19828 app.seinfo); 19829 } catch (InstallerException e) { 19830 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19831 } 19832 } 19833 19834 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19835 try { 19836 // CE storage is unlocked right now, so read out the inode and 19837 // remember for use later when it's locked 19838 // TODO: mark this structure as dirty so we persist it! 19839 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19840 StorageManager.FLAG_STORAGE_CE); 19841 synchronized (mPackages) { 19842 final PackageSetting ps = mSettings.mPackages.get(packageName); 19843 if (ps != null) { 19844 ps.setCeDataInode(ceDataInode, userId); 19845 } 19846 } 19847 } catch (InstallerException e) { 19848 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19849 } 19850 } 19851 19852 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19853 } 19854 19855 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19856 if (pkg == null) { 19857 Slog.wtf(TAG, "Package was null!", new Throwable()); 19858 return; 19859 } 19860 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19862 for (int i = 0; i < childCount; i++) { 19863 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19864 } 19865 } 19866 19867 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19868 final String volumeUuid = pkg.volumeUuid; 19869 final String packageName = pkg.packageName; 19870 final ApplicationInfo app = pkg.applicationInfo; 19871 19872 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19873 // Create a native library symlink only if we have native libraries 19874 // and if the native libraries are 32 bit libraries. We do not provide 19875 // this symlink for 64 bit libraries. 19876 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19877 final String nativeLibPath = app.nativeLibraryDir; 19878 try { 19879 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19880 nativeLibPath, userId); 19881 } catch (InstallerException e) { 19882 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19883 } 19884 } 19885 } 19886 } 19887 19888 /** 19889 * For system apps on non-FBE devices, this method migrates any existing 19890 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19891 * requested by the app. 19892 */ 19893 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19894 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19895 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19896 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19897 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19898 try { 19899 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19900 storageTarget); 19901 } catch (InstallerException e) { 19902 logCriticalInfo(Log.WARN, 19903 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19904 } 19905 return true; 19906 } else { 19907 return false; 19908 } 19909 } 19910 19911 public PackageFreezer freezePackage(String packageName, String killReason) { 19912 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19913 } 19914 19915 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19916 return new PackageFreezer(packageName, userId, killReason); 19917 } 19918 19919 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19920 String killReason) { 19921 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19922 } 19923 19924 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19925 String killReason) { 19926 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19927 return new PackageFreezer(); 19928 } else { 19929 return freezePackage(packageName, userId, killReason); 19930 } 19931 } 19932 19933 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19934 String killReason) { 19935 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19936 } 19937 19938 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19939 String killReason) { 19940 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19941 return new PackageFreezer(); 19942 } else { 19943 return freezePackage(packageName, userId, killReason); 19944 } 19945 } 19946 19947 /** 19948 * Class that freezes and kills the given package upon creation, and 19949 * unfreezes it upon closing. This is typically used when doing surgery on 19950 * app code/data to prevent the app from running while you're working. 19951 */ 19952 private class PackageFreezer implements AutoCloseable { 19953 private final String mPackageName; 19954 private final PackageFreezer[] mChildren; 19955 19956 private final boolean mWeFroze; 19957 19958 private final AtomicBoolean mClosed = new AtomicBoolean(); 19959 private final CloseGuard mCloseGuard = CloseGuard.get(); 19960 19961 /** 19962 * Create and return a stub freezer that doesn't actually do anything, 19963 * typically used when someone requested 19964 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19965 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19966 */ 19967 public PackageFreezer() { 19968 mPackageName = null; 19969 mChildren = null; 19970 mWeFroze = false; 19971 mCloseGuard.open("close"); 19972 } 19973 19974 public PackageFreezer(String packageName, int userId, String killReason) { 19975 synchronized (mPackages) { 19976 mPackageName = packageName; 19977 mWeFroze = mFrozenPackages.add(mPackageName); 19978 19979 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19980 if (ps != null) { 19981 killApplication(ps.name, ps.appId, userId, killReason); 19982 } 19983 19984 final PackageParser.Package p = mPackages.get(packageName); 19985 if (p != null && p.childPackages != null) { 19986 final int N = p.childPackages.size(); 19987 mChildren = new PackageFreezer[N]; 19988 for (int i = 0; i < N; i++) { 19989 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19990 userId, killReason); 19991 } 19992 } else { 19993 mChildren = null; 19994 } 19995 } 19996 mCloseGuard.open("close"); 19997 } 19998 19999 @Override 20000 protected void finalize() throws Throwable { 20001 try { 20002 mCloseGuard.warnIfOpen(); 20003 close(); 20004 } finally { 20005 super.finalize(); 20006 } 20007 } 20008 20009 @Override 20010 public void close() { 20011 mCloseGuard.close(); 20012 if (mClosed.compareAndSet(false, true)) { 20013 synchronized (mPackages) { 20014 if (mWeFroze) { 20015 mFrozenPackages.remove(mPackageName); 20016 } 20017 20018 if (mChildren != null) { 20019 for (PackageFreezer freezer : mChildren) { 20020 freezer.close(); 20021 } 20022 } 20023 } 20024 } 20025 } 20026 } 20027 20028 /** 20029 * Verify that given package is currently frozen. 20030 */ 20031 private void checkPackageFrozen(String packageName) { 20032 synchronized (mPackages) { 20033 if (!mFrozenPackages.contains(packageName)) { 20034 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20035 } 20036 } 20037 } 20038 20039 @Override 20040 public int movePackage(final String packageName, final String volumeUuid) { 20041 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20042 20043 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20044 final int moveId = mNextMoveId.getAndIncrement(); 20045 mHandler.post(new Runnable() { 20046 @Override 20047 public void run() { 20048 try { 20049 movePackageInternal(packageName, volumeUuid, moveId, user); 20050 } catch (PackageManagerException e) { 20051 Slog.w(TAG, "Failed to move " + packageName, e); 20052 mMoveCallbacks.notifyStatusChanged(moveId, 20053 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20054 } 20055 } 20056 }); 20057 return moveId; 20058 } 20059 20060 private void movePackageInternal(final String packageName, final String volumeUuid, 20061 final int moveId, UserHandle user) throws PackageManagerException { 20062 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20063 final PackageManager pm = mContext.getPackageManager(); 20064 20065 final boolean currentAsec; 20066 final String currentVolumeUuid; 20067 final File codeFile; 20068 final String installerPackageName; 20069 final String packageAbiOverride; 20070 final int appId; 20071 final String seinfo; 20072 final String label; 20073 final int targetSdkVersion; 20074 final PackageFreezer freezer; 20075 final int[] installedUserIds; 20076 20077 // reader 20078 synchronized (mPackages) { 20079 final PackageParser.Package pkg = mPackages.get(packageName); 20080 final PackageSetting ps = mSettings.mPackages.get(packageName); 20081 if (pkg == null || ps == null) { 20082 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20083 } 20084 20085 if (pkg.applicationInfo.isSystemApp()) { 20086 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20087 "Cannot move system application"); 20088 } 20089 20090 if (pkg.applicationInfo.isExternalAsec()) { 20091 currentAsec = true; 20092 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20093 } else if (pkg.applicationInfo.isForwardLocked()) { 20094 currentAsec = true; 20095 currentVolumeUuid = "forward_locked"; 20096 } else { 20097 currentAsec = false; 20098 currentVolumeUuid = ps.volumeUuid; 20099 20100 final File probe = new File(pkg.codePath); 20101 final File probeOat = new File(probe, "oat"); 20102 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20103 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20104 "Move only supported for modern cluster style installs"); 20105 } 20106 } 20107 20108 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20109 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20110 "Package already moved to " + volumeUuid); 20111 } 20112 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20113 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20114 "Device admin cannot be moved"); 20115 } 20116 20117 if (mFrozenPackages.contains(packageName)) { 20118 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20119 "Failed to move already frozen package"); 20120 } 20121 20122 codeFile = new File(pkg.codePath); 20123 installerPackageName = ps.installerPackageName; 20124 packageAbiOverride = ps.cpuAbiOverrideString; 20125 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20126 seinfo = pkg.applicationInfo.seinfo; 20127 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20128 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20129 freezer = freezePackage(packageName, "movePackageInternal"); 20130 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20131 } 20132 20133 final Bundle extras = new Bundle(); 20134 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20135 extras.putString(Intent.EXTRA_TITLE, label); 20136 mMoveCallbacks.notifyCreated(moveId, extras); 20137 20138 int installFlags; 20139 final boolean moveCompleteApp; 20140 final File measurePath; 20141 20142 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20143 installFlags = INSTALL_INTERNAL; 20144 moveCompleteApp = !currentAsec; 20145 measurePath = Environment.getDataAppDirectory(volumeUuid); 20146 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20147 installFlags = INSTALL_EXTERNAL; 20148 moveCompleteApp = false; 20149 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20150 } else { 20151 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20152 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20153 || !volume.isMountedWritable()) { 20154 freezer.close(); 20155 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20156 "Move location not mounted private volume"); 20157 } 20158 20159 Preconditions.checkState(!currentAsec); 20160 20161 installFlags = INSTALL_INTERNAL; 20162 moveCompleteApp = true; 20163 measurePath = Environment.getDataAppDirectory(volumeUuid); 20164 } 20165 20166 final PackageStats stats = new PackageStats(null, -1); 20167 synchronized (mInstaller) { 20168 for (int userId : installedUserIds) { 20169 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20170 freezer.close(); 20171 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20172 "Failed to measure package size"); 20173 } 20174 } 20175 } 20176 20177 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20178 + stats.dataSize); 20179 20180 final long startFreeBytes = measurePath.getFreeSpace(); 20181 final long sizeBytes; 20182 if (moveCompleteApp) { 20183 sizeBytes = stats.codeSize + stats.dataSize; 20184 } else { 20185 sizeBytes = stats.codeSize; 20186 } 20187 20188 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20189 freezer.close(); 20190 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20191 "Not enough free space to move"); 20192 } 20193 20194 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20195 20196 final CountDownLatch installedLatch = new CountDownLatch(1); 20197 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20198 @Override 20199 public void onUserActionRequired(Intent intent) throws RemoteException { 20200 throw new IllegalStateException(); 20201 } 20202 20203 @Override 20204 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20205 Bundle extras) throws RemoteException { 20206 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20207 + PackageManager.installStatusToString(returnCode, msg)); 20208 20209 installedLatch.countDown(); 20210 freezer.close(); 20211 20212 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20213 switch (status) { 20214 case PackageInstaller.STATUS_SUCCESS: 20215 mMoveCallbacks.notifyStatusChanged(moveId, 20216 PackageManager.MOVE_SUCCEEDED); 20217 break; 20218 case PackageInstaller.STATUS_FAILURE_STORAGE: 20219 mMoveCallbacks.notifyStatusChanged(moveId, 20220 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20221 break; 20222 default: 20223 mMoveCallbacks.notifyStatusChanged(moveId, 20224 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20225 break; 20226 } 20227 } 20228 }; 20229 20230 final MoveInfo move; 20231 if (moveCompleteApp) { 20232 // Kick off a thread to report progress estimates 20233 new Thread() { 20234 @Override 20235 public void run() { 20236 while (true) { 20237 try { 20238 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20239 break; 20240 } 20241 } catch (InterruptedException ignored) { 20242 } 20243 20244 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20245 final int progress = 10 + (int) MathUtils.constrain( 20246 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20247 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20248 } 20249 } 20250 }.start(); 20251 20252 final String dataAppName = codeFile.getName(); 20253 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20254 dataAppName, appId, seinfo, targetSdkVersion); 20255 } else { 20256 move = null; 20257 } 20258 20259 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20260 20261 final Message msg = mHandler.obtainMessage(INIT_COPY); 20262 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20263 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20264 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20265 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20266 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20267 msg.obj = params; 20268 20269 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20270 System.identityHashCode(msg.obj)); 20271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20272 System.identityHashCode(msg.obj)); 20273 20274 mHandler.sendMessage(msg); 20275 } 20276 20277 @Override 20278 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20279 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20280 20281 final int realMoveId = mNextMoveId.getAndIncrement(); 20282 final Bundle extras = new Bundle(); 20283 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20284 mMoveCallbacks.notifyCreated(realMoveId, extras); 20285 20286 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20287 @Override 20288 public void onCreated(int moveId, Bundle extras) { 20289 // Ignored 20290 } 20291 20292 @Override 20293 public void onStatusChanged(int moveId, int status, long estMillis) { 20294 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20295 } 20296 }; 20297 20298 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20299 storage.setPrimaryStorageUuid(volumeUuid, callback); 20300 return realMoveId; 20301 } 20302 20303 @Override 20304 public int getMoveStatus(int moveId) { 20305 mContext.enforceCallingOrSelfPermission( 20306 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20307 return mMoveCallbacks.mLastStatus.get(moveId); 20308 } 20309 20310 @Override 20311 public void registerMoveCallback(IPackageMoveObserver callback) { 20312 mContext.enforceCallingOrSelfPermission( 20313 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20314 mMoveCallbacks.register(callback); 20315 } 20316 20317 @Override 20318 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20319 mContext.enforceCallingOrSelfPermission( 20320 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20321 mMoveCallbacks.unregister(callback); 20322 } 20323 20324 @Override 20325 public boolean setInstallLocation(int loc) { 20326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20327 null); 20328 if (getInstallLocation() == loc) { 20329 return true; 20330 } 20331 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20332 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20333 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20334 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20335 return true; 20336 } 20337 return false; 20338 } 20339 20340 @Override 20341 public int getInstallLocation() { 20342 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20343 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20344 PackageHelper.APP_INSTALL_AUTO); 20345 } 20346 20347 /** Called by UserManagerService */ 20348 void cleanUpUser(UserManagerService userManager, int userHandle) { 20349 synchronized (mPackages) { 20350 mDirtyUsers.remove(userHandle); 20351 mUserNeedsBadging.delete(userHandle); 20352 mSettings.removeUserLPw(userHandle); 20353 mPendingBroadcasts.remove(userHandle); 20354 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20355 removeUnusedPackagesLPw(userManager, userHandle); 20356 } 20357 } 20358 20359 /** 20360 * We're removing userHandle and would like to remove any downloaded packages 20361 * that are no longer in use by any other user. 20362 * @param userHandle the user being removed 20363 */ 20364 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20365 final boolean DEBUG_CLEAN_APKS = false; 20366 int [] users = userManager.getUserIds(); 20367 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20368 while (psit.hasNext()) { 20369 PackageSetting ps = psit.next(); 20370 if (ps.pkg == null) { 20371 continue; 20372 } 20373 final String packageName = ps.pkg.packageName; 20374 // Skip over if system app 20375 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20376 continue; 20377 } 20378 if (DEBUG_CLEAN_APKS) { 20379 Slog.i(TAG, "Checking package " + packageName); 20380 } 20381 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20382 if (keep) { 20383 if (DEBUG_CLEAN_APKS) { 20384 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20385 } 20386 } else { 20387 for (int i = 0; i < users.length; i++) { 20388 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20389 keep = true; 20390 if (DEBUG_CLEAN_APKS) { 20391 Slog.i(TAG, " Keeping package " + packageName + " for user " 20392 + users[i]); 20393 } 20394 break; 20395 } 20396 } 20397 } 20398 if (!keep) { 20399 if (DEBUG_CLEAN_APKS) { 20400 Slog.i(TAG, " Removing package " + packageName); 20401 } 20402 mHandler.post(new Runnable() { 20403 public void run() { 20404 deletePackageX(packageName, userHandle, 0); 20405 } //end run 20406 }); 20407 } 20408 } 20409 } 20410 20411 /** Called by UserManagerService */ 20412 void createNewUser(int userId) { 20413 synchronized (mInstallLock) { 20414 mSettings.createNewUserLI(this, mInstaller, userId); 20415 } 20416 synchronized (mPackages) { 20417 scheduleWritePackageRestrictionsLocked(userId); 20418 scheduleWritePackageListLocked(userId); 20419 applyFactoryDefaultBrowserLPw(userId); 20420 primeDomainVerificationsLPw(userId); 20421 } 20422 } 20423 20424 void onNewUserCreated(final int userId) { 20425 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20426 // If permission review for legacy apps is required, we represent 20427 // dagerous permissions for such apps as always granted runtime 20428 // permissions to keep per user flag state whether review is needed. 20429 // Hence, if a new user is added we have to propagate dangerous 20430 // permission grants for these legacy apps. 20431 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20432 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20433 | UPDATE_PERMISSIONS_REPLACE_ALL); 20434 } 20435 } 20436 20437 @Override 20438 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20439 mContext.enforceCallingOrSelfPermission( 20440 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20441 "Only package verification agents can read the verifier device identity"); 20442 20443 synchronized (mPackages) { 20444 return mSettings.getVerifierDeviceIdentityLPw(); 20445 } 20446 } 20447 20448 @Override 20449 public void setPermissionEnforced(String permission, boolean enforced) { 20450 // TODO: Now that we no longer change GID for storage, this should to away. 20451 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20452 "setPermissionEnforced"); 20453 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20454 synchronized (mPackages) { 20455 if (mSettings.mReadExternalStorageEnforced == null 20456 || mSettings.mReadExternalStorageEnforced != enforced) { 20457 mSettings.mReadExternalStorageEnforced = enforced; 20458 mSettings.writeLPr(); 20459 } 20460 } 20461 // kill any non-foreground processes so we restart them and 20462 // grant/revoke the GID. 20463 final IActivityManager am = ActivityManagerNative.getDefault(); 20464 if (am != null) { 20465 final long token = Binder.clearCallingIdentity(); 20466 try { 20467 am.killProcessesBelowForeground("setPermissionEnforcement"); 20468 } catch (RemoteException e) { 20469 } finally { 20470 Binder.restoreCallingIdentity(token); 20471 } 20472 } 20473 } else { 20474 throw new IllegalArgumentException("No selective enforcement for " + permission); 20475 } 20476 } 20477 20478 @Override 20479 @Deprecated 20480 public boolean isPermissionEnforced(String permission) { 20481 return true; 20482 } 20483 20484 @Override 20485 public boolean isStorageLow() { 20486 final long token = Binder.clearCallingIdentity(); 20487 try { 20488 final DeviceStorageMonitorInternal 20489 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20490 if (dsm != null) { 20491 return dsm.isMemoryLow(); 20492 } else { 20493 return false; 20494 } 20495 } finally { 20496 Binder.restoreCallingIdentity(token); 20497 } 20498 } 20499 20500 @Override 20501 public IPackageInstaller getPackageInstaller() { 20502 return mInstallerService; 20503 } 20504 20505 private boolean userNeedsBadging(int userId) { 20506 int index = mUserNeedsBadging.indexOfKey(userId); 20507 if (index < 0) { 20508 final UserInfo userInfo; 20509 final long token = Binder.clearCallingIdentity(); 20510 try { 20511 userInfo = sUserManager.getUserInfo(userId); 20512 } finally { 20513 Binder.restoreCallingIdentity(token); 20514 } 20515 final boolean b; 20516 if (userInfo != null && userInfo.isManagedProfile()) { 20517 b = true; 20518 } else { 20519 b = false; 20520 } 20521 mUserNeedsBadging.put(userId, b); 20522 return b; 20523 } 20524 return mUserNeedsBadging.valueAt(index); 20525 } 20526 20527 @Override 20528 public KeySet getKeySetByAlias(String packageName, String alias) { 20529 if (packageName == null || alias == null) { 20530 return null; 20531 } 20532 synchronized(mPackages) { 20533 final PackageParser.Package pkg = mPackages.get(packageName); 20534 if (pkg == null) { 20535 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20536 throw new IllegalArgumentException("Unknown package: " + packageName); 20537 } 20538 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20539 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20540 } 20541 } 20542 20543 @Override 20544 public KeySet getSigningKeySet(String packageName) { 20545 if (packageName == null) { 20546 return null; 20547 } 20548 synchronized(mPackages) { 20549 final PackageParser.Package pkg = mPackages.get(packageName); 20550 if (pkg == null) { 20551 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20552 throw new IllegalArgumentException("Unknown package: " + packageName); 20553 } 20554 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20555 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20556 throw new SecurityException("May not access signing KeySet of other apps."); 20557 } 20558 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20559 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20560 } 20561 } 20562 20563 @Override 20564 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20565 if (packageName == null || ks == null) { 20566 return false; 20567 } 20568 synchronized(mPackages) { 20569 final PackageParser.Package pkg = mPackages.get(packageName); 20570 if (pkg == null) { 20571 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20572 throw new IllegalArgumentException("Unknown package: " + packageName); 20573 } 20574 IBinder ksh = ks.getToken(); 20575 if (ksh instanceof KeySetHandle) { 20576 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20577 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20578 } 20579 return false; 20580 } 20581 } 20582 20583 @Override 20584 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20585 if (packageName == null || ks == null) { 20586 return false; 20587 } 20588 synchronized(mPackages) { 20589 final PackageParser.Package pkg = mPackages.get(packageName); 20590 if (pkg == null) { 20591 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20592 throw new IllegalArgumentException("Unknown package: " + packageName); 20593 } 20594 IBinder ksh = ks.getToken(); 20595 if (ksh instanceof KeySetHandle) { 20596 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20597 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20598 } 20599 return false; 20600 } 20601 } 20602 20603 private void deletePackageIfUnusedLPr(final String packageName) { 20604 PackageSetting ps = mSettings.mPackages.get(packageName); 20605 if (ps == null) { 20606 return; 20607 } 20608 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20609 // TODO Implement atomic delete if package is unused 20610 // It is currently possible that the package will be deleted even if it is installed 20611 // after this method returns. 20612 mHandler.post(new Runnable() { 20613 public void run() { 20614 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20615 } 20616 }); 20617 } 20618 } 20619 20620 /** 20621 * Check and throw if the given before/after packages would be considered a 20622 * downgrade. 20623 */ 20624 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20625 throws PackageManagerException { 20626 if (after.versionCode < before.mVersionCode) { 20627 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20628 "Update version code " + after.versionCode + " is older than current " 20629 + before.mVersionCode); 20630 } else if (after.versionCode == before.mVersionCode) { 20631 if (after.baseRevisionCode < before.baseRevisionCode) { 20632 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20633 "Update base revision code " + after.baseRevisionCode 20634 + " is older than current " + before.baseRevisionCode); 20635 } 20636 20637 if (!ArrayUtils.isEmpty(after.splitNames)) { 20638 for (int i = 0; i < after.splitNames.length; i++) { 20639 final String splitName = after.splitNames[i]; 20640 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20641 if (j != -1) { 20642 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20643 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20644 "Update split " + splitName + " revision code " 20645 + after.splitRevisionCodes[i] + " is older than current " 20646 + before.splitRevisionCodes[j]); 20647 } 20648 } 20649 } 20650 } 20651 } 20652 } 20653 20654 private static class MoveCallbacks extends Handler { 20655 private static final int MSG_CREATED = 1; 20656 private static final int MSG_STATUS_CHANGED = 2; 20657 20658 private final RemoteCallbackList<IPackageMoveObserver> 20659 mCallbacks = new RemoteCallbackList<>(); 20660 20661 private final SparseIntArray mLastStatus = new SparseIntArray(); 20662 20663 public MoveCallbacks(Looper looper) { 20664 super(looper); 20665 } 20666 20667 public void register(IPackageMoveObserver callback) { 20668 mCallbacks.register(callback); 20669 } 20670 20671 public void unregister(IPackageMoveObserver callback) { 20672 mCallbacks.unregister(callback); 20673 } 20674 20675 @Override 20676 public void handleMessage(Message msg) { 20677 final SomeArgs args = (SomeArgs) msg.obj; 20678 final int n = mCallbacks.beginBroadcast(); 20679 for (int i = 0; i < n; i++) { 20680 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20681 try { 20682 invokeCallback(callback, msg.what, args); 20683 } catch (RemoteException ignored) { 20684 } 20685 } 20686 mCallbacks.finishBroadcast(); 20687 args.recycle(); 20688 } 20689 20690 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20691 throws RemoteException { 20692 switch (what) { 20693 case MSG_CREATED: { 20694 callback.onCreated(args.argi1, (Bundle) args.arg2); 20695 break; 20696 } 20697 case MSG_STATUS_CHANGED: { 20698 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20699 break; 20700 } 20701 } 20702 } 20703 20704 private void notifyCreated(int moveId, Bundle extras) { 20705 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20706 20707 final SomeArgs args = SomeArgs.obtain(); 20708 args.argi1 = moveId; 20709 args.arg2 = extras; 20710 obtainMessage(MSG_CREATED, args).sendToTarget(); 20711 } 20712 20713 private void notifyStatusChanged(int moveId, int status) { 20714 notifyStatusChanged(moveId, status, -1); 20715 } 20716 20717 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20718 Slog.v(TAG, "Move " + moveId + " status " + status); 20719 20720 final SomeArgs args = SomeArgs.obtain(); 20721 args.argi1 = moveId; 20722 args.argi2 = status; 20723 args.arg3 = estMillis; 20724 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20725 20726 synchronized (mLastStatus) { 20727 mLastStatus.put(moveId, status); 20728 } 20729 } 20730 } 20731 20732 private final static class OnPermissionChangeListeners extends Handler { 20733 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20734 20735 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20736 new RemoteCallbackList<>(); 20737 20738 public OnPermissionChangeListeners(Looper looper) { 20739 super(looper); 20740 } 20741 20742 @Override 20743 public void handleMessage(Message msg) { 20744 switch (msg.what) { 20745 case MSG_ON_PERMISSIONS_CHANGED: { 20746 final int uid = msg.arg1; 20747 handleOnPermissionsChanged(uid); 20748 } break; 20749 } 20750 } 20751 20752 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20753 mPermissionListeners.register(listener); 20754 20755 } 20756 20757 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20758 mPermissionListeners.unregister(listener); 20759 } 20760 20761 public void onPermissionsChanged(int uid) { 20762 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20763 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20764 } 20765 } 20766 20767 private void handleOnPermissionsChanged(int uid) { 20768 final int count = mPermissionListeners.beginBroadcast(); 20769 try { 20770 for (int i = 0; i < count; i++) { 20771 IOnPermissionsChangeListener callback = mPermissionListeners 20772 .getBroadcastItem(i); 20773 try { 20774 callback.onPermissionsChanged(uid); 20775 } catch (RemoteException e) { 20776 Log.e(TAG, "Permission listener is dead", e); 20777 } 20778 } 20779 } finally { 20780 mPermissionListeners.finishBroadcast(); 20781 } 20782 } 20783 } 20784 20785 private class PackageManagerInternalImpl extends PackageManagerInternal { 20786 @Override 20787 public void setLocationPackagesProvider(PackagesProvider provider) { 20788 synchronized (mPackages) { 20789 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20790 } 20791 } 20792 20793 @Override 20794 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20795 synchronized (mPackages) { 20796 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20797 } 20798 } 20799 20800 @Override 20801 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20802 synchronized (mPackages) { 20803 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20804 } 20805 } 20806 20807 @Override 20808 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20809 synchronized (mPackages) { 20810 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20811 } 20812 } 20813 20814 @Override 20815 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20816 synchronized (mPackages) { 20817 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20818 } 20819 } 20820 20821 @Override 20822 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20823 synchronized (mPackages) { 20824 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20825 } 20826 } 20827 20828 @Override 20829 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20830 synchronized (mPackages) { 20831 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20832 packageName, userId); 20833 } 20834 } 20835 20836 @Override 20837 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20838 synchronized (mPackages) { 20839 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20840 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20841 packageName, userId); 20842 } 20843 } 20844 20845 @Override 20846 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20847 synchronized (mPackages) { 20848 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20849 packageName, userId); 20850 } 20851 } 20852 20853 @Override 20854 public void setKeepUninstalledPackages(final List<String> packageList) { 20855 Preconditions.checkNotNull(packageList); 20856 List<String> removedFromList = null; 20857 synchronized (mPackages) { 20858 if (mKeepUninstalledPackages != null) { 20859 final int packagesCount = mKeepUninstalledPackages.size(); 20860 for (int i = 0; i < packagesCount; i++) { 20861 String oldPackage = mKeepUninstalledPackages.get(i); 20862 if (packageList != null && packageList.contains(oldPackage)) { 20863 continue; 20864 } 20865 if (removedFromList == null) { 20866 removedFromList = new ArrayList<>(); 20867 } 20868 removedFromList.add(oldPackage); 20869 } 20870 } 20871 mKeepUninstalledPackages = new ArrayList<>(packageList); 20872 if (removedFromList != null) { 20873 final int removedCount = removedFromList.size(); 20874 for (int i = 0; i < removedCount; i++) { 20875 deletePackageIfUnusedLPr(removedFromList.get(i)); 20876 } 20877 } 20878 } 20879 } 20880 20881 @Override 20882 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20883 synchronized (mPackages) { 20884 // If we do not support permission review, done. 20885 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20886 return false; 20887 } 20888 20889 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20890 if (packageSetting == null) { 20891 return false; 20892 } 20893 20894 // Permission review applies only to apps not supporting the new permission model. 20895 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20896 return false; 20897 } 20898 20899 // Legacy apps have the permission and get user consent on launch. 20900 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20901 return permissionsState.isPermissionReviewRequired(userId); 20902 } 20903 } 20904 20905 @Override 20906 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20907 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20908 } 20909 20910 @Override 20911 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20912 int userId) { 20913 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20914 } 20915 20916 @Override 20917 public void setDeviceAndProfileOwnerPackages( 20918 int deviceOwnerUserId, String deviceOwnerPackage, 20919 SparseArray<String> profileOwnerPackages) { 20920 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20921 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20922 } 20923 20924 @Override 20925 public boolean isPackageDataProtected(int userId, String packageName) { 20926 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20927 } 20928 } 20929 20930 @Override 20931 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20932 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20933 synchronized (mPackages) { 20934 final long identity = Binder.clearCallingIdentity(); 20935 try { 20936 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20937 packageNames, userId); 20938 } finally { 20939 Binder.restoreCallingIdentity(identity); 20940 } 20941 } 20942 } 20943 20944 private static void enforceSystemOrPhoneCaller(String tag) { 20945 int callingUid = Binder.getCallingUid(); 20946 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20947 throw new SecurityException( 20948 "Cannot call " + tag + " from UID " + callingUid); 20949 } 20950 } 20951 20952 boolean isHistoricalPackageUsageAvailable() { 20953 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20954 } 20955 20956 /** 20957 * Return a <b>copy</b> of the collection of packages known to the package manager. 20958 * @return A copy of the values of mPackages. 20959 */ 20960 Collection<PackageParser.Package> getPackages() { 20961 synchronized (mPackages) { 20962 return new ArrayList<>(mPackages.values()); 20963 } 20964 } 20965 20966 /** 20967 * Logs process start information (including base APK hash) to the security log. 20968 * @hide 20969 */ 20970 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20971 String apkFile, int pid) { 20972 if (!SecurityLog.isLoggingEnabled()) { 20973 return; 20974 } 20975 Bundle data = new Bundle(); 20976 data.putLong("startTimestamp", System.currentTimeMillis()); 20977 data.putString("processName", processName); 20978 data.putInt("uid", uid); 20979 data.putString("seinfo", seinfo); 20980 data.putString("apkFile", apkFile); 20981 data.putInt("pid", pid); 20982 Message msg = mProcessLoggingHandler.obtainMessage( 20983 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20984 msg.setData(data); 20985 mProcessLoggingHandler.sendMessage(msg); 20986 } 20987 20988 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20989 return mCompilerStats.getPackageStats(pkgName); 20990 } 20991 20992 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20993 return getOrCreateCompilerPackageStats(pkg.packageName); 20994 } 20995 20996 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20997 return mCompilerStats.getOrCreatePackageStats(pkgName); 20998 } 20999 21000 public void deleteCompilerPackageStats(String pkgName) { 21001 mCompilerStats.deletePackageStats(pkgName); 21002 } 21003} 21004