PackageManagerService.java revision 2578beccbeacd605728e018cf390c10cef72b48b
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 PACKAGE_SCHEME = "package"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 464 465 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 466 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 467 468 /** Permission grant: not grant the permission. */ 469 private static final int GRANT_DENIED = 1; 470 471 /** Permission grant: grant the permission as an install permission. */ 472 private static final int GRANT_INSTALL = 2; 473 474 /** Permission grant: grant the permission as a runtime one. */ 475 private static final int GRANT_RUNTIME = 3; 476 477 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 478 private static final int GRANT_UPGRADE = 4; 479 480 /** Canonical intent used to identify what counts as a "web browser" app */ 481 private static final Intent sBrowserIntent; 482 static { 483 sBrowserIntent = new Intent(); 484 sBrowserIntent.setAction(Intent.ACTION_VIEW); 485 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 486 sBrowserIntent.setData(Uri.parse("http:")); 487 } 488 489 /** 490 * The set of all protected actions [i.e. those actions for which a high priority 491 * intent filter is disallowed]. 492 */ 493 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 494 static { 495 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 496 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 497 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 498 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 499 } 500 501 // Compilation reasons. 502 public static final int REASON_FIRST_BOOT = 0; 503 public static final int REASON_BOOT = 1; 504 public static final int REASON_INSTALL = 2; 505 public static final int REASON_BACKGROUND_DEXOPT = 3; 506 public static final int REASON_AB_OTA = 4; 507 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 508 public static final int REASON_SHARED_APK = 6; 509 public static final int REASON_FORCED_DEXOPT = 7; 510 public static final int REASON_CORE_APP = 8; 511 512 public static final int REASON_LAST = REASON_CORE_APP; 513 514 /** Special library name that skips shared libraries check during compilation. */ 515 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 516 517 final ServiceThread mHandlerThread; 518 519 final PackageHandler mHandler; 520 521 private final ProcessLoggingHandler mProcessLoggingHandler; 522 523 /** 524 * Messages for {@link #mHandler} that need to wait for system ready before 525 * being dispatched. 526 */ 527 private ArrayList<Message> mPostSystemReadyMessages; 528 529 final int mSdkVersion = Build.VERSION.SDK_INT; 530 531 final Context mContext; 532 final boolean mFactoryTest; 533 final boolean mOnlyCore; 534 final DisplayMetrics mMetrics; 535 final int mDefParseFlags; 536 final String[] mSeparateProcesses; 537 final boolean mIsUpgrade; 538 final boolean mIsPreNUpgrade; 539 final boolean mIsPreNMR1Upgrade; 540 541 @GuardedBy("mPackages") 542 private boolean mDexOptDialogShown; 543 544 /** The location for ASEC container files on internal storage. */ 545 final String mAsecInternalPath; 546 547 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 548 // LOCK HELD. Can be called with mInstallLock held. 549 @GuardedBy("mInstallLock") 550 final Installer mInstaller; 551 552 /** Directory where installed third-party apps stored */ 553 final File mAppInstallDir; 554 final File mEphemeralInstallDir; 555 556 /** 557 * Directory to which applications installed internally have their 558 * 32 bit native libraries copied. 559 */ 560 private File mAppLib32InstallDir; 561 562 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 563 // apps. 564 final File mDrmAppPrivateInstallDir; 565 566 // ---------------------------------------------------------------- 567 568 // Lock for state used when installing and doing other long running 569 // operations. Methods that must be called with this lock held have 570 // the suffix "LI". 571 final Object mInstallLock = new Object(); 572 573 // ---------------------------------------------------------------- 574 575 // Keys are String (package name), values are Package. This also serves 576 // as the lock for the global state. Methods that must be called with 577 // this lock held have the prefix "LP". 578 @GuardedBy("mPackages") 579 final ArrayMap<String, PackageParser.Package> mPackages = 580 new ArrayMap<String, PackageParser.Package>(); 581 582 final ArrayMap<String, Set<String>> mKnownCodebase = 583 new ArrayMap<String, Set<String>>(); 584 585 // Tracks available target package names -> overlay package paths. 586 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 587 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 588 589 /** 590 * Tracks new system packages [received in an OTA] that we expect to 591 * find updated user-installed versions. Keys are package name, values 592 * are package location. 593 */ 594 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 595 /** 596 * Tracks high priority intent filters for protected actions. During boot, certain 597 * filter actions are protected and should never be allowed to have a high priority 598 * intent filter for them. However, there is one, and only one exception -- the 599 * setup wizard. It must be able to define a high priority intent filter for these 600 * actions to ensure there are no escapes from the wizard. We need to delay processing 601 * of these during boot as we need to look at all of the system packages in order 602 * to know which component is the setup wizard. 603 */ 604 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 605 /** 606 * Whether or not processing protected filters should be deferred. 607 */ 608 private boolean mDeferProtectedFilters = true; 609 610 /** 611 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 612 */ 613 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 614 /** 615 * Whether or not system app permissions should be promoted from install to runtime. 616 */ 617 boolean mPromoteSystemApps; 618 619 @GuardedBy("mPackages") 620 final Settings mSettings; 621 622 /** 623 * Set of package names that are currently "frozen", which means active 624 * surgery is being done on the code/data for that package. The platform 625 * will refuse to launch frozen packages to avoid race conditions. 626 * 627 * @see PackageFreezer 628 */ 629 @GuardedBy("mPackages") 630 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 631 632 final ProtectedPackages mProtectedPackages; 633 634 boolean mFirstBoot; 635 636 // System configuration read by SystemConfig. 637 final int[] mGlobalGids; 638 final SparseArray<ArraySet<String>> mSystemPermissions; 639 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 640 641 // If mac_permissions.xml was found for seinfo labeling. 642 boolean mFoundPolicyFile; 643 644 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 645 646 public static final class SharedLibraryEntry { 647 public final String path; 648 public final String apk; 649 650 SharedLibraryEntry(String _path, String _apk) { 651 path = _path; 652 apk = _apk; 653 } 654 } 655 656 // Currently known shared libraries. 657 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 658 new ArrayMap<String, SharedLibraryEntry>(); 659 660 // All available activities, for your resolving pleasure. 661 final ActivityIntentResolver mActivities = 662 new ActivityIntentResolver(); 663 664 // All available receivers, for your resolving pleasure. 665 final ActivityIntentResolver mReceivers = 666 new ActivityIntentResolver(); 667 668 // All available services, for your resolving pleasure. 669 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 670 671 // All available providers, for your resolving pleasure. 672 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 673 674 // Mapping from provider base names (first directory in content URI codePath) 675 // to the provider information. 676 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 677 new ArrayMap<String, PackageParser.Provider>(); 678 679 // Mapping from instrumentation class names to info about them. 680 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 681 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 682 683 // Mapping from permission names to info about them. 684 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 685 new ArrayMap<String, PackageParser.PermissionGroup>(); 686 687 // Packages whose data we have transfered into another package, thus 688 // should no longer exist. 689 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 690 691 // Broadcast actions that are only available to the system. 692 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 693 694 /** List of packages waiting for verification. */ 695 final SparseArray<PackageVerificationState> mPendingVerification 696 = new SparseArray<PackageVerificationState>(); 697 698 /** Set of packages associated with each app op permission. */ 699 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 700 701 final PackageInstallerService mInstallerService; 702 703 private final PackageDexOptimizer mPackageDexOptimizer; 704 705 private AtomicInteger mNextMoveId = new AtomicInteger(); 706 private final MoveCallbacks mMoveCallbacks; 707 708 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 709 710 // Cache of users who need badging. 711 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 712 713 /** Token for keys in mPendingVerification. */ 714 private int mPendingVerificationToken = 0; 715 716 volatile boolean mSystemReady; 717 volatile boolean mSafeMode; 718 volatile boolean mHasSystemUidErrors; 719 720 ApplicationInfo mAndroidApplication; 721 final ActivityInfo mResolveActivity = new ActivityInfo(); 722 final ResolveInfo mResolveInfo = new ResolveInfo(); 723 ComponentName mResolveComponentName; 724 PackageParser.Package mPlatformPackage; 725 ComponentName mCustomResolverComponentName; 726 727 boolean mResolverReplaced = false; 728 729 private final @Nullable ComponentName mIntentFilterVerifierComponent; 730 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 731 732 private int mIntentFilterVerificationToken = 0; 733 734 /** Component that knows whether or not an ephemeral application exists */ 735 final ComponentName mEphemeralResolverComponent; 736 /** The service connection to the ephemeral resolver */ 737 final EphemeralResolverConnection mEphemeralResolverConnection; 738 739 /** Component used to install ephemeral applications */ 740 final ComponentName mEphemeralInstallerComponent; 741 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 742 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 743 744 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 745 = new SparseArray<IntentFilterVerificationState>(); 746 747 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 748 749 // List of packages names to keep cached, even if they are uninstalled for all users 750 private List<String> mKeepUninstalledPackages; 751 752 private UserManagerInternal mUserManagerInternal; 753 754 private static class IFVerificationParams { 755 PackageParser.Package pkg; 756 boolean replacing; 757 int userId; 758 int verifierUid; 759 760 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 761 int _userId, int _verifierUid) { 762 pkg = _pkg; 763 replacing = _replacing; 764 userId = _userId; 765 replacing = _replacing; 766 verifierUid = _verifierUid; 767 } 768 } 769 770 private interface IntentFilterVerifier<T extends IntentFilter> { 771 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 772 T filter, String packageName); 773 void startVerifications(int userId); 774 void receiveVerificationResponse(int verificationId); 775 } 776 777 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 778 private Context mContext; 779 private ComponentName mIntentFilterVerifierComponent; 780 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 781 782 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 783 mContext = context; 784 mIntentFilterVerifierComponent = verifierComponent; 785 } 786 787 private String getDefaultScheme() { 788 return IntentFilter.SCHEME_HTTPS; 789 } 790 791 @Override 792 public void startVerifications(int userId) { 793 // Launch verifications requests 794 int count = mCurrentIntentFilterVerifications.size(); 795 for (int n=0; n<count; n++) { 796 int verificationId = mCurrentIntentFilterVerifications.get(n); 797 final IntentFilterVerificationState ivs = 798 mIntentFilterVerificationStates.get(verificationId); 799 800 String packageName = ivs.getPackageName(); 801 802 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 803 final int filterCount = filters.size(); 804 ArraySet<String> domainsSet = new ArraySet<>(); 805 for (int m=0; m<filterCount; m++) { 806 PackageParser.ActivityIntentInfo filter = filters.get(m); 807 domainsSet.addAll(filter.getHostsList()); 808 } 809 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 810 synchronized (mPackages) { 811 if (mSettings.createIntentFilterVerificationIfNeededLPw( 812 packageName, domainsList) != null) { 813 scheduleWriteSettingsLocked(); 814 } 815 } 816 sendVerificationRequest(userId, verificationId, ivs); 817 } 818 mCurrentIntentFilterVerifications.clear(); 819 } 820 821 private void sendVerificationRequest(int userId, int verificationId, 822 IntentFilterVerificationState ivs) { 823 824 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 827 verificationId); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 830 getDefaultScheme()); 831 verificationIntent.putExtra( 832 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 833 ivs.getHostsString()); 834 verificationIntent.putExtra( 835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 836 ivs.getPackageName()); 837 verificationIntent.setComponent(mIntentFilterVerifierComponent); 838 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 839 840 UserHandle user = new UserHandle(userId); 841 mContext.sendBroadcastAsUser(verificationIntent, user); 842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 843 "Sending IntentFilter verification broadcast"); 844 } 845 846 public void receiveVerificationResponse(int verificationId) { 847 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 848 849 final boolean verified = ivs.isVerified(); 850 851 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 852 final int count = filters.size(); 853 if (DEBUG_DOMAIN_VERIFICATION) { 854 Slog.i(TAG, "Received verification response " + verificationId 855 + " for " + count + " filters, verified=" + verified); 856 } 857 for (int n=0; n<count; n++) { 858 PackageParser.ActivityIntentInfo filter = filters.get(n); 859 filter.setVerified(verified); 860 861 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 862 + " verified with result:" + verified + " and hosts:" 863 + ivs.getHostsString()); 864 } 865 866 mIntentFilterVerificationStates.remove(verificationId); 867 868 final String packageName = ivs.getPackageName(); 869 IntentFilterVerificationInfo ivi = null; 870 871 synchronized (mPackages) { 872 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 873 } 874 if (ivi == null) { 875 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 876 + verificationId + " packageName:" + packageName); 877 return; 878 } 879 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 880 "Updating IntentFilterVerificationInfo for package " + packageName 881 +" verificationId:" + verificationId); 882 883 synchronized (mPackages) { 884 if (verified) { 885 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 886 } else { 887 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 888 } 889 scheduleWriteSettingsLocked(); 890 891 final int userId = ivs.getUserId(); 892 if (userId != UserHandle.USER_ALL) { 893 final int userStatus = 894 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 895 896 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 897 boolean needUpdate = false; 898 899 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 900 // already been set by the User thru the Disambiguation dialog 901 switch (userStatus) { 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 } else { 906 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 907 } 908 needUpdate = true; 909 break; 910 911 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 912 if (verified) { 913 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 914 needUpdate = true; 915 } 916 break; 917 918 default: 919 // Nothing to do 920 } 921 922 if (needUpdate) { 923 mSettings.updateIntentFilterVerificationStatusLPw( 924 packageName, updatedStatus, userId); 925 scheduleWritePackageRestrictionsLocked(userId); 926 } 927 } 928 } 929 } 930 931 @Override 932 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 933 ActivityIntentInfo filter, String packageName) { 934 if (!hasValidDomains(filter)) { 935 return false; 936 } 937 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 938 if (ivs == null) { 939 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 940 packageName); 941 } 942 if (DEBUG_DOMAIN_VERIFICATION) { 943 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 944 } 945 ivs.addFilter(filter); 946 return true; 947 } 948 949 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 950 int userId, int verificationId, String packageName) { 951 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 952 verifierUid, userId, packageName); 953 ivs.setPendingState(); 954 synchronized (mPackages) { 955 mIntentFilterVerificationStates.append(verificationId, ivs); 956 mCurrentIntentFilterVerifications.add(verificationId); 957 } 958 return ivs; 959 } 960 } 961 962 private static boolean hasValidDomains(ActivityIntentInfo filter) { 963 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 964 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 965 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 966 } 967 968 // Set of pending broadcasts for aggregating enable/disable of components. 969 static class PendingPackageBroadcasts { 970 // for each user id, a map of <package name -> components within that package> 971 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 972 973 public PendingPackageBroadcasts() { 974 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 975 } 976 977 public ArrayList<String> get(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 979 return packages.get(packageName); 980 } 981 982 public void put(int userId, String packageName, ArrayList<String> components) { 983 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 984 packages.put(packageName, components); 985 } 986 987 public void remove(int userId, String packageName) { 988 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 989 if (packages != null) { 990 packages.remove(packageName); 991 } 992 } 993 994 public void remove(int userId) { 995 mUidMap.remove(userId); 996 } 997 998 public int userIdCount() { 999 return mUidMap.size(); 1000 } 1001 1002 public int userIdAt(int n) { 1003 return mUidMap.keyAt(n); 1004 } 1005 1006 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1007 return mUidMap.get(userId); 1008 } 1009 1010 public int size() { 1011 // total number of pending broadcast entries across all userIds 1012 int num = 0; 1013 for (int i = 0; i< mUidMap.size(); i++) { 1014 num += mUidMap.valueAt(i).size(); 1015 } 1016 return num; 1017 } 1018 1019 public void clear() { 1020 mUidMap.clear(); 1021 } 1022 1023 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1024 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1025 if (map == null) { 1026 map = new ArrayMap<String, ArrayList<String>>(); 1027 mUidMap.put(userId, map); 1028 } 1029 return map; 1030 } 1031 } 1032 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1033 1034 // Service Connection to remote media container service to copy 1035 // package uri's from external media onto secure containers 1036 // or internal storage. 1037 private IMediaContainerService mContainerService = null; 1038 1039 static final int SEND_PENDING_BROADCAST = 1; 1040 static final int MCS_BOUND = 3; 1041 static final int END_COPY = 4; 1042 static final int INIT_COPY = 5; 1043 static final int MCS_UNBIND = 6; 1044 static final int START_CLEANING_PACKAGE = 7; 1045 static final int FIND_INSTALL_LOC = 8; 1046 static final int POST_INSTALL = 9; 1047 static final int MCS_RECONNECT = 10; 1048 static final int MCS_GIVE_UP = 11; 1049 static final int UPDATED_MEDIA_STATUS = 12; 1050 static final int WRITE_SETTINGS = 13; 1051 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1052 static final int PACKAGE_VERIFIED = 15; 1053 static final int CHECK_PENDING_VERIFICATION = 16; 1054 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1055 static final int INTENT_FILTER_VERIFIED = 18; 1056 static final int WRITE_PACKAGE_LIST = 19; 1057 1058 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1059 1060 // Delay time in millisecs 1061 static final int BROADCAST_DELAY = 10 * 1000; 1062 1063 static UserManagerService sUserManager; 1064 1065 // Stores a list of users whose package restrictions file needs to be updated 1066 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1067 1068 final private DefaultContainerConnection mDefContainerConn = 1069 new DefaultContainerConnection(); 1070 class DefaultContainerConnection implements ServiceConnection { 1071 public void onServiceConnected(ComponentName name, IBinder service) { 1072 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1073 IMediaContainerService imcs = 1074 IMediaContainerService.Stub.asInterface(service); 1075 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1076 } 1077 1078 public void onServiceDisconnected(ComponentName name) { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1080 } 1081 } 1082 1083 // Recordkeeping of restore-after-install operations that are currently in flight 1084 // between the Package Manager and the Backup Manager 1085 static class PostInstallData { 1086 public InstallArgs args; 1087 public PackageInstalledInfo res; 1088 1089 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1090 args = _a; 1091 res = _r; 1092 } 1093 } 1094 1095 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1096 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1097 1098 // XML tags for backup/restore of various bits of state 1099 private static final String TAG_PREFERRED_BACKUP = "pa"; 1100 private static final String TAG_DEFAULT_APPS = "da"; 1101 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1102 1103 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1104 private static final String TAG_ALL_GRANTS = "rt-grants"; 1105 private static final String TAG_GRANT = "grant"; 1106 private static final String ATTR_PACKAGE_NAME = "pkg"; 1107 1108 private static final String TAG_PERMISSION = "perm"; 1109 private static final String ATTR_PERMISSION_NAME = "name"; 1110 private static final String ATTR_IS_GRANTED = "g"; 1111 private static final String ATTR_USER_SET = "set"; 1112 private static final String ATTR_USER_FIXED = "fixed"; 1113 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1114 1115 // System/policy permission grants are not backed up 1116 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_POLICY_FIXED 1118 | FLAG_PERMISSION_SYSTEM_FIXED 1119 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1120 1121 // And we back up these user-adjusted states 1122 private static final int USER_RUNTIME_GRANT_MASK = 1123 FLAG_PERMISSION_USER_SET 1124 | FLAG_PERMISSION_USER_FIXED 1125 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1126 1127 final @Nullable String mRequiredVerifierPackage; 1128 final @NonNull String mRequiredInstallerPackage; 1129 final @NonNull String mRequiredUninstallerPackage; 1130 final @Nullable String mSetupWizardPackage; 1131 final @NonNull String mServicesSystemSharedLibraryPackageName; 1132 final @NonNull String mSharedSystemSharedLibraryPackageName; 1133 1134 private final PackageUsage mPackageUsage = new PackageUsage(); 1135 private final CompilerStats mCompilerStats = new CompilerStats(); 1136 1137 class PackageHandler extends Handler { 1138 private boolean mBound = false; 1139 final ArrayList<HandlerParams> mPendingInstalls = 1140 new ArrayList<HandlerParams>(); 1141 1142 private boolean connectToService() { 1143 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1144 " DefaultContainerService"); 1145 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1147 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1148 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1150 mBound = true; 1151 return true; 1152 } 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1154 return false; 1155 } 1156 1157 private void disconnectService() { 1158 mContainerService = null; 1159 mBound = false; 1160 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1161 mContext.unbindService(mDefContainerConn); 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 } 1164 1165 PackageHandler(Looper looper) { 1166 super(looper); 1167 } 1168 1169 public void handleMessage(Message msg) { 1170 try { 1171 doHandleMessage(msg); 1172 } finally { 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 } 1175 } 1176 1177 void doHandleMessage(Message msg) { 1178 switch (msg.what) { 1179 case INIT_COPY: { 1180 HandlerParams params = (HandlerParams) msg.obj; 1181 int idx = mPendingInstalls.size(); 1182 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1183 // If a bind was already initiated we dont really 1184 // need to do anything. The pending install 1185 // will be processed later on. 1186 if (!mBound) { 1187 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1188 System.identityHashCode(mHandler)); 1189 // If this is the only one pending we might 1190 // have to bind to the service again. 1191 if (!connectToService()) { 1192 Slog.e(TAG, "Failed to bind to media container service"); 1193 params.serviceError(); 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1195 System.identityHashCode(mHandler)); 1196 if (params.traceMethod != null) { 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1198 params.traceCookie); 1199 } 1200 return; 1201 } else { 1202 // Once we bind to the service, the first 1203 // pending request will be processed. 1204 mPendingInstalls.add(idx, params); 1205 } 1206 } else { 1207 mPendingInstalls.add(idx, params); 1208 // Already bound to the service. Just make 1209 // sure we trigger off processing the first request. 1210 if (idx == 0) { 1211 mHandler.sendEmptyMessage(MCS_BOUND); 1212 } 1213 } 1214 break; 1215 } 1216 case MCS_BOUND: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1218 if (msg.obj != null) { 1219 mContainerService = (IMediaContainerService) msg.obj; 1220 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1221 System.identityHashCode(mHandler)); 1222 } 1223 if (mContainerService == null) { 1224 if (!mBound) { 1225 // Something seriously wrong since we are not bound and we are not 1226 // waiting for connection. Bail out. 1227 Slog.e(TAG, "Cannot bind to media container service"); 1228 for (HandlerParams params : mPendingInstalls) { 1229 // Indicate service bind error 1230 params.serviceError(); 1231 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1232 System.identityHashCode(params)); 1233 if (params.traceMethod != null) { 1234 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1235 params.traceMethod, params.traceCookie); 1236 } 1237 return; 1238 } 1239 mPendingInstalls.clear(); 1240 } else { 1241 Slog.w(TAG, "Waiting to connect to media container service"); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 HandlerParams params = mPendingInstalls.get(0); 1245 if (params != null) { 1246 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1247 System.identityHashCode(params)); 1248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1249 if (params.startCopy()) { 1250 // We are done... look for more work or to 1251 // go idle. 1252 if (DEBUG_SD_INSTALL) Log.i(TAG, 1253 "Checking for more work or unbind..."); 1254 // Delete pending install 1255 if (mPendingInstalls.size() > 0) { 1256 mPendingInstalls.remove(0); 1257 } 1258 if (mPendingInstalls.size() == 0) { 1259 if (mBound) { 1260 if (DEBUG_SD_INSTALL) Log.i(TAG, 1261 "Posting delayed MCS_UNBIND"); 1262 removeMessages(MCS_UNBIND); 1263 Message ubmsg = obtainMessage(MCS_UNBIND); 1264 // Unbind after a little delay, to avoid 1265 // continual thrashing. 1266 sendMessageDelayed(ubmsg, 10000); 1267 } 1268 } else { 1269 // There are more pending requests in queue. 1270 // Just post MCS_BOUND message to trigger processing 1271 // of next pending install. 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Posting MCS_BOUND for next work"); 1274 mHandler.sendEmptyMessage(MCS_BOUND); 1275 } 1276 } 1277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1278 } 1279 } else { 1280 // Should never happen ideally. 1281 Slog.w(TAG, "Empty queue"); 1282 } 1283 break; 1284 } 1285 case MCS_RECONNECT: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1287 if (mPendingInstalls.size() > 0) { 1288 if (mBound) { 1289 disconnectService(); 1290 } 1291 if (!connectToService()) { 1292 Slog.e(TAG, "Failed to bind to media container service"); 1293 for (HandlerParams params : mPendingInstalls) { 1294 // Indicate service bind error 1295 params.serviceError(); 1296 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1297 System.identityHashCode(params)); 1298 } 1299 mPendingInstalls.clear(); 1300 } 1301 } 1302 break; 1303 } 1304 case MCS_UNBIND: { 1305 // If there is no actual work left, then time to unbind. 1306 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1307 1308 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1309 if (mBound) { 1310 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1311 1312 disconnectService(); 1313 } 1314 } else if (mPendingInstalls.size() > 0) { 1315 // There are more pending requests in queue. 1316 // Just post MCS_BOUND message to trigger processing 1317 // of next pending install. 1318 mHandler.sendEmptyMessage(MCS_BOUND); 1319 } 1320 1321 break; 1322 } 1323 case MCS_GIVE_UP: { 1324 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1325 HandlerParams params = mPendingInstalls.remove(0); 1326 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1327 System.identityHashCode(params)); 1328 break; 1329 } 1330 case SEND_PENDING_BROADCAST: { 1331 String packages[]; 1332 ArrayList<String> components[]; 1333 int size = 0; 1334 int uids[]; 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1336 synchronized (mPackages) { 1337 if (mPendingBroadcasts == null) { 1338 return; 1339 } 1340 size = mPendingBroadcasts.size(); 1341 if (size <= 0) { 1342 // Nothing to be done. Just return 1343 return; 1344 } 1345 packages = new String[size]; 1346 components = new ArrayList[size]; 1347 uids = new int[size]; 1348 int i = 0; // filling out the above arrays 1349 1350 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1351 int packageUserId = mPendingBroadcasts.userIdAt(n); 1352 Iterator<Map.Entry<String, ArrayList<String>>> it 1353 = mPendingBroadcasts.packagesForUserId(packageUserId) 1354 .entrySet().iterator(); 1355 while (it.hasNext() && i < size) { 1356 Map.Entry<String, ArrayList<String>> ent = it.next(); 1357 packages[i] = ent.getKey(); 1358 components[i] = ent.getValue(); 1359 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1360 uids[i] = (ps != null) 1361 ? UserHandle.getUid(packageUserId, ps.appId) 1362 : -1; 1363 i++; 1364 } 1365 } 1366 size = i; 1367 mPendingBroadcasts.clear(); 1368 } 1369 // Send broadcasts 1370 for (int i = 0; i < size; i++) { 1371 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1372 } 1373 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1374 break; 1375 } 1376 case START_CLEANING_PACKAGE: { 1377 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1378 final String packageName = (String)msg.obj; 1379 final int userId = msg.arg1; 1380 final boolean andCode = msg.arg2 != 0; 1381 synchronized (mPackages) { 1382 if (userId == UserHandle.USER_ALL) { 1383 int[] users = sUserManager.getUserIds(); 1384 for (int user : users) { 1385 mSettings.addPackageToCleanLPw( 1386 new PackageCleanItem(user, packageName, andCode)); 1387 } 1388 } else { 1389 mSettings.addPackageToCleanLPw( 1390 new PackageCleanItem(userId, packageName, andCode)); 1391 } 1392 } 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1394 startCleaningPackages(); 1395 } break; 1396 case POST_INSTALL: { 1397 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1398 1399 PostInstallData data = mRunningInstalls.get(msg.arg1); 1400 final boolean didRestore = (msg.arg2 != 0); 1401 mRunningInstalls.delete(msg.arg1); 1402 1403 if (data != null) { 1404 InstallArgs args = data.args; 1405 PackageInstalledInfo parentRes = data.res; 1406 1407 final boolean grantPermissions = (args.installFlags 1408 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1409 final boolean killApp = (args.installFlags 1410 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1411 final String[] grantedPermissions = args.installGrantPermissions; 1412 1413 // Handle the parent package 1414 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1415 grantedPermissions, didRestore, args.installerPackageName, 1416 args.observer); 1417 1418 // Handle the child packages 1419 final int childCount = (parentRes.addedChildPackages != null) 1420 ? parentRes.addedChildPackages.size() : 0; 1421 for (int i = 0; i < childCount; i++) { 1422 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1423 handlePackagePostInstall(childRes, grantPermissions, killApp, 1424 grantedPermissions, false, args.installerPackageName, 1425 args.observer); 1426 } 1427 1428 // Log tracing if needed 1429 if (args.traceMethod != null) { 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1431 args.traceCookie); 1432 } 1433 } else { 1434 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1435 } 1436 1437 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1438 } break; 1439 case UPDATED_MEDIA_STATUS: { 1440 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1441 boolean reportStatus = msg.arg1 == 1; 1442 boolean doGc = msg.arg2 == 1; 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1444 if (doGc) { 1445 // Force a gc to clear up stale containers. 1446 Runtime.getRuntime().gc(); 1447 } 1448 if (msg.obj != null) { 1449 @SuppressWarnings("unchecked") 1450 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1452 // Unload containers 1453 unloadAllContainers(args); 1454 } 1455 if (reportStatus) { 1456 try { 1457 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1458 PackageHelper.getMountService().finishMediaUpdate(); 1459 } catch (RemoteException e) { 1460 Log.e(TAG, "MountService not running?"); 1461 } 1462 } 1463 } break; 1464 case WRITE_SETTINGS: { 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1466 synchronized (mPackages) { 1467 removeMessages(WRITE_SETTINGS); 1468 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1469 mSettings.writeLPr(); 1470 mDirtyUsers.clear(); 1471 } 1472 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1473 } break; 1474 case WRITE_PACKAGE_RESTRICTIONS: { 1475 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1476 synchronized (mPackages) { 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 for (int userId : mDirtyUsers) { 1479 mSettings.writePackageRestrictionsLPr(userId); 1480 } 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_LIST: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_LIST); 1489 mSettings.writePackageListLPr(msg.arg1); 1490 } 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1492 } break; 1493 case CHECK_PENDING_VERIFICATION: { 1494 final int verificationId = msg.arg1; 1495 final PackageVerificationState state = mPendingVerification.get(verificationId); 1496 1497 if ((state != null) && !state.timeoutExtended()) { 1498 final InstallArgs args = state.getInstallArgs(); 1499 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1500 1501 Slog.i(TAG, "Verification timed out for " + originUri); 1502 mPendingVerification.remove(verificationId); 1503 1504 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1505 1506 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1507 Slog.i(TAG, "Continuing with installation of " + originUri); 1508 state.setVerifierResponse(Binder.getCallingUid(), 1509 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1510 broadcastPackageVerified(verificationId, originUri, 1511 PackageManager.VERIFICATION_ALLOW, 1512 state.getInstallArgs().getUser()); 1513 try { 1514 ret = args.copyApk(mContainerService, true); 1515 } catch (RemoteException e) { 1516 Slog.e(TAG, "Could not contact the ContainerService"); 1517 } 1518 } else { 1519 broadcastPackageVerified(verificationId, originUri, 1520 PackageManager.VERIFICATION_REJECT, 1521 state.getInstallArgs().getUser()); 1522 } 1523 1524 Trace.asyncTraceEnd( 1525 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 Trace.asyncTraceEnd( 1566 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1567 1568 processPendingInstall(args, ret); 1569 mHandler.sendEmptyMessage(MCS_UNBIND); 1570 } 1571 1572 break; 1573 } 1574 case START_INTENT_FILTER_VERIFICATIONS: { 1575 IFVerificationParams params = (IFVerificationParams) msg.obj; 1576 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1577 params.replacing, params.pkg); 1578 break; 1579 } 1580 case INTENT_FILTER_VERIFIED: { 1581 final int verificationId = msg.arg1; 1582 1583 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1584 verificationId); 1585 if (state == null) { 1586 Slog.w(TAG, "Invalid IntentFilter verification token " 1587 + verificationId + " received"); 1588 break; 1589 } 1590 1591 final int userId = state.getUserId(); 1592 1593 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1594 "Processing IntentFilter verification with token:" 1595 + verificationId + " and userId:" + userId); 1596 1597 final IntentFilterVerificationResponse response = 1598 (IntentFilterVerificationResponse) msg.obj; 1599 1600 state.setVerifierResponse(response.callerUid, response.code); 1601 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1603 "IntentFilter verification with token:" + verificationId 1604 + " and userId:" + userId 1605 + " is settings verifier response with response code:" 1606 + response.code); 1607 1608 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1610 + response.getFailedDomainsString()); 1611 } 1612 1613 if (state.isVerificationComplete()) { 1614 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1615 } else { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1617 "IntentFilter verification with token:" + verificationId 1618 + " was not said to be complete"); 1619 } 1620 1621 break; 1622 } 1623 } 1624 } 1625 } 1626 1627 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1628 boolean killApp, String[] grantedPermissions, 1629 boolean launchedForRestore, String installerPackage, 1630 IPackageInstallObserver2 installObserver) { 1631 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1632 // Send the removed broadcasts 1633 if (res.removedInfo != null) { 1634 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1635 } 1636 1637 // Now that we successfully installed the package, grant runtime 1638 // permissions if requested before broadcasting the install. 1639 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1640 >= Build.VERSION_CODES.M) { 1641 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1642 } 1643 1644 final boolean update = res.removedInfo != null 1645 && res.removedInfo.removedPackage != null; 1646 1647 // If this is the first time we have child packages for a disabled privileged 1648 // app that had no children, we grant requested runtime permissions to the new 1649 // children if the parent on the system image had them already granted. 1650 if (res.pkg.parentPackage != null) { 1651 synchronized (mPackages) { 1652 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1653 } 1654 } 1655 1656 synchronized (mPackages) { 1657 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1658 } 1659 1660 final String packageName = res.pkg.applicationInfo.packageName; 1661 Bundle extras = new Bundle(1); 1662 extras.putInt(Intent.EXTRA_UID, res.uid); 1663 1664 // Determine the set of users who are adding this package for 1665 // the first time vs. those who are seeing an update. 1666 int[] firstUsers = EMPTY_INT_ARRAY; 1667 int[] updateUsers = EMPTY_INT_ARRAY; 1668 if (res.origUsers == null || res.origUsers.length == 0) { 1669 firstUsers = res.newUsers; 1670 } else { 1671 for (int newUser : res.newUsers) { 1672 boolean isNew = true; 1673 for (int origUser : res.origUsers) { 1674 if (origUser == newUser) { 1675 isNew = false; 1676 break; 1677 } 1678 } 1679 if (isNew) { 1680 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1681 } else { 1682 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1683 } 1684 } 1685 } 1686 1687 // Send installed broadcasts if the install/update is not ephemeral 1688 if (!isEphemeral(res.pkg)) { 1689 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1690 1691 // Send added for users that see the package for the first time 1692 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1693 extras, 0 /*flags*/, null /*targetPackage*/, 1694 null /*finishedReceiver*/, firstUsers); 1695 1696 // Send added for users that don't see the package for the first time 1697 if (update) { 1698 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1699 } 1700 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1701 extras, 0 /*flags*/, null /*targetPackage*/, 1702 null /*finishedReceiver*/, updateUsers); 1703 1704 // Send replaced for users that don't see the package for the first time 1705 if (update) { 1706 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1707 packageName, extras, 0 /*flags*/, 1708 null /*targetPackage*/, null /*finishedReceiver*/, 1709 updateUsers); 1710 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1711 null /*package*/, null /*extras*/, 0 /*flags*/, 1712 packageName /*targetPackage*/, 1713 null /*finishedReceiver*/, updateUsers); 1714 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1715 // First-install and we did a restore, so we're responsible for the 1716 // first-launch broadcast. 1717 if (DEBUG_BACKUP) { 1718 Slog.i(TAG, "Post-restore of " + packageName 1719 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1720 } 1721 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1722 } 1723 1724 // Send broadcast package appeared if forward locked/external for all users 1725 // treat asec-hosted packages like removable media on upgrade 1726 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1727 if (DEBUG_INSTALL) { 1728 Slog.i(TAG, "upgrading pkg " + res.pkg 1729 + " is ASEC-hosted -> AVAILABLE"); 1730 } 1731 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1732 ArrayList<String> pkgList = new ArrayList<>(1); 1733 pkgList.add(packageName); 1734 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1735 } 1736 } 1737 1738 // Work that needs to happen on first install within each user 1739 if (firstUsers != null && firstUsers.length > 0) { 1740 synchronized (mPackages) { 1741 for (int userId : firstUsers) { 1742 // If this app is a browser and it's newly-installed for some 1743 // users, clear any default-browser state in those users. The 1744 // app's nature doesn't depend on the user, so we can just check 1745 // its browser nature in any user and generalize. 1746 if (packageIsBrowser(packageName, userId)) { 1747 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1748 } 1749 1750 // We may also need to apply pending (restored) runtime 1751 // permission grants within these users. 1752 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1753 } 1754 } 1755 } 1756 1757 // Log current value of "unknown sources" setting 1758 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1759 getUnknownSourcesSettings()); 1760 1761 // Force a gc to clear up things 1762 Runtime.getRuntime().gc(); 1763 1764 // Remove the replaced package's older resources safely now 1765 // We delete after a gc for applications on sdcard. 1766 if (res.removedInfo != null && res.removedInfo.args != null) { 1767 synchronized (mInstallLock) { 1768 res.removedInfo.args.doPostDeleteLI(true); 1769 } 1770 } 1771 } 1772 1773 // If someone is watching installs - notify them 1774 if (installObserver != null) { 1775 try { 1776 Bundle extras = extrasForInstallResult(res); 1777 installObserver.onPackageInstalled(res.name, res.returnCode, 1778 res.returnMsg, extras); 1779 } catch (RemoteException e) { 1780 Slog.i(TAG, "Observer no longer exists."); 1781 } 1782 } 1783 } 1784 1785 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1786 PackageParser.Package pkg) { 1787 if (pkg.parentPackage == null) { 1788 return; 1789 } 1790 if (pkg.requestedPermissions == null) { 1791 return; 1792 } 1793 final PackageSetting disabledSysParentPs = mSettings 1794 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1795 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1796 || !disabledSysParentPs.isPrivileged() 1797 || (disabledSysParentPs.childPackageNames != null 1798 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1799 return; 1800 } 1801 final int[] allUserIds = sUserManager.getUserIds(); 1802 final int permCount = pkg.requestedPermissions.size(); 1803 for (int i = 0; i < permCount; i++) { 1804 String permission = pkg.requestedPermissions.get(i); 1805 BasePermission bp = mSettings.mPermissions.get(permission); 1806 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1807 continue; 1808 } 1809 for (int userId : allUserIds) { 1810 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1811 permission, userId)) { 1812 grantRuntimePermission(pkg.packageName, permission, userId); 1813 } 1814 } 1815 } 1816 } 1817 1818 private StorageEventListener mStorageListener = new StorageEventListener() { 1819 @Override 1820 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1821 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1822 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1823 final String volumeUuid = vol.getFsUuid(); 1824 1825 // Clean up any users or apps that were removed or recreated 1826 // while this volume was missing 1827 reconcileUsers(volumeUuid); 1828 reconcileApps(volumeUuid); 1829 1830 // Clean up any install sessions that expired or were 1831 // cancelled while this volume was missing 1832 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1833 1834 loadPrivatePackages(vol); 1835 1836 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1837 unloadPrivatePackages(vol); 1838 } 1839 } 1840 1841 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1842 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1843 updateExternalMediaStatus(true, false); 1844 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1845 updateExternalMediaStatus(false, false); 1846 } 1847 } 1848 } 1849 1850 @Override 1851 public void onVolumeForgotten(String fsUuid) { 1852 if (TextUtils.isEmpty(fsUuid)) { 1853 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1854 return; 1855 } 1856 1857 // Remove any apps installed on the forgotten volume 1858 synchronized (mPackages) { 1859 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1860 for (PackageSetting ps : packages) { 1861 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1862 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1863 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1864 } 1865 1866 mSettings.onVolumeForgotten(fsUuid); 1867 mSettings.writeLPr(); 1868 } 1869 } 1870 }; 1871 1872 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1873 String[] grantedPermissions) { 1874 for (int userId : userIds) { 1875 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1876 } 1877 1878 // We could have touched GID membership, so flush out packages.list 1879 synchronized (mPackages) { 1880 mSettings.writePackageListLPr(); 1881 } 1882 } 1883 1884 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1885 String[] grantedPermissions) { 1886 SettingBase sb = (SettingBase) pkg.mExtras; 1887 if (sb == null) { 1888 return; 1889 } 1890 1891 PermissionsState permissionsState = sb.getPermissionsState(); 1892 1893 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1894 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1895 1896 for (String permission : pkg.requestedPermissions) { 1897 final BasePermission bp; 1898 synchronized (mPackages) { 1899 bp = mSettings.mPermissions.get(permission); 1900 } 1901 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1902 && (grantedPermissions == null 1903 || ArrayUtils.contains(grantedPermissions, permission))) { 1904 final int flags = permissionsState.getPermissionFlags(permission, userId); 1905 // Installer cannot change immutable permissions. 1906 if ((flags & immutableFlags) == 0) { 1907 grantRuntimePermission(pkg.packageName, permission, userId); 1908 } 1909 } 1910 } 1911 } 1912 1913 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1914 Bundle extras = null; 1915 switch (res.returnCode) { 1916 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1917 extras = new Bundle(); 1918 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1919 res.origPermission); 1920 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1921 res.origPackage); 1922 break; 1923 } 1924 case PackageManager.INSTALL_SUCCEEDED: { 1925 extras = new Bundle(); 1926 extras.putBoolean(Intent.EXTRA_REPLACING, 1927 res.removedInfo != null && res.removedInfo.removedPackage != null); 1928 break; 1929 } 1930 } 1931 return extras; 1932 } 1933 1934 void scheduleWriteSettingsLocked() { 1935 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1936 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1937 } 1938 } 1939 1940 void scheduleWritePackageListLocked(int userId) { 1941 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1942 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1943 msg.arg1 = userId; 1944 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1945 } 1946 } 1947 1948 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1949 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1950 scheduleWritePackageRestrictionsLocked(userId); 1951 } 1952 1953 void scheduleWritePackageRestrictionsLocked(int userId) { 1954 final int[] userIds = (userId == UserHandle.USER_ALL) 1955 ? sUserManager.getUserIds() : new int[]{userId}; 1956 for (int nextUserId : userIds) { 1957 if (!sUserManager.exists(nextUserId)) return; 1958 mDirtyUsers.add(nextUserId); 1959 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1960 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1961 } 1962 } 1963 } 1964 1965 public static PackageManagerService main(Context context, Installer installer, 1966 boolean factoryTest, boolean onlyCore) { 1967 // Self-check for initial settings. 1968 PackageManagerServiceCompilerMapping.checkProperties(); 1969 1970 PackageManagerService m = new PackageManagerService(context, installer, 1971 factoryTest, onlyCore); 1972 m.enableSystemUserPackages(); 1973 ServiceManager.addService("package", m); 1974 return m; 1975 } 1976 1977 private void enableSystemUserPackages() { 1978 if (!UserManager.isSplitSystemUser()) { 1979 return; 1980 } 1981 // For system user, enable apps based on the following conditions: 1982 // - app is whitelisted or belong to one of these groups: 1983 // -- system app which has no launcher icons 1984 // -- system app which has INTERACT_ACROSS_USERS permission 1985 // -- system IME app 1986 // - app is not in the blacklist 1987 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1988 Set<String> enableApps = new ArraySet<>(); 1989 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1990 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1991 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1992 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1993 enableApps.addAll(wlApps); 1994 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1995 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1996 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1997 enableApps.removeAll(blApps); 1998 Log.i(TAG, "Applications installed for system user: " + enableApps); 1999 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2000 UserHandle.SYSTEM); 2001 final int allAppsSize = allAps.size(); 2002 synchronized (mPackages) { 2003 for (int i = 0; i < allAppsSize; i++) { 2004 String pName = allAps.get(i); 2005 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2006 // Should not happen, but we shouldn't be failing if it does 2007 if (pkgSetting == null) { 2008 continue; 2009 } 2010 boolean install = enableApps.contains(pName); 2011 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2012 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2013 + " for system user"); 2014 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2015 } 2016 } 2017 } 2018 } 2019 2020 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2021 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2022 Context.DISPLAY_SERVICE); 2023 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2024 } 2025 2026 /** 2027 * Requests that files preopted on a secondary system partition be copied to the data partition 2028 * if possible. Note that the actual copying of the files is accomplished by init for security 2029 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2030 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2031 */ 2032 private static void requestCopyPreoptedFiles() { 2033 final int WAIT_TIME_MS = 100; 2034 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2035 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2036 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2037 // We will wait for up to 100 seconds. 2038 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2039 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2040 try { 2041 Thread.sleep(WAIT_TIME_MS); 2042 } catch (InterruptedException e) { 2043 // Do nothing 2044 } 2045 if (SystemClock.uptimeMillis() > timeEnd) { 2046 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2047 Slog.wtf(TAG, "cppreopt did not finish!"); 2048 break; 2049 } 2050 } 2051 } 2052 } 2053 2054 public PackageManagerService(Context context, Installer installer, 2055 boolean factoryTest, boolean onlyCore) { 2056 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2057 SystemClock.uptimeMillis()); 2058 2059 if (mSdkVersion <= 0) { 2060 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2061 } 2062 2063 mContext = context; 2064 mFactoryTest = factoryTest; 2065 mOnlyCore = onlyCore; 2066 mMetrics = new DisplayMetrics(); 2067 mSettings = new Settings(mPackages); 2068 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2069 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2070 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2071 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2072 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2073 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2074 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2075 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2076 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2077 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2078 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2079 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2080 2081 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2082 if (separateProcesses != null && separateProcesses.length() > 0) { 2083 if ("*".equals(separateProcesses)) { 2084 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2085 mSeparateProcesses = null; 2086 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2087 } else { 2088 mDefParseFlags = 0; 2089 mSeparateProcesses = separateProcesses.split(","); 2090 Slog.w(TAG, "Running with debug.separate_processes: " 2091 + separateProcesses); 2092 } 2093 } else { 2094 mDefParseFlags = 0; 2095 mSeparateProcesses = null; 2096 } 2097 2098 mInstaller = installer; 2099 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2100 "*dexopt*"); 2101 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2102 2103 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2104 FgThread.get().getLooper()); 2105 2106 getDefaultDisplayMetrics(context, mMetrics); 2107 2108 SystemConfig systemConfig = SystemConfig.getInstance(); 2109 mGlobalGids = systemConfig.getGlobalGids(); 2110 mSystemPermissions = systemConfig.getSystemPermissions(); 2111 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2112 2113 mProtectedPackages = new ProtectedPackages(mContext); 2114 2115 synchronized (mInstallLock) { 2116 // writer 2117 synchronized (mPackages) { 2118 mHandlerThread = new ServiceThread(TAG, 2119 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2120 mHandlerThread.start(); 2121 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2122 mProcessLoggingHandler = new ProcessLoggingHandler(); 2123 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2124 2125 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2126 2127 File dataDir = Environment.getDataDirectory(); 2128 mAppInstallDir = new File(dataDir, "app"); 2129 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2130 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2131 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2132 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2133 2134 sUserManager = new UserManagerService(context, this, mPackages); 2135 2136 // Propagate permission configuration in to package manager. 2137 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2138 = systemConfig.getPermissions(); 2139 for (int i=0; i<permConfig.size(); i++) { 2140 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2141 BasePermission bp = mSettings.mPermissions.get(perm.name); 2142 if (bp == null) { 2143 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2144 mSettings.mPermissions.put(perm.name, bp); 2145 } 2146 if (perm.gids != null) { 2147 bp.setGids(perm.gids, perm.perUser); 2148 } 2149 } 2150 2151 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2152 for (int i=0; i<libConfig.size(); i++) { 2153 mSharedLibraries.put(libConfig.keyAt(i), 2154 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2155 } 2156 2157 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2158 2159 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2160 2161 if (mFirstBoot) { 2162 requestCopyPreoptedFiles(); 2163 } 2164 2165 String customResolverActivity = Resources.getSystem().getString( 2166 R.string.config_customResolverActivity); 2167 if (TextUtils.isEmpty(customResolverActivity)) { 2168 customResolverActivity = null; 2169 } else { 2170 mCustomResolverComponentName = ComponentName.unflattenFromString( 2171 customResolverActivity); 2172 } 2173 2174 long startTime = SystemClock.uptimeMillis(); 2175 2176 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2177 startTime); 2178 2179 // Set flag to monitor and not change apk file paths when 2180 // scanning install directories. 2181 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2182 2183 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2184 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2185 2186 if (bootClassPath == null) { 2187 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2188 } 2189 2190 if (systemServerClassPath == null) { 2191 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2192 } 2193 2194 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2195 final String[] dexCodeInstructionSets = 2196 getDexCodeInstructionSets( 2197 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2198 2199 /** 2200 * Ensure all external libraries have had dexopt run on them. 2201 */ 2202 if (mSharedLibraries.size() > 0) { 2203 // NOTE: For now, we're compiling these system "shared libraries" 2204 // (and framework jars) into all available architectures. It's possible 2205 // to compile them only when we come across an app that uses them (there's 2206 // already logic for that in scanPackageLI) but that adds some complexity. 2207 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2208 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2209 final String lib = libEntry.path; 2210 if (lib == null) { 2211 continue; 2212 } 2213 2214 try { 2215 // Shared libraries do not have profiles so we perform a full 2216 // AOT compilation (if needed). 2217 int dexoptNeeded = DexFile.getDexOptNeeded( 2218 lib, dexCodeInstructionSet, 2219 getCompilerFilterForReason(REASON_SHARED_APK), 2220 false /* newProfile */); 2221 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2222 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2223 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2224 getCompilerFilterForReason(REASON_SHARED_APK), 2225 StorageManager.UUID_PRIVATE_INTERNAL, 2226 SKIP_SHARED_LIBRARY_CHECK); 2227 } 2228 } catch (FileNotFoundException e) { 2229 Slog.w(TAG, "Library not found: " + lib); 2230 } catch (IOException | InstallerException e) { 2231 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2232 + e.getMessage()); 2233 } 2234 } 2235 } 2236 } 2237 2238 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2239 2240 final VersionInfo ver = mSettings.getInternalVersion(); 2241 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2242 2243 // when upgrading from pre-M, promote system app permissions from install to runtime 2244 mPromoteSystemApps = 2245 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2246 2247 // When upgrading from pre-N, we need to handle package extraction like first boot, 2248 // as there is no profiling data available. 2249 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2250 2251 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2252 2253 // save off the names of pre-existing system packages prior to scanning; we don't 2254 // want to automatically grant runtime permissions for new system apps 2255 if (mPromoteSystemApps) { 2256 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2257 while (pkgSettingIter.hasNext()) { 2258 PackageSetting ps = pkgSettingIter.next(); 2259 if (isSystemApp(ps)) { 2260 mExistingSystemPackages.add(ps.name); 2261 } 2262 } 2263 } 2264 2265 // Collect vendor overlay packages. 2266 // (Do this before scanning any apps.) 2267 // For security and version matching reason, only consider 2268 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2269 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2270 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2271 | PackageParser.PARSE_IS_SYSTEM 2272 | PackageParser.PARSE_IS_SYSTEM_DIR 2273 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2274 2275 // Find base frameworks (resource packages without code). 2276 scanDirTracedLI(frameworkDir, mDefParseFlags 2277 | PackageParser.PARSE_IS_SYSTEM 2278 | PackageParser.PARSE_IS_SYSTEM_DIR 2279 | PackageParser.PARSE_IS_PRIVILEGED, 2280 scanFlags | SCAN_NO_DEX, 0); 2281 2282 // Collected privileged system packages. 2283 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2284 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2285 | PackageParser.PARSE_IS_SYSTEM 2286 | PackageParser.PARSE_IS_SYSTEM_DIR 2287 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2288 2289 // Collect ordinary system packages. 2290 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2291 scanDirTracedLI(systemAppDir, mDefParseFlags 2292 | PackageParser.PARSE_IS_SYSTEM 2293 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2294 2295 // Collect all vendor packages. 2296 File vendorAppDir = new File("/vendor/app"); 2297 try { 2298 vendorAppDir = vendorAppDir.getCanonicalFile(); 2299 } catch (IOException e) { 2300 // failed to look up canonical path, continue with original one 2301 } 2302 scanDirTracedLI(vendorAppDir, mDefParseFlags 2303 | PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2305 2306 // Collect all OEM packages. 2307 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2308 scanDirTracedLI(oemAppDir, mDefParseFlags 2309 | PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2311 2312 // Prune any system packages that no longer exist. 2313 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2314 if (!mOnlyCore) { 2315 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2316 while (psit.hasNext()) { 2317 PackageSetting ps = psit.next(); 2318 2319 /* 2320 * If this is not a system app, it can't be a 2321 * disable system app. 2322 */ 2323 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2324 continue; 2325 } 2326 2327 /* 2328 * If the package is scanned, it's not erased. 2329 */ 2330 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2331 if (scannedPkg != null) { 2332 /* 2333 * If the system app is both scanned and in the 2334 * disabled packages list, then it must have been 2335 * added via OTA. Remove it from the currently 2336 * scanned package so the previously user-installed 2337 * application can be scanned. 2338 */ 2339 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2340 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2341 + ps.name + "; removing system app. Last known codePath=" 2342 + ps.codePathString + ", installStatus=" + ps.installStatus 2343 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2344 + scannedPkg.mVersionCode); 2345 removePackageLI(scannedPkg, true); 2346 mExpectingBetter.put(ps.name, ps.codePath); 2347 } 2348 2349 continue; 2350 } 2351 2352 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2353 psit.remove(); 2354 logCriticalInfo(Log.WARN, "System package " + ps.name 2355 + " no longer exists; it's data will be wiped"); 2356 // Actual deletion of code and data will be handled by later 2357 // reconciliation step 2358 } else { 2359 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2360 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2361 possiblyDeletedUpdatedSystemApps.add(ps.name); 2362 } 2363 } 2364 } 2365 } 2366 2367 //look for any incomplete package installations 2368 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2369 for (int i = 0; i < deletePkgsList.size(); i++) { 2370 // Actual deletion of code and data will be handled by later 2371 // reconciliation step 2372 final String packageName = deletePkgsList.get(i).name; 2373 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2374 synchronized (mPackages) { 2375 mSettings.removePackageLPw(packageName); 2376 } 2377 } 2378 2379 //delete tmp files 2380 deleteTempPackageFiles(); 2381 2382 // Remove any shared userIDs that have no associated packages 2383 mSettings.pruneSharedUsersLPw(); 2384 2385 if (!mOnlyCore) { 2386 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2387 SystemClock.uptimeMillis()); 2388 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2389 2390 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2391 | PackageParser.PARSE_FORWARD_LOCK, 2392 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2393 2394 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2395 | PackageParser.PARSE_IS_EPHEMERAL, 2396 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2397 2398 /** 2399 * Remove disable package settings for any updated system 2400 * apps that were removed via an OTA. If they're not a 2401 * previously-updated app, remove them completely. 2402 * Otherwise, just revoke their system-level permissions. 2403 */ 2404 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2405 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2406 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2407 2408 String msg; 2409 if (deletedPkg == null) { 2410 msg = "Updated system package " + deletedAppName 2411 + " no longer exists; it's data will be wiped"; 2412 // Actual deletion of code and data will be handled by later 2413 // reconciliation step 2414 } else { 2415 msg = "Updated system app + " + deletedAppName 2416 + " no longer present; removing system privileges for " 2417 + deletedAppName; 2418 2419 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2420 2421 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2422 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2423 } 2424 logCriticalInfo(Log.WARN, msg); 2425 } 2426 2427 /** 2428 * Make sure all system apps that we expected to appear on 2429 * the userdata partition actually showed up. If they never 2430 * appeared, crawl back and revive the system version. 2431 */ 2432 for (int i = 0; i < mExpectingBetter.size(); i++) { 2433 final String packageName = mExpectingBetter.keyAt(i); 2434 if (!mPackages.containsKey(packageName)) { 2435 final File scanFile = mExpectingBetter.valueAt(i); 2436 2437 logCriticalInfo(Log.WARN, "Expected better " + packageName 2438 + " but never showed up; reverting to system"); 2439 2440 int reparseFlags = mDefParseFlags; 2441 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2442 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR 2444 | PackageParser.PARSE_IS_PRIVILEGED; 2445 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2446 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR; 2448 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2449 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2450 | PackageParser.PARSE_IS_SYSTEM_DIR; 2451 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2452 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2453 | PackageParser.PARSE_IS_SYSTEM_DIR; 2454 } else { 2455 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2456 continue; 2457 } 2458 2459 mSettings.enableSystemPackageLPw(packageName); 2460 2461 try { 2462 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2463 } catch (PackageManagerException e) { 2464 Slog.e(TAG, "Failed to parse original system package: " 2465 + e.getMessage()); 2466 } 2467 } 2468 } 2469 } 2470 mExpectingBetter.clear(); 2471 2472 // Resolve protected action filters. Only the setup wizard is allowed to 2473 // have a high priority filter for these actions. 2474 mSetupWizardPackage = getSetupWizardPackageName(); 2475 if (mProtectedFilters.size() > 0) { 2476 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2477 Slog.i(TAG, "No setup wizard;" 2478 + " All protected intents capped to priority 0"); 2479 } 2480 for (ActivityIntentInfo filter : mProtectedFilters) { 2481 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2482 if (DEBUG_FILTERS) { 2483 Slog.i(TAG, "Found setup wizard;" 2484 + " allow priority " + filter.getPriority() + ";" 2485 + " package: " + filter.activity.info.packageName 2486 + " activity: " + filter.activity.className 2487 + " priority: " + filter.getPriority()); 2488 } 2489 // skip setup wizard; allow it to keep the high priority filter 2490 continue; 2491 } 2492 Slog.w(TAG, "Protected action; cap priority to 0;" 2493 + " package: " + filter.activity.info.packageName 2494 + " activity: " + filter.activity.className 2495 + " origPrio: " + filter.getPriority()); 2496 filter.setPriority(0); 2497 } 2498 } 2499 mDeferProtectedFilters = false; 2500 mProtectedFilters.clear(); 2501 2502 // Now that we know all of the shared libraries, update all clients to have 2503 // the correct library paths. 2504 updateAllSharedLibrariesLPw(); 2505 2506 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2507 // NOTE: We ignore potential failures here during a system scan (like 2508 // the rest of the commands above) because there's precious little we 2509 // can do about it. A settings error is reported, though. 2510 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2511 false /* boot complete */); 2512 } 2513 2514 // Now that we know all the packages we are keeping, 2515 // read and update their last usage times. 2516 mPackageUsage.read(mPackages); 2517 mCompilerStats.read(); 2518 2519 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2520 SystemClock.uptimeMillis()); 2521 Slog.i(TAG, "Time to scan packages: " 2522 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2523 + " seconds"); 2524 2525 // If the platform SDK has changed since the last time we booted, 2526 // we need to re-grant app permission to catch any new ones that 2527 // appear. This is really a hack, and means that apps can in some 2528 // cases get permissions that the user didn't initially explicitly 2529 // allow... it would be nice to have some better way to handle 2530 // this situation. 2531 int updateFlags = UPDATE_PERMISSIONS_ALL; 2532 if (ver.sdkVersion != mSdkVersion) { 2533 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2534 + mSdkVersion + "; regranting permissions for internal storage"); 2535 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2536 } 2537 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2538 ver.sdkVersion = mSdkVersion; 2539 2540 // If this is the first boot or an update from pre-M, and it is a normal 2541 // boot, then we need to initialize the default preferred apps across 2542 // all defined users. 2543 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2544 for (UserInfo user : sUserManager.getUsers(true)) { 2545 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2546 applyFactoryDefaultBrowserLPw(user.id); 2547 primeDomainVerificationsLPw(user.id); 2548 } 2549 } 2550 2551 // Prepare storage for system user really early during boot, 2552 // since core system apps like SettingsProvider and SystemUI 2553 // can't wait for user to start 2554 final int storageFlags; 2555 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2556 storageFlags = StorageManager.FLAG_STORAGE_DE; 2557 } else { 2558 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2559 } 2560 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2561 storageFlags); 2562 2563 // If this is first boot after an OTA, and a normal boot, then 2564 // we need to clear code cache directories. 2565 // Note that we do *not* clear the application profiles. These remain valid 2566 // across OTAs and are used to drive profile verification (post OTA) and 2567 // profile compilation (without waiting to collect a fresh set of profiles). 2568 if (mIsUpgrade && !onlyCore) { 2569 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2570 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2571 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2572 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2573 // No apps are running this early, so no need to freeze 2574 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2575 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2576 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2577 } 2578 } 2579 ver.fingerprint = Build.FINGERPRINT; 2580 } 2581 2582 checkDefaultBrowser(); 2583 2584 // clear only after permissions and other defaults have been updated 2585 mExistingSystemPackages.clear(); 2586 mPromoteSystemApps = false; 2587 2588 // All the changes are done during package scanning. 2589 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2590 2591 // can downgrade to reader 2592 mSettings.writeLPr(); 2593 2594 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2595 // early on (before the package manager declares itself as early) because other 2596 // components in the system server might ask for package contexts for these apps. 2597 // 2598 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2599 // (i.e, that the data partition is unavailable). 2600 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2601 long start = System.nanoTime(); 2602 List<PackageParser.Package> coreApps = new ArrayList<>(); 2603 for (PackageParser.Package pkg : mPackages.values()) { 2604 if (pkg.coreApp) { 2605 coreApps.add(pkg); 2606 } 2607 } 2608 2609 int[] stats = performDexOptUpgrade(coreApps, false, 2610 getCompilerFilterForReason(REASON_CORE_APP)); 2611 2612 final int elapsedTimeSeconds = 2613 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2614 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2615 2616 if (DEBUG_DEXOPT) { 2617 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2618 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2619 } 2620 2621 2622 // TODO: Should we log these stats to tron too ? 2623 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2624 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2625 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2626 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2627 } 2628 2629 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2630 SystemClock.uptimeMillis()); 2631 2632 if (!mOnlyCore) { 2633 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2634 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2635 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2636 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2637 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2638 mIntentFilterVerifierComponent); 2639 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2640 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2641 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2642 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2643 } else { 2644 mRequiredVerifierPackage = null; 2645 mRequiredInstallerPackage = null; 2646 mRequiredUninstallerPackage = null; 2647 mIntentFilterVerifierComponent = null; 2648 mIntentFilterVerifier = null; 2649 mServicesSystemSharedLibraryPackageName = null; 2650 mSharedSystemSharedLibraryPackageName = null; 2651 } 2652 2653 mInstallerService = new PackageInstallerService(context, this); 2654 2655 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2656 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2657 // both the installer and resolver must be present to enable ephemeral 2658 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2659 if (DEBUG_EPHEMERAL) { 2660 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2661 + " installer:" + ephemeralInstallerComponent); 2662 } 2663 mEphemeralResolverComponent = ephemeralResolverComponent; 2664 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2665 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2666 mEphemeralResolverConnection = 2667 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2668 } else { 2669 if (DEBUG_EPHEMERAL) { 2670 final String missingComponent = 2671 (ephemeralResolverComponent == null) 2672 ? (ephemeralInstallerComponent == null) 2673 ? "resolver and installer" 2674 : "resolver" 2675 : "installer"; 2676 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2677 } 2678 mEphemeralResolverComponent = null; 2679 mEphemeralInstallerComponent = null; 2680 mEphemeralResolverConnection = null; 2681 } 2682 2683 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2684 } // synchronized (mPackages) 2685 } // synchronized (mInstallLock) 2686 2687 // Now after opening every single application zip, make sure they 2688 // are all flushed. Not really needed, but keeps things nice and 2689 // tidy. 2690 Runtime.getRuntime().gc(); 2691 2692 // The initial scanning above does many calls into installd while 2693 // holding the mPackages lock, but we're mostly interested in yelling 2694 // once we have a booted system. 2695 mInstaller.setWarnIfHeld(mPackages); 2696 2697 // Expose private service for system components to use. 2698 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2699 } 2700 2701 @Override 2702 public boolean isFirstBoot() { 2703 return mFirstBoot; 2704 } 2705 2706 @Override 2707 public boolean isOnlyCoreApps() { 2708 return mOnlyCore; 2709 } 2710 2711 @Override 2712 public boolean isUpgrade() { 2713 return mIsUpgrade; 2714 } 2715 2716 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2717 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2718 2719 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2720 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2721 UserHandle.USER_SYSTEM); 2722 if (matches.size() == 1) { 2723 return matches.get(0).getComponentInfo().packageName; 2724 } else if (matches.size() == 0) { 2725 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2726 return null; 2727 } 2728 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2729 } 2730 2731 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2732 synchronized (mPackages) { 2733 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2734 if (libraryEntry == null) { 2735 throw new IllegalStateException("Missing required shared library:" + libraryName); 2736 } 2737 return libraryEntry.apk; 2738 } 2739 } 2740 2741 private @NonNull String getRequiredInstallerLPr() { 2742 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2743 intent.addCategory(Intent.CATEGORY_DEFAULT); 2744 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2745 2746 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2747 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2748 UserHandle.USER_SYSTEM); 2749 if (matches.size() == 1) { 2750 ResolveInfo resolveInfo = matches.get(0); 2751 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2752 throw new RuntimeException("The installer must be a privileged app"); 2753 } 2754 return matches.get(0).getComponentInfo().packageName; 2755 } else { 2756 throw new RuntimeException("There must be exactly one installer; found " + matches); 2757 } 2758 } 2759 2760 private @NonNull String getRequiredUninstallerLPr() { 2761 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2762 intent.addCategory(Intent.CATEGORY_DEFAULT); 2763 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2764 2765 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2766 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2767 UserHandle.USER_SYSTEM); 2768 if (resolveInfo == null || 2769 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2770 throw new RuntimeException("There must be exactly one uninstaller; found " 2771 + resolveInfo); 2772 } 2773 return resolveInfo.getComponentInfo().packageName; 2774 } 2775 2776 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2777 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2778 2779 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2780 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2781 UserHandle.USER_SYSTEM); 2782 ResolveInfo best = null; 2783 final int N = matches.size(); 2784 for (int i = 0; i < N; i++) { 2785 final ResolveInfo cur = matches.get(i); 2786 final String packageName = cur.getComponentInfo().packageName; 2787 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2788 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2789 continue; 2790 } 2791 2792 if (best == null || cur.priority > best.priority) { 2793 best = cur; 2794 } 2795 } 2796 2797 if (best != null) { 2798 return best.getComponentInfo().getComponentName(); 2799 } else { 2800 throw new RuntimeException("There must be at least one intent filter verifier"); 2801 } 2802 } 2803 2804 private @Nullable ComponentName getEphemeralResolverLPr() { 2805 final String[] packageArray = 2806 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2807 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2808 if (DEBUG_EPHEMERAL) { 2809 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2810 } 2811 return null; 2812 } 2813 2814 final int resolveFlags = 2815 MATCH_DIRECT_BOOT_AWARE 2816 | MATCH_DIRECT_BOOT_UNAWARE 2817 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2818 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2819 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2820 resolveFlags, UserHandle.USER_SYSTEM); 2821 2822 final int N = resolvers.size(); 2823 if (N == 0) { 2824 if (DEBUG_EPHEMERAL) { 2825 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2826 } 2827 return null; 2828 } 2829 2830 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2831 for (int i = 0; i < N; i++) { 2832 final ResolveInfo info = resolvers.get(i); 2833 2834 if (info.serviceInfo == null) { 2835 continue; 2836 } 2837 2838 final String packageName = info.serviceInfo.packageName; 2839 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2840 if (DEBUG_EPHEMERAL) { 2841 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2842 + " pkg: " + packageName + ", info:" + info); 2843 } 2844 continue; 2845 } 2846 2847 if (DEBUG_EPHEMERAL) { 2848 Slog.v(TAG, "Ephemeral resolver found;" 2849 + " pkg: " + packageName + ", info:" + info); 2850 } 2851 return new ComponentName(packageName, info.serviceInfo.name); 2852 } 2853 if (DEBUG_EPHEMERAL) { 2854 Slog.v(TAG, "Ephemeral resolver NOT found"); 2855 } 2856 return null; 2857 } 2858 2859 private @Nullable ComponentName getEphemeralInstallerLPr() { 2860 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2861 intent.addCategory(Intent.CATEGORY_DEFAULT); 2862 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2863 2864 final int resolveFlags = 2865 MATCH_DIRECT_BOOT_AWARE 2866 | MATCH_DIRECT_BOOT_UNAWARE 2867 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2868 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2869 resolveFlags, UserHandle.USER_SYSTEM); 2870 if (matches.size() == 0) { 2871 return null; 2872 } else if (matches.size() == 1) { 2873 return matches.get(0).getComponentInfo().getComponentName(); 2874 } else { 2875 throw new RuntimeException( 2876 "There must be at most one ephemeral installer; found " + matches); 2877 } 2878 } 2879 2880 private void primeDomainVerificationsLPw(int userId) { 2881 if (DEBUG_DOMAIN_VERIFICATION) { 2882 Slog.d(TAG, "Priming domain verifications in user " + userId); 2883 } 2884 2885 SystemConfig systemConfig = SystemConfig.getInstance(); 2886 ArraySet<String> packages = systemConfig.getLinkedApps(); 2887 ArraySet<String> domains = new ArraySet<String>(); 2888 2889 for (String packageName : packages) { 2890 PackageParser.Package pkg = mPackages.get(packageName); 2891 if (pkg != null) { 2892 if (!pkg.isSystemApp()) { 2893 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2894 continue; 2895 } 2896 2897 domains.clear(); 2898 for (PackageParser.Activity a : pkg.activities) { 2899 for (ActivityIntentInfo filter : a.intents) { 2900 if (hasValidDomains(filter)) { 2901 domains.addAll(filter.getHostsList()); 2902 } 2903 } 2904 } 2905 2906 if (domains.size() > 0) { 2907 if (DEBUG_DOMAIN_VERIFICATION) { 2908 Slog.v(TAG, " + " + packageName); 2909 } 2910 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2911 // state w.r.t. the formal app-linkage "no verification attempted" state; 2912 // and then 'always' in the per-user state actually used for intent resolution. 2913 final IntentFilterVerificationInfo ivi; 2914 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2915 new ArrayList<String>(domains)); 2916 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2917 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2918 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2919 } else { 2920 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2921 + "' does not handle web links"); 2922 } 2923 } else { 2924 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2925 } 2926 } 2927 2928 scheduleWritePackageRestrictionsLocked(userId); 2929 scheduleWriteSettingsLocked(); 2930 } 2931 2932 private void applyFactoryDefaultBrowserLPw(int userId) { 2933 // The default browser app's package name is stored in a string resource, 2934 // with a product-specific overlay used for vendor customization. 2935 String browserPkg = mContext.getResources().getString( 2936 com.android.internal.R.string.default_browser); 2937 if (!TextUtils.isEmpty(browserPkg)) { 2938 // non-empty string => required to be a known package 2939 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2940 if (ps == null) { 2941 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2942 browserPkg = null; 2943 } else { 2944 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2945 } 2946 } 2947 2948 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2949 // default. If there's more than one, just leave everything alone. 2950 if (browserPkg == null) { 2951 calculateDefaultBrowserLPw(userId); 2952 } 2953 } 2954 2955 private void calculateDefaultBrowserLPw(int userId) { 2956 List<String> allBrowsers = resolveAllBrowserApps(userId); 2957 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2958 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2959 } 2960 2961 private List<String> resolveAllBrowserApps(int userId) { 2962 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2963 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2964 PackageManager.MATCH_ALL, userId); 2965 2966 final int count = list.size(); 2967 List<String> result = new ArrayList<String>(count); 2968 for (int i=0; i<count; i++) { 2969 ResolveInfo info = list.get(i); 2970 if (info.activityInfo == null 2971 || !info.handleAllWebDataURI 2972 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2973 || result.contains(info.activityInfo.packageName)) { 2974 continue; 2975 } 2976 result.add(info.activityInfo.packageName); 2977 } 2978 2979 return result; 2980 } 2981 2982 private boolean packageIsBrowser(String packageName, int userId) { 2983 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2984 PackageManager.MATCH_ALL, userId); 2985 final int N = list.size(); 2986 for (int i = 0; i < N; i++) { 2987 ResolveInfo info = list.get(i); 2988 if (packageName.equals(info.activityInfo.packageName)) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 2995 private void checkDefaultBrowser() { 2996 final int myUserId = UserHandle.myUserId(); 2997 final String packageName = getDefaultBrowserPackageName(myUserId); 2998 if (packageName != null) { 2999 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3000 if (info == null) { 3001 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3002 synchronized (mPackages) { 3003 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3004 } 3005 } 3006 } 3007 } 3008 3009 @Override 3010 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3011 throws RemoteException { 3012 try { 3013 return super.onTransact(code, data, reply, flags); 3014 } catch (RuntimeException e) { 3015 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3016 Slog.wtf(TAG, "Package Manager Crash", e); 3017 } 3018 throw e; 3019 } 3020 } 3021 3022 static int[] appendInts(int[] cur, int[] add) { 3023 if (add == null) return cur; 3024 if (cur == null) return add; 3025 final int N = add.length; 3026 for (int i=0; i<N; i++) { 3027 cur = appendInt(cur, add[i]); 3028 } 3029 return cur; 3030 } 3031 3032 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3033 if (!sUserManager.exists(userId)) return null; 3034 if (ps == null) { 3035 return null; 3036 } 3037 final PackageParser.Package p = ps.pkg; 3038 if (p == null) { 3039 return null; 3040 } 3041 3042 final PermissionsState permissionsState = ps.getPermissionsState(); 3043 3044 // Compute GIDs only if requested 3045 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3046 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3047 // Compute granted permissions only if package has requested permissions 3048 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3049 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3050 final PackageUserState state = ps.readUserState(userId); 3051 3052 return PackageParser.generatePackageInfo(p, gids, flags, 3053 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3054 } 3055 3056 @Override 3057 public void checkPackageStartable(String packageName, int userId) { 3058 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3059 3060 synchronized (mPackages) { 3061 final PackageSetting ps = mSettings.mPackages.get(packageName); 3062 if (ps == null) { 3063 throw new SecurityException("Package " + packageName + " was not found!"); 3064 } 3065 3066 if (!ps.getInstalled(userId)) { 3067 throw new SecurityException( 3068 "Package " + packageName + " was not installed for user " + userId + "!"); 3069 } 3070 3071 if (mSafeMode && !ps.isSystem()) { 3072 throw new SecurityException("Package " + packageName + " not a system app!"); 3073 } 3074 3075 if (mFrozenPackages.contains(packageName)) { 3076 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3077 } 3078 3079 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3080 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3081 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3082 } 3083 } 3084 } 3085 3086 @Override 3087 public boolean isPackageAvailable(String packageName, int userId) { 3088 if (!sUserManager.exists(userId)) return false; 3089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3090 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3091 synchronized (mPackages) { 3092 PackageParser.Package p = mPackages.get(packageName); 3093 if (p != null) { 3094 final PackageSetting ps = (PackageSetting) p.mExtras; 3095 if (ps != null) { 3096 final PackageUserState state = ps.readUserState(userId); 3097 if (state != null) { 3098 return PackageParser.isAvailable(state); 3099 } 3100 } 3101 } 3102 } 3103 return false; 3104 } 3105 3106 @Override 3107 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3108 if (!sUserManager.exists(userId)) return null; 3109 flags = updateFlagsForPackage(flags, userId, packageName); 3110 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3111 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3112 // reader 3113 synchronized (mPackages) { 3114 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3115 PackageParser.Package p = null; 3116 if (matchFactoryOnly) { 3117 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3118 if (ps != null) { 3119 return generatePackageInfo(ps, flags, userId); 3120 } 3121 } 3122 if (p == null) { 3123 p = mPackages.get(packageName); 3124 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3125 return null; 3126 } 3127 } 3128 if (DEBUG_PACKAGE_INFO) 3129 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3130 if (p != null) { 3131 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3132 } 3133 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3134 final PackageSetting ps = mSettings.mPackages.get(packageName); 3135 return generatePackageInfo(ps, flags, userId); 3136 } 3137 } 3138 return null; 3139 } 3140 3141 @Override 3142 public String[] currentToCanonicalPackageNames(String[] names) { 3143 String[] out = new String[names.length]; 3144 // reader 3145 synchronized (mPackages) { 3146 for (int i=names.length-1; i>=0; i--) { 3147 PackageSetting ps = mSettings.mPackages.get(names[i]); 3148 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3149 } 3150 } 3151 return out; 3152 } 3153 3154 @Override 3155 public String[] canonicalToCurrentPackageNames(String[] names) { 3156 String[] out = new String[names.length]; 3157 // reader 3158 synchronized (mPackages) { 3159 for (int i=names.length-1; i>=0; i--) { 3160 String cur = mSettings.mRenamedPackages.get(names[i]); 3161 out[i] = cur != null ? cur : names[i]; 3162 } 3163 } 3164 return out; 3165 } 3166 3167 @Override 3168 public int getPackageUid(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return -1; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3173 3174 // reader 3175 synchronized (mPackages) { 3176 final PackageParser.Package p = mPackages.get(packageName); 3177 if (p != null && p.isMatch(flags)) { 3178 return UserHandle.getUid(userId, p.applicationInfo.uid); 3179 } 3180 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3181 final PackageSetting ps = mSettings.mPackages.get(packageName); 3182 if (ps != null && ps.isMatch(flags)) { 3183 return UserHandle.getUid(userId, ps.appId); 3184 } 3185 } 3186 } 3187 3188 return -1; 3189 } 3190 3191 @Override 3192 public int[] getPackageGids(String packageName, int flags, int userId) { 3193 if (!sUserManager.exists(userId)) return null; 3194 flags = updateFlagsForPackage(flags, userId, packageName); 3195 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3196 false /* requireFullPermission */, false /* checkShell */, 3197 "getPackageGids"); 3198 3199 // reader 3200 synchronized (mPackages) { 3201 final PackageParser.Package p = mPackages.get(packageName); 3202 if (p != null && p.isMatch(flags)) { 3203 PackageSetting ps = (PackageSetting) p.mExtras; 3204 return ps.getPermissionsState().computeGids(userId); 3205 } 3206 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3207 final PackageSetting ps = mSettings.mPackages.get(packageName); 3208 if (ps != null && ps.isMatch(flags)) { 3209 return ps.getPermissionsState().computeGids(userId); 3210 } 3211 } 3212 } 3213 3214 return null; 3215 } 3216 3217 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3218 if (bp.perm != null) { 3219 return PackageParser.generatePermissionInfo(bp.perm, flags); 3220 } 3221 PermissionInfo pi = new PermissionInfo(); 3222 pi.name = bp.name; 3223 pi.packageName = bp.sourcePackage; 3224 pi.nonLocalizedLabel = bp.name; 3225 pi.protectionLevel = bp.protectionLevel; 3226 return pi; 3227 } 3228 3229 @Override 3230 public PermissionInfo getPermissionInfo(String name, int flags) { 3231 // reader 3232 synchronized (mPackages) { 3233 final BasePermission p = mSettings.mPermissions.get(name); 3234 if (p != null) { 3235 return generatePermissionInfo(p, flags); 3236 } 3237 return null; 3238 } 3239 } 3240 3241 @Override 3242 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3243 int flags) { 3244 // reader 3245 synchronized (mPackages) { 3246 if (group != null && !mPermissionGroups.containsKey(group)) { 3247 // This is thrown as NameNotFoundException 3248 return null; 3249 } 3250 3251 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3252 for (BasePermission p : mSettings.mPermissions.values()) { 3253 if (group == null) { 3254 if (p.perm == null || p.perm.info.group == null) { 3255 out.add(generatePermissionInfo(p, flags)); 3256 } 3257 } else { 3258 if (p.perm != null && group.equals(p.perm.info.group)) { 3259 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3260 } 3261 } 3262 } 3263 return new ParceledListSlice<>(out); 3264 } 3265 } 3266 3267 @Override 3268 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3269 // reader 3270 synchronized (mPackages) { 3271 return PackageParser.generatePermissionGroupInfo( 3272 mPermissionGroups.get(name), flags); 3273 } 3274 } 3275 3276 @Override 3277 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3278 // reader 3279 synchronized (mPackages) { 3280 final int N = mPermissionGroups.size(); 3281 ArrayList<PermissionGroupInfo> out 3282 = new ArrayList<PermissionGroupInfo>(N); 3283 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3284 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3285 } 3286 return new ParceledListSlice<>(out); 3287 } 3288 } 3289 3290 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3291 int userId) { 3292 if (!sUserManager.exists(userId)) return null; 3293 PackageSetting ps = mSettings.mPackages.get(packageName); 3294 if (ps != null) { 3295 if (ps.pkg == null) { 3296 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3297 if (pInfo != null) { 3298 return pInfo.applicationInfo; 3299 } 3300 return null; 3301 } 3302 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3303 ps.readUserState(userId), userId); 3304 } 3305 return null; 3306 } 3307 3308 @Override 3309 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForApplication(flags, userId, packageName); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3313 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3314 // writer 3315 synchronized (mPackages) { 3316 PackageParser.Package p = mPackages.get(packageName); 3317 if (DEBUG_PACKAGE_INFO) Log.v( 3318 TAG, "getApplicationInfo " + packageName 3319 + ": " + p); 3320 if (p != null) { 3321 PackageSetting ps = mSettings.mPackages.get(packageName); 3322 if (ps == null) return null; 3323 // Note: isEnabledLP() does not apply here - always return info 3324 return PackageParser.generateApplicationInfo( 3325 p, flags, ps.readUserState(userId), userId); 3326 } 3327 if ("android".equals(packageName)||"system".equals(packageName)) { 3328 return mAndroidApplication; 3329 } 3330 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3331 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3332 } 3333 } 3334 return null; 3335 } 3336 3337 @Override 3338 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3339 final IPackageDataObserver observer) { 3340 mContext.enforceCallingOrSelfPermission( 3341 android.Manifest.permission.CLEAR_APP_CACHE, null); 3342 // Queue up an async operation since clearing cache may take a little while. 3343 mHandler.post(new Runnable() { 3344 public void run() { 3345 mHandler.removeCallbacks(this); 3346 boolean success = true; 3347 synchronized (mInstallLock) { 3348 try { 3349 mInstaller.freeCache(volumeUuid, freeStorageSize); 3350 } catch (InstallerException e) { 3351 Slog.w(TAG, "Couldn't clear application caches: " + e); 3352 success = false; 3353 } 3354 } 3355 if (observer != null) { 3356 try { 3357 observer.onRemoveCompleted(null, success); 3358 } catch (RemoteException e) { 3359 Slog.w(TAG, "RemoveException when invoking call back"); 3360 } 3361 } 3362 } 3363 }); 3364 } 3365 3366 @Override 3367 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3368 final IntentSender pi) { 3369 mContext.enforceCallingOrSelfPermission( 3370 android.Manifest.permission.CLEAR_APP_CACHE, null); 3371 // Queue up an async operation since clearing cache may take a little while. 3372 mHandler.post(new Runnable() { 3373 public void run() { 3374 mHandler.removeCallbacks(this); 3375 boolean success = true; 3376 synchronized (mInstallLock) { 3377 try { 3378 mInstaller.freeCache(volumeUuid, freeStorageSize); 3379 } catch (InstallerException e) { 3380 Slog.w(TAG, "Couldn't clear application caches: " + e); 3381 success = false; 3382 } 3383 } 3384 if(pi != null) { 3385 try { 3386 // Callback via pending intent 3387 int code = success ? 1 : 0; 3388 pi.sendIntent(null, code, null, 3389 null, null); 3390 } catch (SendIntentException e1) { 3391 Slog.i(TAG, "Failed to send pending intent"); 3392 } 3393 } 3394 } 3395 }); 3396 } 3397 3398 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3399 synchronized (mInstallLock) { 3400 try { 3401 mInstaller.freeCache(volumeUuid, freeStorageSize); 3402 } catch (InstallerException e) { 3403 throw new IOException("Failed to free enough space", e); 3404 } 3405 } 3406 } 3407 3408 /** 3409 * Update given flags based on encryption status of current user. 3410 */ 3411 private int updateFlags(int flags, int userId) { 3412 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3413 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3414 // Caller expressed an explicit opinion about what encryption 3415 // aware/unaware components they want to see, so fall through and 3416 // give them what they want 3417 } else { 3418 // Caller expressed no opinion, so match based on user state 3419 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3420 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3421 } else { 3422 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3423 } 3424 } 3425 return flags; 3426 } 3427 3428 private UserManagerInternal getUserManagerInternal() { 3429 if (mUserManagerInternal == null) { 3430 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3431 } 3432 return mUserManagerInternal; 3433 } 3434 3435 /** 3436 * Update given flags when being used to request {@link PackageInfo}. 3437 */ 3438 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3439 boolean triaged = true; 3440 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3441 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3442 // Caller is asking for component details, so they'd better be 3443 // asking for specific encryption matching behavior, or be triaged 3444 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3445 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3446 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3447 triaged = false; 3448 } 3449 } 3450 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3451 | PackageManager.MATCH_SYSTEM_ONLY 3452 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3453 triaged = false; 3454 } 3455 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3456 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3457 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3458 } 3459 return updateFlags(flags, userId); 3460 } 3461 3462 /** 3463 * Update given flags when being used to request {@link ApplicationInfo}. 3464 */ 3465 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3466 return updateFlagsForPackage(flags, userId, cookie); 3467 } 3468 3469 /** 3470 * Update given flags when being used to request {@link ComponentInfo}. 3471 */ 3472 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3473 if (cookie instanceof Intent) { 3474 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3475 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3476 } 3477 } 3478 3479 boolean triaged = true; 3480 // Caller is asking for component details, so they'd better be 3481 // asking for specific encryption matching behavior, or be triaged 3482 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3483 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3484 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3485 triaged = false; 3486 } 3487 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3488 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3489 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3490 } 3491 3492 return updateFlags(flags, userId); 3493 } 3494 3495 /** 3496 * Update given flags when being used to request {@link ResolveInfo}. 3497 */ 3498 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3499 // Safe mode means we shouldn't match any third-party components 3500 if (mSafeMode) { 3501 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3502 } 3503 3504 return updateFlagsForComponent(flags, userId, cookie); 3505 } 3506 3507 @Override 3508 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3509 if (!sUserManager.exists(userId)) return null; 3510 flags = updateFlagsForComponent(flags, userId, component); 3511 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3512 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3513 synchronized (mPackages) { 3514 PackageParser.Activity a = mActivities.mActivities.get(component); 3515 3516 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3517 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3518 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3519 if (ps == null) return null; 3520 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3521 userId); 3522 } 3523 if (mResolveComponentName.equals(component)) { 3524 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3525 new PackageUserState(), userId); 3526 } 3527 } 3528 return null; 3529 } 3530 3531 @Override 3532 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3533 String resolvedType) { 3534 synchronized (mPackages) { 3535 if (component.equals(mResolveComponentName)) { 3536 // The resolver supports EVERYTHING! 3537 return true; 3538 } 3539 PackageParser.Activity a = mActivities.mActivities.get(component); 3540 if (a == null) { 3541 return false; 3542 } 3543 for (int i=0; i<a.intents.size(); i++) { 3544 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3545 intent.getData(), intent.getCategories(), TAG) >= 0) { 3546 return true; 3547 } 3548 } 3549 return false; 3550 } 3551 } 3552 3553 @Override 3554 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3555 if (!sUserManager.exists(userId)) return null; 3556 flags = updateFlagsForComponent(flags, userId, component); 3557 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3558 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3559 synchronized (mPackages) { 3560 PackageParser.Activity a = mReceivers.mActivities.get(component); 3561 if (DEBUG_PACKAGE_INFO) Log.v( 3562 TAG, "getReceiverInfo " + component + ": " + a); 3563 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3564 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3565 if (ps == null) return null; 3566 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3567 userId); 3568 } 3569 } 3570 return null; 3571 } 3572 3573 @Override 3574 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3575 if (!sUserManager.exists(userId)) return null; 3576 flags = updateFlagsForComponent(flags, userId, component); 3577 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3578 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3579 synchronized (mPackages) { 3580 PackageParser.Service s = mServices.mServices.get(component); 3581 if (DEBUG_PACKAGE_INFO) Log.v( 3582 TAG, "getServiceInfo " + component + ": " + s); 3583 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3584 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3585 if (ps == null) return null; 3586 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3587 userId); 3588 } 3589 } 3590 return null; 3591 } 3592 3593 @Override 3594 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return null; 3596 flags = updateFlagsForComponent(flags, userId, component); 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3598 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3599 synchronized (mPackages) { 3600 PackageParser.Provider p = mProviders.mProviders.get(component); 3601 if (DEBUG_PACKAGE_INFO) Log.v( 3602 TAG, "getProviderInfo " + component + ": " + p); 3603 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3604 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3605 if (ps == null) return null; 3606 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3607 userId); 3608 } 3609 } 3610 return null; 3611 } 3612 3613 @Override 3614 public String[] getSystemSharedLibraryNames() { 3615 Set<String> libSet; 3616 synchronized (mPackages) { 3617 libSet = mSharedLibraries.keySet(); 3618 int size = libSet.size(); 3619 if (size > 0) { 3620 String[] libs = new String[size]; 3621 libSet.toArray(libs); 3622 return libs; 3623 } 3624 } 3625 return null; 3626 } 3627 3628 @Override 3629 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3630 synchronized (mPackages) { 3631 return mServicesSystemSharedLibraryPackageName; 3632 } 3633 } 3634 3635 @Override 3636 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3637 synchronized (mPackages) { 3638 return mSharedSystemSharedLibraryPackageName; 3639 } 3640 } 3641 3642 @Override 3643 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3644 synchronized (mPackages) { 3645 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3646 3647 final FeatureInfo fi = new FeatureInfo(); 3648 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3649 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3650 res.add(fi); 3651 3652 return new ParceledListSlice<>(res); 3653 } 3654 } 3655 3656 @Override 3657 public boolean hasSystemFeature(String name, int version) { 3658 synchronized (mPackages) { 3659 final FeatureInfo feat = mAvailableFeatures.get(name); 3660 if (feat == null) { 3661 return false; 3662 } else { 3663 return feat.version >= version; 3664 } 3665 } 3666 } 3667 3668 @Override 3669 public int checkPermission(String permName, String pkgName, int userId) { 3670 if (!sUserManager.exists(userId)) { 3671 return PackageManager.PERMISSION_DENIED; 3672 } 3673 3674 synchronized (mPackages) { 3675 final PackageParser.Package p = mPackages.get(pkgName); 3676 if (p != null && p.mExtras != null) { 3677 final PackageSetting ps = (PackageSetting) p.mExtras; 3678 final PermissionsState permissionsState = ps.getPermissionsState(); 3679 if (permissionsState.hasPermission(permName, userId)) { 3680 return PackageManager.PERMISSION_GRANTED; 3681 } 3682 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3683 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3684 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3685 return PackageManager.PERMISSION_GRANTED; 3686 } 3687 } 3688 } 3689 3690 return PackageManager.PERMISSION_DENIED; 3691 } 3692 3693 @Override 3694 public int checkUidPermission(String permName, int uid) { 3695 final int userId = UserHandle.getUserId(uid); 3696 3697 if (!sUserManager.exists(userId)) { 3698 return PackageManager.PERMISSION_DENIED; 3699 } 3700 3701 synchronized (mPackages) { 3702 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3703 if (obj != null) { 3704 final SettingBase ps = (SettingBase) obj; 3705 final PermissionsState permissionsState = ps.getPermissionsState(); 3706 if (permissionsState.hasPermission(permName, userId)) { 3707 return PackageManager.PERMISSION_GRANTED; 3708 } 3709 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3710 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3711 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3712 return PackageManager.PERMISSION_GRANTED; 3713 } 3714 } else { 3715 ArraySet<String> perms = mSystemPermissions.get(uid); 3716 if (perms != null) { 3717 if (perms.contains(permName)) { 3718 return PackageManager.PERMISSION_GRANTED; 3719 } 3720 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3721 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3722 return PackageManager.PERMISSION_GRANTED; 3723 } 3724 } 3725 } 3726 } 3727 3728 return PackageManager.PERMISSION_DENIED; 3729 } 3730 3731 @Override 3732 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3733 if (UserHandle.getCallingUserId() != userId) { 3734 mContext.enforceCallingPermission( 3735 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3736 "isPermissionRevokedByPolicy for user " + userId); 3737 } 3738 3739 if (checkPermission(permission, packageName, userId) 3740 == PackageManager.PERMISSION_GRANTED) { 3741 return false; 3742 } 3743 3744 final long identity = Binder.clearCallingIdentity(); 3745 try { 3746 final int flags = getPermissionFlags(permission, packageName, userId); 3747 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3748 } finally { 3749 Binder.restoreCallingIdentity(identity); 3750 } 3751 } 3752 3753 @Override 3754 public String getPermissionControllerPackageName() { 3755 synchronized (mPackages) { 3756 return mRequiredInstallerPackage; 3757 } 3758 } 3759 3760 /** 3761 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3762 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3763 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3764 * @param message the message to log on security exception 3765 */ 3766 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3767 boolean checkShell, String message) { 3768 if (userId < 0) { 3769 throw new IllegalArgumentException("Invalid userId " + userId); 3770 } 3771 if (checkShell) { 3772 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3773 } 3774 if (userId == UserHandle.getUserId(callingUid)) return; 3775 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3776 if (requireFullPermission) { 3777 mContext.enforceCallingOrSelfPermission( 3778 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3779 } else { 3780 try { 3781 mContext.enforceCallingOrSelfPermission( 3782 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3783 } catch (SecurityException se) { 3784 mContext.enforceCallingOrSelfPermission( 3785 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3786 } 3787 } 3788 } 3789 } 3790 3791 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3792 if (callingUid == Process.SHELL_UID) { 3793 if (userHandle >= 0 3794 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3795 throw new SecurityException("Shell does not have permission to access user " 3796 + userHandle); 3797 } else if (userHandle < 0) { 3798 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3799 + Debug.getCallers(3)); 3800 } 3801 } 3802 } 3803 3804 private BasePermission findPermissionTreeLP(String permName) { 3805 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3806 if (permName.startsWith(bp.name) && 3807 permName.length() > bp.name.length() && 3808 permName.charAt(bp.name.length()) == '.') { 3809 return bp; 3810 } 3811 } 3812 return null; 3813 } 3814 3815 private BasePermission checkPermissionTreeLP(String permName) { 3816 if (permName != null) { 3817 BasePermission bp = findPermissionTreeLP(permName); 3818 if (bp != null) { 3819 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3820 return bp; 3821 } 3822 throw new SecurityException("Calling uid " 3823 + Binder.getCallingUid() 3824 + " is not allowed to add to permission tree " 3825 + bp.name + " owned by uid " + bp.uid); 3826 } 3827 } 3828 throw new SecurityException("No permission tree found for " + permName); 3829 } 3830 3831 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3832 if (s1 == null) { 3833 return s2 == null; 3834 } 3835 if (s2 == null) { 3836 return false; 3837 } 3838 if (s1.getClass() != s2.getClass()) { 3839 return false; 3840 } 3841 return s1.equals(s2); 3842 } 3843 3844 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3845 if (pi1.icon != pi2.icon) return false; 3846 if (pi1.logo != pi2.logo) return false; 3847 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3848 if (!compareStrings(pi1.name, pi2.name)) return false; 3849 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3850 // We'll take care of setting this one. 3851 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3852 // These are not currently stored in settings. 3853 //if (!compareStrings(pi1.group, pi2.group)) return false; 3854 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3855 //if (pi1.labelRes != pi2.labelRes) return false; 3856 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3857 return true; 3858 } 3859 3860 int permissionInfoFootprint(PermissionInfo info) { 3861 int size = info.name.length(); 3862 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3863 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3864 return size; 3865 } 3866 3867 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3868 int size = 0; 3869 for (BasePermission perm : mSettings.mPermissions.values()) { 3870 if (perm.uid == tree.uid) { 3871 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3872 } 3873 } 3874 return size; 3875 } 3876 3877 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3878 // We calculate the max size of permissions defined by this uid and throw 3879 // if that plus the size of 'info' would exceed our stated maximum. 3880 if (tree.uid != Process.SYSTEM_UID) { 3881 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3882 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3883 throw new SecurityException("Permission tree size cap exceeded"); 3884 } 3885 } 3886 } 3887 3888 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3889 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3890 throw new SecurityException("Label must be specified in permission"); 3891 } 3892 BasePermission tree = checkPermissionTreeLP(info.name); 3893 BasePermission bp = mSettings.mPermissions.get(info.name); 3894 boolean added = bp == null; 3895 boolean changed = true; 3896 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3897 if (added) { 3898 enforcePermissionCapLocked(info, tree); 3899 bp = new BasePermission(info.name, tree.sourcePackage, 3900 BasePermission.TYPE_DYNAMIC); 3901 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3902 throw new SecurityException( 3903 "Not allowed to modify non-dynamic permission " 3904 + info.name); 3905 } else { 3906 if (bp.protectionLevel == fixedLevel 3907 && bp.perm.owner.equals(tree.perm.owner) 3908 && bp.uid == tree.uid 3909 && comparePermissionInfos(bp.perm.info, info)) { 3910 changed = false; 3911 } 3912 } 3913 bp.protectionLevel = fixedLevel; 3914 info = new PermissionInfo(info); 3915 info.protectionLevel = fixedLevel; 3916 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3917 bp.perm.info.packageName = tree.perm.info.packageName; 3918 bp.uid = tree.uid; 3919 if (added) { 3920 mSettings.mPermissions.put(info.name, bp); 3921 } 3922 if (changed) { 3923 if (!async) { 3924 mSettings.writeLPr(); 3925 } else { 3926 scheduleWriteSettingsLocked(); 3927 } 3928 } 3929 return added; 3930 } 3931 3932 @Override 3933 public boolean addPermission(PermissionInfo info) { 3934 synchronized (mPackages) { 3935 return addPermissionLocked(info, false); 3936 } 3937 } 3938 3939 @Override 3940 public boolean addPermissionAsync(PermissionInfo info) { 3941 synchronized (mPackages) { 3942 return addPermissionLocked(info, true); 3943 } 3944 } 3945 3946 @Override 3947 public void removePermission(String name) { 3948 synchronized (mPackages) { 3949 checkPermissionTreeLP(name); 3950 BasePermission bp = mSettings.mPermissions.get(name); 3951 if (bp != null) { 3952 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3953 throw new SecurityException( 3954 "Not allowed to modify non-dynamic permission " 3955 + name); 3956 } 3957 mSettings.mPermissions.remove(name); 3958 mSettings.writeLPr(); 3959 } 3960 } 3961 } 3962 3963 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3964 BasePermission bp) { 3965 int index = pkg.requestedPermissions.indexOf(bp.name); 3966 if (index == -1) { 3967 throw new SecurityException("Package " + pkg.packageName 3968 + " has not requested permission " + bp.name); 3969 } 3970 if (!bp.isRuntime() && !bp.isDevelopment()) { 3971 throw new SecurityException("Permission " + bp.name 3972 + " is not a changeable permission type"); 3973 } 3974 } 3975 3976 @Override 3977 public void grantRuntimePermission(String packageName, String name, final int userId) { 3978 if (!sUserManager.exists(userId)) { 3979 Log.e(TAG, "No such user:" + userId); 3980 return; 3981 } 3982 3983 mContext.enforceCallingOrSelfPermission( 3984 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3985 "grantRuntimePermission"); 3986 3987 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3988 true /* requireFullPermission */, true /* checkShell */, 3989 "grantRuntimePermission"); 3990 3991 final int uid; 3992 final SettingBase sb; 3993 3994 synchronized (mPackages) { 3995 final PackageParser.Package pkg = mPackages.get(packageName); 3996 if (pkg == null) { 3997 throw new IllegalArgumentException("Unknown package: " + packageName); 3998 } 3999 4000 final BasePermission bp = mSettings.mPermissions.get(name); 4001 if (bp == null) { 4002 throw new IllegalArgumentException("Unknown permission: " + name); 4003 } 4004 4005 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4006 4007 // If a permission review is required for legacy apps we represent 4008 // their permissions as always granted runtime ones since we need 4009 // to keep the review required permission flag per user while an 4010 // install permission's state is shared across all users. 4011 if (Build.PERMISSIONS_REVIEW_REQUIRED 4012 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4013 && bp.isRuntime()) { 4014 return; 4015 } 4016 4017 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4018 sb = (SettingBase) pkg.mExtras; 4019 if (sb == null) { 4020 throw new IllegalArgumentException("Unknown package: " + packageName); 4021 } 4022 4023 final PermissionsState permissionsState = sb.getPermissionsState(); 4024 4025 final int flags = permissionsState.getPermissionFlags(name, userId); 4026 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4027 throw new SecurityException("Cannot grant system fixed permission " 4028 + name + " for package " + packageName); 4029 } 4030 4031 if (bp.isDevelopment()) { 4032 // Development permissions must be handled specially, since they are not 4033 // normal runtime permissions. For now they apply to all users. 4034 if (permissionsState.grantInstallPermission(bp) != 4035 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4036 scheduleWriteSettingsLocked(); 4037 } 4038 return; 4039 } 4040 4041 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4042 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4043 return; 4044 } 4045 4046 final int result = permissionsState.grantRuntimePermission(bp, userId); 4047 switch (result) { 4048 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4049 return; 4050 } 4051 4052 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4053 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4054 mHandler.post(new Runnable() { 4055 @Override 4056 public void run() { 4057 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4058 } 4059 }); 4060 } 4061 break; 4062 } 4063 4064 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4065 4066 // Not critical if that is lost - app has to request again. 4067 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4068 } 4069 4070 // Only need to do this if user is initialized. Otherwise it's a new user 4071 // and there are no processes running as the user yet and there's no need 4072 // to make an expensive call to remount processes for the changed permissions. 4073 if (READ_EXTERNAL_STORAGE.equals(name) 4074 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4075 final long token = Binder.clearCallingIdentity(); 4076 try { 4077 if (sUserManager.isInitialized(userId)) { 4078 MountServiceInternal mountServiceInternal = LocalServices.getService( 4079 MountServiceInternal.class); 4080 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4081 } 4082 } finally { 4083 Binder.restoreCallingIdentity(token); 4084 } 4085 } 4086 } 4087 4088 @Override 4089 public void revokeRuntimePermission(String packageName, String name, int userId) { 4090 if (!sUserManager.exists(userId)) { 4091 Log.e(TAG, "No such user:" + userId); 4092 return; 4093 } 4094 4095 mContext.enforceCallingOrSelfPermission( 4096 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4097 "revokeRuntimePermission"); 4098 4099 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4100 true /* requireFullPermission */, true /* checkShell */, 4101 "revokeRuntimePermission"); 4102 4103 final int appId; 4104 4105 synchronized (mPackages) { 4106 final PackageParser.Package pkg = mPackages.get(packageName); 4107 if (pkg == null) { 4108 throw new IllegalArgumentException("Unknown package: " + packageName); 4109 } 4110 4111 final BasePermission bp = mSettings.mPermissions.get(name); 4112 if (bp == null) { 4113 throw new IllegalArgumentException("Unknown permission: " + name); 4114 } 4115 4116 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4117 4118 // If a permission review is required for legacy apps we represent 4119 // their permissions as always granted runtime ones since we need 4120 // to keep the review required permission flag per user while an 4121 // install permission's state is shared across all users. 4122 if (Build.PERMISSIONS_REVIEW_REQUIRED 4123 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4124 && bp.isRuntime()) { 4125 return; 4126 } 4127 4128 SettingBase sb = (SettingBase) pkg.mExtras; 4129 if (sb == null) { 4130 throw new IllegalArgumentException("Unknown package: " + packageName); 4131 } 4132 4133 final PermissionsState permissionsState = sb.getPermissionsState(); 4134 4135 final int flags = permissionsState.getPermissionFlags(name, userId); 4136 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4137 throw new SecurityException("Cannot revoke system fixed permission " 4138 + name + " for package " + packageName); 4139 } 4140 4141 if (bp.isDevelopment()) { 4142 // Development permissions must be handled specially, since they are not 4143 // normal runtime permissions. For now they apply to all users. 4144 if (permissionsState.revokeInstallPermission(bp) != 4145 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4146 scheduleWriteSettingsLocked(); 4147 } 4148 return; 4149 } 4150 4151 if (permissionsState.revokeRuntimePermission(bp, userId) == 4152 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4153 return; 4154 } 4155 4156 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4157 4158 // Critical, after this call app should never have the permission. 4159 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4160 4161 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4162 } 4163 4164 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4165 } 4166 4167 @Override 4168 public void resetRuntimePermissions() { 4169 mContext.enforceCallingOrSelfPermission( 4170 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4171 "revokeRuntimePermission"); 4172 4173 int callingUid = Binder.getCallingUid(); 4174 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4175 mContext.enforceCallingOrSelfPermission( 4176 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4177 "resetRuntimePermissions"); 4178 } 4179 4180 synchronized (mPackages) { 4181 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4182 for (int userId : UserManagerService.getInstance().getUserIds()) { 4183 final int packageCount = mPackages.size(); 4184 for (int i = 0; i < packageCount; i++) { 4185 PackageParser.Package pkg = mPackages.valueAt(i); 4186 if (!(pkg.mExtras instanceof PackageSetting)) { 4187 continue; 4188 } 4189 PackageSetting ps = (PackageSetting) pkg.mExtras; 4190 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4191 } 4192 } 4193 } 4194 } 4195 4196 @Override 4197 public int getPermissionFlags(String name, String packageName, int userId) { 4198 if (!sUserManager.exists(userId)) { 4199 return 0; 4200 } 4201 4202 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4203 4204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4205 true /* requireFullPermission */, false /* checkShell */, 4206 "getPermissionFlags"); 4207 4208 synchronized (mPackages) { 4209 final PackageParser.Package pkg = mPackages.get(packageName); 4210 if (pkg == null) { 4211 return 0; 4212 } 4213 4214 final BasePermission bp = mSettings.mPermissions.get(name); 4215 if (bp == null) { 4216 return 0; 4217 } 4218 4219 SettingBase sb = (SettingBase) pkg.mExtras; 4220 if (sb == null) { 4221 return 0; 4222 } 4223 4224 PermissionsState permissionsState = sb.getPermissionsState(); 4225 return permissionsState.getPermissionFlags(name, userId); 4226 } 4227 } 4228 4229 @Override 4230 public void updatePermissionFlags(String name, String packageName, int flagMask, 4231 int flagValues, int userId) { 4232 if (!sUserManager.exists(userId)) { 4233 return; 4234 } 4235 4236 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4237 4238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4239 true /* requireFullPermission */, true /* checkShell */, 4240 "updatePermissionFlags"); 4241 4242 // Only the system can change these flags and nothing else. 4243 if (getCallingUid() != Process.SYSTEM_UID) { 4244 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4245 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4246 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4247 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4248 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4249 } 4250 4251 synchronized (mPackages) { 4252 final PackageParser.Package pkg = mPackages.get(packageName); 4253 if (pkg == null) { 4254 throw new IllegalArgumentException("Unknown package: " + packageName); 4255 } 4256 4257 final BasePermission bp = mSettings.mPermissions.get(name); 4258 if (bp == null) { 4259 throw new IllegalArgumentException("Unknown permission: " + name); 4260 } 4261 4262 SettingBase sb = (SettingBase) pkg.mExtras; 4263 if (sb == null) { 4264 throw new IllegalArgumentException("Unknown package: " + packageName); 4265 } 4266 4267 PermissionsState permissionsState = sb.getPermissionsState(); 4268 4269 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4270 4271 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4272 // Install and runtime permissions are stored in different places, 4273 // so figure out what permission changed and persist the change. 4274 if (permissionsState.getInstallPermissionState(name) != null) { 4275 scheduleWriteSettingsLocked(); 4276 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4277 || hadState) { 4278 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4279 } 4280 } 4281 } 4282 } 4283 4284 /** 4285 * Update the permission flags for all packages and runtime permissions of a user in order 4286 * to allow device or profile owner to remove POLICY_FIXED. 4287 */ 4288 @Override 4289 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4290 if (!sUserManager.exists(userId)) { 4291 return; 4292 } 4293 4294 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4295 4296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4297 true /* requireFullPermission */, true /* checkShell */, 4298 "updatePermissionFlagsForAllApps"); 4299 4300 // Only the system can change system fixed flags. 4301 if (getCallingUid() != Process.SYSTEM_UID) { 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4304 } 4305 4306 synchronized (mPackages) { 4307 boolean changed = false; 4308 final int packageCount = mPackages.size(); 4309 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4310 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4311 SettingBase sb = (SettingBase) pkg.mExtras; 4312 if (sb == null) { 4313 continue; 4314 } 4315 PermissionsState permissionsState = sb.getPermissionsState(); 4316 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4317 userId, flagMask, flagValues); 4318 } 4319 if (changed) { 4320 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4321 } 4322 } 4323 } 4324 4325 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4326 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4327 != PackageManager.PERMISSION_GRANTED 4328 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4329 != PackageManager.PERMISSION_GRANTED) { 4330 throw new SecurityException(message + " requires " 4331 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4332 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4333 } 4334 } 4335 4336 @Override 4337 public boolean shouldShowRequestPermissionRationale(String permissionName, 4338 String packageName, int userId) { 4339 if (UserHandle.getCallingUserId() != userId) { 4340 mContext.enforceCallingPermission( 4341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4342 "canShowRequestPermissionRationale for user " + userId); 4343 } 4344 4345 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4346 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4347 return false; 4348 } 4349 4350 if (checkPermission(permissionName, packageName, userId) 4351 == PackageManager.PERMISSION_GRANTED) { 4352 return false; 4353 } 4354 4355 final int flags; 4356 4357 final long identity = Binder.clearCallingIdentity(); 4358 try { 4359 flags = getPermissionFlags(permissionName, 4360 packageName, userId); 4361 } finally { 4362 Binder.restoreCallingIdentity(identity); 4363 } 4364 4365 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4366 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4367 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4368 4369 if ((flags & fixedFlags) != 0) { 4370 return false; 4371 } 4372 4373 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4374 } 4375 4376 @Override 4377 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4378 mContext.enforceCallingOrSelfPermission( 4379 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4380 "addOnPermissionsChangeListener"); 4381 4382 synchronized (mPackages) { 4383 mOnPermissionChangeListeners.addListenerLocked(listener); 4384 } 4385 } 4386 4387 @Override 4388 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4389 synchronized (mPackages) { 4390 mOnPermissionChangeListeners.removeListenerLocked(listener); 4391 } 4392 } 4393 4394 @Override 4395 public boolean isProtectedBroadcast(String actionName) { 4396 synchronized (mPackages) { 4397 if (mProtectedBroadcasts.contains(actionName)) { 4398 return true; 4399 } else if (actionName != null) { 4400 // TODO: remove these terrible hacks 4401 if (actionName.startsWith("android.net.netmon.lingerExpired") 4402 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4403 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4404 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4405 return true; 4406 } 4407 } 4408 } 4409 return false; 4410 } 4411 4412 @Override 4413 public int checkSignatures(String pkg1, String pkg2) { 4414 synchronized (mPackages) { 4415 final PackageParser.Package p1 = mPackages.get(pkg1); 4416 final PackageParser.Package p2 = mPackages.get(pkg2); 4417 if (p1 == null || p1.mExtras == null 4418 || p2 == null || p2.mExtras == null) { 4419 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4420 } 4421 return compareSignatures(p1.mSignatures, p2.mSignatures); 4422 } 4423 } 4424 4425 @Override 4426 public int checkUidSignatures(int uid1, int uid2) { 4427 // Map to base uids. 4428 uid1 = UserHandle.getAppId(uid1); 4429 uid2 = UserHandle.getAppId(uid2); 4430 // reader 4431 synchronized (mPackages) { 4432 Signature[] s1; 4433 Signature[] s2; 4434 Object obj = mSettings.getUserIdLPr(uid1); 4435 if (obj != null) { 4436 if (obj instanceof SharedUserSetting) { 4437 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4438 } else if (obj instanceof PackageSetting) { 4439 s1 = ((PackageSetting)obj).signatures.mSignatures; 4440 } else { 4441 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4442 } 4443 } else { 4444 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4445 } 4446 obj = mSettings.getUserIdLPr(uid2); 4447 if (obj != null) { 4448 if (obj instanceof SharedUserSetting) { 4449 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4450 } else if (obj instanceof PackageSetting) { 4451 s2 = ((PackageSetting)obj).signatures.mSignatures; 4452 } else { 4453 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4454 } 4455 } else { 4456 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4457 } 4458 return compareSignatures(s1, s2); 4459 } 4460 } 4461 4462 /** 4463 * This method should typically only be used when granting or revoking 4464 * permissions, since the app may immediately restart after this call. 4465 * <p> 4466 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4467 * guard your work against the app being relaunched. 4468 */ 4469 private void killUid(int appId, int userId, String reason) { 4470 final long identity = Binder.clearCallingIdentity(); 4471 try { 4472 IActivityManager am = ActivityManagerNative.getDefault(); 4473 if (am != null) { 4474 try { 4475 am.killUid(appId, userId, reason); 4476 } catch (RemoteException e) { 4477 /* ignore - same process */ 4478 } 4479 } 4480 } finally { 4481 Binder.restoreCallingIdentity(identity); 4482 } 4483 } 4484 4485 /** 4486 * Compares two sets of signatures. Returns: 4487 * <br /> 4488 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4489 * <br /> 4490 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4491 * <br /> 4492 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4493 * <br /> 4494 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4495 * <br /> 4496 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4497 */ 4498 static int compareSignatures(Signature[] s1, Signature[] s2) { 4499 if (s1 == null) { 4500 return s2 == null 4501 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4502 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4503 } 4504 4505 if (s2 == null) { 4506 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4507 } 4508 4509 if (s1.length != s2.length) { 4510 return PackageManager.SIGNATURE_NO_MATCH; 4511 } 4512 4513 // Since both signature sets are of size 1, we can compare without HashSets. 4514 if (s1.length == 1) { 4515 return s1[0].equals(s2[0]) ? 4516 PackageManager.SIGNATURE_MATCH : 4517 PackageManager.SIGNATURE_NO_MATCH; 4518 } 4519 4520 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4521 for (Signature sig : s1) { 4522 set1.add(sig); 4523 } 4524 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4525 for (Signature sig : s2) { 4526 set2.add(sig); 4527 } 4528 // Make sure s2 contains all signatures in s1. 4529 if (set1.equals(set2)) { 4530 return PackageManager.SIGNATURE_MATCH; 4531 } 4532 return PackageManager.SIGNATURE_NO_MATCH; 4533 } 4534 4535 /** 4536 * If the database version for this type of package (internal storage or 4537 * external storage) is less than the version where package signatures 4538 * were updated, return true. 4539 */ 4540 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4541 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4542 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4543 } 4544 4545 /** 4546 * Used for backward compatibility to make sure any packages with 4547 * certificate chains get upgraded to the new style. {@code existingSigs} 4548 * will be in the old format (since they were stored on disk from before the 4549 * system upgrade) and {@code scannedSigs} will be in the newer format. 4550 */ 4551 private int compareSignaturesCompat(PackageSignatures existingSigs, 4552 PackageParser.Package scannedPkg) { 4553 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4554 return PackageManager.SIGNATURE_NO_MATCH; 4555 } 4556 4557 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4558 for (Signature sig : existingSigs.mSignatures) { 4559 existingSet.add(sig); 4560 } 4561 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4562 for (Signature sig : scannedPkg.mSignatures) { 4563 try { 4564 Signature[] chainSignatures = sig.getChainSignatures(); 4565 for (Signature chainSig : chainSignatures) { 4566 scannedCompatSet.add(chainSig); 4567 } 4568 } catch (CertificateEncodingException e) { 4569 scannedCompatSet.add(sig); 4570 } 4571 } 4572 /* 4573 * Make sure the expanded scanned set contains all signatures in the 4574 * existing one. 4575 */ 4576 if (scannedCompatSet.equals(existingSet)) { 4577 // Migrate the old signatures to the new scheme. 4578 existingSigs.assignSignatures(scannedPkg.mSignatures); 4579 // The new KeySets will be re-added later in the scanning process. 4580 synchronized (mPackages) { 4581 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4582 } 4583 return PackageManager.SIGNATURE_MATCH; 4584 } 4585 return PackageManager.SIGNATURE_NO_MATCH; 4586 } 4587 4588 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4589 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4590 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4591 } 4592 4593 private int compareSignaturesRecover(PackageSignatures existingSigs, 4594 PackageParser.Package scannedPkg) { 4595 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 String msg = null; 4600 try { 4601 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4602 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4603 + scannedPkg.packageName); 4604 return PackageManager.SIGNATURE_MATCH; 4605 } 4606 } catch (CertificateException e) { 4607 msg = e.getMessage(); 4608 } 4609 4610 logCriticalInfo(Log.INFO, 4611 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4612 return PackageManager.SIGNATURE_NO_MATCH; 4613 } 4614 4615 @Override 4616 public List<String> getAllPackages() { 4617 synchronized (mPackages) { 4618 return new ArrayList<String>(mPackages.keySet()); 4619 } 4620 } 4621 4622 @Override 4623 public String[] getPackagesForUid(int uid) { 4624 uid = UserHandle.getAppId(uid); 4625 // reader 4626 synchronized (mPackages) { 4627 Object obj = mSettings.getUserIdLPr(uid); 4628 if (obj instanceof SharedUserSetting) { 4629 final SharedUserSetting sus = (SharedUserSetting) obj; 4630 final int N = sus.packages.size(); 4631 final String[] res = new String[N]; 4632 for (int i = 0; i < N; i++) { 4633 res[i] = sus.packages.valueAt(i).name; 4634 } 4635 return res; 4636 } else if (obj instanceof PackageSetting) { 4637 final PackageSetting ps = (PackageSetting) obj; 4638 return new String[] { ps.name }; 4639 } 4640 } 4641 return null; 4642 } 4643 4644 @Override 4645 public String getNameForUid(int uid) { 4646 // reader 4647 synchronized (mPackages) { 4648 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4649 if (obj instanceof SharedUserSetting) { 4650 final SharedUserSetting sus = (SharedUserSetting) obj; 4651 return sus.name + ":" + sus.userId; 4652 } else if (obj instanceof PackageSetting) { 4653 final PackageSetting ps = (PackageSetting) obj; 4654 return ps.name; 4655 } 4656 } 4657 return null; 4658 } 4659 4660 @Override 4661 public int getUidForSharedUser(String sharedUserName) { 4662 if(sharedUserName == null) { 4663 return -1; 4664 } 4665 // reader 4666 synchronized (mPackages) { 4667 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4668 if (suid == null) { 4669 return -1; 4670 } 4671 return suid.userId; 4672 } 4673 } 4674 4675 @Override 4676 public int getFlagsForUid(int uid) { 4677 synchronized (mPackages) { 4678 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4679 if (obj instanceof SharedUserSetting) { 4680 final SharedUserSetting sus = (SharedUserSetting) obj; 4681 return sus.pkgFlags; 4682 } else if (obj instanceof PackageSetting) { 4683 final PackageSetting ps = (PackageSetting) obj; 4684 return ps.pkgFlags; 4685 } 4686 } 4687 return 0; 4688 } 4689 4690 @Override 4691 public int getPrivateFlagsForUid(int uid) { 4692 synchronized (mPackages) { 4693 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4694 if (obj instanceof SharedUserSetting) { 4695 final SharedUserSetting sus = (SharedUserSetting) obj; 4696 return sus.pkgPrivateFlags; 4697 } else if (obj instanceof PackageSetting) { 4698 final PackageSetting ps = (PackageSetting) obj; 4699 return ps.pkgPrivateFlags; 4700 } 4701 } 4702 return 0; 4703 } 4704 4705 @Override 4706 public boolean isUidPrivileged(int uid) { 4707 uid = UserHandle.getAppId(uid); 4708 // reader 4709 synchronized (mPackages) { 4710 Object obj = mSettings.getUserIdLPr(uid); 4711 if (obj instanceof SharedUserSetting) { 4712 final SharedUserSetting sus = (SharedUserSetting) obj; 4713 final Iterator<PackageSetting> it = sus.packages.iterator(); 4714 while (it.hasNext()) { 4715 if (it.next().isPrivileged()) { 4716 return true; 4717 } 4718 } 4719 } else if (obj instanceof PackageSetting) { 4720 final PackageSetting ps = (PackageSetting) obj; 4721 return ps.isPrivileged(); 4722 } 4723 } 4724 return false; 4725 } 4726 4727 @Override 4728 public String[] getAppOpPermissionPackages(String permissionName) { 4729 synchronized (mPackages) { 4730 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4731 if (pkgs == null) { 4732 return null; 4733 } 4734 return pkgs.toArray(new String[pkgs.size()]); 4735 } 4736 } 4737 4738 @Override 4739 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4740 int flags, int userId) { 4741 try { 4742 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4743 4744 if (!sUserManager.exists(userId)) return null; 4745 flags = updateFlagsForResolve(flags, userId, intent); 4746 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4747 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4748 4749 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4750 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4751 flags, userId); 4752 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4753 4754 final ResolveInfo bestChoice = 4755 chooseBestActivity(intent, resolvedType, flags, query, userId); 4756 return bestChoice; 4757 } finally { 4758 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4759 } 4760 } 4761 4762 @Override 4763 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4764 IntentFilter filter, int match, ComponentName activity) { 4765 final int userId = UserHandle.getCallingUserId(); 4766 if (DEBUG_PREFERRED) { 4767 Log.v(TAG, "setLastChosenActivity intent=" + intent 4768 + " resolvedType=" + resolvedType 4769 + " flags=" + flags 4770 + " filter=" + filter 4771 + " match=" + match 4772 + " activity=" + activity); 4773 filter.dump(new PrintStreamPrinter(System.out), " "); 4774 } 4775 intent.setComponent(null); 4776 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4777 userId); 4778 // Find any earlier preferred or last chosen entries and nuke them 4779 findPreferredActivity(intent, resolvedType, 4780 flags, query, 0, false, true, false, userId); 4781 // Add the new activity as the last chosen for this filter 4782 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4783 "Setting last chosen"); 4784 } 4785 4786 @Override 4787 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4788 final int userId = UserHandle.getCallingUserId(); 4789 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4790 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4791 userId); 4792 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4793 false, false, false, userId); 4794 } 4795 4796 private boolean isEphemeralDisabled() { 4797 // ephemeral apps have been disabled across the board 4798 if (DISABLE_EPHEMERAL_APPS) { 4799 return true; 4800 } 4801 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4802 if (!mSystemReady) { 4803 return true; 4804 } 4805 return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0; 4806 } 4807 4808 private boolean isEphemeralAllowed( 4809 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4810 boolean skipPackageCheck) { 4811 // Short circuit and return early if possible. 4812 if (isEphemeralDisabled()) { 4813 return false; 4814 } 4815 final int callingUser = UserHandle.getCallingUserId(); 4816 if (callingUser != UserHandle.USER_SYSTEM) { 4817 return false; 4818 } 4819 if (mEphemeralResolverConnection == null) { 4820 return false; 4821 } 4822 if (intent.getComponent() != null) { 4823 return false; 4824 } 4825 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4826 return false; 4827 } 4828 if (!skipPackageCheck && intent.getPackage() != null) { 4829 return false; 4830 } 4831 final boolean isWebUri = hasWebURI(intent); 4832 if (!isWebUri || intent.getData().getHost() == null) { 4833 return false; 4834 } 4835 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4836 synchronized (mPackages) { 4837 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4838 for (int n = 0; n < count; n++) { 4839 ResolveInfo info = resolvedActivities.get(n); 4840 String packageName = info.activityInfo.packageName; 4841 PackageSetting ps = mSettings.mPackages.get(packageName); 4842 if (ps != null) { 4843 // Try to get the status from User settings first 4844 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4845 int status = (int) (packedStatus >> 32); 4846 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4847 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4848 if (DEBUG_EPHEMERAL) { 4849 Slog.v(TAG, "DENY ephemeral apps;" 4850 + " pkg: " + packageName + ", status: " + status); 4851 } 4852 return false; 4853 } 4854 } 4855 } 4856 } 4857 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4858 return true; 4859 } 4860 4861 private static EphemeralResolveInfo getEphemeralResolveInfo( 4862 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4863 String resolvedType, int userId, String packageName) { 4864 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4865 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4866 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4867 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4868 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4869 ephemeralPrefixCount); 4870 final int[] shaPrefix = digest.getDigestPrefix(); 4871 final byte[][] digestBytes = digest.getDigestBytes(); 4872 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4873 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4874 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4875 // No hash prefix match; there are no ephemeral apps for this domain. 4876 return null; 4877 } 4878 4879 // Go in reverse order so we match the narrowest scope first. 4880 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4881 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4882 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4883 continue; 4884 } 4885 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4886 // No filters; this should never happen. 4887 if (filters.isEmpty()) { 4888 continue; 4889 } 4890 if (packageName != null 4891 && !packageName.equals(ephemeralApplication.getPackageName())) { 4892 continue; 4893 } 4894 // We have a domain match; resolve the filters to see if anything matches. 4895 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4896 for (int j = filters.size() - 1; j >= 0; --j) { 4897 final EphemeralResolveIntentInfo intentInfo = 4898 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4899 ephemeralResolver.addFilter(intentInfo); 4900 } 4901 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4902 intent, resolvedType, false /*defaultOnly*/, userId); 4903 if (!matchedResolveInfoList.isEmpty()) { 4904 return matchedResolveInfoList.get(0); 4905 } 4906 } 4907 } 4908 // Hash or filter mis-match; no ephemeral apps for this domain. 4909 return null; 4910 } 4911 4912 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4913 int flags, List<ResolveInfo> query, int userId) { 4914 if (query != null) { 4915 final int N = query.size(); 4916 if (N == 1) { 4917 return query.get(0); 4918 } else if (N > 1) { 4919 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4920 // If there is more than one activity with the same priority, 4921 // then let the user decide between them. 4922 ResolveInfo r0 = query.get(0); 4923 ResolveInfo r1 = query.get(1); 4924 if (DEBUG_INTENT_MATCHING || debug) { 4925 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4926 + r1.activityInfo.name + "=" + r1.priority); 4927 } 4928 // If the first activity has a higher priority, or a different 4929 // default, then it is always desirable to pick it. 4930 if (r0.priority != r1.priority 4931 || r0.preferredOrder != r1.preferredOrder 4932 || r0.isDefault != r1.isDefault) { 4933 return query.get(0); 4934 } 4935 // If we have saved a preference for a preferred activity for 4936 // this Intent, use that. 4937 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4938 flags, query, r0.priority, true, false, debug, userId); 4939 if (ri != null) { 4940 return ri; 4941 } 4942 ri = new ResolveInfo(mResolveInfo); 4943 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4944 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4945 // If all of the options come from the same package, show the application's 4946 // label and icon instead of the generic resolver's. 4947 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4948 // and then throw away the ResolveInfo itself, meaning that the caller loses 4949 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4950 // a fallback for this case; we only set the target package's resources on 4951 // the ResolveInfo, not the ActivityInfo. 4952 final String intentPackage = intent.getPackage(); 4953 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4954 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4955 ri.resolvePackageName = intentPackage; 4956 if (userNeedsBadging(userId)) { 4957 ri.noResourceId = true; 4958 } else { 4959 ri.icon = appi.icon; 4960 } 4961 ri.iconResourceId = appi.icon; 4962 ri.labelRes = appi.labelRes; 4963 } 4964 ri.activityInfo.applicationInfo = new ApplicationInfo( 4965 ri.activityInfo.applicationInfo); 4966 if (userId != 0) { 4967 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4968 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4969 } 4970 // Make sure that the resolver is displayable in car mode 4971 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4972 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4973 return ri; 4974 } 4975 } 4976 return null; 4977 } 4978 4979 /** 4980 * Return true if the given list is not empty and all of its contents have 4981 * an activityInfo with the given package name. 4982 */ 4983 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4984 if (ArrayUtils.isEmpty(list)) { 4985 return false; 4986 } 4987 for (int i = 0, N = list.size(); i < N; i++) { 4988 final ResolveInfo ri = list.get(i); 4989 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4990 if (ai == null || !packageName.equals(ai.packageName)) { 4991 return false; 4992 } 4993 } 4994 return true; 4995 } 4996 4997 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4998 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4999 final int N = query.size(); 5000 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5001 .get(userId); 5002 // Get the list of persistent preferred activities that handle the intent 5003 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5004 List<PersistentPreferredActivity> pprefs = ppir != null 5005 ? ppir.queryIntent(intent, resolvedType, 5006 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5007 : null; 5008 if (pprefs != null && pprefs.size() > 0) { 5009 final int M = pprefs.size(); 5010 for (int i=0; i<M; i++) { 5011 final PersistentPreferredActivity ppa = pprefs.get(i); 5012 if (DEBUG_PREFERRED || debug) { 5013 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5014 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5015 + "\n component=" + ppa.mComponent); 5016 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5017 } 5018 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5019 flags | MATCH_DISABLED_COMPONENTS, userId); 5020 if (DEBUG_PREFERRED || debug) { 5021 Slog.v(TAG, "Found persistent preferred activity:"); 5022 if (ai != null) { 5023 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5024 } else { 5025 Slog.v(TAG, " null"); 5026 } 5027 } 5028 if (ai == null) { 5029 // This previously registered persistent preferred activity 5030 // component is no longer known. Ignore it and do NOT remove it. 5031 continue; 5032 } 5033 for (int j=0; j<N; j++) { 5034 final ResolveInfo ri = query.get(j); 5035 if (!ri.activityInfo.applicationInfo.packageName 5036 .equals(ai.applicationInfo.packageName)) { 5037 continue; 5038 } 5039 if (!ri.activityInfo.name.equals(ai.name)) { 5040 continue; 5041 } 5042 // Found a persistent preference that can handle the intent. 5043 if (DEBUG_PREFERRED || debug) { 5044 Slog.v(TAG, "Returning persistent preferred activity: " + 5045 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5046 } 5047 return ri; 5048 } 5049 } 5050 } 5051 return null; 5052 } 5053 5054 // TODO: handle preferred activities missing while user has amnesia 5055 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5056 List<ResolveInfo> query, int priority, boolean always, 5057 boolean removeMatches, boolean debug, int userId) { 5058 if (!sUserManager.exists(userId)) return null; 5059 flags = updateFlagsForResolve(flags, userId, intent); 5060 // writer 5061 synchronized (mPackages) { 5062 if (intent.getSelector() != null) { 5063 intent = intent.getSelector(); 5064 } 5065 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5066 5067 // Try to find a matching persistent preferred activity. 5068 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5069 debug, userId); 5070 5071 // If a persistent preferred activity matched, use it. 5072 if (pri != null) { 5073 return pri; 5074 } 5075 5076 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5077 // Get the list of preferred activities that handle the intent 5078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5079 List<PreferredActivity> prefs = pir != null 5080 ? pir.queryIntent(intent, resolvedType, 5081 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5082 : null; 5083 if (prefs != null && prefs.size() > 0) { 5084 boolean changed = false; 5085 try { 5086 // First figure out how good the original match set is. 5087 // We will only allow preferred activities that came 5088 // from the same match quality. 5089 int match = 0; 5090 5091 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5092 5093 final int N = query.size(); 5094 for (int j=0; j<N; j++) { 5095 final ResolveInfo ri = query.get(j); 5096 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5097 + ": 0x" + Integer.toHexString(match)); 5098 if (ri.match > match) { 5099 match = ri.match; 5100 } 5101 } 5102 5103 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5104 + Integer.toHexString(match)); 5105 5106 match &= IntentFilter.MATCH_CATEGORY_MASK; 5107 final int M = prefs.size(); 5108 for (int i=0; i<M; i++) { 5109 final PreferredActivity pa = prefs.get(i); 5110 if (DEBUG_PREFERRED || debug) { 5111 Slog.v(TAG, "Checking PreferredActivity ds=" 5112 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5113 + "\n component=" + pa.mPref.mComponent); 5114 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5115 } 5116 if (pa.mPref.mMatch != match) { 5117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5118 + Integer.toHexString(pa.mPref.mMatch)); 5119 continue; 5120 } 5121 // If it's not an "always" type preferred activity and that's what we're 5122 // looking for, skip it. 5123 if (always && !pa.mPref.mAlways) { 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5125 continue; 5126 } 5127 final ActivityInfo ai = getActivityInfo( 5128 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5129 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5130 userId); 5131 if (DEBUG_PREFERRED || debug) { 5132 Slog.v(TAG, "Found preferred activity:"); 5133 if (ai != null) { 5134 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5135 } else { 5136 Slog.v(TAG, " null"); 5137 } 5138 } 5139 if (ai == null) { 5140 // This previously registered preferred activity 5141 // component is no longer known. Most likely an update 5142 // to the app was installed and in the new version this 5143 // component no longer exists. Clean it up by removing 5144 // it from the preferred activities list, and skip it. 5145 Slog.w(TAG, "Removing dangling preferred activity: " 5146 + pa.mPref.mComponent); 5147 pir.removeFilter(pa); 5148 changed = true; 5149 continue; 5150 } 5151 for (int j=0; j<N; j++) { 5152 final ResolveInfo ri = query.get(j); 5153 if (!ri.activityInfo.applicationInfo.packageName 5154 .equals(ai.applicationInfo.packageName)) { 5155 continue; 5156 } 5157 if (!ri.activityInfo.name.equals(ai.name)) { 5158 continue; 5159 } 5160 5161 if (removeMatches) { 5162 pir.removeFilter(pa); 5163 changed = true; 5164 if (DEBUG_PREFERRED) { 5165 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5166 } 5167 break; 5168 } 5169 5170 // Okay we found a previously set preferred or last chosen app. 5171 // If the result set is different from when this 5172 // was created, we need to clear it and re-ask the 5173 // user their preference, if we're looking for an "always" type entry. 5174 if (always && !pa.mPref.sameSet(query)) { 5175 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5176 + intent + " type " + resolvedType); 5177 if (DEBUG_PREFERRED) { 5178 Slog.v(TAG, "Removing preferred activity since set changed " 5179 + pa.mPref.mComponent); 5180 } 5181 pir.removeFilter(pa); 5182 // Re-add the filter as a "last chosen" entry (!always) 5183 PreferredActivity lastChosen = new PreferredActivity( 5184 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5185 pir.addFilter(lastChosen); 5186 changed = true; 5187 return null; 5188 } 5189 5190 // Yay! Either the set matched or we're looking for the last chosen 5191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5192 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5193 return ri; 5194 } 5195 } 5196 } finally { 5197 if (changed) { 5198 if (DEBUG_PREFERRED) { 5199 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5200 } 5201 scheduleWritePackageRestrictionsLocked(userId); 5202 } 5203 } 5204 } 5205 } 5206 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5207 return null; 5208 } 5209 5210 /* 5211 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5212 */ 5213 @Override 5214 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5215 int targetUserId) { 5216 mContext.enforceCallingOrSelfPermission( 5217 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5218 List<CrossProfileIntentFilter> matches = 5219 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5220 if (matches != null) { 5221 int size = matches.size(); 5222 for (int i = 0; i < size; i++) { 5223 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5224 } 5225 } 5226 if (hasWebURI(intent)) { 5227 // cross-profile app linking works only towards the parent. 5228 final UserInfo parent = getProfileParent(sourceUserId); 5229 synchronized(mPackages) { 5230 int flags = updateFlagsForResolve(0, parent.id, intent); 5231 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5232 intent, resolvedType, flags, sourceUserId, parent.id); 5233 return xpDomainInfo != null; 5234 } 5235 } 5236 return false; 5237 } 5238 5239 private UserInfo getProfileParent(int userId) { 5240 final long identity = Binder.clearCallingIdentity(); 5241 try { 5242 return sUserManager.getProfileParent(userId); 5243 } finally { 5244 Binder.restoreCallingIdentity(identity); 5245 } 5246 } 5247 5248 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5249 String resolvedType, int userId) { 5250 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5251 if (resolver != null) { 5252 return resolver.queryIntent(intent, resolvedType, false, userId); 5253 } 5254 return null; 5255 } 5256 5257 @Override 5258 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5259 String resolvedType, int flags, int userId) { 5260 try { 5261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5262 5263 return new ParceledListSlice<>( 5264 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5265 } finally { 5266 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5267 } 5268 } 5269 5270 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5271 String resolvedType, int flags, int userId) { 5272 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5273 flags = updateFlagsForResolve(flags, userId, intent); 5274 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5275 false /* requireFullPermission */, false /* checkShell */, 5276 "query intent activities"); 5277 ComponentName comp = intent.getComponent(); 5278 if (comp == null) { 5279 if (intent.getSelector() != null) { 5280 intent = intent.getSelector(); 5281 comp = intent.getComponent(); 5282 } 5283 } 5284 5285 if (comp != null) { 5286 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5287 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5288 if (ai != null) { 5289 final ResolveInfo ri = new ResolveInfo(); 5290 ri.activityInfo = ai; 5291 list.add(ri); 5292 } 5293 return list; 5294 } 5295 5296 // reader 5297 boolean sortResult = false; 5298 boolean addEphemeral = false; 5299 boolean matchEphemeralPackage = false; 5300 List<ResolveInfo> result; 5301 final String pkgName = intent.getPackage(); 5302 synchronized (mPackages) { 5303 if (pkgName == null) { 5304 List<CrossProfileIntentFilter> matchingFilters = 5305 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5306 // Check for results that need to skip the current profile. 5307 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5308 resolvedType, flags, userId); 5309 if (xpResolveInfo != null) { 5310 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5311 xpResult.add(xpResolveInfo); 5312 return filterIfNotSystemUser(xpResult, userId); 5313 } 5314 5315 // Check for results in the current profile. 5316 result = filterIfNotSystemUser(mActivities.queryIntent( 5317 intent, resolvedType, flags, userId), userId); 5318 addEphemeral = 5319 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5320 5321 // Check for cross profile results. 5322 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5323 xpResolveInfo = queryCrossProfileIntents( 5324 matchingFilters, intent, resolvedType, flags, userId, 5325 hasNonNegativePriorityResult); 5326 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5327 boolean isVisibleToUser = filterIfNotSystemUser( 5328 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5329 if (isVisibleToUser) { 5330 result.add(xpResolveInfo); 5331 sortResult = true; 5332 } 5333 } 5334 if (hasWebURI(intent)) { 5335 CrossProfileDomainInfo xpDomainInfo = null; 5336 final UserInfo parent = getProfileParent(userId); 5337 if (parent != null) { 5338 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5339 flags, userId, parent.id); 5340 } 5341 if (xpDomainInfo != null) { 5342 if (xpResolveInfo != null) { 5343 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5344 // in the result. 5345 result.remove(xpResolveInfo); 5346 } 5347 if (result.size() == 0 && !addEphemeral) { 5348 result.add(xpDomainInfo.resolveInfo); 5349 return result; 5350 } 5351 } 5352 if (result.size() > 1 || addEphemeral) { 5353 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5354 intent, flags, result, xpDomainInfo, userId); 5355 sortResult = true; 5356 } 5357 } 5358 } else { 5359 final PackageParser.Package pkg = mPackages.get(pkgName); 5360 if (pkg != null) { 5361 result = filterIfNotSystemUser( 5362 mActivities.queryIntentForPackage( 5363 intent, resolvedType, flags, pkg.activities, userId), 5364 userId); 5365 } else { 5366 // the caller wants to resolve for a particular package; however, there 5367 // were no installed results, so, try to find an ephemeral result 5368 addEphemeral = isEphemeralAllowed( 5369 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5370 matchEphemeralPackage = true; 5371 result = new ArrayList<ResolveInfo>(); 5372 } 5373 } 5374 } 5375 if (addEphemeral) { 5376 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5377 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5378 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5379 matchEphemeralPackage ? pkgName : null); 5380 if (ai != null) { 5381 if (DEBUG_EPHEMERAL) { 5382 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5383 } 5384 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5385 ephemeralInstaller.ephemeralResolveInfo = ai; 5386 // make sure this resolver is the default 5387 ephemeralInstaller.isDefault = true; 5388 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5389 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5390 // add a non-generic filter 5391 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5392 ephemeralInstaller.filter.addDataPath( 5393 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5394 result.add(ephemeralInstaller); 5395 } 5396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5397 } 5398 if (sortResult) { 5399 Collections.sort(result, mResolvePrioritySorter); 5400 } 5401 return result; 5402 } 5403 5404 private static class CrossProfileDomainInfo { 5405 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5406 ResolveInfo resolveInfo; 5407 /* Best domain verification status of the activities found in the other profile */ 5408 int bestDomainVerificationStatus; 5409 } 5410 5411 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5412 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5413 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5414 sourceUserId)) { 5415 return null; 5416 } 5417 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5418 resolvedType, flags, parentUserId); 5419 5420 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5421 return null; 5422 } 5423 CrossProfileDomainInfo result = null; 5424 int size = resultTargetUser.size(); 5425 for (int i = 0; i < size; i++) { 5426 ResolveInfo riTargetUser = resultTargetUser.get(i); 5427 // Intent filter verification is only for filters that specify a host. So don't return 5428 // those that handle all web uris. 5429 if (riTargetUser.handleAllWebDataURI) { 5430 continue; 5431 } 5432 String packageName = riTargetUser.activityInfo.packageName; 5433 PackageSetting ps = mSettings.mPackages.get(packageName); 5434 if (ps == null) { 5435 continue; 5436 } 5437 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5438 int status = (int)(verificationState >> 32); 5439 if (result == null) { 5440 result = new CrossProfileDomainInfo(); 5441 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5442 sourceUserId, parentUserId); 5443 result.bestDomainVerificationStatus = status; 5444 } else { 5445 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5446 result.bestDomainVerificationStatus); 5447 } 5448 } 5449 // Don't consider matches with status NEVER across profiles. 5450 if (result != null && result.bestDomainVerificationStatus 5451 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5452 return null; 5453 } 5454 return result; 5455 } 5456 5457 /** 5458 * Verification statuses are ordered from the worse to the best, except for 5459 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5460 */ 5461 private int bestDomainVerificationStatus(int status1, int status2) { 5462 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5463 return status2; 5464 } 5465 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5466 return status1; 5467 } 5468 return (int) MathUtils.max(status1, status2); 5469 } 5470 5471 private boolean isUserEnabled(int userId) { 5472 long callingId = Binder.clearCallingIdentity(); 5473 try { 5474 UserInfo userInfo = sUserManager.getUserInfo(userId); 5475 return userInfo != null && userInfo.isEnabled(); 5476 } finally { 5477 Binder.restoreCallingIdentity(callingId); 5478 } 5479 } 5480 5481 /** 5482 * Filter out activities with systemUserOnly flag set, when current user is not System. 5483 * 5484 * @return filtered list 5485 */ 5486 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5487 if (userId == UserHandle.USER_SYSTEM) { 5488 return resolveInfos; 5489 } 5490 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5491 ResolveInfo info = resolveInfos.get(i); 5492 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5493 resolveInfos.remove(i); 5494 } 5495 } 5496 return resolveInfos; 5497 } 5498 5499 /** 5500 * @param resolveInfos list of resolve infos in descending priority order 5501 * @return if the list contains a resolve info with non-negative priority 5502 */ 5503 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5504 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5505 } 5506 5507 private static boolean hasWebURI(Intent intent) { 5508 if (intent.getData() == null) { 5509 return false; 5510 } 5511 final String scheme = intent.getScheme(); 5512 if (TextUtils.isEmpty(scheme)) { 5513 return false; 5514 } 5515 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5516 } 5517 5518 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5519 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5520 int userId) { 5521 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5522 5523 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5524 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5525 candidates.size()); 5526 } 5527 5528 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5529 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5530 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5531 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5532 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5533 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5534 5535 synchronized (mPackages) { 5536 final int count = candidates.size(); 5537 // First, try to use linked apps. Partition the candidates into four lists: 5538 // one for the final results, one for the "do not use ever", one for "undefined status" 5539 // and finally one for "browser app type". 5540 for (int n=0; n<count; n++) { 5541 ResolveInfo info = candidates.get(n); 5542 String packageName = info.activityInfo.packageName; 5543 PackageSetting ps = mSettings.mPackages.get(packageName); 5544 if (ps != null) { 5545 // Add to the special match all list (Browser use case) 5546 if (info.handleAllWebDataURI) { 5547 matchAllList.add(info); 5548 continue; 5549 } 5550 // Try to get the status from User settings first 5551 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5552 int status = (int)(packedStatus >> 32); 5553 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5554 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5555 if (DEBUG_DOMAIN_VERIFICATION) { 5556 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5557 + " : linkgen=" + linkGeneration); 5558 } 5559 // Use link-enabled generation as preferredOrder, i.e. 5560 // prefer newly-enabled over earlier-enabled. 5561 info.preferredOrder = linkGeneration; 5562 alwaysList.add(info); 5563 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5564 if (DEBUG_DOMAIN_VERIFICATION) { 5565 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5566 } 5567 neverList.add(info); 5568 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5569 if (DEBUG_DOMAIN_VERIFICATION) { 5570 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5571 } 5572 alwaysAskList.add(info); 5573 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5574 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5575 if (DEBUG_DOMAIN_VERIFICATION) { 5576 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5577 } 5578 undefinedList.add(info); 5579 } 5580 } 5581 } 5582 5583 // We'll want to include browser possibilities in a few cases 5584 boolean includeBrowser = false; 5585 5586 // First try to add the "always" resolution(s) for the current user, if any 5587 if (alwaysList.size() > 0) { 5588 result.addAll(alwaysList); 5589 } else { 5590 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5591 result.addAll(undefinedList); 5592 // Maybe add one for the other profile. 5593 if (xpDomainInfo != null && ( 5594 xpDomainInfo.bestDomainVerificationStatus 5595 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5596 result.add(xpDomainInfo.resolveInfo); 5597 } 5598 includeBrowser = true; 5599 } 5600 5601 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5602 // If there were 'always' entries their preferred order has been set, so we also 5603 // back that off to make the alternatives equivalent 5604 if (alwaysAskList.size() > 0) { 5605 for (ResolveInfo i : result) { 5606 i.preferredOrder = 0; 5607 } 5608 result.addAll(alwaysAskList); 5609 includeBrowser = true; 5610 } 5611 5612 if (includeBrowser) { 5613 // Also add browsers (all of them or only the default one) 5614 if (DEBUG_DOMAIN_VERIFICATION) { 5615 Slog.v(TAG, " ...including browsers in candidate set"); 5616 } 5617 if ((matchFlags & MATCH_ALL) != 0) { 5618 result.addAll(matchAllList); 5619 } else { 5620 // Browser/generic handling case. If there's a default browser, go straight 5621 // to that (but only if there is no other higher-priority match). 5622 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5623 int maxMatchPrio = 0; 5624 ResolveInfo defaultBrowserMatch = null; 5625 final int numCandidates = matchAllList.size(); 5626 for (int n = 0; n < numCandidates; n++) { 5627 ResolveInfo info = matchAllList.get(n); 5628 // track the highest overall match priority... 5629 if (info.priority > maxMatchPrio) { 5630 maxMatchPrio = info.priority; 5631 } 5632 // ...and the highest-priority default browser match 5633 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5634 if (defaultBrowserMatch == null 5635 || (defaultBrowserMatch.priority < info.priority)) { 5636 if (debug) { 5637 Slog.v(TAG, "Considering default browser match " + info); 5638 } 5639 defaultBrowserMatch = info; 5640 } 5641 } 5642 } 5643 if (defaultBrowserMatch != null 5644 && defaultBrowserMatch.priority >= maxMatchPrio 5645 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5646 { 5647 if (debug) { 5648 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5649 } 5650 result.add(defaultBrowserMatch); 5651 } else { 5652 result.addAll(matchAllList); 5653 } 5654 } 5655 5656 // If there is nothing selected, add all candidates and remove the ones that the user 5657 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5658 if (result.size() == 0) { 5659 result.addAll(candidates); 5660 result.removeAll(neverList); 5661 } 5662 } 5663 } 5664 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5665 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5666 result.size()); 5667 for (ResolveInfo info : result) { 5668 Slog.v(TAG, " + " + info.activityInfo); 5669 } 5670 } 5671 return result; 5672 } 5673 5674 // Returns a packed value as a long: 5675 // 5676 // high 'int'-sized word: link status: undefined/ask/never/always. 5677 // low 'int'-sized word: relative priority among 'always' results. 5678 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5679 long result = ps.getDomainVerificationStatusForUser(userId); 5680 // if none available, get the master status 5681 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5682 if (ps.getIntentFilterVerificationInfo() != null) { 5683 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5684 } 5685 } 5686 return result; 5687 } 5688 5689 private ResolveInfo querySkipCurrentProfileIntents( 5690 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5691 int flags, int sourceUserId) { 5692 if (matchingFilters != null) { 5693 int size = matchingFilters.size(); 5694 for (int i = 0; i < size; i ++) { 5695 CrossProfileIntentFilter filter = matchingFilters.get(i); 5696 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5697 // Checking if there are activities in the target user that can handle the 5698 // intent. 5699 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5700 resolvedType, flags, sourceUserId); 5701 if (resolveInfo != null) { 5702 return resolveInfo; 5703 } 5704 } 5705 } 5706 } 5707 return null; 5708 } 5709 5710 // Return matching ResolveInfo in target user if any. 5711 private ResolveInfo queryCrossProfileIntents( 5712 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5713 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5714 if (matchingFilters != null) { 5715 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5716 // match the same intent. For performance reasons, it is better not to 5717 // run queryIntent twice for the same userId 5718 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5719 int size = matchingFilters.size(); 5720 for (int i = 0; i < size; i++) { 5721 CrossProfileIntentFilter filter = matchingFilters.get(i); 5722 int targetUserId = filter.getTargetUserId(); 5723 boolean skipCurrentProfile = 5724 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5725 boolean skipCurrentProfileIfNoMatchFound = 5726 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5727 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5728 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5729 // Checking if there are activities in the target user that can handle the 5730 // intent. 5731 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5732 resolvedType, flags, sourceUserId); 5733 if (resolveInfo != null) return resolveInfo; 5734 alreadyTriedUserIds.put(targetUserId, true); 5735 } 5736 } 5737 } 5738 return null; 5739 } 5740 5741 /** 5742 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5743 * will forward the intent to the filter's target user. 5744 * Otherwise, returns null. 5745 */ 5746 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5747 String resolvedType, int flags, int sourceUserId) { 5748 int targetUserId = filter.getTargetUserId(); 5749 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5750 resolvedType, flags, targetUserId); 5751 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5752 // If all the matches in the target profile are suspended, return null. 5753 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5754 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5755 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5756 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5757 targetUserId); 5758 } 5759 } 5760 } 5761 return null; 5762 } 5763 5764 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5765 int sourceUserId, int targetUserId) { 5766 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5767 long ident = Binder.clearCallingIdentity(); 5768 boolean targetIsProfile; 5769 try { 5770 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5771 } finally { 5772 Binder.restoreCallingIdentity(ident); 5773 } 5774 String className; 5775 if (targetIsProfile) { 5776 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5777 } else { 5778 className = FORWARD_INTENT_TO_PARENT; 5779 } 5780 ComponentName forwardingActivityComponentName = new ComponentName( 5781 mAndroidApplication.packageName, className); 5782 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5783 sourceUserId); 5784 if (!targetIsProfile) { 5785 forwardingActivityInfo.showUserIcon = targetUserId; 5786 forwardingResolveInfo.noResourceId = true; 5787 } 5788 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5789 forwardingResolveInfo.priority = 0; 5790 forwardingResolveInfo.preferredOrder = 0; 5791 forwardingResolveInfo.match = 0; 5792 forwardingResolveInfo.isDefault = true; 5793 forwardingResolveInfo.filter = filter; 5794 forwardingResolveInfo.targetUserId = targetUserId; 5795 return forwardingResolveInfo; 5796 } 5797 5798 @Override 5799 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5800 Intent[] specifics, String[] specificTypes, Intent intent, 5801 String resolvedType, int flags, int userId) { 5802 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5803 specificTypes, intent, resolvedType, flags, userId)); 5804 } 5805 5806 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5807 Intent[] specifics, String[] specificTypes, Intent intent, 5808 String resolvedType, int flags, int userId) { 5809 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5810 flags = updateFlagsForResolve(flags, userId, intent); 5811 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5812 false /* requireFullPermission */, false /* checkShell */, 5813 "query intent activity options"); 5814 final String resultsAction = intent.getAction(); 5815 5816 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5817 | PackageManager.GET_RESOLVED_FILTER, userId); 5818 5819 if (DEBUG_INTENT_MATCHING) { 5820 Log.v(TAG, "Query " + intent + ": " + results); 5821 } 5822 5823 int specificsPos = 0; 5824 int N; 5825 5826 // todo: note that the algorithm used here is O(N^2). This 5827 // isn't a problem in our current environment, but if we start running 5828 // into situations where we have more than 5 or 10 matches then this 5829 // should probably be changed to something smarter... 5830 5831 // First we go through and resolve each of the specific items 5832 // that were supplied, taking care of removing any corresponding 5833 // duplicate items in the generic resolve list. 5834 if (specifics != null) { 5835 for (int i=0; i<specifics.length; i++) { 5836 final Intent sintent = specifics[i]; 5837 if (sintent == null) { 5838 continue; 5839 } 5840 5841 if (DEBUG_INTENT_MATCHING) { 5842 Log.v(TAG, "Specific #" + i + ": " + sintent); 5843 } 5844 5845 String action = sintent.getAction(); 5846 if (resultsAction != null && resultsAction.equals(action)) { 5847 // If this action was explicitly requested, then don't 5848 // remove things that have it. 5849 action = null; 5850 } 5851 5852 ResolveInfo ri = null; 5853 ActivityInfo ai = null; 5854 5855 ComponentName comp = sintent.getComponent(); 5856 if (comp == null) { 5857 ri = resolveIntent( 5858 sintent, 5859 specificTypes != null ? specificTypes[i] : null, 5860 flags, userId); 5861 if (ri == null) { 5862 continue; 5863 } 5864 if (ri == mResolveInfo) { 5865 // ACK! Must do something better with this. 5866 } 5867 ai = ri.activityInfo; 5868 comp = new ComponentName(ai.applicationInfo.packageName, 5869 ai.name); 5870 } else { 5871 ai = getActivityInfo(comp, flags, userId); 5872 if (ai == null) { 5873 continue; 5874 } 5875 } 5876 5877 // Look for any generic query activities that are duplicates 5878 // of this specific one, and remove them from the results. 5879 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5880 N = results.size(); 5881 int j; 5882 for (j=specificsPos; j<N; j++) { 5883 ResolveInfo sri = results.get(j); 5884 if ((sri.activityInfo.name.equals(comp.getClassName()) 5885 && sri.activityInfo.applicationInfo.packageName.equals( 5886 comp.getPackageName())) 5887 || (action != null && sri.filter.matchAction(action))) { 5888 results.remove(j); 5889 if (DEBUG_INTENT_MATCHING) Log.v( 5890 TAG, "Removing duplicate item from " + j 5891 + " due to specific " + specificsPos); 5892 if (ri == null) { 5893 ri = sri; 5894 } 5895 j--; 5896 N--; 5897 } 5898 } 5899 5900 // Add this specific item to its proper place. 5901 if (ri == null) { 5902 ri = new ResolveInfo(); 5903 ri.activityInfo = ai; 5904 } 5905 results.add(specificsPos, ri); 5906 ri.specificIndex = i; 5907 specificsPos++; 5908 } 5909 } 5910 5911 // Now we go through the remaining generic results and remove any 5912 // duplicate actions that are found here. 5913 N = results.size(); 5914 for (int i=specificsPos; i<N-1; i++) { 5915 final ResolveInfo rii = results.get(i); 5916 if (rii.filter == null) { 5917 continue; 5918 } 5919 5920 // Iterate over all of the actions of this result's intent 5921 // filter... typically this should be just one. 5922 final Iterator<String> it = rii.filter.actionsIterator(); 5923 if (it == null) { 5924 continue; 5925 } 5926 while (it.hasNext()) { 5927 final String action = it.next(); 5928 if (resultsAction != null && resultsAction.equals(action)) { 5929 // If this action was explicitly requested, then don't 5930 // remove things that have it. 5931 continue; 5932 } 5933 for (int j=i+1; j<N; j++) { 5934 final ResolveInfo rij = results.get(j); 5935 if (rij.filter != null && rij.filter.hasAction(action)) { 5936 results.remove(j); 5937 if (DEBUG_INTENT_MATCHING) Log.v( 5938 TAG, "Removing duplicate item from " + j 5939 + " due to action " + action + " at " + i); 5940 j--; 5941 N--; 5942 } 5943 } 5944 } 5945 5946 // If the caller didn't request filter information, drop it now 5947 // so we don't have to marshall/unmarshall it. 5948 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5949 rii.filter = null; 5950 } 5951 } 5952 5953 // Filter out the caller activity if so requested. 5954 if (caller != null) { 5955 N = results.size(); 5956 for (int i=0; i<N; i++) { 5957 ActivityInfo ainfo = results.get(i).activityInfo; 5958 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5959 && caller.getClassName().equals(ainfo.name)) { 5960 results.remove(i); 5961 break; 5962 } 5963 } 5964 } 5965 5966 // If the caller didn't request filter information, 5967 // drop them now so we don't have to 5968 // marshall/unmarshall it. 5969 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5970 N = results.size(); 5971 for (int i=0; i<N; i++) { 5972 results.get(i).filter = null; 5973 } 5974 } 5975 5976 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5977 return results; 5978 } 5979 5980 @Override 5981 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5982 String resolvedType, int flags, int userId) { 5983 return new ParceledListSlice<>( 5984 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5985 } 5986 5987 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5988 String resolvedType, int flags, int userId) { 5989 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5990 flags = updateFlagsForResolve(flags, userId, intent); 5991 ComponentName comp = intent.getComponent(); 5992 if (comp == null) { 5993 if (intent.getSelector() != null) { 5994 intent = intent.getSelector(); 5995 comp = intent.getComponent(); 5996 } 5997 } 5998 if (comp != null) { 5999 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6000 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6001 if (ai != null) { 6002 ResolveInfo ri = new ResolveInfo(); 6003 ri.activityInfo = ai; 6004 list.add(ri); 6005 } 6006 return list; 6007 } 6008 6009 // reader 6010 synchronized (mPackages) { 6011 String pkgName = intent.getPackage(); 6012 if (pkgName == null) { 6013 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6014 } 6015 final PackageParser.Package pkg = mPackages.get(pkgName); 6016 if (pkg != null) { 6017 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6018 userId); 6019 } 6020 return Collections.emptyList(); 6021 } 6022 } 6023 6024 @Override 6025 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6026 if (!sUserManager.exists(userId)) return null; 6027 flags = updateFlagsForResolve(flags, userId, intent); 6028 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6029 if (query != null) { 6030 if (query.size() >= 1) { 6031 // If there is more than one service with the same priority, 6032 // just arbitrarily pick the first one. 6033 return query.get(0); 6034 } 6035 } 6036 return null; 6037 } 6038 6039 @Override 6040 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6041 String resolvedType, int flags, int userId) { 6042 return new ParceledListSlice<>( 6043 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6044 } 6045 6046 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6047 String resolvedType, int flags, int userId) { 6048 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6049 flags = updateFlagsForResolve(flags, userId, intent); 6050 ComponentName comp = intent.getComponent(); 6051 if (comp == null) { 6052 if (intent.getSelector() != null) { 6053 intent = intent.getSelector(); 6054 comp = intent.getComponent(); 6055 } 6056 } 6057 if (comp != null) { 6058 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6059 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6060 if (si != null) { 6061 final ResolveInfo ri = new ResolveInfo(); 6062 ri.serviceInfo = si; 6063 list.add(ri); 6064 } 6065 return list; 6066 } 6067 6068 // reader 6069 synchronized (mPackages) { 6070 String pkgName = intent.getPackage(); 6071 if (pkgName == null) { 6072 return mServices.queryIntent(intent, resolvedType, flags, userId); 6073 } 6074 final PackageParser.Package pkg = mPackages.get(pkgName); 6075 if (pkg != null) { 6076 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6077 userId); 6078 } 6079 return Collections.emptyList(); 6080 } 6081 } 6082 6083 @Override 6084 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6085 String resolvedType, int flags, int userId) { 6086 return new ParceledListSlice<>( 6087 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6088 } 6089 6090 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6091 Intent intent, String resolvedType, int flags, int userId) { 6092 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6093 flags = updateFlagsForResolve(flags, userId, intent); 6094 ComponentName comp = intent.getComponent(); 6095 if (comp == null) { 6096 if (intent.getSelector() != null) { 6097 intent = intent.getSelector(); 6098 comp = intent.getComponent(); 6099 } 6100 } 6101 if (comp != null) { 6102 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6103 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6104 if (pi != null) { 6105 final ResolveInfo ri = new ResolveInfo(); 6106 ri.providerInfo = pi; 6107 list.add(ri); 6108 } 6109 return list; 6110 } 6111 6112 // reader 6113 synchronized (mPackages) { 6114 String pkgName = intent.getPackage(); 6115 if (pkgName == null) { 6116 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6117 } 6118 final PackageParser.Package pkg = mPackages.get(pkgName); 6119 if (pkg != null) { 6120 return mProviders.queryIntentForPackage( 6121 intent, resolvedType, flags, pkg.providers, userId); 6122 } 6123 return Collections.emptyList(); 6124 } 6125 } 6126 6127 @Override 6128 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6129 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6130 flags = updateFlagsForPackage(flags, userId, null); 6131 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6132 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6133 true /* requireFullPermission */, false /* checkShell */, 6134 "get installed packages"); 6135 6136 // writer 6137 synchronized (mPackages) { 6138 ArrayList<PackageInfo> list; 6139 if (listUninstalled) { 6140 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6141 for (PackageSetting ps : mSettings.mPackages.values()) { 6142 final PackageInfo pi; 6143 if (ps.pkg != null) { 6144 pi = generatePackageInfo(ps, flags, userId); 6145 } else { 6146 pi = generatePackageInfo(ps, flags, userId); 6147 } 6148 if (pi != null) { 6149 list.add(pi); 6150 } 6151 } 6152 } else { 6153 list = new ArrayList<PackageInfo>(mPackages.size()); 6154 for (PackageParser.Package p : mPackages.values()) { 6155 final PackageInfo pi = 6156 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6157 if (pi != null) { 6158 list.add(pi); 6159 } 6160 } 6161 } 6162 6163 return new ParceledListSlice<PackageInfo>(list); 6164 } 6165 } 6166 6167 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6168 String[] permissions, boolean[] tmp, int flags, int userId) { 6169 int numMatch = 0; 6170 final PermissionsState permissionsState = ps.getPermissionsState(); 6171 for (int i=0; i<permissions.length; i++) { 6172 final String permission = permissions[i]; 6173 if (permissionsState.hasPermission(permission, userId)) { 6174 tmp[i] = true; 6175 numMatch++; 6176 } else { 6177 tmp[i] = false; 6178 } 6179 } 6180 if (numMatch == 0) { 6181 return; 6182 } 6183 final PackageInfo pi; 6184 if (ps.pkg != null) { 6185 pi = generatePackageInfo(ps, flags, userId); 6186 } else { 6187 pi = generatePackageInfo(ps, flags, userId); 6188 } 6189 // The above might return null in cases of uninstalled apps or install-state 6190 // skew across users/profiles. 6191 if (pi != null) { 6192 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6193 if (numMatch == permissions.length) { 6194 pi.requestedPermissions = permissions; 6195 } else { 6196 pi.requestedPermissions = new String[numMatch]; 6197 numMatch = 0; 6198 for (int i=0; i<permissions.length; i++) { 6199 if (tmp[i]) { 6200 pi.requestedPermissions[numMatch] = permissions[i]; 6201 numMatch++; 6202 } 6203 } 6204 } 6205 } 6206 list.add(pi); 6207 } 6208 } 6209 6210 @Override 6211 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6212 String[] permissions, int flags, int userId) { 6213 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6214 flags = updateFlagsForPackage(flags, userId, permissions); 6215 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6216 6217 // writer 6218 synchronized (mPackages) { 6219 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6220 boolean[] tmpBools = new boolean[permissions.length]; 6221 if (listUninstalled) { 6222 for (PackageSetting ps : mSettings.mPackages.values()) { 6223 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6224 } 6225 } else { 6226 for (PackageParser.Package pkg : mPackages.values()) { 6227 PackageSetting ps = (PackageSetting)pkg.mExtras; 6228 if (ps != null) { 6229 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6230 userId); 6231 } 6232 } 6233 } 6234 6235 return new ParceledListSlice<PackageInfo>(list); 6236 } 6237 } 6238 6239 @Override 6240 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6241 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6242 flags = updateFlagsForApplication(flags, userId, null); 6243 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6244 6245 // writer 6246 synchronized (mPackages) { 6247 ArrayList<ApplicationInfo> list; 6248 if (listUninstalled) { 6249 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6250 for (PackageSetting ps : mSettings.mPackages.values()) { 6251 ApplicationInfo ai; 6252 if (ps.pkg != null) { 6253 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6254 ps.readUserState(userId), userId); 6255 } else { 6256 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6257 } 6258 if (ai != null) { 6259 list.add(ai); 6260 } 6261 } 6262 } else { 6263 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6264 for (PackageParser.Package p : mPackages.values()) { 6265 if (p.mExtras != null) { 6266 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6267 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6268 if (ai != null) { 6269 list.add(ai); 6270 } 6271 } 6272 } 6273 } 6274 6275 return new ParceledListSlice<ApplicationInfo>(list); 6276 } 6277 } 6278 6279 @Override 6280 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6281 if (isEphemeralDisabled()) { 6282 return null; 6283 } 6284 6285 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6286 "getEphemeralApplications"); 6287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6288 true /* requireFullPermission */, false /* checkShell */, 6289 "getEphemeralApplications"); 6290 synchronized (mPackages) { 6291 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6292 .getEphemeralApplicationsLPw(userId); 6293 if (ephemeralApps != null) { 6294 return new ParceledListSlice<>(ephemeralApps); 6295 } 6296 } 6297 return null; 6298 } 6299 6300 @Override 6301 public boolean isEphemeralApplication(String packageName, int userId) { 6302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6303 true /* requireFullPermission */, false /* checkShell */, 6304 "isEphemeral"); 6305 if (isEphemeralDisabled()) { 6306 return false; 6307 } 6308 6309 if (!isCallerSameApp(packageName)) { 6310 return false; 6311 } 6312 synchronized (mPackages) { 6313 PackageParser.Package pkg = mPackages.get(packageName); 6314 if (pkg != null) { 6315 return pkg.applicationInfo.isEphemeralApp(); 6316 } 6317 } 6318 return false; 6319 } 6320 6321 @Override 6322 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6323 if (isEphemeralDisabled()) { 6324 return null; 6325 } 6326 6327 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6328 true /* requireFullPermission */, false /* checkShell */, 6329 "getCookie"); 6330 if (!isCallerSameApp(packageName)) { 6331 return null; 6332 } 6333 synchronized (mPackages) { 6334 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6335 packageName, userId); 6336 } 6337 } 6338 6339 @Override 6340 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6341 if (isEphemeralDisabled()) { 6342 return true; 6343 } 6344 6345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6346 true /* requireFullPermission */, true /* checkShell */, 6347 "setCookie"); 6348 if (!isCallerSameApp(packageName)) { 6349 return false; 6350 } 6351 synchronized (mPackages) { 6352 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6353 packageName, cookie, userId); 6354 } 6355 } 6356 6357 @Override 6358 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6359 if (isEphemeralDisabled()) { 6360 return null; 6361 } 6362 6363 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6364 "getEphemeralApplicationIcon"); 6365 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6366 true /* requireFullPermission */, false /* checkShell */, 6367 "getEphemeralApplicationIcon"); 6368 synchronized (mPackages) { 6369 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6370 packageName, userId); 6371 } 6372 } 6373 6374 private boolean isCallerSameApp(String packageName) { 6375 PackageParser.Package pkg = mPackages.get(packageName); 6376 return pkg != null 6377 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6378 } 6379 6380 @Override 6381 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6382 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6383 } 6384 6385 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6386 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6387 6388 // reader 6389 synchronized (mPackages) { 6390 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6391 final int userId = UserHandle.getCallingUserId(); 6392 while (i.hasNext()) { 6393 final PackageParser.Package p = i.next(); 6394 if (p.applicationInfo == null) continue; 6395 6396 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6397 && !p.applicationInfo.isDirectBootAware(); 6398 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6399 && p.applicationInfo.isDirectBootAware(); 6400 6401 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6402 && (!mSafeMode || isSystemApp(p)) 6403 && (matchesUnaware || matchesAware)) { 6404 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6405 if (ps != null) { 6406 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6407 ps.readUserState(userId), userId); 6408 if (ai != null) { 6409 finalList.add(ai); 6410 } 6411 } 6412 } 6413 } 6414 } 6415 6416 return finalList; 6417 } 6418 6419 @Override 6420 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6421 if (!sUserManager.exists(userId)) return null; 6422 flags = updateFlagsForComponent(flags, userId, name); 6423 // reader 6424 synchronized (mPackages) { 6425 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6426 PackageSetting ps = provider != null 6427 ? mSettings.mPackages.get(provider.owner.packageName) 6428 : null; 6429 return ps != null 6430 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6431 ? PackageParser.generateProviderInfo(provider, flags, 6432 ps.readUserState(userId), userId) 6433 : null; 6434 } 6435 } 6436 6437 /** 6438 * @deprecated 6439 */ 6440 @Deprecated 6441 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6442 // reader 6443 synchronized (mPackages) { 6444 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6445 .entrySet().iterator(); 6446 final int userId = UserHandle.getCallingUserId(); 6447 while (i.hasNext()) { 6448 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6449 PackageParser.Provider p = entry.getValue(); 6450 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6451 6452 if (ps != null && p.syncable 6453 && (!mSafeMode || (p.info.applicationInfo.flags 6454 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6455 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6456 ps.readUserState(userId), userId); 6457 if (info != null) { 6458 outNames.add(entry.getKey()); 6459 outInfo.add(info); 6460 } 6461 } 6462 } 6463 } 6464 } 6465 6466 @Override 6467 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6468 int uid, int flags) { 6469 final int userId = processName != null ? UserHandle.getUserId(uid) 6470 : UserHandle.getCallingUserId(); 6471 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6472 flags = updateFlagsForComponent(flags, userId, processName); 6473 6474 ArrayList<ProviderInfo> finalList = null; 6475 // reader 6476 synchronized (mPackages) { 6477 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6478 while (i.hasNext()) { 6479 final PackageParser.Provider p = i.next(); 6480 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6481 if (ps != null && p.info.authority != null 6482 && (processName == null 6483 || (p.info.processName.equals(processName) 6484 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6485 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6486 if (finalList == null) { 6487 finalList = new ArrayList<ProviderInfo>(3); 6488 } 6489 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6490 ps.readUserState(userId), userId); 6491 if (info != null) { 6492 finalList.add(info); 6493 } 6494 } 6495 } 6496 } 6497 6498 if (finalList != null) { 6499 Collections.sort(finalList, mProviderInitOrderSorter); 6500 return new ParceledListSlice<ProviderInfo>(finalList); 6501 } 6502 6503 return ParceledListSlice.emptyList(); 6504 } 6505 6506 @Override 6507 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6508 // reader 6509 synchronized (mPackages) { 6510 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6511 return PackageParser.generateInstrumentationInfo(i, flags); 6512 } 6513 } 6514 6515 @Override 6516 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6517 String targetPackage, int flags) { 6518 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6519 } 6520 6521 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6522 int flags) { 6523 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6524 6525 // reader 6526 synchronized (mPackages) { 6527 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6528 while (i.hasNext()) { 6529 final PackageParser.Instrumentation p = i.next(); 6530 if (targetPackage == null 6531 || targetPackage.equals(p.info.targetPackage)) { 6532 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6533 flags); 6534 if (ii != null) { 6535 finalList.add(ii); 6536 } 6537 } 6538 } 6539 } 6540 6541 return finalList; 6542 } 6543 6544 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6545 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6546 if (overlays == null) { 6547 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6548 return; 6549 } 6550 for (PackageParser.Package opkg : overlays.values()) { 6551 // Not much to do if idmap fails: we already logged the error 6552 // and we certainly don't want to abort installation of pkg simply 6553 // because an overlay didn't fit properly. For these reasons, 6554 // ignore the return value of createIdmapForPackagePairLI. 6555 createIdmapForPackagePairLI(pkg, opkg); 6556 } 6557 } 6558 6559 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6560 PackageParser.Package opkg) { 6561 if (!opkg.mTrustedOverlay) { 6562 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6563 opkg.baseCodePath + ": overlay not trusted"); 6564 return false; 6565 } 6566 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6567 if (overlaySet == null) { 6568 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6569 opkg.baseCodePath + " but target package has no known overlays"); 6570 return false; 6571 } 6572 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6573 // TODO: generate idmap for split APKs 6574 try { 6575 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6576 } catch (InstallerException e) { 6577 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6578 + opkg.baseCodePath); 6579 return false; 6580 } 6581 PackageParser.Package[] overlayArray = 6582 overlaySet.values().toArray(new PackageParser.Package[0]); 6583 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6584 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6585 return p1.mOverlayPriority - p2.mOverlayPriority; 6586 } 6587 }; 6588 Arrays.sort(overlayArray, cmp); 6589 6590 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6591 int i = 0; 6592 for (PackageParser.Package p : overlayArray) { 6593 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6594 } 6595 return true; 6596 } 6597 6598 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6599 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6600 try { 6601 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6602 } finally { 6603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6604 } 6605 } 6606 6607 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6608 final File[] files = dir.listFiles(); 6609 if (ArrayUtils.isEmpty(files)) { 6610 Log.d(TAG, "No files in app dir " + dir); 6611 return; 6612 } 6613 6614 if (DEBUG_PACKAGE_SCANNING) { 6615 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6616 + " flags=0x" + Integer.toHexString(parseFlags)); 6617 } 6618 6619 for (File file : files) { 6620 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6621 && !PackageInstallerService.isStageName(file.getName()); 6622 if (!isPackage) { 6623 // Ignore entries which are not packages 6624 continue; 6625 } 6626 try { 6627 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6628 scanFlags, currentTime, null); 6629 } catch (PackageManagerException e) { 6630 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6631 6632 // Delete invalid userdata apps 6633 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6634 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6635 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6636 removeCodePathLI(file); 6637 } 6638 } 6639 } 6640 } 6641 6642 private static File getSettingsProblemFile() { 6643 File dataDir = Environment.getDataDirectory(); 6644 File systemDir = new File(dataDir, "system"); 6645 File fname = new File(systemDir, "uiderrors.txt"); 6646 return fname; 6647 } 6648 6649 static void reportSettingsProblem(int priority, String msg) { 6650 logCriticalInfo(priority, msg); 6651 } 6652 6653 static void logCriticalInfo(int priority, String msg) { 6654 Slog.println(priority, TAG, msg); 6655 EventLogTags.writePmCriticalInfo(msg); 6656 try { 6657 File fname = getSettingsProblemFile(); 6658 FileOutputStream out = new FileOutputStream(fname, true); 6659 PrintWriter pw = new FastPrintWriter(out); 6660 SimpleDateFormat formatter = new SimpleDateFormat(); 6661 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6662 pw.println(dateString + ": " + msg); 6663 pw.close(); 6664 FileUtils.setPermissions( 6665 fname.toString(), 6666 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6667 -1, -1); 6668 } catch (java.io.IOException e) { 6669 } 6670 } 6671 6672 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6673 if (srcFile.isDirectory()) { 6674 final File baseFile = new File(pkg.baseCodePath); 6675 long maxModifiedTime = baseFile.lastModified(); 6676 if (pkg.splitCodePaths != null) { 6677 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6678 final File splitFile = new File(pkg.splitCodePaths[i]); 6679 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6680 } 6681 } 6682 return maxModifiedTime; 6683 } 6684 return srcFile.lastModified(); 6685 } 6686 6687 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6688 final int policyFlags) throws PackageManagerException { 6689 // When upgrading from pre-N MR1, verify the package time stamp using the package 6690 // directory and not the APK file. 6691 final long lastModifiedTime = mIsPreNMR1Upgrade 6692 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6693 if (ps != null 6694 && ps.codePath.equals(srcFile) 6695 && ps.timeStamp == lastModifiedTime 6696 && !isCompatSignatureUpdateNeeded(pkg) 6697 && !isRecoverSignatureUpdateNeeded(pkg)) { 6698 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6699 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6700 ArraySet<PublicKey> signingKs; 6701 synchronized (mPackages) { 6702 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6703 } 6704 if (ps.signatures.mSignatures != null 6705 && ps.signatures.mSignatures.length != 0 6706 && signingKs != null) { 6707 // Optimization: reuse the existing cached certificates 6708 // if the package appears to be unchanged. 6709 pkg.mSignatures = ps.signatures.mSignatures; 6710 pkg.mSigningKeys = signingKs; 6711 return; 6712 } 6713 6714 Slog.w(TAG, "PackageSetting for " + ps.name 6715 + " is missing signatures. Collecting certs again to recover them."); 6716 } else { 6717 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6718 } 6719 6720 try { 6721 PackageParser.collectCertificates(pkg, policyFlags); 6722 } catch (PackageParserException e) { 6723 throw PackageManagerException.from(e); 6724 } 6725 } 6726 6727 /** 6728 * Traces a package scan. 6729 * @see #scanPackageLI(File, int, int, long, UserHandle) 6730 */ 6731 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6732 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6733 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6734 try { 6735 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6736 } finally { 6737 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6738 } 6739 } 6740 6741 /** 6742 * Scans a package and returns the newly parsed package. 6743 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6744 */ 6745 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6746 long currentTime, UserHandle user) throws PackageManagerException { 6747 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6748 PackageParser pp = new PackageParser(); 6749 pp.setSeparateProcesses(mSeparateProcesses); 6750 pp.setOnlyCoreApps(mOnlyCore); 6751 pp.setDisplayMetrics(mMetrics); 6752 6753 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6754 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6755 } 6756 6757 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6758 final PackageParser.Package pkg; 6759 try { 6760 pkg = pp.parsePackage(scanFile, parseFlags); 6761 } catch (PackageParserException e) { 6762 throw PackageManagerException.from(e); 6763 } finally { 6764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6765 } 6766 6767 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6768 } 6769 6770 /** 6771 * Scans a package and returns the newly parsed package. 6772 * @throws PackageManagerException on a parse error. 6773 */ 6774 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6775 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6776 throws PackageManagerException { 6777 // If the package has children and this is the first dive in the function 6778 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6779 // packages (parent and children) would be successfully scanned before the 6780 // actual scan since scanning mutates internal state and we want to atomically 6781 // install the package and its children. 6782 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6783 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6784 scanFlags |= SCAN_CHECK_ONLY; 6785 } 6786 } else { 6787 scanFlags &= ~SCAN_CHECK_ONLY; 6788 } 6789 6790 // Scan the parent 6791 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6792 scanFlags, currentTime, user); 6793 6794 // Scan the children 6795 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6796 for (int i = 0; i < childCount; i++) { 6797 PackageParser.Package childPackage = pkg.childPackages.get(i); 6798 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6799 currentTime, user); 6800 } 6801 6802 6803 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6804 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6805 } 6806 6807 return scannedPkg; 6808 } 6809 6810 /** 6811 * Scans a package and returns the newly parsed package. 6812 * @throws PackageManagerException on a parse error. 6813 */ 6814 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6815 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6816 throws PackageManagerException { 6817 PackageSetting ps = null; 6818 PackageSetting updatedPkg; 6819 // reader 6820 synchronized (mPackages) { 6821 // Look to see if we already know about this package. 6822 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6823 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6824 // This package has been renamed to its original name. Let's 6825 // use that. 6826 ps = mSettings.peekPackageLPr(oldName); 6827 } 6828 // If there was no original package, see one for the real package name. 6829 if (ps == null) { 6830 ps = mSettings.peekPackageLPr(pkg.packageName); 6831 } 6832 // Check to see if this package could be hiding/updating a system 6833 // package. Must look for it either under the original or real 6834 // package name depending on our state. 6835 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6836 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6837 6838 // If this is a package we don't know about on the system partition, we 6839 // may need to remove disabled child packages on the system partition 6840 // or may need to not add child packages if the parent apk is updated 6841 // on the data partition and no longer defines this child package. 6842 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6843 // If this is a parent package for an updated system app and this system 6844 // app got an OTA update which no longer defines some of the child packages 6845 // we have to prune them from the disabled system packages. 6846 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6847 if (disabledPs != null) { 6848 final int scannedChildCount = (pkg.childPackages != null) 6849 ? pkg.childPackages.size() : 0; 6850 final int disabledChildCount = disabledPs.childPackageNames != null 6851 ? disabledPs.childPackageNames.size() : 0; 6852 for (int i = 0; i < disabledChildCount; i++) { 6853 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6854 boolean disabledPackageAvailable = false; 6855 for (int j = 0; j < scannedChildCount; j++) { 6856 PackageParser.Package childPkg = pkg.childPackages.get(j); 6857 if (childPkg.packageName.equals(disabledChildPackageName)) { 6858 disabledPackageAvailable = true; 6859 break; 6860 } 6861 } 6862 if (!disabledPackageAvailable) { 6863 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6864 } 6865 } 6866 } 6867 } 6868 } 6869 6870 boolean updatedPkgBetter = false; 6871 // First check if this is a system package that may involve an update 6872 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6873 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6874 // it needs to drop FLAG_PRIVILEGED. 6875 if (locationIsPrivileged(scanFile)) { 6876 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6877 } else { 6878 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6879 } 6880 6881 if (ps != null && !ps.codePath.equals(scanFile)) { 6882 // The path has changed from what was last scanned... check the 6883 // version of the new path against what we have stored to determine 6884 // what to do. 6885 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6886 if (pkg.mVersionCode <= ps.versionCode) { 6887 // The system package has been updated and the code path does not match 6888 // Ignore entry. Skip it. 6889 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6890 + " ignored: updated version " + ps.versionCode 6891 + " better than this " + pkg.mVersionCode); 6892 if (!updatedPkg.codePath.equals(scanFile)) { 6893 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6894 + ps.name + " changing from " + updatedPkg.codePathString 6895 + " to " + scanFile); 6896 updatedPkg.codePath = scanFile; 6897 updatedPkg.codePathString = scanFile.toString(); 6898 updatedPkg.resourcePath = scanFile; 6899 updatedPkg.resourcePathString = scanFile.toString(); 6900 } 6901 updatedPkg.pkg = pkg; 6902 updatedPkg.versionCode = pkg.mVersionCode; 6903 6904 // Update the disabled system child packages to point to the package too. 6905 final int childCount = updatedPkg.childPackageNames != null 6906 ? updatedPkg.childPackageNames.size() : 0; 6907 for (int i = 0; i < childCount; i++) { 6908 String childPackageName = updatedPkg.childPackageNames.get(i); 6909 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6910 childPackageName); 6911 if (updatedChildPkg != null) { 6912 updatedChildPkg.pkg = pkg; 6913 updatedChildPkg.versionCode = pkg.mVersionCode; 6914 } 6915 } 6916 6917 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6918 + scanFile + " ignored: updated version " + ps.versionCode 6919 + " better than this " + pkg.mVersionCode); 6920 } else { 6921 // The current app on the system partition is better than 6922 // what we have updated to on the data partition; switch 6923 // back to the system partition version. 6924 // At this point, its safely assumed that package installation for 6925 // apps in system partition will go through. If not there won't be a working 6926 // version of the app 6927 // writer 6928 synchronized (mPackages) { 6929 // Just remove the loaded entries from package lists. 6930 mPackages.remove(ps.name); 6931 } 6932 6933 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6934 + " reverting from " + ps.codePathString 6935 + ": new version " + pkg.mVersionCode 6936 + " better than installed " + ps.versionCode); 6937 6938 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6939 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6940 synchronized (mInstallLock) { 6941 args.cleanUpResourcesLI(); 6942 } 6943 synchronized (mPackages) { 6944 mSettings.enableSystemPackageLPw(ps.name); 6945 } 6946 updatedPkgBetter = true; 6947 } 6948 } 6949 } 6950 6951 if (updatedPkg != null) { 6952 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6953 // initially 6954 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6955 6956 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6957 // flag set initially 6958 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6959 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6960 } 6961 } 6962 6963 // Verify certificates against what was last scanned 6964 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6965 6966 /* 6967 * A new system app appeared, but we already had a non-system one of the 6968 * same name installed earlier. 6969 */ 6970 boolean shouldHideSystemApp = false; 6971 if (updatedPkg == null && ps != null 6972 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6973 /* 6974 * Check to make sure the signatures match first. If they don't, 6975 * wipe the installed application and its data. 6976 */ 6977 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6978 != PackageManager.SIGNATURE_MATCH) { 6979 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6980 + " signatures don't match existing userdata copy; removing"); 6981 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6982 "scanPackageInternalLI")) { 6983 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6984 } 6985 ps = null; 6986 } else { 6987 /* 6988 * If the newly-added system app is an older version than the 6989 * already installed version, hide it. It will be scanned later 6990 * and re-added like an update. 6991 */ 6992 if (pkg.mVersionCode <= ps.versionCode) { 6993 shouldHideSystemApp = true; 6994 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6995 + " but new version " + pkg.mVersionCode + " better than installed " 6996 + ps.versionCode + "; hiding system"); 6997 } else { 6998 /* 6999 * The newly found system app is a newer version that the 7000 * one previously installed. Simply remove the 7001 * already-installed application and replace it with our own 7002 * while keeping the application data. 7003 */ 7004 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7005 + " reverting from " + ps.codePathString + ": new version " 7006 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7007 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7008 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7009 synchronized (mInstallLock) { 7010 args.cleanUpResourcesLI(); 7011 } 7012 } 7013 } 7014 } 7015 7016 // The apk is forward locked (not public) if its code and resources 7017 // are kept in different files. (except for app in either system or 7018 // vendor path). 7019 // TODO grab this value from PackageSettings 7020 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7021 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7022 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7023 } 7024 } 7025 7026 // TODO: extend to support forward-locked splits 7027 String resourcePath = null; 7028 String baseResourcePath = null; 7029 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7030 if (ps != null && ps.resourcePathString != null) { 7031 resourcePath = ps.resourcePathString; 7032 baseResourcePath = ps.resourcePathString; 7033 } else { 7034 // Should not happen at all. Just log an error. 7035 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7036 } 7037 } else { 7038 resourcePath = pkg.codePath; 7039 baseResourcePath = pkg.baseCodePath; 7040 } 7041 7042 // Set application objects path explicitly. 7043 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7044 pkg.setApplicationInfoCodePath(pkg.codePath); 7045 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7046 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7047 pkg.setApplicationInfoResourcePath(resourcePath); 7048 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7049 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7050 7051 // Note that we invoke the following method only if we are about to unpack an application 7052 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7053 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7054 7055 /* 7056 * If the system app should be overridden by a previously installed 7057 * data, hide the system app now and let the /data/app scan pick it up 7058 * again. 7059 */ 7060 if (shouldHideSystemApp) { 7061 synchronized (mPackages) { 7062 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7063 } 7064 } 7065 7066 return scannedPkg; 7067 } 7068 7069 private static String fixProcessName(String defProcessName, 7070 String processName, int uid) { 7071 if (processName == null) { 7072 return defProcessName; 7073 } 7074 return processName; 7075 } 7076 7077 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7078 throws PackageManagerException { 7079 if (pkgSetting.signatures.mSignatures != null) { 7080 // Already existing package. Make sure signatures match 7081 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7082 == PackageManager.SIGNATURE_MATCH; 7083 if (!match) { 7084 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7085 == PackageManager.SIGNATURE_MATCH; 7086 } 7087 if (!match) { 7088 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7089 == PackageManager.SIGNATURE_MATCH; 7090 } 7091 if (!match) { 7092 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7093 + pkg.packageName + " signatures do not match the " 7094 + "previously installed version; ignoring!"); 7095 } 7096 } 7097 7098 // Check for shared user signatures 7099 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7100 // Already existing package. Make sure signatures match 7101 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7102 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7103 if (!match) { 7104 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7105 == PackageManager.SIGNATURE_MATCH; 7106 } 7107 if (!match) { 7108 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7109 == PackageManager.SIGNATURE_MATCH; 7110 } 7111 if (!match) { 7112 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7113 "Package " + pkg.packageName 7114 + " has no signatures that match those in shared user " 7115 + pkgSetting.sharedUser.name + "; ignoring!"); 7116 } 7117 } 7118 } 7119 7120 /** 7121 * Enforces that only the system UID or root's UID can call a method exposed 7122 * via Binder. 7123 * 7124 * @param message used as message if SecurityException is thrown 7125 * @throws SecurityException if the caller is not system or root 7126 */ 7127 private static final void enforceSystemOrRoot(String message) { 7128 final int uid = Binder.getCallingUid(); 7129 if (uid != Process.SYSTEM_UID && uid != 0) { 7130 throw new SecurityException(message); 7131 } 7132 } 7133 7134 @Override 7135 public void performFstrimIfNeeded() { 7136 enforceSystemOrRoot("Only the system can request fstrim"); 7137 7138 // Before everything else, see whether we need to fstrim. 7139 try { 7140 IMountService ms = PackageHelper.getMountService(); 7141 if (ms != null) { 7142 boolean doTrim = false; 7143 final long interval = android.provider.Settings.Global.getLong( 7144 mContext.getContentResolver(), 7145 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7146 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7147 if (interval > 0) { 7148 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7149 if (timeSinceLast > interval) { 7150 doTrim = true; 7151 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7152 + "; running immediately"); 7153 } 7154 } 7155 if (doTrim) { 7156 final boolean dexOptDialogShown; 7157 synchronized (mPackages) { 7158 dexOptDialogShown = mDexOptDialogShown; 7159 } 7160 if (!isFirstBoot() && dexOptDialogShown) { 7161 try { 7162 ActivityManagerNative.getDefault().showBootMessage( 7163 mContext.getResources().getString( 7164 R.string.android_upgrading_fstrim), true); 7165 } catch (RemoteException e) { 7166 } 7167 } 7168 ms.runMaintenance(); 7169 } 7170 } else { 7171 Slog.e(TAG, "Mount service unavailable!"); 7172 } 7173 } catch (RemoteException e) { 7174 // Can't happen; MountService is local 7175 } 7176 } 7177 7178 @Override 7179 public void updatePackagesIfNeeded() { 7180 enforceSystemOrRoot("Only the system can request package update"); 7181 7182 // We need to re-extract after an OTA. 7183 boolean causeUpgrade = isUpgrade(); 7184 7185 // First boot or factory reset. 7186 // Note: we also handle devices that are upgrading to N right now as if it is their 7187 // first boot, as they do not have profile data. 7188 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7189 7190 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7191 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7192 7193 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7194 return; 7195 } 7196 7197 List<PackageParser.Package> pkgs; 7198 synchronized (mPackages) { 7199 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7200 } 7201 7202 final long startTime = System.nanoTime(); 7203 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7204 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7205 7206 final int elapsedTimeSeconds = 7207 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7208 7209 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7210 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7211 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7212 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7213 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7214 } 7215 7216 /** 7217 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7218 * containing statistics about the invocation. The array consists of three elements, 7219 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7220 * and {@code numberOfPackagesFailed}. 7221 */ 7222 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7223 String compilerFilter) { 7224 7225 int numberOfPackagesVisited = 0; 7226 int numberOfPackagesOptimized = 0; 7227 int numberOfPackagesSkipped = 0; 7228 int numberOfPackagesFailed = 0; 7229 final int numberOfPackagesToDexopt = pkgs.size(); 7230 7231 for (PackageParser.Package pkg : pkgs) { 7232 numberOfPackagesVisited++; 7233 7234 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7235 if (DEBUG_DEXOPT) { 7236 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7237 } 7238 numberOfPackagesSkipped++; 7239 continue; 7240 } 7241 7242 if (DEBUG_DEXOPT) { 7243 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7244 numberOfPackagesToDexopt + ": " + pkg.packageName); 7245 } 7246 7247 if (showDialog) { 7248 try { 7249 ActivityManagerNative.getDefault().showBootMessage( 7250 mContext.getResources().getString(R.string.android_upgrading_apk, 7251 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7252 } catch (RemoteException e) { 7253 } 7254 synchronized (mPackages) { 7255 mDexOptDialogShown = true; 7256 } 7257 } 7258 7259 // If the OTA updates a system app which was previously preopted to a non-preopted state 7260 // the app might end up being verified at runtime. That's because by default the apps 7261 // are verify-profile but for preopted apps there's no profile. 7262 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7263 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7264 // filter (by default interpret-only). 7265 // Note that at this stage unused apps are already filtered. 7266 if (isSystemApp(pkg) && 7267 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7268 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7269 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7270 } 7271 7272 // checkProfiles is false to avoid merging profiles during boot which 7273 // might interfere with background compilation (b/28612421). 7274 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7275 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7276 // trade-off worth doing to save boot time work. 7277 int dexOptStatus = performDexOptTraced(pkg.packageName, 7278 false /* checkProfiles */, 7279 compilerFilter, 7280 false /* force */); 7281 switch (dexOptStatus) { 7282 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7283 numberOfPackagesOptimized++; 7284 break; 7285 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7286 numberOfPackagesSkipped++; 7287 break; 7288 case PackageDexOptimizer.DEX_OPT_FAILED: 7289 numberOfPackagesFailed++; 7290 break; 7291 default: 7292 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7293 break; 7294 } 7295 } 7296 7297 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7298 numberOfPackagesFailed }; 7299 } 7300 7301 @Override 7302 public void notifyPackageUse(String packageName, int reason) { 7303 synchronized (mPackages) { 7304 PackageParser.Package p = mPackages.get(packageName); 7305 if (p == null) { 7306 return; 7307 } 7308 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7309 } 7310 } 7311 7312 // TODO: this is not used nor needed. Delete it. 7313 @Override 7314 public boolean performDexOptIfNeeded(String packageName) { 7315 int dexOptStatus = performDexOptTraced(packageName, 7316 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7317 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7318 } 7319 7320 @Override 7321 public boolean performDexOpt(String packageName, 7322 boolean checkProfiles, int compileReason, boolean force) { 7323 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7324 getCompilerFilterForReason(compileReason), force); 7325 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7326 } 7327 7328 @Override 7329 public boolean performDexOptMode(String packageName, 7330 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7331 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7332 targetCompilerFilter, force); 7333 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7334 } 7335 7336 private int performDexOptTraced(String packageName, 7337 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7338 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7339 try { 7340 return performDexOptInternal(packageName, checkProfiles, 7341 targetCompilerFilter, force); 7342 } finally { 7343 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7344 } 7345 } 7346 7347 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7348 // if the package can now be considered up to date for the given filter. 7349 private int performDexOptInternal(String packageName, 7350 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7351 PackageParser.Package p; 7352 synchronized (mPackages) { 7353 p = mPackages.get(packageName); 7354 if (p == null) { 7355 // Package could not be found. Report failure. 7356 return PackageDexOptimizer.DEX_OPT_FAILED; 7357 } 7358 mPackageUsage.maybeWriteAsync(mPackages); 7359 mCompilerStats.maybeWriteAsync(); 7360 } 7361 long callingId = Binder.clearCallingIdentity(); 7362 try { 7363 synchronized (mInstallLock) { 7364 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7365 targetCompilerFilter, force); 7366 } 7367 } finally { 7368 Binder.restoreCallingIdentity(callingId); 7369 } 7370 } 7371 7372 public ArraySet<String> getOptimizablePackages() { 7373 ArraySet<String> pkgs = new ArraySet<String>(); 7374 synchronized (mPackages) { 7375 for (PackageParser.Package p : mPackages.values()) { 7376 if (PackageDexOptimizer.canOptimizePackage(p)) { 7377 pkgs.add(p.packageName); 7378 } 7379 } 7380 } 7381 return pkgs; 7382 } 7383 7384 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7385 boolean checkProfiles, String targetCompilerFilter, 7386 boolean force) { 7387 // Select the dex optimizer based on the force parameter. 7388 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7389 // allocate an object here. 7390 PackageDexOptimizer pdo = force 7391 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7392 : mPackageDexOptimizer; 7393 7394 // Optimize all dependencies first. Note: we ignore the return value and march on 7395 // on errors. 7396 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7397 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7398 if (!deps.isEmpty()) { 7399 for (PackageParser.Package depPackage : deps) { 7400 // TODO: Analyze and investigate if we (should) profile libraries. 7401 // Currently this will do a full compilation of the library by default. 7402 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7403 false /* checkProfiles */, 7404 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7405 getOrCreateCompilerPackageStats(depPackage)); 7406 } 7407 } 7408 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7409 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7410 } 7411 7412 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7413 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7414 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7415 Set<String> collectedNames = new HashSet<>(); 7416 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7417 7418 retValue.remove(p); 7419 7420 return retValue; 7421 } else { 7422 return Collections.emptyList(); 7423 } 7424 } 7425 7426 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7427 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7428 if (!collectedNames.contains(p.packageName)) { 7429 collectedNames.add(p.packageName); 7430 collected.add(p); 7431 7432 if (p.usesLibraries != null) { 7433 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7434 } 7435 if (p.usesOptionalLibraries != null) { 7436 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7437 collectedNames); 7438 } 7439 } 7440 } 7441 7442 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7443 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7444 for (String libName : libs) { 7445 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7446 if (libPkg != null) { 7447 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7448 } 7449 } 7450 } 7451 7452 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7453 synchronized (mPackages) { 7454 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7455 if (lib != null && lib.apk != null) { 7456 return mPackages.get(lib.apk); 7457 } 7458 } 7459 return null; 7460 } 7461 7462 public void shutdown() { 7463 mPackageUsage.writeNow(mPackages); 7464 mCompilerStats.writeNow(); 7465 } 7466 7467 @Override 7468 public void dumpProfiles(String packageName) { 7469 PackageParser.Package pkg; 7470 synchronized (mPackages) { 7471 pkg = mPackages.get(packageName); 7472 if (pkg == null) { 7473 throw new IllegalArgumentException("Unknown package: " + packageName); 7474 } 7475 } 7476 /* Only the shell, root, or the app user should be able to dump profiles. */ 7477 int callingUid = Binder.getCallingUid(); 7478 if (callingUid != Process.SHELL_UID && 7479 callingUid != Process.ROOT_UID && 7480 callingUid != pkg.applicationInfo.uid) { 7481 throw new SecurityException("dumpProfiles"); 7482 } 7483 7484 synchronized (mInstallLock) { 7485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7486 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7487 try { 7488 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7489 String gid = Integer.toString(sharedGid); 7490 String codePaths = TextUtils.join(";", allCodePaths); 7491 mInstaller.dumpProfiles(gid, packageName, codePaths); 7492 } catch (InstallerException e) { 7493 Slog.w(TAG, "Failed to dump profiles", e); 7494 } 7495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7496 } 7497 } 7498 7499 @Override 7500 public void forceDexOpt(String packageName) { 7501 enforceSystemOrRoot("forceDexOpt"); 7502 7503 PackageParser.Package pkg; 7504 synchronized (mPackages) { 7505 pkg = mPackages.get(packageName); 7506 if (pkg == null) { 7507 throw new IllegalArgumentException("Unknown package: " + packageName); 7508 } 7509 } 7510 7511 synchronized (mInstallLock) { 7512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7513 7514 // Whoever is calling forceDexOpt wants a fully compiled package. 7515 // Don't use profiles since that may cause compilation to be skipped. 7516 final int res = performDexOptInternalWithDependenciesLI(pkg, 7517 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7518 true /* force */); 7519 7520 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7521 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7522 throw new IllegalStateException("Failed to dexopt: " + res); 7523 } 7524 } 7525 } 7526 7527 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7528 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7529 Slog.w(TAG, "Unable to update from " + oldPkg.name 7530 + " to " + newPkg.packageName 7531 + ": old package not in system partition"); 7532 return false; 7533 } else if (mPackages.get(oldPkg.name) != null) { 7534 Slog.w(TAG, "Unable to update from " + oldPkg.name 7535 + " to " + newPkg.packageName 7536 + ": old package still exists"); 7537 return false; 7538 } 7539 return true; 7540 } 7541 7542 void removeCodePathLI(File codePath) { 7543 if (codePath.isDirectory()) { 7544 try { 7545 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7546 } catch (InstallerException e) { 7547 Slog.w(TAG, "Failed to remove code path", e); 7548 } 7549 } else { 7550 codePath.delete(); 7551 } 7552 } 7553 7554 private int[] resolveUserIds(int userId) { 7555 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7556 } 7557 7558 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7559 if (pkg == null) { 7560 Slog.wtf(TAG, "Package was null!", new Throwable()); 7561 return; 7562 } 7563 clearAppDataLeafLIF(pkg, userId, flags); 7564 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7565 for (int i = 0; i < childCount; i++) { 7566 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7567 } 7568 } 7569 7570 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7571 final PackageSetting ps; 7572 synchronized (mPackages) { 7573 ps = mSettings.mPackages.get(pkg.packageName); 7574 } 7575 for (int realUserId : resolveUserIds(userId)) { 7576 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7577 try { 7578 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7579 ceDataInode); 7580 } catch (InstallerException e) { 7581 Slog.w(TAG, String.valueOf(e)); 7582 } 7583 } 7584 } 7585 7586 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7587 if (pkg == null) { 7588 Slog.wtf(TAG, "Package was null!", new Throwable()); 7589 return; 7590 } 7591 destroyAppDataLeafLIF(pkg, userId, flags); 7592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7593 for (int i = 0; i < childCount; i++) { 7594 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7595 } 7596 } 7597 7598 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7599 final PackageSetting ps; 7600 synchronized (mPackages) { 7601 ps = mSettings.mPackages.get(pkg.packageName); 7602 } 7603 for (int realUserId : resolveUserIds(userId)) { 7604 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7605 try { 7606 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7607 ceDataInode); 7608 } catch (InstallerException e) { 7609 Slog.w(TAG, String.valueOf(e)); 7610 } 7611 } 7612 } 7613 7614 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7615 if (pkg == null) { 7616 Slog.wtf(TAG, "Package was null!", new Throwable()); 7617 return; 7618 } 7619 destroyAppProfilesLeafLIF(pkg); 7620 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7621 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7622 for (int i = 0; i < childCount; i++) { 7623 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7624 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7625 true /* removeBaseMarker */); 7626 } 7627 } 7628 7629 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7630 boolean removeBaseMarker) { 7631 if (pkg.isForwardLocked()) { 7632 return; 7633 } 7634 7635 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7636 try { 7637 path = PackageManagerServiceUtils.realpath(new File(path)); 7638 } catch (IOException e) { 7639 // TODO: Should we return early here ? 7640 Slog.w(TAG, "Failed to get canonical path", e); 7641 continue; 7642 } 7643 7644 final String useMarker = path.replace('/', '@'); 7645 for (int realUserId : resolveUserIds(userId)) { 7646 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7647 if (removeBaseMarker) { 7648 File foreignUseMark = new File(profileDir, useMarker); 7649 if (foreignUseMark.exists()) { 7650 if (!foreignUseMark.delete()) { 7651 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7652 + pkg.packageName); 7653 } 7654 } 7655 } 7656 7657 File[] markers = profileDir.listFiles(); 7658 if (markers != null) { 7659 final String searchString = "@" + pkg.packageName + "@"; 7660 // We also delete all markers that contain the package name we're 7661 // uninstalling. These are associated with secondary dex-files belonging 7662 // to the package. Reconstructing the path of these dex files is messy 7663 // in general. 7664 for (File marker : markers) { 7665 if (marker.getName().indexOf(searchString) > 0) { 7666 if (!marker.delete()) { 7667 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7668 + pkg.packageName); 7669 } 7670 } 7671 } 7672 } 7673 } 7674 } 7675 } 7676 7677 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7678 try { 7679 mInstaller.destroyAppProfiles(pkg.packageName); 7680 } catch (InstallerException e) { 7681 Slog.w(TAG, String.valueOf(e)); 7682 } 7683 } 7684 7685 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7686 if (pkg == null) { 7687 Slog.wtf(TAG, "Package was null!", new Throwable()); 7688 return; 7689 } 7690 clearAppProfilesLeafLIF(pkg); 7691 // We don't remove the base foreign use marker when clearing profiles because 7692 // we will rename it when the app is updated. Unlike the actual profile contents, 7693 // the foreign use marker is good across installs. 7694 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7695 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7696 for (int i = 0; i < childCount; i++) { 7697 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7698 } 7699 } 7700 7701 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7702 try { 7703 mInstaller.clearAppProfiles(pkg.packageName); 7704 } catch (InstallerException e) { 7705 Slog.w(TAG, String.valueOf(e)); 7706 } 7707 } 7708 7709 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7710 long lastUpdateTime) { 7711 // Set parent install/update time 7712 PackageSetting ps = (PackageSetting) pkg.mExtras; 7713 if (ps != null) { 7714 ps.firstInstallTime = firstInstallTime; 7715 ps.lastUpdateTime = lastUpdateTime; 7716 } 7717 // Set children install/update time 7718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7719 for (int i = 0; i < childCount; i++) { 7720 PackageParser.Package childPkg = pkg.childPackages.get(i); 7721 ps = (PackageSetting) childPkg.mExtras; 7722 if (ps != null) { 7723 ps.firstInstallTime = firstInstallTime; 7724 ps.lastUpdateTime = lastUpdateTime; 7725 } 7726 } 7727 } 7728 7729 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7730 PackageParser.Package changingLib) { 7731 if (file.path != null) { 7732 usesLibraryFiles.add(file.path); 7733 return; 7734 } 7735 PackageParser.Package p = mPackages.get(file.apk); 7736 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7737 // If we are doing this while in the middle of updating a library apk, 7738 // then we need to make sure to use that new apk for determining the 7739 // dependencies here. (We haven't yet finished committing the new apk 7740 // to the package manager state.) 7741 if (p == null || p.packageName.equals(changingLib.packageName)) { 7742 p = changingLib; 7743 } 7744 } 7745 if (p != null) { 7746 usesLibraryFiles.addAll(p.getAllCodePaths()); 7747 } 7748 } 7749 7750 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7751 PackageParser.Package changingLib) throws PackageManagerException { 7752 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7753 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7754 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7755 for (int i=0; i<N; i++) { 7756 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7757 if (file == null) { 7758 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7759 "Package " + pkg.packageName + " requires unavailable shared library " 7760 + pkg.usesLibraries.get(i) + "; failing!"); 7761 } 7762 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7763 } 7764 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7765 for (int i=0; i<N; i++) { 7766 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7767 if (file == null) { 7768 Slog.w(TAG, "Package " + pkg.packageName 7769 + " desires unavailable shared library " 7770 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7771 } else { 7772 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7773 } 7774 } 7775 N = usesLibraryFiles.size(); 7776 if (N > 0) { 7777 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7778 } else { 7779 pkg.usesLibraryFiles = null; 7780 } 7781 } 7782 } 7783 7784 private static boolean hasString(List<String> list, List<String> which) { 7785 if (list == null) { 7786 return false; 7787 } 7788 for (int i=list.size()-1; i>=0; i--) { 7789 for (int j=which.size()-1; j>=0; j--) { 7790 if (which.get(j).equals(list.get(i))) { 7791 return true; 7792 } 7793 } 7794 } 7795 return false; 7796 } 7797 7798 private void updateAllSharedLibrariesLPw() { 7799 for (PackageParser.Package pkg : mPackages.values()) { 7800 try { 7801 updateSharedLibrariesLPw(pkg, null); 7802 } catch (PackageManagerException e) { 7803 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7804 } 7805 } 7806 } 7807 7808 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7809 PackageParser.Package changingPkg) { 7810 ArrayList<PackageParser.Package> res = null; 7811 for (PackageParser.Package pkg : mPackages.values()) { 7812 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7813 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7814 if (res == null) { 7815 res = new ArrayList<PackageParser.Package>(); 7816 } 7817 res.add(pkg); 7818 try { 7819 updateSharedLibrariesLPw(pkg, changingPkg); 7820 } catch (PackageManagerException e) { 7821 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7822 } 7823 } 7824 } 7825 return res; 7826 } 7827 7828 /** 7829 * Derive the value of the {@code cpuAbiOverride} based on the provided 7830 * value and an optional stored value from the package settings. 7831 */ 7832 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7833 String cpuAbiOverride = null; 7834 7835 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7836 cpuAbiOverride = null; 7837 } else if (abiOverride != null) { 7838 cpuAbiOverride = abiOverride; 7839 } else if (settings != null) { 7840 cpuAbiOverride = settings.cpuAbiOverrideString; 7841 } 7842 7843 return cpuAbiOverride; 7844 } 7845 7846 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7847 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7848 throws PackageManagerException { 7849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7850 // If the package has children and this is the first dive in the function 7851 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7852 // whether all packages (parent and children) would be successfully scanned 7853 // before the actual scan since scanning mutates internal state and we want 7854 // to atomically install the package and its children. 7855 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7856 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7857 scanFlags |= SCAN_CHECK_ONLY; 7858 } 7859 } else { 7860 scanFlags &= ~SCAN_CHECK_ONLY; 7861 } 7862 7863 final PackageParser.Package scannedPkg; 7864 try { 7865 // Scan the parent 7866 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7867 // Scan the children 7868 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7869 for (int i = 0; i < childCount; i++) { 7870 PackageParser.Package childPkg = pkg.childPackages.get(i); 7871 scanPackageLI(childPkg, policyFlags, 7872 scanFlags, currentTime, user); 7873 } 7874 } finally { 7875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7876 } 7877 7878 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7879 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7880 } 7881 7882 return scannedPkg; 7883 } 7884 7885 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7886 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7887 boolean success = false; 7888 try { 7889 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7890 currentTime, user); 7891 success = true; 7892 return res; 7893 } finally { 7894 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7895 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7896 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7897 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7898 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7899 } 7900 } 7901 } 7902 7903 /** 7904 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7905 */ 7906 private static boolean apkHasCode(String fileName) { 7907 StrictJarFile jarFile = null; 7908 try { 7909 jarFile = new StrictJarFile(fileName, 7910 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7911 return jarFile.findEntry("classes.dex") != null; 7912 } catch (IOException ignore) { 7913 } finally { 7914 try { 7915 if (jarFile != null) { 7916 jarFile.close(); 7917 } 7918 } catch (IOException ignore) {} 7919 } 7920 return false; 7921 } 7922 7923 /** 7924 * Enforces code policy for the package. This ensures that if an APK has 7925 * declared hasCode="true" in its manifest that the APK actually contains 7926 * code. 7927 * 7928 * @throws PackageManagerException If bytecode could not be found when it should exist 7929 */ 7930 private static void enforceCodePolicy(PackageParser.Package pkg) 7931 throws PackageManagerException { 7932 final boolean shouldHaveCode = 7933 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7934 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7935 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7936 "Package " + pkg.baseCodePath + " code is missing"); 7937 } 7938 7939 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7940 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7941 final boolean splitShouldHaveCode = 7942 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7943 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7944 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7945 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7946 } 7947 } 7948 } 7949 } 7950 7951 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7952 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7953 throws PackageManagerException { 7954 final File scanFile = new File(pkg.codePath); 7955 if (pkg.applicationInfo.getCodePath() == null || 7956 pkg.applicationInfo.getResourcePath() == null) { 7957 // Bail out. The resource and code paths haven't been set. 7958 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7959 "Code and resource paths haven't been set correctly"); 7960 } 7961 7962 // Apply policy 7963 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7964 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7965 if (pkg.applicationInfo.isDirectBootAware()) { 7966 // we're direct boot aware; set for all components 7967 for (PackageParser.Service s : pkg.services) { 7968 s.info.encryptionAware = s.info.directBootAware = true; 7969 } 7970 for (PackageParser.Provider p : pkg.providers) { 7971 p.info.encryptionAware = p.info.directBootAware = true; 7972 } 7973 for (PackageParser.Activity a : pkg.activities) { 7974 a.info.encryptionAware = a.info.directBootAware = true; 7975 } 7976 for (PackageParser.Activity r : pkg.receivers) { 7977 r.info.encryptionAware = r.info.directBootAware = true; 7978 } 7979 } 7980 } else { 7981 // Only allow system apps to be flagged as core apps. 7982 pkg.coreApp = false; 7983 // clear flags not applicable to regular apps 7984 pkg.applicationInfo.privateFlags &= 7985 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7986 pkg.applicationInfo.privateFlags &= 7987 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7988 } 7989 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7990 7991 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7992 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7993 } 7994 7995 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7996 enforceCodePolicy(pkg); 7997 } 7998 7999 if (mCustomResolverComponentName != null && 8000 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8001 setUpCustomResolverActivity(pkg); 8002 } 8003 8004 if (pkg.packageName.equals("android")) { 8005 synchronized (mPackages) { 8006 if (mAndroidApplication != null) { 8007 Slog.w(TAG, "*************************************************"); 8008 Slog.w(TAG, "Core android package being redefined. Skipping."); 8009 Slog.w(TAG, " file=" + scanFile); 8010 Slog.w(TAG, "*************************************************"); 8011 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8012 "Core android package being redefined. Skipping."); 8013 } 8014 8015 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8016 // Set up information for our fall-back user intent resolution activity. 8017 mPlatformPackage = pkg; 8018 pkg.mVersionCode = mSdkVersion; 8019 mAndroidApplication = pkg.applicationInfo; 8020 8021 if (!mResolverReplaced) { 8022 mResolveActivity.applicationInfo = mAndroidApplication; 8023 mResolveActivity.name = ResolverActivity.class.getName(); 8024 mResolveActivity.packageName = mAndroidApplication.packageName; 8025 mResolveActivity.processName = "system:ui"; 8026 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8027 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8028 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8029 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8030 mResolveActivity.exported = true; 8031 mResolveActivity.enabled = true; 8032 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8033 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8034 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8035 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8036 | ActivityInfo.CONFIG_ORIENTATION 8037 | ActivityInfo.CONFIG_KEYBOARD 8038 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8039 mResolveInfo.activityInfo = mResolveActivity; 8040 mResolveInfo.priority = 0; 8041 mResolveInfo.preferredOrder = 0; 8042 mResolveInfo.match = 0; 8043 mResolveComponentName = new ComponentName( 8044 mAndroidApplication.packageName, mResolveActivity.name); 8045 } 8046 } 8047 } 8048 } 8049 8050 if (DEBUG_PACKAGE_SCANNING) { 8051 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8052 Log.d(TAG, "Scanning package " + pkg.packageName); 8053 } 8054 8055 synchronized (mPackages) { 8056 if (mPackages.containsKey(pkg.packageName) 8057 || mSharedLibraries.containsKey(pkg.packageName)) { 8058 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8059 "Application package " + pkg.packageName 8060 + " already installed. Skipping duplicate."); 8061 } 8062 8063 // If we're only installing presumed-existing packages, require that the 8064 // scanned APK is both already known and at the path previously established 8065 // for it. Previously unknown packages we pick up normally, but if we have an 8066 // a priori expectation about this package's install presence, enforce it. 8067 // With a singular exception for new system packages. When an OTA contains 8068 // a new system package, we allow the codepath to change from a system location 8069 // to the user-installed location. If we don't allow this change, any newer, 8070 // user-installed version of the application will be ignored. 8071 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8072 if (mExpectingBetter.containsKey(pkg.packageName)) { 8073 logCriticalInfo(Log.WARN, 8074 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8075 } else { 8076 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8077 if (known != null) { 8078 if (DEBUG_PACKAGE_SCANNING) { 8079 Log.d(TAG, "Examining " + pkg.codePath 8080 + " and requiring known paths " + known.codePathString 8081 + " & " + known.resourcePathString); 8082 } 8083 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8084 || !pkg.applicationInfo.getResourcePath().equals( 8085 known.resourcePathString)) { 8086 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8087 "Application package " + pkg.packageName 8088 + " found at " + pkg.applicationInfo.getCodePath() 8089 + " but expected at " + known.codePathString 8090 + "; ignoring."); 8091 } 8092 } 8093 } 8094 } 8095 } 8096 8097 // Initialize package source and resource directories 8098 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8099 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8100 8101 SharedUserSetting suid = null; 8102 PackageSetting pkgSetting = null; 8103 8104 if (!isSystemApp(pkg)) { 8105 // Only system apps can use these features. 8106 pkg.mOriginalPackages = null; 8107 pkg.mRealPackage = null; 8108 pkg.mAdoptPermissions = null; 8109 } 8110 8111 // Getting the package setting may have a side-effect, so if we 8112 // are only checking if scan would succeed, stash a copy of the 8113 // old setting to restore at the end. 8114 PackageSetting nonMutatedPs = null; 8115 8116 // writer 8117 synchronized (mPackages) { 8118 if (pkg.mSharedUserId != null) { 8119 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8120 if (suid == null) { 8121 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8122 "Creating application package " + pkg.packageName 8123 + " for shared user failed"); 8124 } 8125 if (DEBUG_PACKAGE_SCANNING) { 8126 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8127 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8128 + "): packages=" + suid.packages); 8129 } 8130 } 8131 8132 // Check if we are renaming from an original package name. 8133 PackageSetting origPackage = null; 8134 String realName = null; 8135 if (pkg.mOriginalPackages != null) { 8136 // This package may need to be renamed to a previously 8137 // installed name. Let's check on that... 8138 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8139 if (pkg.mOriginalPackages.contains(renamed)) { 8140 // This package had originally been installed as the 8141 // original name, and we have already taken care of 8142 // transitioning to the new one. Just update the new 8143 // one to continue using the old name. 8144 realName = pkg.mRealPackage; 8145 if (!pkg.packageName.equals(renamed)) { 8146 // Callers into this function may have already taken 8147 // care of renaming the package; only do it here if 8148 // it is not already done. 8149 pkg.setPackageName(renamed); 8150 } 8151 8152 } else { 8153 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8154 if ((origPackage = mSettings.peekPackageLPr( 8155 pkg.mOriginalPackages.get(i))) != null) { 8156 // We do have the package already installed under its 8157 // original name... should we use it? 8158 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8159 // New package is not compatible with original. 8160 origPackage = null; 8161 continue; 8162 } else if (origPackage.sharedUser != null) { 8163 // Make sure uid is compatible between packages. 8164 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8165 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8166 + " to " + pkg.packageName + ": old uid " 8167 + origPackage.sharedUser.name 8168 + " differs from " + pkg.mSharedUserId); 8169 origPackage = null; 8170 continue; 8171 } 8172 // TODO: Add case when shared user id is added [b/28144775] 8173 } else { 8174 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8175 + pkg.packageName + " to old name " + origPackage.name); 8176 } 8177 break; 8178 } 8179 } 8180 } 8181 } 8182 8183 if (mTransferedPackages.contains(pkg.packageName)) { 8184 Slog.w(TAG, "Package " + pkg.packageName 8185 + " was transferred to another, but its .apk remains"); 8186 } 8187 8188 // See comments in nonMutatedPs declaration 8189 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8190 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8191 if (foundPs != null) { 8192 nonMutatedPs = new PackageSetting(foundPs); 8193 } 8194 } 8195 8196 // Just create the setting, don't add it yet. For already existing packages 8197 // the PkgSetting exists already and doesn't have to be created. 8198 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8199 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8200 pkg.applicationInfo.primaryCpuAbi, 8201 pkg.applicationInfo.secondaryCpuAbi, 8202 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8203 user, false); 8204 if (pkgSetting == null) { 8205 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8206 "Creating application package " + pkg.packageName + " failed"); 8207 } 8208 8209 if (pkgSetting.origPackage != null) { 8210 // If we are first transitioning from an original package, 8211 // fix up the new package's name now. We need to do this after 8212 // looking up the package under its new name, so getPackageLP 8213 // can take care of fiddling things correctly. 8214 pkg.setPackageName(origPackage.name); 8215 8216 // File a report about this. 8217 String msg = "New package " + pkgSetting.realName 8218 + " renamed to replace old package " + pkgSetting.name; 8219 reportSettingsProblem(Log.WARN, msg); 8220 8221 // Make a note of it. 8222 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8223 mTransferedPackages.add(origPackage.name); 8224 } 8225 8226 // No longer need to retain this. 8227 pkgSetting.origPackage = null; 8228 } 8229 8230 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8231 // Make a note of it. 8232 mTransferedPackages.add(pkg.packageName); 8233 } 8234 8235 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8236 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8237 } 8238 8239 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8240 // Check all shared libraries and map to their actual file path. 8241 // We only do this here for apps not on a system dir, because those 8242 // are the only ones that can fail an install due to this. We 8243 // will take care of the system apps by updating all of their 8244 // library paths after the scan is done. 8245 updateSharedLibrariesLPw(pkg, null); 8246 } 8247 8248 if (mFoundPolicyFile) { 8249 SELinuxMMAC.assignSeinfoValue(pkg); 8250 } 8251 8252 pkg.applicationInfo.uid = pkgSetting.appId; 8253 pkg.mExtras = pkgSetting; 8254 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8255 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8256 // We just determined the app is signed correctly, so bring 8257 // over the latest parsed certs. 8258 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8259 } else { 8260 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8261 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8262 "Package " + pkg.packageName + " upgrade keys do not match the " 8263 + "previously installed version"); 8264 } else { 8265 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8266 String msg = "System package " + pkg.packageName 8267 + " signature changed; retaining data."; 8268 reportSettingsProblem(Log.WARN, msg); 8269 } 8270 } 8271 } else { 8272 try { 8273 verifySignaturesLP(pkgSetting, pkg); 8274 // We just determined the app is signed correctly, so bring 8275 // over the latest parsed certs. 8276 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8277 } catch (PackageManagerException e) { 8278 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8279 throw e; 8280 } 8281 // The signature has changed, but this package is in the system 8282 // image... let's recover! 8283 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8284 // However... if this package is part of a shared user, but it 8285 // doesn't match the signature of the shared user, let's fail. 8286 // What this means is that you can't change the signatures 8287 // associated with an overall shared user, which doesn't seem all 8288 // that unreasonable. 8289 if (pkgSetting.sharedUser != null) { 8290 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8291 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8292 throw new PackageManagerException( 8293 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8294 "Signature mismatch for shared user: " 8295 + pkgSetting.sharedUser); 8296 } 8297 } 8298 // File a report about this. 8299 String msg = "System package " + pkg.packageName 8300 + " signature changed; retaining data."; 8301 reportSettingsProblem(Log.WARN, msg); 8302 } 8303 } 8304 // Verify that this new package doesn't have any content providers 8305 // that conflict with existing packages. Only do this if the 8306 // package isn't already installed, since we don't want to break 8307 // things that are installed. 8308 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8309 final int N = pkg.providers.size(); 8310 int i; 8311 for (i=0; i<N; i++) { 8312 PackageParser.Provider p = pkg.providers.get(i); 8313 if (p.info.authority != null) { 8314 String names[] = p.info.authority.split(";"); 8315 for (int j = 0; j < names.length; j++) { 8316 if (mProvidersByAuthority.containsKey(names[j])) { 8317 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8318 final String otherPackageName = 8319 ((other != null && other.getComponentName() != null) ? 8320 other.getComponentName().getPackageName() : "?"); 8321 throw new PackageManagerException( 8322 INSTALL_FAILED_CONFLICTING_PROVIDER, 8323 "Can't install because provider name " + names[j] 8324 + " (in package " + pkg.applicationInfo.packageName 8325 + ") is already used by " + otherPackageName); 8326 } 8327 } 8328 } 8329 } 8330 } 8331 8332 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8333 // This package wants to adopt ownership of permissions from 8334 // another package. 8335 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8336 final String origName = pkg.mAdoptPermissions.get(i); 8337 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8338 if (orig != null) { 8339 if (verifyPackageUpdateLPr(orig, pkg)) { 8340 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8341 + pkg.packageName); 8342 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8343 } 8344 } 8345 } 8346 } 8347 } 8348 8349 final String pkgName = pkg.packageName; 8350 8351 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8352 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8353 pkg.applicationInfo.processName = fixProcessName( 8354 pkg.applicationInfo.packageName, 8355 pkg.applicationInfo.processName, 8356 pkg.applicationInfo.uid); 8357 8358 if (pkg != mPlatformPackage) { 8359 // Get all of our default paths setup 8360 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8361 } 8362 8363 final String path = scanFile.getPath(); 8364 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8365 8366 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8367 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8368 8369 // Some system apps still use directory structure for native libraries 8370 // in which case we might end up not detecting abi solely based on apk 8371 // structure. Try to detect abi based on directory structure. 8372 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8373 pkg.applicationInfo.primaryCpuAbi == null) { 8374 setBundledAppAbisAndRoots(pkg, pkgSetting); 8375 setNativeLibraryPaths(pkg); 8376 } 8377 8378 } else { 8379 if ((scanFlags & SCAN_MOVE) != 0) { 8380 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8381 // but we already have this packages package info in the PackageSetting. We just 8382 // use that and derive the native library path based on the new codepath. 8383 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8384 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8385 } 8386 8387 // Set native library paths again. For moves, the path will be updated based on the 8388 // ABIs we've determined above. For non-moves, the path will be updated based on the 8389 // ABIs we determined during compilation, but the path will depend on the final 8390 // package path (after the rename away from the stage path). 8391 setNativeLibraryPaths(pkg); 8392 } 8393 8394 // This is a special case for the "system" package, where the ABI is 8395 // dictated by the zygote configuration (and init.rc). We should keep track 8396 // of this ABI so that we can deal with "normal" applications that run under 8397 // the same UID correctly. 8398 if (mPlatformPackage == pkg) { 8399 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8400 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8401 } 8402 8403 // If there's a mismatch between the abi-override in the package setting 8404 // and the abiOverride specified for the install. Warn about this because we 8405 // would've already compiled the app without taking the package setting into 8406 // account. 8407 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8408 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8409 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8410 " for package " + pkg.packageName); 8411 } 8412 } 8413 8414 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8415 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8416 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8417 8418 // Copy the derived override back to the parsed package, so that we can 8419 // update the package settings accordingly. 8420 pkg.cpuAbiOverride = cpuAbiOverride; 8421 8422 if (DEBUG_ABI_SELECTION) { 8423 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8424 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8425 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8426 } 8427 8428 // Push the derived path down into PackageSettings so we know what to 8429 // clean up at uninstall time. 8430 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8431 8432 if (DEBUG_ABI_SELECTION) { 8433 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8434 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8435 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8436 } 8437 8438 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8439 // We don't do this here during boot because we can do it all 8440 // at once after scanning all existing packages. 8441 // 8442 // We also do this *before* we perform dexopt on this package, so that 8443 // we can avoid redundant dexopts, and also to make sure we've got the 8444 // code and package path correct. 8445 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8446 pkg, true /* boot complete */); 8447 } 8448 8449 if (mFactoryTest && pkg.requestedPermissions.contains( 8450 android.Manifest.permission.FACTORY_TEST)) { 8451 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8452 } 8453 8454 if (isSystemApp(pkg)) { 8455 pkgSetting.isOrphaned = true; 8456 } 8457 8458 ArrayList<PackageParser.Package> clientLibPkgs = null; 8459 8460 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8461 if (nonMutatedPs != null) { 8462 synchronized (mPackages) { 8463 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8464 } 8465 } 8466 return pkg; 8467 } 8468 8469 // Only privileged apps and updated privileged apps can add child packages. 8470 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8471 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8472 throw new PackageManagerException("Only privileged apps and updated " 8473 + "privileged apps can add child packages. Ignoring package " 8474 + pkg.packageName); 8475 } 8476 final int childCount = pkg.childPackages.size(); 8477 for (int i = 0; i < childCount; i++) { 8478 PackageParser.Package childPkg = pkg.childPackages.get(i); 8479 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8480 childPkg.packageName)) { 8481 throw new PackageManagerException("Cannot override a child package of " 8482 + "another disabled system app. Ignoring package " + pkg.packageName); 8483 } 8484 } 8485 } 8486 8487 // writer 8488 synchronized (mPackages) { 8489 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8490 // Only system apps can add new shared libraries. 8491 if (pkg.libraryNames != null) { 8492 for (int i=0; i<pkg.libraryNames.size(); i++) { 8493 String name = pkg.libraryNames.get(i); 8494 boolean allowed = false; 8495 if (pkg.isUpdatedSystemApp()) { 8496 // New library entries can only be added through the 8497 // system image. This is important to get rid of a lot 8498 // of nasty edge cases: for example if we allowed a non- 8499 // system update of the app to add a library, then uninstalling 8500 // the update would make the library go away, and assumptions 8501 // we made such as through app install filtering would now 8502 // have allowed apps on the device which aren't compatible 8503 // with it. Better to just have the restriction here, be 8504 // conservative, and create many fewer cases that can negatively 8505 // impact the user experience. 8506 final PackageSetting sysPs = mSettings 8507 .getDisabledSystemPkgLPr(pkg.packageName); 8508 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8509 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8510 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8511 allowed = true; 8512 break; 8513 } 8514 } 8515 } 8516 } else { 8517 allowed = true; 8518 } 8519 if (allowed) { 8520 if (!mSharedLibraries.containsKey(name)) { 8521 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8522 } else if (!name.equals(pkg.packageName)) { 8523 Slog.w(TAG, "Package " + pkg.packageName + " library " 8524 + name + " already exists; skipping"); 8525 } 8526 } else { 8527 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8528 + name + " that is not declared on system image; skipping"); 8529 } 8530 } 8531 if ((scanFlags & SCAN_BOOTING) == 0) { 8532 // If we are not booting, we need to update any applications 8533 // that are clients of our shared library. If we are booting, 8534 // this will all be done once the scan is complete. 8535 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8536 } 8537 } 8538 } 8539 } 8540 8541 if ((scanFlags & SCAN_BOOTING) != 0) { 8542 // No apps can run during boot scan, so they don't need to be frozen 8543 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8544 // Caller asked to not kill app, so it's probably not frozen 8545 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8546 // Caller asked us to ignore frozen check for some reason; they 8547 // probably didn't know the package name 8548 } else { 8549 // We're doing major surgery on this package, so it better be frozen 8550 // right now to keep it from launching 8551 checkPackageFrozen(pkgName); 8552 } 8553 8554 // Also need to kill any apps that are dependent on the library. 8555 if (clientLibPkgs != null) { 8556 for (int i=0; i<clientLibPkgs.size(); i++) { 8557 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8558 killApplication(clientPkg.applicationInfo.packageName, 8559 clientPkg.applicationInfo.uid, "update lib"); 8560 } 8561 } 8562 8563 // Make sure we're not adding any bogus keyset info 8564 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8565 ksms.assertScannedPackageValid(pkg); 8566 8567 // writer 8568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8569 8570 boolean createIdmapFailed = false; 8571 synchronized (mPackages) { 8572 // We don't expect installation to fail beyond this point 8573 8574 if (pkgSetting.pkg != null) { 8575 // Note that |user| might be null during the initial boot scan. If a codePath 8576 // for an app has changed during a boot scan, it's due to an app update that's 8577 // part of the system partition and marker changes must be applied to all users. 8578 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8579 (user != null) ? user : UserHandle.ALL); 8580 } 8581 8582 // Add the new setting to mSettings 8583 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8584 // Add the new setting to mPackages 8585 mPackages.put(pkg.applicationInfo.packageName, pkg); 8586 // Make sure we don't accidentally delete its data. 8587 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8588 while (iter.hasNext()) { 8589 PackageCleanItem item = iter.next(); 8590 if (pkgName.equals(item.packageName)) { 8591 iter.remove(); 8592 } 8593 } 8594 8595 // Take care of first install / last update times. 8596 if (currentTime != 0) { 8597 if (pkgSetting.firstInstallTime == 0) { 8598 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8599 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8600 pkgSetting.lastUpdateTime = currentTime; 8601 } 8602 } else if (pkgSetting.firstInstallTime == 0) { 8603 // We need *something*. Take time time stamp of the file. 8604 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8605 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8606 if (scanFileTime != pkgSetting.timeStamp) { 8607 // A package on the system image has changed; consider this 8608 // to be an update. 8609 pkgSetting.lastUpdateTime = scanFileTime; 8610 } 8611 } 8612 8613 // Add the package's KeySets to the global KeySetManagerService 8614 ksms.addScannedPackageLPw(pkg); 8615 8616 int N = pkg.providers.size(); 8617 StringBuilder r = null; 8618 int i; 8619 for (i=0; i<N; i++) { 8620 PackageParser.Provider p = pkg.providers.get(i); 8621 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8622 p.info.processName, pkg.applicationInfo.uid); 8623 mProviders.addProvider(p); 8624 p.syncable = p.info.isSyncable; 8625 if (p.info.authority != null) { 8626 String names[] = p.info.authority.split(";"); 8627 p.info.authority = null; 8628 for (int j = 0; j < names.length; j++) { 8629 if (j == 1 && p.syncable) { 8630 // We only want the first authority for a provider to possibly be 8631 // syncable, so if we already added this provider using a different 8632 // authority clear the syncable flag. We copy the provider before 8633 // changing it because the mProviders object contains a reference 8634 // to a provider that we don't want to change. 8635 // Only do this for the second authority since the resulting provider 8636 // object can be the same for all future authorities for this provider. 8637 p = new PackageParser.Provider(p); 8638 p.syncable = false; 8639 } 8640 if (!mProvidersByAuthority.containsKey(names[j])) { 8641 mProvidersByAuthority.put(names[j], p); 8642 if (p.info.authority == null) { 8643 p.info.authority = names[j]; 8644 } else { 8645 p.info.authority = p.info.authority + ";" + names[j]; 8646 } 8647 if (DEBUG_PACKAGE_SCANNING) { 8648 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8649 Log.d(TAG, "Registered content provider: " + names[j] 8650 + ", className = " + p.info.name + ", isSyncable = " 8651 + p.info.isSyncable); 8652 } 8653 } else { 8654 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8655 Slog.w(TAG, "Skipping provider name " + names[j] + 8656 " (in package " + pkg.applicationInfo.packageName + 8657 "): name already used by " 8658 + ((other != null && other.getComponentName() != null) 8659 ? other.getComponentName().getPackageName() : "?")); 8660 } 8661 } 8662 } 8663 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8664 if (r == null) { 8665 r = new StringBuilder(256); 8666 } else { 8667 r.append(' '); 8668 } 8669 r.append(p.info.name); 8670 } 8671 } 8672 if (r != null) { 8673 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8674 } 8675 8676 N = pkg.services.size(); 8677 r = null; 8678 for (i=0; i<N; i++) { 8679 PackageParser.Service s = pkg.services.get(i); 8680 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8681 s.info.processName, pkg.applicationInfo.uid); 8682 mServices.addService(s); 8683 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8684 if (r == null) { 8685 r = new StringBuilder(256); 8686 } else { 8687 r.append(' '); 8688 } 8689 r.append(s.info.name); 8690 } 8691 } 8692 if (r != null) { 8693 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8694 } 8695 8696 N = pkg.receivers.size(); 8697 r = null; 8698 for (i=0; i<N; i++) { 8699 PackageParser.Activity a = pkg.receivers.get(i); 8700 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8701 a.info.processName, pkg.applicationInfo.uid); 8702 mReceivers.addActivity(a, "receiver"); 8703 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8704 if (r == null) { 8705 r = new StringBuilder(256); 8706 } else { 8707 r.append(' '); 8708 } 8709 r.append(a.info.name); 8710 } 8711 } 8712 if (r != null) { 8713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8714 } 8715 8716 N = pkg.activities.size(); 8717 r = null; 8718 for (i=0; i<N; i++) { 8719 PackageParser.Activity a = pkg.activities.get(i); 8720 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8721 a.info.processName, pkg.applicationInfo.uid); 8722 mActivities.addActivity(a, "activity"); 8723 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8724 if (r == null) { 8725 r = new StringBuilder(256); 8726 } else { 8727 r.append(' '); 8728 } 8729 r.append(a.info.name); 8730 } 8731 } 8732 if (r != null) { 8733 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8734 } 8735 8736 N = pkg.permissionGroups.size(); 8737 r = null; 8738 for (i=0; i<N; i++) { 8739 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8740 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8741 final String curPackageName = cur == null ? null : cur.info.packageName; 8742 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8743 if (cur == null || isPackageUpdate) { 8744 mPermissionGroups.put(pg.info.name, pg); 8745 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8746 if (r == null) { 8747 r = new StringBuilder(256); 8748 } else { 8749 r.append(' '); 8750 } 8751 if (isPackageUpdate) { 8752 r.append("UPD:"); 8753 } 8754 r.append(pg.info.name); 8755 } 8756 } else { 8757 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8758 + pg.info.packageName + " ignored: original from " 8759 + cur.info.packageName); 8760 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8761 if (r == null) { 8762 r = new StringBuilder(256); 8763 } else { 8764 r.append(' '); 8765 } 8766 r.append("DUP:"); 8767 r.append(pg.info.name); 8768 } 8769 } 8770 } 8771 if (r != null) { 8772 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8773 } 8774 8775 N = pkg.permissions.size(); 8776 r = null; 8777 for (i=0; i<N; i++) { 8778 PackageParser.Permission p = pkg.permissions.get(i); 8779 8780 // Assume by default that we did not install this permission into the system. 8781 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8782 8783 // Now that permission groups have a special meaning, we ignore permission 8784 // groups for legacy apps to prevent unexpected behavior. In particular, 8785 // permissions for one app being granted to someone just becase they happen 8786 // to be in a group defined by another app (before this had no implications). 8787 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8788 p.group = mPermissionGroups.get(p.info.group); 8789 // Warn for a permission in an unknown group. 8790 if (p.info.group != null && p.group == null) { 8791 Slog.w(TAG, "Permission " + p.info.name + " from package " 8792 + p.info.packageName + " in an unknown group " + p.info.group); 8793 } 8794 } 8795 8796 ArrayMap<String, BasePermission> permissionMap = 8797 p.tree ? mSettings.mPermissionTrees 8798 : mSettings.mPermissions; 8799 BasePermission bp = permissionMap.get(p.info.name); 8800 8801 // Allow system apps to redefine non-system permissions 8802 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8803 final boolean currentOwnerIsSystem = (bp.perm != null 8804 && isSystemApp(bp.perm.owner)); 8805 if (isSystemApp(p.owner)) { 8806 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8807 // It's a built-in permission and no owner, take ownership now 8808 bp.packageSetting = pkgSetting; 8809 bp.perm = p; 8810 bp.uid = pkg.applicationInfo.uid; 8811 bp.sourcePackage = p.info.packageName; 8812 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8813 } else if (!currentOwnerIsSystem) { 8814 String msg = "New decl " + p.owner + " of permission " 8815 + p.info.name + " is system; overriding " + bp.sourcePackage; 8816 reportSettingsProblem(Log.WARN, msg); 8817 bp = null; 8818 } 8819 } 8820 } 8821 8822 if (bp == null) { 8823 bp = new BasePermission(p.info.name, p.info.packageName, 8824 BasePermission.TYPE_NORMAL); 8825 permissionMap.put(p.info.name, bp); 8826 } 8827 8828 if (bp.perm == null) { 8829 if (bp.sourcePackage == null 8830 || bp.sourcePackage.equals(p.info.packageName)) { 8831 BasePermission tree = findPermissionTreeLP(p.info.name); 8832 if (tree == null 8833 || tree.sourcePackage.equals(p.info.packageName)) { 8834 bp.packageSetting = pkgSetting; 8835 bp.perm = p; 8836 bp.uid = pkg.applicationInfo.uid; 8837 bp.sourcePackage = p.info.packageName; 8838 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8839 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8840 if (r == null) { 8841 r = new StringBuilder(256); 8842 } else { 8843 r.append(' '); 8844 } 8845 r.append(p.info.name); 8846 } 8847 } else { 8848 Slog.w(TAG, "Permission " + p.info.name + " from package " 8849 + p.info.packageName + " ignored: base tree " 8850 + tree.name + " is from package " 8851 + tree.sourcePackage); 8852 } 8853 } else { 8854 Slog.w(TAG, "Permission " + p.info.name + " from package " 8855 + p.info.packageName + " ignored: original from " 8856 + bp.sourcePackage); 8857 } 8858 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8859 if (r == null) { 8860 r = new StringBuilder(256); 8861 } else { 8862 r.append(' '); 8863 } 8864 r.append("DUP:"); 8865 r.append(p.info.name); 8866 } 8867 if (bp.perm == p) { 8868 bp.protectionLevel = p.info.protectionLevel; 8869 } 8870 } 8871 8872 if (r != null) { 8873 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8874 } 8875 8876 N = pkg.instrumentation.size(); 8877 r = null; 8878 for (i=0; i<N; i++) { 8879 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8880 a.info.packageName = pkg.applicationInfo.packageName; 8881 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8882 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8883 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8884 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8885 a.info.dataDir = pkg.applicationInfo.dataDir; 8886 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8887 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8888 8889 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8890 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8891 mInstrumentation.put(a.getComponentName(), a); 8892 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8893 if (r == null) { 8894 r = new StringBuilder(256); 8895 } else { 8896 r.append(' '); 8897 } 8898 r.append(a.info.name); 8899 } 8900 } 8901 if (r != null) { 8902 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8903 } 8904 8905 if (pkg.protectedBroadcasts != null) { 8906 N = pkg.protectedBroadcasts.size(); 8907 for (i=0; i<N; i++) { 8908 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8909 } 8910 } 8911 8912 pkgSetting.setTimeStamp(scanFileTime); 8913 8914 // Create idmap files for pairs of (packages, overlay packages). 8915 // Note: "android", ie framework-res.apk, is handled by native layers. 8916 if (pkg.mOverlayTarget != null) { 8917 // This is an overlay package. 8918 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8919 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8920 mOverlays.put(pkg.mOverlayTarget, 8921 new ArrayMap<String, PackageParser.Package>()); 8922 } 8923 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8924 map.put(pkg.packageName, pkg); 8925 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8926 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8927 createIdmapFailed = true; 8928 } 8929 } 8930 } else if (mOverlays.containsKey(pkg.packageName) && 8931 !pkg.packageName.equals("android")) { 8932 // This is a regular package, with one or more known overlay packages. 8933 createIdmapsForPackageLI(pkg); 8934 } 8935 } 8936 8937 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8938 8939 if (createIdmapFailed) { 8940 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8941 "scanPackageLI failed to createIdmap"); 8942 } 8943 return pkg; 8944 } 8945 8946 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8947 PackageParser.Package update, UserHandle user) { 8948 if (existing.applicationInfo == null || update.applicationInfo == null) { 8949 // This isn't due to an app installation. 8950 return; 8951 } 8952 8953 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8954 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8955 8956 // The codePath hasn't changed, so there's nothing for us to do. 8957 if (Objects.equals(oldCodePath, newCodePath)) { 8958 return; 8959 } 8960 8961 File canonicalNewCodePath; 8962 try { 8963 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8964 } catch (IOException e) { 8965 Slog.w(TAG, "Failed to get canonical path.", e); 8966 return; 8967 } 8968 8969 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8970 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8971 // that the last component of the path (i.e, the name) doesn't need canonicalization 8972 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8973 // but may change in the future. Hopefully this function won't exist at that point. 8974 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8975 oldCodePath.getName()); 8976 8977 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8978 // with "@". 8979 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8980 if (!oldMarkerPrefix.endsWith("@")) { 8981 oldMarkerPrefix += "@"; 8982 } 8983 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8984 if (!newMarkerPrefix.endsWith("@")) { 8985 newMarkerPrefix += "@"; 8986 } 8987 8988 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8989 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8990 for (String updatedPath : updatedPaths) { 8991 String updatedPathName = new File(updatedPath).getName(); 8992 markerSuffixes.add(updatedPathName.replace('/', '@')); 8993 } 8994 8995 for (int userId : resolveUserIds(user.getIdentifier())) { 8996 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8997 8998 for (String markerSuffix : markerSuffixes) { 8999 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9000 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9001 if (oldForeignUseMark.exists()) { 9002 try { 9003 Os.rename(oldForeignUseMark.getAbsolutePath(), 9004 newForeignUseMark.getAbsolutePath()); 9005 } catch (ErrnoException e) { 9006 Slog.w(TAG, "Failed to rename foreign use marker", e); 9007 oldForeignUseMark.delete(); 9008 } 9009 } 9010 } 9011 } 9012 } 9013 9014 /** 9015 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9016 * is derived purely on the basis of the contents of {@code scanFile} and 9017 * {@code cpuAbiOverride}. 9018 * 9019 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9020 */ 9021 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9022 String cpuAbiOverride, boolean extractLibs) 9023 throws PackageManagerException { 9024 // TODO: We can probably be smarter about this stuff. For installed apps, 9025 // we can calculate this information at install time once and for all. For 9026 // system apps, we can probably assume that this information doesn't change 9027 // after the first boot scan. As things stand, we do lots of unnecessary work. 9028 9029 // Give ourselves some initial paths; we'll come back for another 9030 // pass once we've determined ABI below. 9031 setNativeLibraryPaths(pkg); 9032 9033 // We would never need to extract libs for forward-locked and external packages, 9034 // since the container service will do it for us. We shouldn't attempt to 9035 // extract libs from system app when it was not updated. 9036 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9037 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9038 extractLibs = false; 9039 } 9040 9041 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9042 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9043 9044 NativeLibraryHelper.Handle handle = null; 9045 try { 9046 handle = NativeLibraryHelper.Handle.create(pkg); 9047 // TODO(multiArch): This can be null for apps that didn't go through the 9048 // usual installation process. We can calculate it again, like we 9049 // do during install time. 9050 // 9051 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9052 // unnecessary. 9053 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9054 9055 // Null out the abis so that they can be recalculated. 9056 pkg.applicationInfo.primaryCpuAbi = null; 9057 pkg.applicationInfo.secondaryCpuAbi = null; 9058 if (isMultiArch(pkg.applicationInfo)) { 9059 // Warn if we've set an abiOverride for multi-lib packages.. 9060 // By definition, we need to copy both 32 and 64 bit libraries for 9061 // such packages. 9062 if (pkg.cpuAbiOverride != null 9063 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9064 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9065 } 9066 9067 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9068 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9069 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9070 if (extractLibs) { 9071 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9072 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9073 useIsaSpecificSubdirs); 9074 } else { 9075 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9076 } 9077 } 9078 9079 maybeThrowExceptionForMultiArchCopy( 9080 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9081 9082 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9083 if (extractLibs) { 9084 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9085 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9086 useIsaSpecificSubdirs); 9087 } else { 9088 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9089 } 9090 } 9091 9092 maybeThrowExceptionForMultiArchCopy( 9093 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9094 9095 if (abi64 >= 0) { 9096 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9097 } 9098 9099 if (abi32 >= 0) { 9100 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9101 if (abi64 >= 0) { 9102 if (pkg.use32bitAbi) { 9103 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9104 pkg.applicationInfo.primaryCpuAbi = abi; 9105 } else { 9106 pkg.applicationInfo.secondaryCpuAbi = abi; 9107 } 9108 } else { 9109 pkg.applicationInfo.primaryCpuAbi = abi; 9110 } 9111 } 9112 9113 } else { 9114 String[] abiList = (cpuAbiOverride != null) ? 9115 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9116 9117 // Enable gross and lame hacks for apps that are built with old 9118 // SDK tools. We must scan their APKs for renderscript bitcode and 9119 // not launch them if it's present. Don't bother checking on devices 9120 // that don't have 64 bit support. 9121 boolean needsRenderScriptOverride = false; 9122 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9123 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9124 abiList = Build.SUPPORTED_32_BIT_ABIS; 9125 needsRenderScriptOverride = true; 9126 } 9127 9128 final int copyRet; 9129 if (extractLibs) { 9130 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9131 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9132 } else { 9133 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9134 } 9135 9136 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9137 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9138 "Error unpackaging native libs for app, errorCode=" + copyRet); 9139 } 9140 9141 if (copyRet >= 0) { 9142 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9143 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9144 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9145 } else if (needsRenderScriptOverride) { 9146 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9147 } 9148 } 9149 } catch (IOException ioe) { 9150 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9151 } finally { 9152 IoUtils.closeQuietly(handle); 9153 } 9154 9155 // Now that we've calculated the ABIs and determined if it's an internal app, 9156 // we will go ahead and populate the nativeLibraryPath. 9157 setNativeLibraryPaths(pkg); 9158 } 9159 9160 /** 9161 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9162 * i.e, so that all packages can be run inside a single process if required. 9163 * 9164 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9165 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9166 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9167 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9168 * updating a package that belongs to a shared user. 9169 * 9170 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9171 * adds unnecessary complexity. 9172 */ 9173 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9174 PackageParser.Package scannedPackage, boolean bootComplete) { 9175 String requiredInstructionSet = null; 9176 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9177 requiredInstructionSet = VMRuntime.getInstructionSet( 9178 scannedPackage.applicationInfo.primaryCpuAbi); 9179 } 9180 9181 PackageSetting requirer = null; 9182 for (PackageSetting ps : packagesForUser) { 9183 // If packagesForUser contains scannedPackage, we skip it. This will happen 9184 // when scannedPackage is an update of an existing package. Without this check, 9185 // we will never be able to change the ABI of any package belonging to a shared 9186 // user, even if it's compatible with other packages. 9187 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9188 if (ps.primaryCpuAbiString == null) { 9189 continue; 9190 } 9191 9192 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9193 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9194 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9195 // this but there's not much we can do. 9196 String errorMessage = "Instruction set mismatch, " 9197 + ((requirer == null) ? "[caller]" : requirer) 9198 + " requires " + requiredInstructionSet + " whereas " + ps 9199 + " requires " + instructionSet; 9200 Slog.w(TAG, errorMessage); 9201 } 9202 9203 if (requiredInstructionSet == null) { 9204 requiredInstructionSet = instructionSet; 9205 requirer = ps; 9206 } 9207 } 9208 } 9209 9210 if (requiredInstructionSet != null) { 9211 String adjustedAbi; 9212 if (requirer != null) { 9213 // requirer != null implies that either scannedPackage was null or that scannedPackage 9214 // did not require an ABI, in which case we have to adjust scannedPackage to match 9215 // the ABI of the set (which is the same as requirer's ABI) 9216 adjustedAbi = requirer.primaryCpuAbiString; 9217 if (scannedPackage != null) { 9218 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9219 } 9220 } else { 9221 // requirer == null implies that we're updating all ABIs in the set to 9222 // match scannedPackage. 9223 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9224 } 9225 9226 for (PackageSetting ps : packagesForUser) { 9227 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9228 if (ps.primaryCpuAbiString != null) { 9229 continue; 9230 } 9231 9232 ps.primaryCpuAbiString = adjustedAbi; 9233 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9234 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9235 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9236 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9237 + " (requirer=" 9238 + (requirer == null ? "null" : requirer.pkg.packageName) 9239 + ", scannedPackage=" 9240 + (scannedPackage != null ? scannedPackage.packageName : "null") 9241 + ")"); 9242 try { 9243 mInstaller.rmdex(ps.codePathString, 9244 getDexCodeInstructionSet(getPreferredInstructionSet())); 9245 } catch (InstallerException ignored) { 9246 } 9247 } 9248 } 9249 } 9250 } 9251 } 9252 9253 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9254 synchronized (mPackages) { 9255 mResolverReplaced = true; 9256 // Set up information for custom user intent resolution activity. 9257 mResolveActivity.applicationInfo = pkg.applicationInfo; 9258 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9259 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9260 mResolveActivity.processName = pkg.applicationInfo.packageName; 9261 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9262 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9263 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9264 mResolveActivity.theme = 0; 9265 mResolveActivity.exported = true; 9266 mResolveActivity.enabled = true; 9267 mResolveInfo.activityInfo = mResolveActivity; 9268 mResolveInfo.priority = 0; 9269 mResolveInfo.preferredOrder = 0; 9270 mResolveInfo.match = 0; 9271 mResolveComponentName = mCustomResolverComponentName; 9272 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9273 mResolveComponentName); 9274 } 9275 } 9276 9277 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9278 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9279 9280 // Set up information for ephemeral installer activity 9281 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9282 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9283 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9284 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9285 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9286 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9287 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9288 mEphemeralInstallerActivity.theme = 0; 9289 mEphemeralInstallerActivity.exported = true; 9290 mEphemeralInstallerActivity.enabled = true; 9291 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9292 mEphemeralInstallerInfo.priority = 0; 9293 mEphemeralInstallerInfo.preferredOrder = 1; 9294 mEphemeralInstallerInfo.isDefault = true; 9295 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9296 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9297 9298 if (DEBUG_EPHEMERAL) { 9299 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9300 } 9301 } 9302 9303 private static String calculateBundledApkRoot(final String codePathString) { 9304 final File codePath = new File(codePathString); 9305 final File codeRoot; 9306 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9307 codeRoot = Environment.getRootDirectory(); 9308 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9309 codeRoot = Environment.getOemDirectory(); 9310 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9311 codeRoot = Environment.getVendorDirectory(); 9312 } else { 9313 // Unrecognized code path; take its top real segment as the apk root: 9314 // e.g. /something/app/blah.apk => /something 9315 try { 9316 File f = codePath.getCanonicalFile(); 9317 File parent = f.getParentFile(); // non-null because codePath is a file 9318 File tmp; 9319 while ((tmp = parent.getParentFile()) != null) { 9320 f = parent; 9321 parent = tmp; 9322 } 9323 codeRoot = f; 9324 Slog.w(TAG, "Unrecognized code path " 9325 + codePath + " - using " + codeRoot); 9326 } catch (IOException e) { 9327 // Can't canonicalize the code path -- shenanigans? 9328 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9329 return Environment.getRootDirectory().getPath(); 9330 } 9331 } 9332 return codeRoot.getPath(); 9333 } 9334 9335 /** 9336 * Derive and set the location of native libraries for the given package, 9337 * which varies depending on where and how the package was installed. 9338 */ 9339 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9340 final ApplicationInfo info = pkg.applicationInfo; 9341 final String codePath = pkg.codePath; 9342 final File codeFile = new File(codePath); 9343 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9344 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9345 9346 info.nativeLibraryRootDir = null; 9347 info.nativeLibraryRootRequiresIsa = false; 9348 info.nativeLibraryDir = null; 9349 info.secondaryNativeLibraryDir = null; 9350 9351 if (isApkFile(codeFile)) { 9352 // Monolithic install 9353 if (bundledApp) { 9354 // If "/system/lib64/apkname" exists, assume that is the per-package 9355 // native library directory to use; otherwise use "/system/lib/apkname". 9356 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9357 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9358 getPrimaryInstructionSet(info)); 9359 9360 // This is a bundled system app so choose the path based on the ABI. 9361 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9362 // is just the default path. 9363 final String apkName = deriveCodePathName(codePath); 9364 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9365 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9366 apkName).getAbsolutePath(); 9367 9368 if (info.secondaryCpuAbi != null) { 9369 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9370 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9371 secondaryLibDir, apkName).getAbsolutePath(); 9372 } 9373 } else if (asecApp) { 9374 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9375 .getAbsolutePath(); 9376 } else { 9377 final String apkName = deriveCodePathName(codePath); 9378 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9379 .getAbsolutePath(); 9380 } 9381 9382 info.nativeLibraryRootRequiresIsa = false; 9383 info.nativeLibraryDir = info.nativeLibraryRootDir; 9384 } else { 9385 // Cluster install 9386 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9387 info.nativeLibraryRootRequiresIsa = true; 9388 9389 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9390 getPrimaryInstructionSet(info)).getAbsolutePath(); 9391 9392 if (info.secondaryCpuAbi != null) { 9393 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9394 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9395 } 9396 } 9397 } 9398 9399 /** 9400 * Calculate the abis and roots for a bundled app. These can uniquely 9401 * be determined from the contents of the system partition, i.e whether 9402 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9403 * of this information, and instead assume that the system was built 9404 * sensibly. 9405 */ 9406 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9407 PackageSetting pkgSetting) { 9408 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9409 9410 // If "/system/lib64/apkname" exists, assume that is the per-package 9411 // native library directory to use; otherwise use "/system/lib/apkname". 9412 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9413 setBundledAppAbi(pkg, apkRoot, apkName); 9414 // pkgSetting might be null during rescan following uninstall of updates 9415 // to a bundled app, so accommodate that possibility. The settings in 9416 // that case will be established later from the parsed package. 9417 // 9418 // If the settings aren't null, sync them up with what we've just derived. 9419 // note that apkRoot isn't stored in the package settings. 9420 if (pkgSetting != null) { 9421 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9422 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9423 } 9424 } 9425 9426 /** 9427 * Deduces the ABI of a bundled app and sets the relevant fields on the 9428 * parsed pkg object. 9429 * 9430 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9431 * under which system libraries are installed. 9432 * @param apkName the name of the installed package. 9433 */ 9434 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9435 final File codeFile = new File(pkg.codePath); 9436 9437 final boolean has64BitLibs; 9438 final boolean has32BitLibs; 9439 if (isApkFile(codeFile)) { 9440 // Monolithic install 9441 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9442 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9443 } else { 9444 // Cluster install 9445 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9446 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9447 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9448 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9449 has64BitLibs = (new File(rootDir, isa)).exists(); 9450 } else { 9451 has64BitLibs = false; 9452 } 9453 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9454 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9455 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9456 has32BitLibs = (new File(rootDir, isa)).exists(); 9457 } else { 9458 has32BitLibs = false; 9459 } 9460 } 9461 9462 if (has64BitLibs && !has32BitLibs) { 9463 // The package has 64 bit libs, but not 32 bit libs. Its primary 9464 // ABI should be 64 bit. We can safely assume here that the bundled 9465 // native libraries correspond to the most preferred ABI in the list. 9466 9467 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9468 pkg.applicationInfo.secondaryCpuAbi = null; 9469 } else if (has32BitLibs && !has64BitLibs) { 9470 // The package has 32 bit libs but not 64 bit libs. Its primary 9471 // ABI should be 32 bit. 9472 9473 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9474 pkg.applicationInfo.secondaryCpuAbi = null; 9475 } else if (has32BitLibs && has64BitLibs) { 9476 // The application has both 64 and 32 bit bundled libraries. We check 9477 // here that the app declares multiArch support, and warn if it doesn't. 9478 // 9479 // We will be lenient here and record both ABIs. The primary will be the 9480 // ABI that's higher on the list, i.e, a device that's configured to prefer 9481 // 64 bit apps will see a 64 bit primary ABI, 9482 9483 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9484 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9485 } 9486 9487 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9488 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9489 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9490 } else { 9491 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9492 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9493 } 9494 } else { 9495 pkg.applicationInfo.primaryCpuAbi = null; 9496 pkg.applicationInfo.secondaryCpuAbi = null; 9497 } 9498 } 9499 9500 private void killApplication(String pkgName, int appId, String reason) { 9501 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9502 } 9503 9504 private void killApplication(String pkgName, int appId, int userId, String reason) { 9505 // Request the ActivityManager to kill the process(only for existing packages) 9506 // so that we do not end up in a confused state while the user is still using the older 9507 // version of the application while the new one gets installed. 9508 final long token = Binder.clearCallingIdentity(); 9509 try { 9510 IActivityManager am = ActivityManagerNative.getDefault(); 9511 if (am != null) { 9512 try { 9513 am.killApplication(pkgName, appId, userId, reason); 9514 } catch (RemoteException e) { 9515 } 9516 } 9517 } finally { 9518 Binder.restoreCallingIdentity(token); 9519 } 9520 } 9521 9522 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9523 // Remove the parent package setting 9524 PackageSetting ps = (PackageSetting) pkg.mExtras; 9525 if (ps != null) { 9526 removePackageLI(ps, chatty); 9527 } 9528 // Remove the child package setting 9529 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9530 for (int i = 0; i < childCount; i++) { 9531 PackageParser.Package childPkg = pkg.childPackages.get(i); 9532 ps = (PackageSetting) childPkg.mExtras; 9533 if (ps != null) { 9534 removePackageLI(ps, chatty); 9535 } 9536 } 9537 } 9538 9539 void removePackageLI(PackageSetting ps, boolean chatty) { 9540 if (DEBUG_INSTALL) { 9541 if (chatty) 9542 Log.d(TAG, "Removing package " + ps.name); 9543 } 9544 9545 // writer 9546 synchronized (mPackages) { 9547 mPackages.remove(ps.name); 9548 final PackageParser.Package pkg = ps.pkg; 9549 if (pkg != null) { 9550 cleanPackageDataStructuresLILPw(pkg, chatty); 9551 } 9552 } 9553 } 9554 9555 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9556 if (DEBUG_INSTALL) { 9557 if (chatty) 9558 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9559 } 9560 9561 // writer 9562 synchronized (mPackages) { 9563 // Remove the parent package 9564 mPackages.remove(pkg.applicationInfo.packageName); 9565 cleanPackageDataStructuresLILPw(pkg, chatty); 9566 9567 // Remove the child packages 9568 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9569 for (int i = 0; i < childCount; i++) { 9570 PackageParser.Package childPkg = pkg.childPackages.get(i); 9571 mPackages.remove(childPkg.applicationInfo.packageName); 9572 cleanPackageDataStructuresLILPw(childPkg, chatty); 9573 } 9574 } 9575 } 9576 9577 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9578 int N = pkg.providers.size(); 9579 StringBuilder r = null; 9580 int i; 9581 for (i=0; i<N; i++) { 9582 PackageParser.Provider p = pkg.providers.get(i); 9583 mProviders.removeProvider(p); 9584 if (p.info.authority == null) { 9585 9586 /* There was another ContentProvider with this authority when 9587 * this app was installed so this authority is null, 9588 * Ignore it as we don't have to unregister the provider. 9589 */ 9590 continue; 9591 } 9592 String names[] = p.info.authority.split(";"); 9593 for (int j = 0; j < names.length; j++) { 9594 if (mProvidersByAuthority.get(names[j]) == p) { 9595 mProvidersByAuthority.remove(names[j]); 9596 if (DEBUG_REMOVE) { 9597 if (chatty) 9598 Log.d(TAG, "Unregistered content provider: " + names[j] 9599 + ", className = " + p.info.name + ", isSyncable = " 9600 + p.info.isSyncable); 9601 } 9602 } 9603 } 9604 if (DEBUG_REMOVE && chatty) { 9605 if (r == null) { 9606 r = new StringBuilder(256); 9607 } else { 9608 r.append(' '); 9609 } 9610 r.append(p.info.name); 9611 } 9612 } 9613 if (r != null) { 9614 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9615 } 9616 9617 N = pkg.services.size(); 9618 r = null; 9619 for (i=0; i<N; i++) { 9620 PackageParser.Service s = pkg.services.get(i); 9621 mServices.removeService(s); 9622 if (chatty) { 9623 if (r == null) { 9624 r = new StringBuilder(256); 9625 } else { 9626 r.append(' '); 9627 } 9628 r.append(s.info.name); 9629 } 9630 } 9631 if (r != null) { 9632 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9633 } 9634 9635 N = pkg.receivers.size(); 9636 r = null; 9637 for (i=0; i<N; i++) { 9638 PackageParser.Activity a = pkg.receivers.get(i); 9639 mReceivers.removeActivity(a, "receiver"); 9640 if (DEBUG_REMOVE && chatty) { 9641 if (r == null) { 9642 r = new StringBuilder(256); 9643 } else { 9644 r.append(' '); 9645 } 9646 r.append(a.info.name); 9647 } 9648 } 9649 if (r != null) { 9650 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9651 } 9652 9653 N = pkg.activities.size(); 9654 r = null; 9655 for (i=0; i<N; i++) { 9656 PackageParser.Activity a = pkg.activities.get(i); 9657 mActivities.removeActivity(a, "activity"); 9658 if (DEBUG_REMOVE && chatty) { 9659 if (r == null) { 9660 r = new StringBuilder(256); 9661 } else { 9662 r.append(' '); 9663 } 9664 r.append(a.info.name); 9665 } 9666 } 9667 if (r != null) { 9668 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9669 } 9670 9671 N = pkg.permissions.size(); 9672 r = null; 9673 for (i=0; i<N; i++) { 9674 PackageParser.Permission p = pkg.permissions.get(i); 9675 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9676 if (bp == null) { 9677 bp = mSettings.mPermissionTrees.get(p.info.name); 9678 } 9679 if (bp != null && bp.perm == p) { 9680 bp.perm = null; 9681 if (DEBUG_REMOVE && chatty) { 9682 if (r == null) { 9683 r = new StringBuilder(256); 9684 } else { 9685 r.append(' '); 9686 } 9687 r.append(p.info.name); 9688 } 9689 } 9690 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9691 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9692 if (appOpPkgs != null) { 9693 appOpPkgs.remove(pkg.packageName); 9694 } 9695 } 9696 } 9697 if (r != null) { 9698 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9699 } 9700 9701 N = pkg.requestedPermissions.size(); 9702 r = null; 9703 for (i=0; i<N; i++) { 9704 String perm = pkg.requestedPermissions.get(i); 9705 BasePermission bp = mSettings.mPermissions.get(perm); 9706 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9707 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9708 if (appOpPkgs != null) { 9709 appOpPkgs.remove(pkg.packageName); 9710 if (appOpPkgs.isEmpty()) { 9711 mAppOpPermissionPackages.remove(perm); 9712 } 9713 } 9714 } 9715 } 9716 if (r != null) { 9717 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9718 } 9719 9720 N = pkg.instrumentation.size(); 9721 r = null; 9722 for (i=0; i<N; i++) { 9723 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9724 mInstrumentation.remove(a.getComponentName()); 9725 if (DEBUG_REMOVE && chatty) { 9726 if (r == null) { 9727 r = new StringBuilder(256); 9728 } else { 9729 r.append(' '); 9730 } 9731 r.append(a.info.name); 9732 } 9733 } 9734 if (r != null) { 9735 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9736 } 9737 9738 r = null; 9739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9740 // Only system apps can hold shared libraries. 9741 if (pkg.libraryNames != null) { 9742 for (i=0; i<pkg.libraryNames.size(); i++) { 9743 String name = pkg.libraryNames.get(i); 9744 SharedLibraryEntry cur = mSharedLibraries.get(name); 9745 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9746 mSharedLibraries.remove(name); 9747 if (DEBUG_REMOVE && chatty) { 9748 if (r == null) { 9749 r = new StringBuilder(256); 9750 } else { 9751 r.append(' '); 9752 } 9753 r.append(name); 9754 } 9755 } 9756 } 9757 } 9758 } 9759 if (r != null) { 9760 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9761 } 9762 } 9763 9764 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9765 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9766 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9767 return true; 9768 } 9769 } 9770 return false; 9771 } 9772 9773 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9774 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9775 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9776 9777 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9778 // Update the parent permissions 9779 updatePermissionsLPw(pkg.packageName, pkg, flags); 9780 // Update the child permissions 9781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9782 for (int i = 0; i < childCount; i++) { 9783 PackageParser.Package childPkg = pkg.childPackages.get(i); 9784 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9785 } 9786 } 9787 9788 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9789 int flags) { 9790 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9791 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9792 } 9793 9794 private void updatePermissionsLPw(String changingPkg, 9795 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9796 // Make sure there are no dangling permission trees. 9797 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9798 while (it.hasNext()) { 9799 final BasePermission bp = it.next(); 9800 if (bp.packageSetting == null) { 9801 // We may not yet have parsed the package, so just see if 9802 // we still know about its settings. 9803 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9804 } 9805 if (bp.packageSetting == null) { 9806 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9807 + " from package " + bp.sourcePackage); 9808 it.remove(); 9809 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9810 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9811 Slog.i(TAG, "Removing old permission tree: " + bp.name 9812 + " from package " + bp.sourcePackage); 9813 flags |= UPDATE_PERMISSIONS_ALL; 9814 it.remove(); 9815 } 9816 } 9817 } 9818 9819 // Make sure all dynamic permissions have been assigned to a package, 9820 // and make sure there are no dangling permissions. 9821 it = mSettings.mPermissions.values().iterator(); 9822 while (it.hasNext()) { 9823 final BasePermission bp = it.next(); 9824 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9825 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9826 + bp.name + " pkg=" + bp.sourcePackage 9827 + " info=" + bp.pendingInfo); 9828 if (bp.packageSetting == null && bp.pendingInfo != null) { 9829 final BasePermission tree = findPermissionTreeLP(bp.name); 9830 if (tree != null && tree.perm != null) { 9831 bp.packageSetting = tree.packageSetting; 9832 bp.perm = new PackageParser.Permission(tree.perm.owner, 9833 new PermissionInfo(bp.pendingInfo)); 9834 bp.perm.info.packageName = tree.perm.info.packageName; 9835 bp.perm.info.name = bp.name; 9836 bp.uid = tree.uid; 9837 } 9838 } 9839 } 9840 if (bp.packageSetting == null) { 9841 // We may not yet have parsed the package, so just see if 9842 // we still know about its settings. 9843 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9844 } 9845 if (bp.packageSetting == null) { 9846 Slog.w(TAG, "Removing dangling permission: " + bp.name 9847 + " from package " + bp.sourcePackage); 9848 it.remove(); 9849 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9850 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9851 Slog.i(TAG, "Removing old permission: " + bp.name 9852 + " from package " + bp.sourcePackage); 9853 flags |= UPDATE_PERMISSIONS_ALL; 9854 it.remove(); 9855 } 9856 } 9857 } 9858 9859 // Now update the permissions for all packages, in particular 9860 // replace the granted permissions of the system packages. 9861 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9862 for (PackageParser.Package pkg : mPackages.values()) { 9863 if (pkg != pkgInfo) { 9864 // Only replace for packages on requested volume 9865 final String volumeUuid = getVolumeUuidForPackage(pkg); 9866 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9867 && Objects.equals(replaceVolumeUuid, volumeUuid); 9868 grantPermissionsLPw(pkg, replace, changingPkg); 9869 } 9870 } 9871 } 9872 9873 if (pkgInfo != null) { 9874 // Only replace for packages on requested volume 9875 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9876 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9877 && Objects.equals(replaceVolumeUuid, volumeUuid); 9878 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9879 } 9880 } 9881 9882 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9883 String packageOfInterest) { 9884 // IMPORTANT: There are two types of permissions: install and runtime. 9885 // Install time permissions are granted when the app is installed to 9886 // all device users and users added in the future. Runtime permissions 9887 // are granted at runtime explicitly to specific users. Normal and signature 9888 // protected permissions are install time permissions. Dangerous permissions 9889 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9890 // otherwise they are runtime permissions. This function does not manage 9891 // runtime permissions except for the case an app targeting Lollipop MR1 9892 // being upgraded to target a newer SDK, in which case dangerous permissions 9893 // are transformed from install time to runtime ones. 9894 9895 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9896 if (ps == null) { 9897 return; 9898 } 9899 9900 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9901 9902 PermissionsState permissionsState = ps.getPermissionsState(); 9903 PermissionsState origPermissions = permissionsState; 9904 9905 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9906 9907 boolean runtimePermissionsRevoked = false; 9908 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9909 9910 boolean changedInstallPermission = false; 9911 9912 if (replace) { 9913 ps.installPermissionsFixed = false; 9914 if (!ps.isSharedUser()) { 9915 origPermissions = new PermissionsState(permissionsState); 9916 permissionsState.reset(); 9917 } else { 9918 // We need to know only about runtime permission changes since the 9919 // calling code always writes the install permissions state but 9920 // the runtime ones are written only if changed. The only cases of 9921 // changed runtime permissions here are promotion of an install to 9922 // runtime and revocation of a runtime from a shared user. 9923 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9924 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9925 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9926 runtimePermissionsRevoked = true; 9927 } 9928 } 9929 } 9930 9931 permissionsState.setGlobalGids(mGlobalGids); 9932 9933 final int N = pkg.requestedPermissions.size(); 9934 for (int i=0; i<N; i++) { 9935 final String name = pkg.requestedPermissions.get(i); 9936 final BasePermission bp = mSettings.mPermissions.get(name); 9937 9938 if (DEBUG_INSTALL) { 9939 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9940 } 9941 9942 if (bp == null || bp.packageSetting == null) { 9943 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9944 Slog.w(TAG, "Unknown permission " + name 9945 + " in package " + pkg.packageName); 9946 } 9947 continue; 9948 } 9949 9950 final String perm = bp.name; 9951 boolean allowedSig = false; 9952 int grant = GRANT_DENIED; 9953 9954 // Keep track of app op permissions. 9955 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9956 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9957 if (pkgs == null) { 9958 pkgs = new ArraySet<>(); 9959 mAppOpPermissionPackages.put(bp.name, pkgs); 9960 } 9961 pkgs.add(pkg.packageName); 9962 } 9963 9964 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9965 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9966 >= Build.VERSION_CODES.M; 9967 switch (level) { 9968 case PermissionInfo.PROTECTION_NORMAL: { 9969 // For all apps normal permissions are install time ones. 9970 grant = GRANT_INSTALL; 9971 } break; 9972 9973 case PermissionInfo.PROTECTION_DANGEROUS: { 9974 // If a permission review is required for legacy apps we represent 9975 // their permissions as always granted runtime ones since we need 9976 // to keep the review required permission flag per user while an 9977 // install permission's state is shared across all users. 9978 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9979 // For legacy apps dangerous permissions are install time ones. 9980 grant = GRANT_INSTALL; 9981 } else if (origPermissions.hasInstallPermission(bp.name)) { 9982 // For legacy apps that became modern, install becomes runtime. 9983 grant = GRANT_UPGRADE; 9984 } else if (mPromoteSystemApps 9985 && isSystemApp(ps) 9986 && mExistingSystemPackages.contains(ps.name)) { 9987 // For legacy system apps, install becomes runtime. 9988 // We cannot check hasInstallPermission() for system apps since those 9989 // permissions were granted implicitly and not persisted pre-M. 9990 grant = GRANT_UPGRADE; 9991 } else { 9992 // For modern apps keep runtime permissions unchanged. 9993 grant = GRANT_RUNTIME; 9994 } 9995 } break; 9996 9997 case PermissionInfo.PROTECTION_SIGNATURE: { 9998 // For all apps signature permissions are install time ones. 9999 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10000 if (allowedSig) { 10001 grant = GRANT_INSTALL; 10002 } 10003 } break; 10004 } 10005 10006 if (DEBUG_INSTALL) { 10007 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10008 } 10009 10010 if (grant != GRANT_DENIED) { 10011 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10012 // If this is an existing, non-system package, then 10013 // we can't add any new permissions to it. 10014 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10015 // Except... if this is a permission that was added 10016 // to the platform (note: need to only do this when 10017 // updating the platform). 10018 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10019 grant = GRANT_DENIED; 10020 } 10021 } 10022 } 10023 10024 switch (grant) { 10025 case GRANT_INSTALL: { 10026 // Revoke this as runtime permission to handle the case of 10027 // a runtime permission being downgraded to an install one. 10028 // Also in permission review mode we keep dangerous permissions 10029 // for legacy apps 10030 for (int userId : UserManagerService.getInstance().getUserIds()) { 10031 if (origPermissions.getRuntimePermissionState( 10032 bp.name, userId) != null) { 10033 // Revoke the runtime permission and clear the flags. 10034 origPermissions.revokeRuntimePermission(bp, userId); 10035 origPermissions.updatePermissionFlags(bp, userId, 10036 PackageManager.MASK_PERMISSION_FLAGS, 0); 10037 // If we revoked a permission permission, we have to write. 10038 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10039 changedRuntimePermissionUserIds, userId); 10040 } 10041 } 10042 // Grant an install permission. 10043 if (permissionsState.grantInstallPermission(bp) != 10044 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10045 changedInstallPermission = true; 10046 } 10047 } break; 10048 10049 case GRANT_RUNTIME: { 10050 // Grant previously granted runtime permissions. 10051 for (int userId : UserManagerService.getInstance().getUserIds()) { 10052 PermissionState permissionState = origPermissions 10053 .getRuntimePermissionState(bp.name, userId); 10054 int flags = permissionState != null 10055 ? permissionState.getFlags() : 0; 10056 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10057 if (permissionsState.grantRuntimePermission(bp, userId) == 10058 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10059 // If we cannot put the permission as it was, we have to write. 10060 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10061 changedRuntimePermissionUserIds, userId); 10062 } 10063 // If the app supports runtime permissions no need for a review. 10064 if (Build.PERMISSIONS_REVIEW_REQUIRED 10065 && appSupportsRuntimePermissions 10066 && (flags & PackageManager 10067 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10068 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10069 // Since we changed the flags, we have to write. 10070 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10071 changedRuntimePermissionUserIds, userId); 10072 } 10073 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10074 && !appSupportsRuntimePermissions) { 10075 // For legacy apps that need a permission review, every new 10076 // runtime permission is granted but it is pending a review. 10077 // We also need to review only platform defined runtime 10078 // permissions as these are the only ones the platform knows 10079 // how to disable the API to simulate revocation as legacy 10080 // apps don't expect to run with revoked permissions. 10081 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10082 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10083 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10084 // We changed the flags, hence have to write. 10085 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10086 changedRuntimePermissionUserIds, userId); 10087 } 10088 } 10089 if (permissionsState.grantRuntimePermission(bp, userId) 10090 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10091 // We changed the permission, hence have to write. 10092 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10093 changedRuntimePermissionUserIds, userId); 10094 } 10095 } 10096 // Propagate the permission flags. 10097 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10098 } 10099 } break; 10100 10101 case GRANT_UPGRADE: { 10102 // Grant runtime permissions for a previously held install permission. 10103 PermissionState permissionState = origPermissions 10104 .getInstallPermissionState(bp.name); 10105 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10106 10107 if (origPermissions.revokeInstallPermission(bp) 10108 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10109 // We will be transferring the permission flags, so clear them. 10110 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10111 PackageManager.MASK_PERMISSION_FLAGS, 0); 10112 changedInstallPermission = true; 10113 } 10114 10115 // If the permission is not to be promoted to runtime we ignore it and 10116 // also its other flags as they are not applicable to install permissions. 10117 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10118 for (int userId : currentUserIds) { 10119 if (permissionsState.grantRuntimePermission(bp, userId) != 10120 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10121 // Transfer the permission flags. 10122 permissionsState.updatePermissionFlags(bp, userId, 10123 flags, flags); 10124 // If we granted the permission, we have to write. 10125 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10126 changedRuntimePermissionUserIds, userId); 10127 } 10128 } 10129 } 10130 } break; 10131 10132 default: { 10133 if (packageOfInterest == null 10134 || packageOfInterest.equals(pkg.packageName)) { 10135 Slog.w(TAG, "Not granting permission " + perm 10136 + " to package " + pkg.packageName 10137 + " because it was previously installed without"); 10138 } 10139 } break; 10140 } 10141 } else { 10142 if (permissionsState.revokeInstallPermission(bp) != 10143 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10144 // Also drop the permission flags. 10145 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10146 PackageManager.MASK_PERMISSION_FLAGS, 0); 10147 changedInstallPermission = true; 10148 Slog.i(TAG, "Un-granting permission " + perm 10149 + " from package " + pkg.packageName 10150 + " (protectionLevel=" + bp.protectionLevel 10151 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10152 + ")"); 10153 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10154 // Don't print warning for app op permissions, since it is fine for them 10155 // not to be granted, there is a UI for the user to decide. 10156 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10157 Slog.w(TAG, "Not granting permission " + perm 10158 + " to package " + pkg.packageName 10159 + " (protectionLevel=" + bp.protectionLevel 10160 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10161 + ")"); 10162 } 10163 } 10164 } 10165 } 10166 10167 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10168 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10169 // This is the first that we have heard about this package, so the 10170 // permissions we have now selected are fixed until explicitly 10171 // changed. 10172 ps.installPermissionsFixed = true; 10173 } 10174 10175 // Persist the runtime permissions state for users with changes. If permissions 10176 // were revoked because no app in the shared user declares them we have to 10177 // write synchronously to avoid losing runtime permissions state. 10178 for (int userId : changedRuntimePermissionUserIds) { 10179 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10180 } 10181 10182 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10183 } 10184 10185 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10186 boolean allowed = false; 10187 final int NP = PackageParser.NEW_PERMISSIONS.length; 10188 for (int ip=0; ip<NP; ip++) { 10189 final PackageParser.NewPermissionInfo npi 10190 = PackageParser.NEW_PERMISSIONS[ip]; 10191 if (npi.name.equals(perm) 10192 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10193 allowed = true; 10194 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10195 + pkg.packageName); 10196 break; 10197 } 10198 } 10199 return allowed; 10200 } 10201 10202 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10203 BasePermission bp, PermissionsState origPermissions) { 10204 boolean allowed; 10205 allowed = (compareSignatures( 10206 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10207 == PackageManager.SIGNATURE_MATCH) 10208 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10209 == PackageManager.SIGNATURE_MATCH); 10210 if (!allowed && (bp.protectionLevel 10211 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10212 if (isSystemApp(pkg)) { 10213 // For updated system applications, a system permission 10214 // is granted only if it had been defined by the original application. 10215 if (pkg.isUpdatedSystemApp()) { 10216 final PackageSetting sysPs = mSettings 10217 .getDisabledSystemPkgLPr(pkg.packageName); 10218 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10219 // If the original was granted this permission, we take 10220 // that grant decision as read and propagate it to the 10221 // update. 10222 if (sysPs.isPrivileged()) { 10223 allowed = true; 10224 } 10225 } else { 10226 // The system apk may have been updated with an older 10227 // version of the one on the data partition, but which 10228 // granted a new system permission that it didn't have 10229 // before. In this case we do want to allow the app to 10230 // now get the new permission if the ancestral apk is 10231 // privileged to get it. 10232 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10233 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10234 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10235 allowed = true; 10236 break; 10237 } 10238 } 10239 } 10240 // Also if a privileged parent package on the system image or any of 10241 // its children requested a privileged permission, the updated child 10242 // packages can also get the permission. 10243 if (pkg.parentPackage != null) { 10244 final PackageSetting disabledSysParentPs = mSettings 10245 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10246 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10247 && disabledSysParentPs.isPrivileged()) { 10248 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10249 allowed = true; 10250 } else if (disabledSysParentPs.pkg.childPackages != null) { 10251 final int count = disabledSysParentPs.pkg.childPackages.size(); 10252 for (int i = 0; i < count; i++) { 10253 PackageParser.Package disabledSysChildPkg = 10254 disabledSysParentPs.pkg.childPackages.get(i); 10255 if (isPackageRequestingPermission(disabledSysChildPkg, 10256 perm)) { 10257 allowed = true; 10258 break; 10259 } 10260 } 10261 } 10262 } 10263 } 10264 } 10265 } else { 10266 allowed = isPrivilegedApp(pkg); 10267 } 10268 } 10269 } 10270 if (!allowed) { 10271 if (!allowed && (bp.protectionLevel 10272 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10273 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10274 // If this was a previously normal/dangerous permission that got moved 10275 // to a system permission as part of the runtime permission redesign, then 10276 // we still want to blindly grant it to old apps. 10277 allowed = true; 10278 } 10279 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10280 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10281 // If this permission is to be granted to the system installer and 10282 // this app is an installer, then it gets the permission. 10283 allowed = true; 10284 } 10285 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10286 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10287 // If this permission is to be granted to the system verifier and 10288 // this app is a verifier, then it gets the permission. 10289 allowed = true; 10290 } 10291 if (!allowed && (bp.protectionLevel 10292 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10293 && isSystemApp(pkg)) { 10294 // Any pre-installed system app is allowed to get this permission. 10295 allowed = true; 10296 } 10297 if (!allowed && (bp.protectionLevel 10298 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10299 // For development permissions, a development permission 10300 // is granted only if it was already granted. 10301 allowed = origPermissions.hasInstallPermission(perm); 10302 } 10303 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10304 && pkg.packageName.equals(mSetupWizardPackage)) { 10305 // If this permission is to be granted to the system setup wizard and 10306 // this app is a setup wizard, then it gets the permission. 10307 allowed = true; 10308 } 10309 } 10310 return allowed; 10311 } 10312 10313 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10314 final int permCount = pkg.requestedPermissions.size(); 10315 for (int j = 0; j < permCount; j++) { 10316 String requestedPermission = pkg.requestedPermissions.get(j); 10317 if (permission.equals(requestedPermission)) { 10318 return true; 10319 } 10320 } 10321 return false; 10322 } 10323 10324 final class ActivityIntentResolver 10325 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10326 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10327 boolean defaultOnly, int userId) { 10328 if (!sUserManager.exists(userId)) return null; 10329 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10330 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10331 } 10332 10333 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10334 int userId) { 10335 if (!sUserManager.exists(userId)) return null; 10336 mFlags = flags; 10337 return super.queryIntent(intent, resolvedType, 10338 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10339 } 10340 10341 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10342 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10343 if (!sUserManager.exists(userId)) return null; 10344 if (packageActivities == null) { 10345 return null; 10346 } 10347 mFlags = flags; 10348 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10349 final int N = packageActivities.size(); 10350 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10351 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10352 10353 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10354 for (int i = 0; i < N; ++i) { 10355 intentFilters = packageActivities.get(i).intents; 10356 if (intentFilters != null && intentFilters.size() > 0) { 10357 PackageParser.ActivityIntentInfo[] array = 10358 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10359 intentFilters.toArray(array); 10360 listCut.add(array); 10361 } 10362 } 10363 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10364 } 10365 10366 /** 10367 * Finds a privileged activity that matches the specified activity names. 10368 */ 10369 private PackageParser.Activity findMatchingActivity( 10370 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10371 for (PackageParser.Activity sysActivity : activityList) { 10372 if (sysActivity.info.name.equals(activityInfo.name)) { 10373 return sysActivity; 10374 } 10375 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10376 return sysActivity; 10377 } 10378 if (sysActivity.info.targetActivity != null) { 10379 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10380 return sysActivity; 10381 } 10382 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10383 return sysActivity; 10384 } 10385 } 10386 } 10387 return null; 10388 } 10389 10390 public class IterGenerator<E> { 10391 public Iterator<E> generate(ActivityIntentInfo info) { 10392 return null; 10393 } 10394 } 10395 10396 public class ActionIterGenerator extends IterGenerator<String> { 10397 @Override 10398 public Iterator<String> generate(ActivityIntentInfo info) { 10399 return info.actionsIterator(); 10400 } 10401 } 10402 10403 public class CategoriesIterGenerator extends IterGenerator<String> { 10404 @Override 10405 public Iterator<String> generate(ActivityIntentInfo info) { 10406 return info.categoriesIterator(); 10407 } 10408 } 10409 10410 public class SchemesIterGenerator extends IterGenerator<String> { 10411 @Override 10412 public Iterator<String> generate(ActivityIntentInfo info) { 10413 return info.schemesIterator(); 10414 } 10415 } 10416 10417 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10418 @Override 10419 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10420 return info.authoritiesIterator(); 10421 } 10422 } 10423 10424 /** 10425 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10426 * MODIFIED. Do not pass in a list that should not be changed. 10427 */ 10428 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10429 IterGenerator<T> generator, Iterator<T> searchIterator) { 10430 // loop through the set of actions; every one must be found in the intent filter 10431 while (searchIterator.hasNext()) { 10432 // we must have at least one filter in the list to consider a match 10433 if (intentList.size() == 0) { 10434 break; 10435 } 10436 10437 final T searchAction = searchIterator.next(); 10438 10439 // loop through the set of intent filters 10440 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10441 while (intentIter.hasNext()) { 10442 final ActivityIntentInfo intentInfo = intentIter.next(); 10443 boolean selectionFound = false; 10444 10445 // loop through the intent filter's selection criteria; at least one 10446 // of them must match the searched criteria 10447 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10448 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10449 final T intentSelection = intentSelectionIter.next(); 10450 if (intentSelection != null && intentSelection.equals(searchAction)) { 10451 selectionFound = true; 10452 break; 10453 } 10454 } 10455 10456 // the selection criteria wasn't found in this filter's set; this filter 10457 // is not a potential match 10458 if (!selectionFound) { 10459 intentIter.remove(); 10460 } 10461 } 10462 } 10463 } 10464 10465 private boolean isProtectedAction(ActivityIntentInfo filter) { 10466 final Iterator<String> actionsIter = filter.actionsIterator(); 10467 while (actionsIter != null && actionsIter.hasNext()) { 10468 final String filterAction = actionsIter.next(); 10469 if (PROTECTED_ACTIONS.contains(filterAction)) { 10470 return true; 10471 } 10472 } 10473 return false; 10474 } 10475 10476 /** 10477 * Adjusts the priority of the given intent filter according to policy. 10478 * <p> 10479 * <ul> 10480 * <li>The priority for non privileged applications is capped to '0'</li> 10481 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10482 * <li>The priority for unbundled updates to privileged applications is capped to the 10483 * priority defined on the system partition</li> 10484 * </ul> 10485 * <p> 10486 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10487 * allowed to obtain any priority on any action. 10488 */ 10489 private void adjustPriority( 10490 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10491 // nothing to do; priority is fine as-is 10492 if (intent.getPriority() <= 0) { 10493 return; 10494 } 10495 10496 final ActivityInfo activityInfo = intent.activity.info; 10497 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10498 10499 final boolean privilegedApp = 10500 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10501 if (!privilegedApp) { 10502 // non-privileged applications can never define a priority >0 10503 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10504 + " package: " + applicationInfo.packageName 10505 + " activity: " + intent.activity.className 10506 + " origPrio: " + intent.getPriority()); 10507 intent.setPriority(0); 10508 return; 10509 } 10510 10511 if (systemActivities == null) { 10512 // the system package is not disabled; we're parsing the system partition 10513 if (isProtectedAction(intent)) { 10514 if (mDeferProtectedFilters) { 10515 // We can't deal with these just yet. No component should ever obtain a 10516 // >0 priority for a protected actions, with ONE exception -- the setup 10517 // wizard. The setup wizard, however, cannot be known until we're able to 10518 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10519 // until all intent filters have been processed. Chicken, meet egg. 10520 // Let the filter temporarily have a high priority and rectify the 10521 // priorities after all system packages have been scanned. 10522 mProtectedFilters.add(intent); 10523 if (DEBUG_FILTERS) { 10524 Slog.i(TAG, "Protected action; save for later;" 10525 + " package: " + applicationInfo.packageName 10526 + " activity: " + intent.activity.className 10527 + " origPrio: " + intent.getPriority()); 10528 } 10529 return; 10530 } else { 10531 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10532 Slog.i(TAG, "No setup wizard;" 10533 + " All protected intents capped to priority 0"); 10534 } 10535 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10536 if (DEBUG_FILTERS) { 10537 Slog.i(TAG, "Found setup wizard;" 10538 + " allow priority " + intent.getPriority() + ";" 10539 + " package: " + intent.activity.info.packageName 10540 + " activity: " + intent.activity.className 10541 + " priority: " + intent.getPriority()); 10542 } 10543 // setup wizard gets whatever it wants 10544 return; 10545 } 10546 Slog.w(TAG, "Protected action; cap priority to 0;" 10547 + " package: " + intent.activity.info.packageName 10548 + " activity: " + intent.activity.className 10549 + " origPrio: " + intent.getPriority()); 10550 intent.setPriority(0); 10551 return; 10552 } 10553 } 10554 // privileged apps on the system image get whatever priority they request 10555 return; 10556 } 10557 10558 // privileged app unbundled update ... try to find the same activity 10559 final PackageParser.Activity foundActivity = 10560 findMatchingActivity(systemActivities, activityInfo); 10561 if (foundActivity == null) { 10562 // this is a new activity; it cannot obtain >0 priority 10563 if (DEBUG_FILTERS) { 10564 Slog.i(TAG, "New activity; cap priority to 0;" 10565 + " package: " + applicationInfo.packageName 10566 + " activity: " + intent.activity.className 10567 + " origPrio: " + intent.getPriority()); 10568 } 10569 intent.setPriority(0); 10570 return; 10571 } 10572 10573 // found activity, now check for filter equivalence 10574 10575 // a shallow copy is enough; we modify the list, not its contents 10576 final List<ActivityIntentInfo> intentListCopy = 10577 new ArrayList<>(foundActivity.intents); 10578 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10579 10580 // find matching action subsets 10581 final Iterator<String> actionsIterator = intent.actionsIterator(); 10582 if (actionsIterator != null) { 10583 getIntentListSubset( 10584 intentListCopy, new ActionIterGenerator(), actionsIterator); 10585 if (intentListCopy.size() == 0) { 10586 // no more intents to match; we're not equivalent 10587 if (DEBUG_FILTERS) { 10588 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10589 + " package: " + applicationInfo.packageName 10590 + " activity: " + intent.activity.className 10591 + " origPrio: " + intent.getPriority()); 10592 } 10593 intent.setPriority(0); 10594 return; 10595 } 10596 } 10597 10598 // find matching category subsets 10599 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10600 if (categoriesIterator != null) { 10601 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10602 categoriesIterator); 10603 if (intentListCopy.size() == 0) { 10604 // no more intents to match; we're not equivalent 10605 if (DEBUG_FILTERS) { 10606 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10607 + " package: " + applicationInfo.packageName 10608 + " activity: " + intent.activity.className 10609 + " origPrio: " + intent.getPriority()); 10610 } 10611 intent.setPriority(0); 10612 return; 10613 } 10614 } 10615 10616 // find matching schemes subsets 10617 final Iterator<String> schemesIterator = intent.schemesIterator(); 10618 if (schemesIterator != null) { 10619 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10620 schemesIterator); 10621 if (intentListCopy.size() == 0) { 10622 // no more intents to match; we're not equivalent 10623 if (DEBUG_FILTERS) { 10624 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10625 + " package: " + applicationInfo.packageName 10626 + " activity: " + intent.activity.className 10627 + " origPrio: " + intent.getPriority()); 10628 } 10629 intent.setPriority(0); 10630 return; 10631 } 10632 } 10633 10634 // find matching authorities subsets 10635 final Iterator<IntentFilter.AuthorityEntry> 10636 authoritiesIterator = intent.authoritiesIterator(); 10637 if (authoritiesIterator != null) { 10638 getIntentListSubset(intentListCopy, 10639 new AuthoritiesIterGenerator(), 10640 authoritiesIterator); 10641 if (intentListCopy.size() == 0) { 10642 // no more intents to match; we're not equivalent 10643 if (DEBUG_FILTERS) { 10644 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10645 + " package: " + applicationInfo.packageName 10646 + " activity: " + intent.activity.className 10647 + " origPrio: " + intent.getPriority()); 10648 } 10649 intent.setPriority(0); 10650 return; 10651 } 10652 } 10653 10654 // we found matching filter(s); app gets the max priority of all intents 10655 int cappedPriority = 0; 10656 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10657 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10658 } 10659 if (intent.getPriority() > cappedPriority) { 10660 if (DEBUG_FILTERS) { 10661 Slog.i(TAG, "Found matching filter(s);" 10662 + " cap priority to " + cappedPriority + ";" 10663 + " package: " + applicationInfo.packageName 10664 + " activity: " + intent.activity.className 10665 + " origPrio: " + intent.getPriority()); 10666 } 10667 intent.setPriority(cappedPriority); 10668 return; 10669 } 10670 // all this for nothing; the requested priority was <= what was on the system 10671 } 10672 10673 public final void addActivity(PackageParser.Activity a, String type) { 10674 mActivities.put(a.getComponentName(), a); 10675 if (DEBUG_SHOW_INFO) 10676 Log.v( 10677 TAG, " " + type + " " + 10678 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10679 if (DEBUG_SHOW_INFO) 10680 Log.v(TAG, " Class=" + a.info.name); 10681 final int NI = a.intents.size(); 10682 for (int j=0; j<NI; j++) { 10683 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10684 if ("activity".equals(type)) { 10685 final PackageSetting ps = 10686 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10687 final List<PackageParser.Activity> systemActivities = 10688 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10689 adjustPriority(systemActivities, intent); 10690 } 10691 if (DEBUG_SHOW_INFO) { 10692 Log.v(TAG, " IntentFilter:"); 10693 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10694 } 10695 if (!intent.debugCheck()) { 10696 Log.w(TAG, "==> For Activity " + a.info.name); 10697 } 10698 addFilter(intent); 10699 } 10700 } 10701 10702 public final void removeActivity(PackageParser.Activity a, String type) { 10703 mActivities.remove(a.getComponentName()); 10704 if (DEBUG_SHOW_INFO) { 10705 Log.v(TAG, " " + type + " " 10706 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10707 : a.info.name) + ":"); 10708 Log.v(TAG, " Class=" + a.info.name); 10709 } 10710 final int NI = a.intents.size(); 10711 for (int j=0; j<NI; j++) { 10712 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10713 if (DEBUG_SHOW_INFO) { 10714 Log.v(TAG, " IntentFilter:"); 10715 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10716 } 10717 removeFilter(intent); 10718 } 10719 } 10720 10721 @Override 10722 protected boolean allowFilterResult( 10723 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10724 ActivityInfo filterAi = filter.activity.info; 10725 for (int i=dest.size()-1; i>=0; i--) { 10726 ActivityInfo destAi = dest.get(i).activityInfo; 10727 if (destAi.name == filterAi.name 10728 && destAi.packageName == filterAi.packageName) { 10729 return false; 10730 } 10731 } 10732 return true; 10733 } 10734 10735 @Override 10736 protected ActivityIntentInfo[] newArray(int size) { 10737 return new ActivityIntentInfo[size]; 10738 } 10739 10740 @Override 10741 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10742 if (!sUserManager.exists(userId)) return true; 10743 PackageParser.Package p = filter.activity.owner; 10744 if (p != null) { 10745 PackageSetting ps = (PackageSetting)p.mExtras; 10746 if (ps != null) { 10747 // System apps are never considered stopped for purposes of 10748 // filtering, because there may be no way for the user to 10749 // actually re-launch them. 10750 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10751 && ps.getStopped(userId); 10752 } 10753 } 10754 return false; 10755 } 10756 10757 @Override 10758 protected boolean isPackageForFilter(String packageName, 10759 PackageParser.ActivityIntentInfo info) { 10760 return packageName.equals(info.activity.owner.packageName); 10761 } 10762 10763 @Override 10764 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10765 int match, int userId) { 10766 if (!sUserManager.exists(userId)) return null; 10767 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10768 return null; 10769 } 10770 final PackageParser.Activity activity = info.activity; 10771 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10772 if (ps == null) { 10773 return null; 10774 } 10775 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10776 ps.readUserState(userId), userId); 10777 if (ai == null) { 10778 return null; 10779 } 10780 final ResolveInfo res = new ResolveInfo(); 10781 res.activityInfo = ai; 10782 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10783 res.filter = info; 10784 } 10785 if (info != null) { 10786 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10787 } 10788 res.priority = info.getPriority(); 10789 res.preferredOrder = activity.owner.mPreferredOrder; 10790 //System.out.println("Result: " + res.activityInfo.className + 10791 // " = " + res.priority); 10792 res.match = match; 10793 res.isDefault = info.hasDefault; 10794 res.labelRes = info.labelRes; 10795 res.nonLocalizedLabel = info.nonLocalizedLabel; 10796 if (userNeedsBadging(userId)) { 10797 res.noResourceId = true; 10798 } else { 10799 res.icon = info.icon; 10800 } 10801 res.iconResourceId = info.icon; 10802 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10803 return res; 10804 } 10805 10806 @Override 10807 protected void sortResults(List<ResolveInfo> results) { 10808 Collections.sort(results, mResolvePrioritySorter); 10809 } 10810 10811 @Override 10812 protected void dumpFilter(PrintWriter out, String prefix, 10813 PackageParser.ActivityIntentInfo filter) { 10814 out.print(prefix); out.print( 10815 Integer.toHexString(System.identityHashCode(filter.activity))); 10816 out.print(' '); 10817 filter.activity.printComponentShortName(out); 10818 out.print(" filter "); 10819 out.println(Integer.toHexString(System.identityHashCode(filter))); 10820 } 10821 10822 @Override 10823 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10824 return filter.activity; 10825 } 10826 10827 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10828 PackageParser.Activity activity = (PackageParser.Activity)label; 10829 out.print(prefix); out.print( 10830 Integer.toHexString(System.identityHashCode(activity))); 10831 out.print(' '); 10832 activity.printComponentShortName(out); 10833 if (count > 1) { 10834 out.print(" ("); out.print(count); out.print(" filters)"); 10835 } 10836 out.println(); 10837 } 10838 10839 // Keys are String (activity class name), values are Activity. 10840 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10841 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10842 private int mFlags; 10843 } 10844 10845 private final class ServiceIntentResolver 10846 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10847 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10848 boolean defaultOnly, int userId) { 10849 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10850 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10851 } 10852 10853 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10854 int userId) { 10855 if (!sUserManager.exists(userId)) return null; 10856 mFlags = flags; 10857 return super.queryIntent(intent, resolvedType, 10858 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10859 } 10860 10861 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10862 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10863 if (!sUserManager.exists(userId)) return null; 10864 if (packageServices == null) { 10865 return null; 10866 } 10867 mFlags = flags; 10868 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10869 final int N = packageServices.size(); 10870 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10871 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10872 10873 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10874 for (int i = 0; i < N; ++i) { 10875 intentFilters = packageServices.get(i).intents; 10876 if (intentFilters != null && intentFilters.size() > 0) { 10877 PackageParser.ServiceIntentInfo[] array = 10878 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10879 intentFilters.toArray(array); 10880 listCut.add(array); 10881 } 10882 } 10883 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10884 } 10885 10886 public final void addService(PackageParser.Service s) { 10887 mServices.put(s.getComponentName(), s); 10888 if (DEBUG_SHOW_INFO) { 10889 Log.v(TAG, " " 10890 + (s.info.nonLocalizedLabel != null 10891 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10892 Log.v(TAG, " Class=" + s.info.name); 10893 } 10894 final int NI = s.intents.size(); 10895 int j; 10896 for (j=0; j<NI; j++) { 10897 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10898 if (DEBUG_SHOW_INFO) { 10899 Log.v(TAG, " IntentFilter:"); 10900 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10901 } 10902 if (!intent.debugCheck()) { 10903 Log.w(TAG, "==> For Service " + s.info.name); 10904 } 10905 addFilter(intent); 10906 } 10907 } 10908 10909 public final void removeService(PackageParser.Service s) { 10910 mServices.remove(s.getComponentName()); 10911 if (DEBUG_SHOW_INFO) { 10912 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10913 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10914 Log.v(TAG, " Class=" + s.info.name); 10915 } 10916 final int NI = s.intents.size(); 10917 int j; 10918 for (j=0; j<NI; j++) { 10919 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10920 if (DEBUG_SHOW_INFO) { 10921 Log.v(TAG, " IntentFilter:"); 10922 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10923 } 10924 removeFilter(intent); 10925 } 10926 } 10927 10928 @Override 10929 protected boolean allowFilterResult( 10930 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10931 ServiceInfo filterSi = filter.service.info; 10932 for (int i=dest.size()-1; i>=0; i--) { 10933 ServiceInfo destAi = dest.get(i).serviceInfo; 10934 if (destAi.name == filterSi.name 10935 && destAi.packageName == filterSi.packageName) { 10936 return false; 10937 } 10938 } 10939 return true; 10940 } 10941 10942 @Override 10943 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10944 return new PackageParser.ServiceIntentInfo[size]; 10945 } 10946 10947 @Override 10948 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10949 if (!sUserManager.exists(userId)) return true; 10950 PackageParser.Package p = filter.service.owner; 10951 if (p != null) { 10952 PackageSetting ps = (PackageSetting)p.mExtras; 10953 if (ps != null) { 10954 // System apps are never considered stopped for purposes of 10955 // filtering, because there may be no way for the user to 10956 // actually re-launch them. 10957 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10958 && ps.getStopped(userId); 10959 } 10960 } 10961 return false; 10962 } 10963 10964 @Override 10965 protected boolean isPackageForFilter(String packageName, 10966 PackageParser.ServiceIntentInfo info) { 10967 return packageName.equals(info.service.owner.packageName); 10968 } 10969 10970 @Override 10971 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10972 int match, int userId) { 10973 if (!sUserManager.exists(userId)) return null; 10974 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10975 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10976 return null; 10977 } 10978 final PackageParser.Service service = info.service; 10979 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10980 if (ps == null) { 10981 return null; 10982 } 10983 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10984 ps.readUserState(userId), userId); 10985 if (si == null) { 10986 return null; 10987 } 10988 final ResolveInfo res = new ResolveInfo(); 10989 res.serviceInfo = si; 10990 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10991 res.filter = filter; 10992 } 10993 res.priority = info.getPriority(); 10994 res.preferredOrder = service.owner.mPreferredOrder; 10995 res.match = match; 10996 res.isDefault = info.hasDefault; 10997 res.labelRes = info.labelRes; 10998 res.nonLocalizedLabel = info.nonLocalizedLabel; 10999 res.icon = info.icon; 11000 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11001 return res; 11002 } 11003 11004 @Override 11005 protected void sortResults(List<ResolveInfo> results) { 11006 Collections.sort(results, mResolvePrioritySorter); 11007 } 11008 11009 @Override 11010 protected void dumpFilter(PrintWriter out, String prefix, 11011 PackageParser.ServiceIntentInfo filter) { 11012 out.print(prefix); out.print( 11013 Integer.toHexString(System.identityHashCode(filter.service))); 11014 out.print(' '); 11015 filter.service.printComponentShortName(out); 11016 out.print(" filter "); 11017 out.println(Integer.toHexString(System.identityHashCode(filter))); 11018 } 11019 11020 @Override 11021 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11022 return filter.service; 11023 } 11024 11025 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11026 PackageParser.Service service = (PackageParser.Service)label; 11027 out.print(prefix); out.print( 11028 Integer.toHexString(System.identityHashCode(service))); 11029 out.print(' '); 11030 service.printComponentShortName(out); 11031 if (count > 1) { 11032 out.print(" ("); out.print(count); out.print(" filters)"); 11033 } 11034 out.println(); 11035 } 11036 11037// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11038// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11039// final List<ResolveInfo> retList = Lists.newArrayList(); 11040// while (i.hasNext()) { 11041// final ResolveInfo resolveInfo = (ResolveInfo) i; 11042// if (isEnabledLP(resolveInfo.serviceInfo)) { 11043// retList.add(resolveInfo); 11044// } 11045// } 11046// return retList; 11047// } 11048 11049 // Keys are String (activity class name), values are Activity. 11050 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11051 = new ArrayMap<ComponentName, PackageParser.Service>(); 11052 private int mFlags; 11053 }; 11054 11055 private final class ProviderIntentResolver 11056 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11057 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11058 boolean defaultOnly, int userId) { 11059 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11060 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11061 } 11062 11063 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11064 int userId) { 11065 if (!sUserManager.exists(userId)) 11066 return null; 11067 mFlags = flags; 11068 return super.queryIntent(intent, resolvedType, 11069 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11070 } 11071 11072 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11073 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11074 if (!sUserManager.exists(userId)) 11075 return null; 11076 if (packageProviders == null) { 11077 return null; 11078 } 11079 mFlags = flags; 11080 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11081 final int N = packageProviders.size(); 11082 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11083 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11084 11085 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11086 for (int i = 0; i < N; ++i) { 11087 intentFilters = packageProviders.get(i).intents; 11088 if (intentFilters != null && intentFilters.size() > 0) { 11089 PackageParser.ProviderIntentInfo[] array = 11090 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11091 intentFilters.toArray(array); 11092 listCut.add(array); 11093 } 11094 } 11095 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11096 } 11097 11098 public final void addProvider(PackageParser.Provider p) { 11099 if (mProviders.containsKey(p.getComponentName())) { 11100 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11101 return; 11102 } 11103 11104 mProviders.put(p.getComponentName(), p); 11105 if (DEBUG_SHOW_INFO) { 11106 Log.v(TAG, " " 11107 + (p.info.nonLocalizedLabel != null 11108 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11109 Log.v(TAG, " Class=" + p.info.name); 11110 } 11111 final int NI = p.intents.size(); 11112 int j; 11113 for (j = 0; j < NI; j++) { 11114 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11115 if (DEBUG_SHOW_INFO) { 11116 Log.v(TAG, " IntentFilter:"); 11117 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11118 } 11119 if (!intent.debugCheck()) { 11120 Log.w(TAG, "==> For Provider " + p.info.name); 11121 } 11122 addFilter(intent); 11123 } 11124 } 11125 11126 public final void removeProvider(PackageParser.Provider p) { 11127 mProviders.remove(p.getComponentName()); 11128 if (DEBUG_SHOW_INFO) { 11129 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11130 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11131 Log.v(TAG, " Class=" + p.info.name); 11132 } 11133 final int NI = p.intents.size(); 11134 int j; 11135 for (j = 0; j < NI; j++) { 11136 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11137 if (DEBUG_SHOW_INFO) { 11138 Log.v(TAG, " IntentFilter:"); 11139 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11140 } 11141 removeFilter(intent); 11142 } 11143 } 11144 11145 @Override 11146 protected boolean allowFilterResult( 11147 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11148 ProviderInfo filterPi = filter.provider.info; 11149 for (int i = dest.size() - 1; i >= 0; i--) { 11150 ProviderInfo destPi = dest.get(i).providerInfo; 11151 if (destPi.name == filterPi.name 11152 && destPi.packageName == filterPi.packageName) { 11153 return false; 11154 } 11155 } 11156 return true; 11157 } 11158 11159 @Override 11160 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11161 return new PackageParser.ProviderIntentInfo[size]; 11162 } 11163 11164 @Override 11165 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11166 if (!sUserManager.exists(userId)) 11167 return true; 11168 PackageParser.Package p = filter.provider.owner; 11169 if (p != null) { 11170 PackageSetting ps = (PackageSetting) p.mExtras; 11171 if (ps != null) { 11172 // System apps are never considered stopped for purposes of 11173 // filtering, because there may be no way for the user to 11174 // actually re-launch them. 11175 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11176 && ps.getStopped(userId); 11177 } 11178 } 11179 return false; 11180 } 11181 11182 @Override 11183 protected boolean isPackageForFilter(String packageName, 11184 PackageParser.ProviderIntentInfo info) { 11185 return packageName.equals(info.provider.owner.packageName); 11186 } 11187 11188 @Override 11189 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11190 int match, int userId) { 11191 if (!sUserManager.exists(userId)) 11192 return null; 11193 final PackageParser.ProviderIntentInfo info = filter; 11194 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11195 return null; 11196 } 11197 final PackageParser.Provider provider = info.provider; 11198 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11199 if (ps == null) { 11200 return null; 11201 } 11202 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11203 ps.readUserState(userId), userId); 11204 if (pi == null) { 11205 return null; 11206 } 11207 final ResolveInfo res = new ResolveInfo(); 11208 res.providerInfo = pi; 11209 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11210 res.filter = filter; 11211 } 11212 res.priority = info.getPriority(); 11213 res.preferredOrder = provider.owner.mPreferredOrder; 11214 res.match = match; 11215 res.isDefault = info.hasDefault; 11216 res.labelRes = info.labelRes; 11217 res.nonLocalizedLabel = info.nonLocalizedLabel; 11218 res.icon = info.icon; 11219 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11220 return res; 11221 } 11222 11223 @Override 11224 protected void sortResults(List<ResolveInfo> results) { 11225 Collections.sort(results, mResolvePrioritySorter); 11226 } 11227 11228 @Override 11229 protected void dumpFilter(PrintWriter out, String prefix, 11230 PackageParser.ProviderIntentInfo filter) { 11231 out.print(prefix); 11232 out.print( 11233 Integer.toHexString(System.identityHashCode(filter.provider))); 11234 out.print(' '); 11235 filter.provider.printComponentShortName(out); 11236 out.print(" filter "); 11237 out.println(Integer.toHexString(System.identityHashCode(filter))); 11238 } 11239 11240 @Override 11241 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11242 return filter.provider; 11243 } 11244 11245 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11246 PackageParser.Provider provider = (PackageParser.Provider)label; 11247 out.print(prefix); out.print( 11248 Integer.toHexString(System.identityHashCode(provider))); 11249 out.print(' '); 11250 provider.printComponentShortName(out); 11251 if (count > 1) { 11252 out.print(" ("); out.print(count); out.print(" filters)"); 11253 } 11254 out.println(); 11255 } 11256 11257 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11258 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11259 private int mFlags; 11260 } 11261 11262 private static final class EphemeralIntentResolver 11263 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11264 @Override 11265 protected EphemeralResolveIntentInfo[] newArray(int size) { 11266 return new EphemeralResolveIntentInfo[size]; 11267 } 11268 11269 @Override 11270 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11271 return true; 11272 } 11273 11274 @Override 11275 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11276 int userId) { 11277 if (!sUserManager.exists(userId)) { 11278 return null; 11279 } 11280 return info.getEphemeralResolveInfo(); 11281 } 11282 } 11283 11284 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11285 new Comparator<ResolveInfo>() { 11286 public int compare(ResolveInfo r1, ResolveInfo r2) { 11287 int v1 = r1.priority; 11288 int v2 = r2.priority; 11289 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11290 if (v1 != v2) { 11291 return (v1 > v2) ? -1 : 1; 11292 } 11293 v1 = r1.preferredOrder; 11294 v2 = r2.preferredOrder; 11295 if (v1 != v2) { 11296 return (v1 > v2) ? -1 : 1; 11297 } 11298 if (r1.isDefault != r2.isDefault) { 11299 return r1.isDefault ? -1 : 1; 11300 } 11301 v1 = r1.match; 11302 v2 = r2.match; 11303 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11304 if (v1 != v2) { 11305 return (v1 > v2) ? -1 : 1; 11306 } 11307 if (r1.system != r2.system) { 11308 return r1.system ? -1 : 1; 11309 } 11310 if (r1.activityInfo != null) { 11311 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11312 } 11313 if (r1.serviceInfo != null) { 11314 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11315 } 11316 if (r1.providerInfo != null) { 11317 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11318 } 11319 return 0; 11320 } 11321 }; 11322 11323 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11324 new Comparator<ProviderInfo>() { 11325 public int compare(ProviderInfo p1, ProviderInfo p2) { 11326 final int v1 = p1.initOrder; 11327 final int v2 = p2.initOrder; 11328 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11329 } 11330 }; 11331 11332 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11333 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11334 final int[] userIds) { 11335 mHandler.post(new Runnable() { 11336 @Override 11337 public void run() { 11338 try { 11339 final IActivityManager am = ActivityManagerNative.getDefault(); 11340 if (am == null) return; 11341 final int[] resolvedUserIds; 11342 if (userIds == null) { 11343 resolvedUserIds = am.getRunningUserIds(); 11344 } else { 11345 resolvedUserIds = userIds; 11346 } 11347 for (int id : resolvedUserIds) { 11348 final Intent intent = new Intent(action, 11349 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11350 if (extras != null) { 11351 intent.putExtras(extras); 11352 } 11353 if (targetPkg != null) { 11354 intent.setPackage(targetPkg); 11355 } 11356 // Modify the UID when posting to other users 11357 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11358 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11359 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11360 intent.putExtra(Intent.EXTRA_UID, uid); 11361 } 11362 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11363 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11364 if (DEBUG_BROADCASTS) { 11365 RuntimeException here = new RuntimeException("here"); 11366 here.fillInStackTrace(); 11367 Slog.d(TAG, "Sending to user " + id + ": " 11368 + intent.toShortString(false, true, false, false) 11369 + " " + intent.getExtras(), here); 11370 } 11371 am.broadcastIntent(null, intent, null, finishedReceiver, 11372 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11373 null, finishedReceiver != null, false, id); 11374 } 11375 } catch (RemoteException ex) { 11376 } 11377 } 11378 }); 11379 } 11380 11381 /** 11382 * Check if the external storage media is available. This is true if there 11383 * is a mounted external storage medium or if the external storage is 11384 * emulated. 11385 */ 11386 private boolean isExternalMediaAvailable() { 11387 return mMediaMounted || Environment.isExternalStorageEmulated(); 11388 } 11389 11390 @Override 11391 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11392 // writer 11393 synchronized (mPackages) { 11394 if (!isExternalMediaAvailable()) { 11395 // If the external storage is no longer mounted at this point, 11396 // the caller may not have been able to delete all of this 11397 // packages files and can not delete any more. Bail. 11398 return null; 11399 } 11400 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11401 if (lastPackage != null) { 11402 pkgs.remove(lastPackage); 11403 } 11404 if (pkgs.size() > 0) { 11405 return pkgs.get(0); 11406 } 11407 } 11408 return null; 11409 } 11410 11411 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11412 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11413 userId, andCode ? 1 : 0, packageName); 11414 if (mSystemReady) { 11415 msg.sendToTarget(); 11416 } else { 11417 if (mPostSystemReadyMessages == null) { 11418 mPostSystemReadyMessages = new ArrayList<>(); 11419 } 11420 mPostSystemReadyMessages.add(msg); 11421 } 11422 } 11423 11424 void startCleaningPackages() { 11425 // reader 11426 if (!isExternalMediaAvailable()) { 11427 return; 11428 } 11429 synchronized (mPackages) { 11430 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11431 return; 11432 } 11433 } 11434 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11435 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11436 IActivityManager am = ActivityManagerNative.getDefault(); 11437 if (am != null) { 11438 try { 11439 am.startService(null, intent, null, mContext.getOpPackageName(), 11440 UserHandle.USER_SYSTEM); 11441 } catch (RemoteException e) { 11442 } 11443 } 11444 } 11445 11446 @Override 11447 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11448 int installFlags, String installerPackageName, int userId) { 11449 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11450 11451 final int callingUid = Binder.getCallingUid(); 11452 enforceCrossUserPermission(callingUid, userId, 11453 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11454 11455 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11456 try { 11457 if (observer != null) { 11458 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11459 } 11460 } catch (RemoteException re) { 11461 } 11462 return; 11463 } 11464 11465 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11466 installFlags |= PackageManager.INSTALL_FROM_ADB; 11467 11468 } else { 11469 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11470 // about installerPackageName. 11471 11472 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11473 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11474 } 11475 11476 UserHandle user; 11477 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11478 user = UserHandle.ALL; 11479 } else { 11480 user = new UserHandle(userId); 11481 } 11482 11483 // Only system components can circumvent runtime permissions when installing. 11484 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11485 && mContext.checkCallingOrSelfPermission(Manifest.permission 11486 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11487 throw new SecurityException("You need the " 11488 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11489 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11490 } 11491 11492 final File originFile = new File(originPath); 11493 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11494 11495 final Message msg = mHandler.obtainMessage(INIT_COPY); 11496 final VerificationInfo verificationInfo = new VerificationInfo( 11497 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11498 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11499 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11500 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11501 null /*certificates*/); 11502 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11503 msg.obj = params; 11504 11505 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11506 System.identityHashCode(msg.obj)); 11507 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11508 System.identityHashCode(msg.obj)); 11509 11510 mHandler.sendMessage(msg); 11511 } 11512 11513 void installStage(String packageName, File stagedDir, String stagedCid, 11514 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11515 String installerPackageName, int installerUid, UserHandle user, 11516 Certificate[][] certificates) { 11517 if (DEBUG_EPHEMERAL) { 11518 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11519 Slog.d(TAG, "Ephemeral install of " + packageName); 11520 } 11521 } 11522 final VerificationInfo verificationInfo = new VerificationInfo( 11523 sessionParams.originatingUri, sessionParams.referrerUri, 11524 sessionParams.originatingUid, installerUid); 11525 11526 final OriginInfo origin; 11527 if (stagedDir != null) { 11528 origin = OriginInfo.fromStagedFile(stagedDir); 11529 } else { 11530 origin = OriginInfo.fromStagedContainer(stagedCid); 11531 } 11532 11533 final Message msg = mHandler.obtainMessage(INIT_COPY); 11534 final InstallParams params = new InstallParams(origin, null, observer, 11535 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11536 verificationInfo, user, sessionParams.abiOverride, 11537 sessionParams.grantedRuntimePermissions, certificates); 11538 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11539 msg.obj = params; 11540 11541 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11542 System.identityHashCode(msg.obj)); 11543 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11544 System.identityHashCode(msg.obj)); 11545 11546 mHandler.sendMessage(msg); 11547 } 11548 11549 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11550 int userId) { 11551 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11552 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11553 } 11554 11555 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11556 int appId, int userId) { 11557 Bundle extras = new Bundle(1); 11558 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11559 11560 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11561 packageName, extras, 0, null, null, new int[] {userId}); 11562 try { 11563 IActivityManager am = ActivityManagerNative.getDefault(); 11564 if (isSystem && am.isUserRunning(userId, 0)) { 11565 // The just-installed/enabled app is bundled on the system, so presumed 11566 // to be able to run automatically without needing an explicit launch. 11567 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11568 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11569 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11570 .setPackage(packageName); 11571 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11572 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11573 } 11574 } catch (RemoteException e) { 11575 // shouldn't happen 11576 Slog.w(TAG, "Unable to bootstrap installed package", e); 11577 } 11578 } 11579 11580 @Override 11581 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11582 int userId) { 11583 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11584 PackageSetting pkgSetting; 11585 final int uid = Binder.getCallingUid(); 11586 enforceCrossUserPermission(uid, userId, 11587 true /* requireFullPermission */, true /* checkShell */, 11588 "setApplicationHiddenSetting for user " + userId); 11589 11590 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11591 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11592 return false; 11593 } 11594 11595 long callingId = Binder.clearCallingIdentity(); 11596 try { 11597 boolean sendAdded = false; 11598 boolean sendRemoved = false; 11599 // writer 11600 synchronized (mPackages) { 11601 pkgSetting = mSettings.mPackages.get(packageName); 11602 if (pkgSetting == null) { 11603 return false; 11604 } 11605 // Do not allow "android" is being disabled 11606 if ("android".equals(packageName)) { 11607 Slog.w(TAG, "Cannot hide package: android"); 11608 return false; 11609 } 11610 // Only allow protected packages to hide themselves. 11611 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11612 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11613 Slog.w(TAG, "Not hiding protected package: " + packageName); 11614 return false; 11615 } 11616 11617 if (pkgSetting.getHidden(userId) != hidden) { 11618 pkgSetting.setHidden(hidden, userId); 11619 mSettings.writePackageRestrictionsLPr(userId); 11620 if (hidden) { 11621 sendRemoved = true; 11622 } else { 11623 sendAdded = true; 11624 } 11625 } 11626 } 11627 if (sendAdded) { 11628 sendPackageAddedForUser(packageName, pkgSetting, userId); 11629 return true; 11630 } 11631 if (sendRemoved) { 11632 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11633 "hiding pkg"); 11634 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11635 return true; 11636 } 11637 } finally { 11638 Binder.restoreCallingIdentity(callingId); 11639 } 11640 return false; 11641 } 11642 11643 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11644 int userId) { 11645 final PackageRemovedInfo info = new PackageRemovedInfo(); 11646 info.removedPackage = packageName; 11647 info.removedUsers = new int[] {userId}; 11648 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11649 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11650 } 11651 11652 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11653 if (pkgList.length > 0) { 11654 Bundle extras = new Bundle(1); 11655 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11656 11657 sendPackageBroadcast( 11658 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11659 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11660 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11661 new int[] {userId}); 11662 } 11663 } 11664 11665 /** 11666 * Returns true if application is not found or there was an error. Otherwise it returns 11667 * the hidden state of the package for the given user. 11668 */ 11669 @Override 11670 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11672 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11673 true /* requireFullPermission */, false /* checkShell */, 11674 "getApplicationHidden for user " + userId); 11675 PackageSetting pkgSetting; 11676 long callingId = Binder.clearCallingIdentity(); 11677 try { 11678 // writer 11679 synchronized (mPackages) { 11680 pkgSetting = mSettings.mPackages.get(packageName); 11681 if (pkgSetting == null) { 11682 return true; 11683 } 11684 return pkgSetting.getHidden(userId); 11685 } 11686 } finally { 11687 Binder.restoreCallingIdentity(callingId); 11688 } 11689 } 11690 11691 /** 11692 * @hide 11693 */ 11694 @Override 11695 public int installExistingPackageAsUser(String packageName, int userId) { 11696 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11697 null); 11698 PackageSetting pkgSetting; 11699 final int uid = Binder.getCallingUid(); 11700 enforceCrossUserPermission(uid, userId, 11701 true /* requireFullPermission */, true /* checkShell */, 11702 "installExistingPackage for user " + userId); 11703 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11704 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11705 } 11706 11707 long callingId = Binder.clearCallingIdentity(); 11708 try { 11709 boolean installed = false; 11710 11711 // writer 11712 synchronized (mPackages) { 11713 pkgSetting = mSettings.mPackages.get(packageName); 11714 if (pkgSetting == null) { 11715 return PackageManager.INSTALL_FAILED_INVALID_URI; 11716 } 11717 if (!pkgSetting.getInstalled(userId)) { 11718 pkgSetting.setInstalled(true, userId); 11719 pkgSetting.setHidden(false, userId); 11720 mSettings.writePackageRestrictionsLPr(userId); 11721 installed = true; 11722 } 11723 } 11724 11725 if (installed) { 11726 if (pkgSetting.pkg != null) { 11727 synchronized (mInstallLock) { 11728 // We don't need to freeze for a brand new install 11729 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11730 } 11731 } 11732 sendPackageAddedForUser(packageName, pkgSetting, userId); 11733 } 11734 } finally { 11735 Binder.restoreCallingIdentity(callingId); 11736 } 11737 11738 return PackageManager.INSTALL_SUCCEEDED; 11739 } 11740 11741 boolean isUserRestricted(int userId, String restrictionKey) { 11742 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11743 if (restrictions.getBoolean(restrictionKey, false)) { 11744 Log.w(TAG, "User is restricted: " + restrictionKey); 11745 return true; 11746 } 11747 return false; 11748 } 11749 11750 @Override 11751 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11752 int userId) { 11753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11754 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11755 true /* requireFullPermission */, true /* checkShell */, 11756 "setPackagesSuspended for user " + userId); 11757 11758 if (ArrayUtils.isEmpty(packageNames)) { 11759 return packageNames; 11760 } 11761 11762 // List of package names for whom the suspended state has changed. 11763 List<String> changedPackages = new ArrayList<>(packageNames.length); 11764 // List of package names for whom the suspended state is not set as requested in this 11765 // method. 11766 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11767 long callingId = Binder.clearCallingIdentity(); 11768 try { 11769 for (int i = 0; i < packageNames.length; i++) { 11770 String packageName = packageNames[i]; 11771 boolean changed = false; 11772 final int appId; 11773 synchronized (mPackages) { 11774 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11775 if (pkgSetting == null) { 11776 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11777 + "\". Skipping suspending/un-suspending."); 11778 unactionedPackages.add(packageName); 11779 continue; 11780 } 11781 appId = pkgSetting.appId; 11782 if (pkgSetting.getSuspended(userId) != suspended) { 11783 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11784 unactionedPackages.add(packageName); 11785 continue; 11786 } 11787 pkgSetting.setSuspended(suspended, userId); 11788 mSettings.writePackageRestrictionsLPr(userId); 11789 changed = true; 11790 changedPackages.add(packageName); 11791 } 11792 } 11793 11794 if (changed && suspended) { 11795 killApplication(packageName, UserHandle.getUid(userId, appId), 11796 "suspending package"); 11797 } 11798 } 11799 } finally { 11800 Binder.restoreCallingIdentity(callingId); 11801 } 11802 11803 if (!changedPackages.isEmpty()) { 11804 sendPackagesSuspendedForUser(changedPackages.toArray( 11805 new String[changedPackages.size()]), userId, suspended); 11806 } 11807 11808 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11809 } 11810 11811 @Override 11812 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11813 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11814 true /* requireFullPermission */, false /* checkShell */, 11815 "isPackageSuspendedForUser for user " + userId); 11816 synchronized (mPackages) { 11817 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11818 if (pkgSetting == null) { 11819 throw new IllegalArgumentException("Unknown target package: " + packageName); 11820 } 11821 return pkgSetting.getSuspended(userId); 11822 } 11823 } 11824 11825 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11826 if (isPackageDeviceAdmin(packageName, userId)) { 11827 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11828 + "\": has an active device admin"); 11829 return false; 11830 } 11831 11832 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11833 if (packageName.equals(activeLauncherPackageName)) { 11834 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11835 + "\": contains the active launcher"); 11836 return false; 11837 } 11838 11839 if (packageName.equals(mRequiredInstallerPackage)) { 11840 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11841 + "\": required for package installation"); 11842 return false; 11843 } 11844 11845 if (packageName.equals(mRequiredUninstallerPackage)) { 11846 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11847 + "\": required for package uninstallation"); 11848 return false; 11849 } 11850 11851 if (packageName.equals(mRequiredVerifierPackage)) { 11852 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11853 + "\": required for package verification"); 11854 return false; 11855 } 11856 11857 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11858 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11859 + "\": is the default dialer"); 11860 return false; 11861 } 11862 11863 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11864 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11865 + "\": protected package"); 11866 return false; 11867 } 11868 11869 return true; 11870 } 11871 11872 private String getActiveLauncherPackageName(int userId) { 11873 Intent intent = new Intent(Intent.ACTION_MAIN); 11874 intent.addCategory(Intent.CATEGORY_HOME); 11875 ResolveInfo resolveInfo = resolveIntent( 11876 intent, 11877 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11878 PackageManager.MATCH_DEFAULT_ONLY, 11879 userId); 11880 11881 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11882 } 11883 11884 private String getDefaultDialerPackageName(int userId) { 11885 synchronized (mPackages) { 11886 return mSettings.getDefaultDialerPackageNameLPw(userId); 11887 } 11888 } 11889 11890 @Override 11891 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11892 mContext.enforceCallingOrSelfPermission( 11893 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11894 "Only package verification agents can verify applications"); 11895 11896 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11897 final PackageVerificationResponse response = new PackageVerificationResponse( 11898 verificationCode, Binder.getCallingUid()); 11899 msg.arg1 = id; 11900 msg.obj = response; 11901 mHandler.sendMessage(msg); 11902 } 11903 11904 @Override 11905 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11906 long millisecondsToDelay) { 11907 mContext.enforceCallingOrSelfPermission( 11908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11909 "Only package verification agents can extend verification timeouts"); 11910 11911 final PackageVerificationState state = mPendingVerification.get(id); 11912 final PackageVerificationResponse response = new PackageVerificationResponse( 11913 verificationCodeAtTimeout, Binder.getCallingUid()); 11914 11915 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11916 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11917 } 11918 if (millisecondsToDelay < 0) { 11919 millisecondsToDelay = 0; 11920 } 11921 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11922 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11923 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11924 } 11925 11926 if ((state != null) && !state.timeoutExtended()) { 11927 state.extendTimeout(); 11928 11929 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11930 msg.arg1 = id; 11931 msg.obj = response; 11932 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11933 } 11934 } 11935 11936 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11937 int verificationCode, UserHandle user) { 11938 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11939 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11940 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11941 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11942 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11943 11944 mContext.sendBroadcastAsUser(intent, user, 11945 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11946 } 11947 11948 private ComponentName matchComponentForVerifier(String packageName, 11949 List<ResolveInfo> receivers) { 11950 ActivityInfo targetReceiver = null; 11951 11952 final int NR = receivers.size(); 11953 for (int i = 0; i < NR; i++) { 11954 final ResolveInfo info = receivers.get(i); 11955 if (info.activityInfo == null) { 11956 continue; 11957 } 11958 11959 if (packageName.equals(info.activityInfo.packageName)) { 11960 targetReceiver = info.activityInfo; 11961 break; 11962 } 11963 } 11964 11965 if (targetReceiver == null) { 11966 return null; 11967 } 11968 11969 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11970 } 11971 11972 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11973 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11974 if (pkgInfo.verifiers.length == 0) { 11975 return null; 11976 } 11977 11978 final int N = pkgInfo.verifiers.length; 11979 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11980 for (int i = 0; i < N; i++) { 11981 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11982 11983 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11984 receivers); 11985 if (comp == null) { 11986 continue; 11987 } 11988 11989 final int verifierUid = getUidForVerifier(verifierInfo); 11990 if (verifierUid == -1) { 11991 continue; 11992 } 11993 11994 if (DEBUG_VERIFY) { 11995 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11996 + " with the correct signature"); 11997 } 11998 sufficientVerifiers.add(comp); 11999 verificationState.addSufficientVerifier(verifierUid); 12000 } 12001 12002 return sufficientVerifiers; 12003 } 12004 12005 private int getUidForVerifier(VerifierInfo verifierInfo) { 12006 synchronized (mPackages) { 12007 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12008 if (pkg == null) { 12009 return -1; 12010 } else if (pkg.mSignatures.length != 1) { 12011 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12012 + " has more than one signature; ignoring"); 12013 return -1; 12014 } 12015 12016 /* 12017 * If the public key of the package's signature does not match 12018 * our expected public key, then this is a different package and 12019 * we should skip. 12020 */ 12021 12022 final byte[] expectedPublicKey; 12023 try { 12024 final Signature verifierSig = pkg.mSignatures[0]; 12025 final PublicKey publicKey = verifierSig.getPublicKey(); 12026 expectedPublicKey = publicKey.getEncoded(); 12027 } catch (CertificateException e) { 12028 return -1; 12029 } 12030 12031 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12032 12033 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12034 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12035 + " does not have the expected public key; ignoring"); 12036 return -1; 12037 } 12038 12039 return pkg.applicationInfo.uid; 12040 } 12041 } 12042 12043 @Override 12044 public void finishPackageInstall(int token, boolean didLaunch) { 12045 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12046 12047 if (DEBUG_INSTALL) { 12048 Slog.v(TAG, "BM finishing package install for " + token); 12049 } 12050 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12051 12052 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12053 mHandler.sendMessage(msg); 12054 } 12055 12056 /** 12057 * Get the verification agent timeout. 12058 * 12059 * @return verification timeout in milliseconds 12060 */ 12061 private long getVerificationTimeout() { 12062 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12063 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12064 DEFAULT_VERIFICATION_TIMEOUT); 12065 } 12066 12067 /** 12068 * Get the default verification agent response code. 12069 * 12070 * @return default verification response code 12071 */ 12072 private int getDefaultVerificationResponse() { 12073 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12074 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12075 DEFAULT_VERIFICATION_RESPONSE); 12076 } 12077 12078 /** 12079 * Check whether or not package verification has been enabled. 12080 * 12081 * @return true if verification should be performed 12082 */ 12083 private boolean isVerificationEnabled(int userId, int installFlags) { 12084 if (!DEFAULT_VERIFY_ENABLE) { 12085 return false; 12086 } 12087 // Ephemeral apps don't get the full verification treatment 12088 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12089 if (DEBUG_EPHEMERAL) { 12090 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12091 } 12092 return false; 12093 } 12094 12095 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12096 12097 // Check if installing from ADB 12098 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12099 // Do not run verification in a test harness environment 12100 if (ActivityManager.isRunningInTestHarness()) { 12101 return false; 12102 } 12103 if (ensureVerifyAppsEnabled) { 12104 return true; 12105 } 12106 // Check if the developer does not want package verification for ADB installs 12107 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12108 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12109 return false; 12110 } 12111 } 12112 12113 if (ensureVerifyAppsEnabled) { 12114 return true; 12115 } 12116 12117 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12118 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12119 } 12120 12121 @Override 12122 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12123 throws RemoteException { 12124 mContext.enforceCallingOrSelfPermission( 12125 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12126 "Only intentfilter verification agents can verify applications"); 12127 12128 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12129 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12130 Binder.getCallingUid(), verificationCode, failedDomains); 12131 msg.arg1 = id; 12132 msg.obj = response; 12133 mHandler.sendMessage(msg); 12134 } 12135 12136 @Override 12137 public int getIntentVerificationStatus(String packageName, int userId) { 12138 synchronized (mPackages) { 12139 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12140 } 12141 } 12142 12143 @Override 12144 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12145 mContext.enforceCallingOrSelfPermission( 12146 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12147 12148 boolean result = false; 12149 synchronized (mPackages) { 12150 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12151 } 12152 if (result) { 12153 scheduleWritePackageRestrictionsLocked(userId); 12154 } 12155 return result; 12156 } 12157 12158 @Override 12159 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12160 String packageName) { 12161 synchronized (mPackages) { 12162 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12163 } 12164 } 12165 12166 @Override 12167 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12168 if (TextUtils.isEmpty(packageName)) { 12169 return ParceledListSlice.emptyList(); 12170 } 12171 synchronized (mPackages) { 12172 PackageParser.Package pkg = mPackages.get(packageName); 12173 if (pkg == null || pkg.activities == null) { 12174 return ParceledListSlice.emptyList(); 12175 } 12176 final int count = pkg.activities.size(); 12177 ArrayList<IntentFilter> result = new ArrayList<>(); 12178 for (int n=0; n<count; n++) { 12179 PackageParser.Activity activity = pkg.activities.get(n); 12180 if (activity.intents != null && activity.intents.size() > 0) { 12181 result.addAll(activity.intents); 12182 } 12183 } 12184 return new ParceledListSlice<>(result); 12185 } 12186 } 12187 12188 @Override 12189 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12190 mContext.enforceCallingOrSelfPermission( 12191 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12192 12193 synchronized (mPackages) { 12194 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12195 if (packageName != null) { 12196 result |= updateIntentVerificationStatus(packageName, 12197 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12198 userId); 12199 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12200 packageName, userId); 12201 } 12202 return result; 12203 } 12204 } 12205 12206 @Override 12207 public String getDefaultBrowserPackageName(int userId) { 12208 synchronized (mPackages) { 12209 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12210 } 12211 } 12212 12213 /** 12214 * Get the "allow unknown sources" setting. 12215 * 12216 * @return the current "allow unknown sources" setting 12217 */ 12218 private int getUnknownSourcesSettings() { 12219 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12220 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12221 -1); 12222 } 12223 12224 @Override 12225 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12226 final int uid = Binder.getCallingUid(); 12227 // writer 12228 synchronized (mPackages) { 12229 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12230 if (targetPackageSetting == null) { 12231 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12232 } 12233 12234 PackageSetting installerPackageSetting; 12235 if (installerPackageName != null) { 12236 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12237 if (installerPackageSetting == null) { 12238 throw new IllegalArgumentException("Unknown installer package: " 12239 + installerPackageName); 12240 } 12241 } else { 12242 installerPackageSetting = null; 12243 } 12244 12245 Signature[] callerSignature; 12246 Object obj = mSettings.getUserIdLPr(uid); 12247 if (obj != null) { 12248 if (obj instanceof SharedUserSetting) { 12249 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12250 } else if (obj instanceof PackageSetting) { 12251 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12252 } else { 12253 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12254 } 12255 } else { 12256 throw new SecurityException("Unknown calling UID: " + uid); 12257 } 12258 12259 // Verify: can't set installerPackageName to a package that is 12260 // not signed with the same cert as the caller. 12261 if (installerPackageSetting != null) { 12262 if (compareSignatures(callerSignature, 12263 installerPackageSetting.signatures.mSignatures) 12264 != PackageManager.SIGNATURE_MATCH) { 12265 throw new SecurityException( 12266 "Caller does not have same cert as new installer package " 12267 + installerPackageName); 12268 } 12269 } 12270 12271 // Verify: if target already has an installer package, it must 12272 // be signed with the same cert as the caller. 12273 if (targetPackageSetting.installerPackageName != null) { 12274 PackageSetting setting = mSettings.mPackages.get( 12275 targetPackageSetting.installerPackageName); 12276 // If the currently set package isn't valid, then it's always 12277 // okay to change it. 12278 if (setting != null) { 12279 if (compareSignatures(callerSignature, 12280 setting.signatures.mSignatures) 12281 != PackageManager.SIGNATURE_MATCH) { 12282 throw new SecurityException( 12283 "Caller does not have same cert as old installer package " 12284 + targetPackageSetting.installerPackageName); 12285 } 12286 } 12287 } 12288 12289 // Okay! 12290 targetPackageSetting.installerPackageName = installerPackageName; 12291 if (installerPackageName != null) { 12292 mSettings.mInstallerPackages.add(installerPackageName); 12293 } 12294 scheduleWriteSettingsLocked(); 12295 } 12296 } 12297 12298 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12299 // Queue up an async operation since the package installation may take a little while. 12300 mHandler.post(new Runnable() { 12301 public void run() { 12302 mHandler.removeCallbacks(this); 12303 // Result object to be returned 12304 PackageInstalledInfo res = new PackageInstalledInfo(); 12305 res.setReturnCode(currentStatus); 12306 res.uid = -1; 12307 res.pkg = null; 12308 res.removedInfo = null; 12309 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12310 args.doPreInstall(res.returnCode); 12311 synchronized (mInstallLock) { 12312 installPackageTracedLI(args, res); 12313 } 12314 args.doPostInstall(res.returnCode, res.uid); 12315 } 12316 12317 // A restore should be performed at this point if (a) the install 12318 // succeeded, (b) the operation is not an update, and (c) the new 12319 // package has not opted out of backup participation. 12320 final boolean update = res.removedInfo != null 12321 && res.removedInfo.removedPackage != null; 12322 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12323 boolean doRestore = !update 12324 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12325 12326 // Set up the post-install work request bookkeeping. This will be used 12327 // and cleaned up by the post-install event handling regardless of whether 12328 // there's a restore pass performed. Token values are >= 1. 12329 int token; 12330 if (mNextInstallToken < 0) mNextInstallToken = 1; 12331 token = mNextInstallToken++; 12332 12333 PostInstallData data = new PostInstallData(args, res); 12334 mRunningInstalls.put(token, data); 12335 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12336 12337 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12338 // Pass responsibility to the Backup Manager. It will perform a 12339 // restore if appropriate, then pass responsibility back to the 12340 // Package Manager to run the post-install observer callbacks 12341 // and broadcasts. 12342 IBackupManager bm = IBackupManager.Stub.asInterface( 12343 ServiceManager.getService(Context.BACKUP_SERVICE)); 12344 if (bm != null) { 12345 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12346 + " to BM for possible restore"); 12347 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12348 try { 12349 // TODO: http://b/22388012 12350 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12351 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12352 } else { 12353 doRestore = false; 12354 } 12355 } catch (RemoteException e) { 12356 // can't happen; the backup manager is local 12357 } catch (Exception e) { 12358 Slog.e(TAG, "Exception trying to enqueue restore", e); 12359 doRestore = false; 12360 } 12361 } else { 12362 Slog.e(TAG, "Backup Manager not found!"); 12363 doRestore = false; 12364 } 12365 } 12366 12367 if (!doRestore) { 12368 // No restore possible, or the Backup Manager was mysteriously not 12369 // available -- just fire the post-install work request directly. 12370 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12371 12372 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12373 12374 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12375 mHandler.sendMessage(msg); 12376 } 12377 } 12378 }); 12379 } 12380 12381 /** 12382 * Callback from PackageSettings whenever an app is first transitioned out of the 12383 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12384 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12385 * here whether the app is the target of an ongoing install, and only send the 12386 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12387 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12388 * handling. 12389 */ 12390 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12391 // Serialize this with the rest of the install-process message chain. In the 12392 // restore-at-install case, this Runnable will necessarily run before the 12393 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12394 // are coherent. In the non-restore case, the app has already completed install 12395 // and been launched through some other means, so it is not in a problematic 12396 // state for observers to see the FIRST_LAUNCH signal. 12397 mHandler.post(new Runnable() { 12398 @Override 12399 public void run() { 12400 for (int i = 0; i < mRunningInstalls.size(); i++) { 12401 final PostInstallData data = mRunningInstalls.valueAt(i); 12402 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12403 continue; 12404 } 12405 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12406 // right package; but is it for the right user? 12407 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12408 if (userId == data.res.newUsers[uIndex]) { 12409 if (DEBUG_BACKUP) { 12410 Slog.i(TAG, "Package " + pkgName 12411 + " being restored so deferring FIRST_LAUNCH"); 12412 } 12413 return; 12414 } 12415 } 12416 } 12417 } 12418 // didn't find it, so not being restored 12419 if (DEBUG_BACKUP) { 12420 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12421 } 12422 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12423 } 12424 }); 12425 } 12426 12427 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12428 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12429 installerPkg, null, userIds); 12430 } 12431 12432 private abstract class HandlerParams { 12433 private static final int MAX_RETRIES = 4; 12434 12435 /** 12436 * Number of times startCopy() has been attempted and had a non-fatal 12437 * error. 12438 */ 12439 private int mRetries = 0; 12440 12441 /** User handle for the user requesting the information or installation. */ 12442 private final UserHandle mUser; 12443 String traceMethod; 12444 int traceCookie; 12445 12446 HandlerParams(UserHandle user) { 12447 mUser = user; 12448 } 12449 12450 UserHandle getUser() { 12451 return mUser; 12452 } 12453 12454 HandlerParams setTraceMethod(String traceMethod) { 12455 this.traceMethod = traceMethod; 12456 return this; 12457 } 12458 12459 HandlerParams setTraceCookie(int traceCookie) { 12460 this.traceCookie = traceCookie; 12461 return this; 12462 } 12463 12464 final boolean startCopy() { 12465 boolean res; 12466 try { 12467 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12468 12469 if (++mRetries > MAX_RETRIES) { 12470 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12471 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12472 handleServiceError(); 12473 return false; 12474 } else { 12475 handleStartCopy(); 12476 res = true; 12477 } 12478 } catch (RemoteException e) { 12479 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12480 mHandler.sendEmptyMessage(MCS_RECONNECT); 12481 res = false; 12482 } 12483 handleReturnCode(); 12484 return res; 12485 } 12486 12487 final void serviceError() { 12488 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12489 handleServiceError(); 12490 handleReturnCode(); 12491 } 12492 12493 abstract void handleStartCopy() throws RemoteException; 12494 abstract void handleServiceError(); 12495 abstract void handleReturnCode(); 12496 } 12497 12498 class MeasureParams extends HandlerParams { 12499 private final PackageStats mStats; 12500 private boolean mSuccess; 12501 12502 private final IPackageStatsObserver mObserver; 12503 12504 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12505 super(new UserHandle(stats.userHandle)); 12506 mObserver = observer; 12507 mStats = stats; 12508 } 12509 12510 @Override 12511 public String toString() { 12512 return "MeasureParams{" 12513 + Integer.toHexString(System.identityHashCode(this)) 12514 + " " + mStats.packageName + "}"; 12515 } 12516 12517 @Override 12518 void handleStartCopy() throws RemoteException { 12519 synchronized (mInstallLock) { 12520 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12521 } 12522 12523 if (mSuccess) { 12524 boolean mounted = false; 12525 try { 12526 final String status = Environment.getExternalStorageState(); 12527 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12528 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12529 } catch (Exception e) { 12530 } 12531 12532 if (mounted) { 12533 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12534 12535 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12536 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12537 12538 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12539 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12540 12541 // Always subtract cache size, since it's a subdirectory 12542 mStats.externalDataSize -= mStats.externalCacheSize; 12543 12544 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12545 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12546 12547 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12548 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12549 } 12550 } 12551 } 12552 12553 @Override 12554 void handleReturnCode() { 12555 if (mObserver != null) { 12556 try { 12557 mObserver.onGetStatsCompleted(mStats, mSuccess); 12558 } catch (RemoteException e) { 12559 Slog.i(TAG, "Observer no longer exists."); 12560 } 12561 } 12562 } 12563 12564 @Override 12565 void handleServiceError() { 12566 Slog.e(TAG, "Could not measure application " + mStats.packageName 12567 + " external storage"); 12568 } 12569 } 12570 12571 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12572 throws RemoteException { 12573 long result = 0; 12574 for (File path : paths) { 12575 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12576 } 12577 return result; 12578 } 12579 12580 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12581 for (File path : paths) { 12582 try { 12583 mcs.clearDirectory(path.getAbsolutePath()); 12584 } catch (RemoteException e) { 12585 } 12586 } 12587 } 12588 12589 static class OriginInfo { 12590 /** 12591 * Location where install is coming from, before it has been 12592 * copied/renamed into place. This could be a single monolithic APK 12593 * file, or a cluster directory. This location may be untrusted. 12594 */ 12595 final File file; 12596 final String cid; 12597 12598 /** 12599 * Flag indicating that {@link #file} or {@link #cid} has already been 12600 * staged, meaning downstream users don't need to defensively copy the 12601 * contents. 12602 */ 12603 final boolean staged; 12604 12605 /** 12606 * Flag indicating that {@link #file} or {@link #cid} is an already 12607 * installed app that is being moved. 12608 */ 12609 final boolean existing; 12610 12611 final String resolvedPath; 12612 final File resolvedFile; 12613 12614 static OriginInfo fromNothing() { 12615 return new OriginInfo(null, null, false, false); 12616 } 12617 12618 static OriginInfo fromUntrustedFile(File file) { 12619 return new OriginInfo(file, null, false, false); 12620 } 12621 12622 static OriginInfo fromExistingFile(File file) { 12623 return new OriginInfo(file, null, false, true); 12624 } 12625 12626 static OriginInfo fromStagedFile(File file) { 12627 return new OriginInfo(file, null, true, false); 12628 } 12629 12630 static OriginInfo fromStagedContainer(String cid) { 12631 return new OriginInfo(null, cid, true, false); 12632 } 12633 12634 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12635 this.file = file; 12636 this.cid = cid; 12637 this.staged = staged; 12638 this.existing = existing; 12639 12640 if (cid != null) { 12641 resolvedPath = PackageHelper.getSdDir(cid); 12642 resolvedFile = new File(resolvedPath); 12643 } else if (file != null) { 12644 resolvedPath = file.getAbsolutePath(); 12645 resolvedFile = file; 12646 } else { 12647 resolvedPath = null; 12648 resolvedFile = null; 12649 } 12650 } 12651 } 12652 12653 static class MoveInfo { 12654 final int moveId; 12655 final String fromUuid; 12656 final String toUuid; 12657 final String packageName; 12658 final String dataAppName; 12659 final int appId; 12660 final String seinfo; 12661 final int targetSdkVersion; 12662 12663 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12664 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12665 this.moveId = moveId; 12666 this.fromUuid = fromUuid; 12667 this.toUuid = toUuid; 12668 this.packageName = packageName; 12669 this.dataAppName = dataAppName; 12670 this.appId = appId; 12671 this.seinfo = seinfo; 12672 this.targetSdkVersion = targetSdkVersion; 12673 } 12674 } 12675 12676 static class VerificationInfo { 12677 /** A constant used to indicate that a uid value is not present. */ 12678 public static final int NO_UID = -1; 12679 12680 /** URI referencing where the package was downloaded from. */ 12681 final Uri originatingUri; 12682 12683 /** HTTP referrer URI associated with the originatingURI. */ 12684 final Uri referrer; 12685 12686 /** UID of the application that the install request originated from. */ 12687 final int originatingUid; 12688 12689 /** UID of application requesting the install */ 12690 final int installerUid; 12691 12692 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12693 this.originatingUri = originatingUri; 12694 this.referrer = referrer; 12695 this.originatingUid = originatingUid; 12696 this.installerUid = installerUid; 12697 } 12698 } 12699 12700 class InstallParams extends HandlerParams { 12701 final OriginInfo origin; 12702 final MoveInfo move; 12703 final IPackageInstallObserver2 observer; 12704 int installFlags; 12705 final String installerPackageName; 12706 final String volumeUuid; 12707 private InstallArgs mArgs; 12708 private int mRet; 12709 final String packageAbiOverride; 12710 final String[] grantedRuntimePermissions; 12711 final VerificationInfo verificationInfo; 12712 final Certificate[][] certificates; 12713 12714 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12715 int installFlags, String installerPackageName, String volumeUuid, 12716 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12717 String[] grantedPermissions, Certificate[][] certificates) { 12718 super(user); 12719 this.origin = origin; 12720 this.move = move; 12721 this.observer = observer; 12722 this.installFlags = installFlags; 12723 this.installerPackageName = installerPackageName; 12724 this.volumeUuid = volumeUuid; 12725 this.verificationInfo = verificationInfo; 12726 this.packageAbiOverride = packageAbiOverride; 12727 this.grantedRuntimePermissions = grantedPermissions; 12728 this.certificates = certificates; 12729 } 12730 12731 @Override 12732 public String toString() { 12733 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12734 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12735 } 12736 12737 private int installLocationPolicy(PackageInfoLite pkgLite) { 12738 String packageName = pkgLite.packageName; 12739 int installLocation = pkgLite.installLocation; 12740 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12741 // reader 12742 synchronized (mPackages) { 12743 // Currently installed package which the new package is attempting to replace or 12744 // null if no such package is installed. 12745 PackageParser.Package installedPkg = mPackages.get(packageName); 12746 // Package which currently owns the data which the new package will own if installed. 12747 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12748 // will be null whereas dataOwnerPkg will contain information about the package 12749 // which was uninstalled while keeping its data. 12750 PackageParser.Package dataOwnerPkg = installedPkg; 12751 if (dataOwnerPkg == null) { 12752 PackageSetting ps = mSettings.mPackages.get(packageName); 12753 if (ps != null) { 12754 dataOwnerPkg = ps.pkg; 12755 } 12756 } 12757 12758 if (dataOwnerPkg != null) { 12759 // If installed, the package will get access to data left on the device by its 12760 // predecessor. As a security measure, this is permited only if this is not a 12761 // version downgrade or if the predecessor package is marked as debuggable and 12762 // a downgrade is explicitly requested. 12763 // 12764 // On debuggable platform builds, downgrades are permitted even for 12765 // non-debuggable packages to make testing easier. Debuggable platform builds do 12766 // not offer security guarantees and thus it's OK to disable some security 12767 // mechanisms to make debugging/testing easier on those builds. However, even on 12768 // debuggable builds downgrades of packages are permitted only if requested via 12769 // installFlags. This is because we aim to keep the behavior of debuggable 12770 // platform builds as close as possible to the behavior of non-debuggable 12771 // platform builds. 12772 final boolean downgradeRequested = 12773 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12774 final boolean packageDebuggable = 12775 (dataOwnerPkg.applicationInfo.flags 12776 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12777 final boolean downgradePermitted = 12778 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12779 if (!downgradePermitted) { 12780 try { 12781 checkDowngrade(dataOwnerPkg, pkgLite); 12782 } catch (PackageManagerException e) { 12783 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12784 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12785 } 12786 } 12787 } 12788 12789 if (installedPkg != null) { 12790 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12791 // Check for updated system application. 12792 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12793 if (onSd) { 12794 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12795 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12796 } 12797 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12798 } else { 12799 if (onSd) { 12800 // Install flag overrides everything. 12801 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12802 } 12803 // If current upgrade specifies particular preference 12804 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12805 // Application explicitly specified internal. 12806 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12807 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12808 // App explictly prefers external. Let policy decide 12809 } else { 12810 // Prefer previous location 12811 if (isExternal(installedPkg)) { 12812 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12813 } 12814 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12815 } 12816 } 12817 } else { 12818 // Invalid install. Return error code 12819 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12820 } 12821 } 12822 } 12823 // All the special cases have been taken care of. 12824 // Return result based on recommended install location. 12825 if (onSd) { 12826 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12827 } 12828 return pkgLite.recommendedInstallLocation; 12829 } 12830 12831 /* 12832 * Invoke remote method to get package information and install 12833 * location values. Override install location based on default 12834 * policy if needed and then create install arguments based 12835 * on the install location. 12836 */ 12837 public void handleStartCopy() throws RemoteException { 12838 int ret = PackageManager.INSTALL_SUCCEEDED; 12839 12840 // If we're already staged, we've firmly committed to an install location 12841 if (origin.staged) { 12842 if (origin.file != null) { 12843 installFlags |= PackageManager.INSTALL_INTERNAL; 12844 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12845 } else if (origin.cid != null) { 12846 installFlags |= PackageManager.INSTALL_EXTERNAL; 12847 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12848 } else { 12849 throw new IllegalStateException("Invalid stage location"); 12850 } 12851 } 12852 12853 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12854 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12855 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12856 PackageInfoLite pkgLite = null; 12857 12858 if (onInt && onSd) { 12859 // Check if both bits are set. 12860 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12861 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12862 } else if (onSd && ephemeral) { 12863 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12864 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12865 } else { 12866 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12867 packageAbiOverride); 12868 12869 if (DEBUG_EPHEMERAL && ephemeral) { 12870 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12871 } 12872 12873 /* 12874 * If we have too little free space, try to free cache 12875 * before giving up. 12876 */ 12877 if (!origin.staged && pkgLite.recommendedInstallLocation 12878 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12879 // TODO: focus freeing disk space on the target device 12880 final StorageManager storage = StorageManager.from(mContext); 12881 final long lowThreshold = storage.getStorageLowBytes( 12882 Environment.getDataDirectory()); 12883 12884 final long sizeBytes = mContainerService.calculateInstalledSize( 12885 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12886 12887 try { 12888 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12889 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12890 installFlags, packageAbiOverride); 12891 } catch (InstallerException e) { 12892 Slog.w(TAG, "Failed to free cache", e); 12893 } 12894 12895 /* 12896 * The cache free must have deleted the file we 12897 * downloaded to install. 12898 * 12899 * TODO: fix the "freeCache" call to not delete 12900 * the file we care about. 12901 */ 12902 if (pkgLite.recommendedInstallLocation 12903 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12904 pkgLite.recommendedInstallLocation 12905 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12906 } 12907 } 12908 } 12909 12910 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12911 int loc = pkgLite.recommendedInstallLocation; 12912 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12913 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12914 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12915 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12916 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12917 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12918 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12919 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12920 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12921 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12922 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12923 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12924 } else { 12925 // Override with defaults if needed. 12926 loc = installLocationPolicy(pkgLite); 12927 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12928 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12929 } else if (!onSd && !onInt) { 12930 // Override install location with flags 12931 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12932 // Set the flag to install on external media. 12933 installFlags |= PackageManager.INSTALL_EXTERNAL; 12934 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12935 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12936 if (DEBUG_EPHEMERAL) { 12937 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12938 } 12939 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12940 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12941 |PackageManager.INSTALL_INTERNAL); 12942 } else { 12943 // Make sure the flag for installing on external 12944 // media is unset 12945 installFlags |= PackageManager.INSTALL_INTERNAL; 12946 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12947 } 12948 } 12949 } 12950 } 12951 12952 final InstallArgs args = createInstallArgs(this); 12953 mArgs = args; 12954 12955 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12956 // TODO: http://b/22976637 12957 // Apps installed for "all" users use the device owner to verify the app 12958 UserHandle verifierUser = getUser(); 12959 if (verifierUser == UserHandle.ALL) { 12960 verifierUser = UserHandle.SYSTEM; 12961 } 12962 12963 /* 12964 * Determine if we have any installed package verifiers. If we 12965 * do, then we'll defer to them to verify the packages. 12966 */ 12967 final int requiredUid = mRequiredVerifierPackage == null ? -1 12968 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12969 verifierUser.getIdentifier()); 12970 if (!origin.existing && requiredUid != -1 12971 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12972 final Intent verification = new Intent( 12973 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12974 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12975 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12976 PACKAGE_MIME_TYPE); 12977 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12978 12979 // Query all live verifiers based on current user state 12980 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12981 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12982 12983 if (DEBUG_VERIFY) { 12984 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12985 + verification.toString() + " with " + pkgLite.verifiers.length 12986 + " optional verifiers"); 12987 } 12988 12989 final int verificationId = mPendingVerificationToken++; 12990 12991 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12992 12993 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12994 installerPackageName); 12995 12996 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12997 installFlags); 12998 12999 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13000 pkgLite.packageName); 13001 13002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13003 pkgLite.versionCode); 13004 13005 if (verificationInfo != null) { 13006 if (verificationInfo.originatingUri != null) { 13007 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13008 verificationInfo.originatingUri); 13009 } 13010 if (verificationInfo.referrer != null) { 13011 verification.putExtra(Intent.EXTRA_REFERRER, 13012 verificationInfo.referrer); 13013 } 13014 if (verificationInfo.originatingUid >= 0) { 13015 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13016 verificationInfo.originatingUid); 13017 } 13018 if (verificationInfo.installerUid >= 0) { 13019 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13020 verificationInfo.installerUid); 13021 } 13022 } 13023 13024 final PackageVerificationState verificationState = new PackageVerificationState( 13025 requiredUid, args); 13026 13027 mPendingVerification.append(verificationId, verificationState); 13028 13029 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13030 receivers, verificationState); 13031 13032 /* 13033 * If any sufficient verifiers were listed in the package 13034 * manifest, attempt to ask them. 13035 */ 13036 if (sufficientVerifiers != null) { 13037 final int N = sufficientVerifiers.size(); 13038 if (N == 0) { 13039 Slog.i(TAG, "Additional verifiers required, but none installed."); 13040 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13041 } else { 13042 for (int i = 0; i < N; i++) { 13043 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13044 13045 final Intent sufficientIntent = new Intent(verification); 13046 sufficientIntent.setComponent(verifierComponent); 13047 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13048 } 13049 } 13050 } 13051 13052 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13053 mRequiredVerifierPackage, receivers); 13054 if (ret == PackageManager.INSTALL_SUCCEEDED 13055 && mRequiredVerifierPackage != null) { 13056 Trace.asyncTraceBegin( 13057 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13058 /* 13059 * Send the intent to the required verification agent, 13060 * but only start the verification timeout after the 13061 * target BroadcastReceivers have run. 13062 */ 13063 verification.setComponent(requiredVerifierComponent); 13064 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13065 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13066 new BroadcastReceiver() { 13067 @Override 13068 public void onReceive(Context context, Intent intent) { 13069 final Message msg = mHandler 13070 .obtainMessage(CHECK_PENDING_VERIFICATION); 13071 msg.arg1 = verificationId; 13072 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13073 } 13074 }, null, 0, null, null); 13075 13076 /* 13077 * We don't want the copy to proceed until verification 13078 * succeeds, so null out this field. 13079 */ 13080 mArgs = null; 13081 } 13082 } else { 13083 /* 13084 * No package verification is enabled, so immediately start 13085 * the remote call to initiate copy using temporary file. 13086 */ 13087 ret = args.copyApk(mContainerService, true); 13088 } 13089 } 13090 13091 mRet = ret; 13092 } 13093 13094 @Override 13095 void handleReturnCode() { 13096 // If mArgs is null, then MCS couldn't be reached. When it 13097 // reconnects, it will try again to install. At that point, this 13098 // will succeed. 13099 if (mArgs != null) { 13100 processPendingInstall(mArgs, mRet); 13101 } 13102 } 13103 13104 @Override 13105 void handleServiceError() { 13106 mArgs = createInstallArgs(this); 13107 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13108 } 13109 13110 public boolean isForwardLocked() { 13111 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13112 } 13113 } 13114 13115 /** 13116 * Used during creation of InstallArgs 13117 * 13118 * @param installFlags package installation flags 13119 * @return true if should be installed on external storage 13120 */ 13121 private static boolean installOnExternalAsec(int installFlags) { 13122 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13123 return false; 13124 } 13125 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13126 return true; 13127 } 13128 return false; 13129 } 13130 13131 /** 13132 * Used during creation of InstallArgs 13133 * 13134 * @param installFlags package installation flags 13135 * @return true if should be installed as forward locked 13136 */ 13137 private static boolean installForwardLocked(int installFlags) { 13138 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13139 } 13140 13141 private InstallArgs createInstallArgs(InstallParams params) { 13142 if (params.move != null) { 13143 return new MoveInstallArgs(params); 13144 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13145 return new AsecInstallArgs(params); 13146 } else { 13147 return new FileInstallArgs(params); 13148 } 13149 } 13150 13151 /** 13152 * Create args that describe an existing installed package. Typically used 13153 * when cleaning up old installs, or used as a move source. 13154 */ 13155 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13156 String resourcePath, String[] instructionSets) { 13157 final boolean isInAsec; 13158 if (installOnExternalAsec(installFlags)) { 13159 /* Apps on SD card are always in ASEC containers. */ 13160 isInAsec = true; 13161 } else if (installForwardLocked(installFlags) 13162 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13163 /* 13164 * Forward-locked apps are only in ASEC containers if they're the 13165 * new style 13166 */ 13167 isInAsec = true; 13168 } else { 13169 isInAsec = false; 13170 } 13171 13172 if (isInAsec) { 13173 return new AsecInstallArgs(codePath, instructionSets, 13174 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13175 } else { 13176 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13177 } 13178 } 13179 13180 static abstract class InstallArgs { 13181 /** @see InstallParams#origin */ 13182 final OriginInfo origin; 13183 /** @see InstallParams#move */ 13184 final MoveInfo move; 13185 13186 final IPackageInstallObserver2 observer; 13187 // Always refers to PackageManager flags only 13188 final int installFlags; 13189 final String installerPackageName; 13190 final String volumeUuid; 13191 final UserHandle user; 13192 final String abiOverride; 13193 final String[] installGrantPermissions; 13194 /** If non-null, drop an async trace when the install completes */ 13195 final String traceMethod; 13196 final int traceCookie; 13197 final Certificate[][] certificates; 13198 13199 // The list of instruction sets supported by this app. This is currently 13200 // only used during the rmdex() phase to clean up resources. We can get rid of this 13201 // if we move dex files under the common app path. 13202 /* nullable */ String[] instructionSets; 13203 13204 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13205 int installFlags, String installerPackageName, String volumeUuid, 13206 UserHandle user, String[] instructionSets, 13207 String abiOverride, String[] installGrantPermissions, 13208 String traceMethod, int traceCookie, Certificate[][] certificates) { 13209 this.origin = origin; 13210 this.move = move; 13211 this.installFlags = installFlags; 13212 this.observer = observer; 13213 this.installerPackageName = installerPackageName; 13214 this.volumeUuid = volumeUuid; 13215 this.user = user; 13216 this.instructionSets = instructionSets; 13217 this.abiOverride = abiOverride; 13218 this.installGrantPermissions = installGrantPermissions; 13219 this.traceMethod = traceMethod; 13220 this.traceCookie = traceCookie; 13221 this.certificates = certificates; 13222 } 13223 13224 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13225 abstract int doPreInstall(int status); 13226 13227 /** 13228 * Rename package into final resting place. All paths on the given 13229 * scanned package should be updated to reflect the rename. 13230 */ 13231 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13232 abstract int doPostInstall(int status, int uid); 13233 13234 /** @see PackageSettingBase#codePathString */ 13235 abstract String getCodePath(); 13236 /** @see PackageSettingBase#resourcePathString */ 13237 abstract String getResourcePath(); 13238 13239 // Need installer lock especially for dex file removal. 13240 abstract void cleanUpResourcesLI(); 13241 abstract boolean doPostDeleteLI(boolean delete); 13242 13243 /** 13244 * Called before the source arguments are copied. This is used mostly 13245 * for MoveParams when it needs to read the source file to put it in the 13246 * destination. 13247 */ 13248 int doPreCopy() { 13249 return PackageManager.INSTALL_SUCCEEDED; 13250 } 13251 13252 /** 13253 * Called after the source arguments are copied. This is used mostly for 13254 * MoveParams when it needs to read the source file to put it in the 13255 * destination. 13256 */ 13257 int doPostCopy(int uid) { 13258 return PackageManager.INSTALL_SUCCEEDED; 13259 } 13260 13261 protected boolean isFwdLocked() { 13262 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13263 } 13264 13265 protected boolean isExternalAsec() { 13266 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13267 } 13268 13269 protected boolean isEphemeral() { 13270 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13271 } 13272 13273 UserHandle getUser() { 13274 return user; 13275 } 13276 } 13277 13278 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13279 if (!allCodePaths.isEmpty()) { 13280 if (instructionSets == null) { 13281 throw new IllegalStateException("instructionSet == null"); 13282 } 13283 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13284 for (String codePath : allCodePaths) { 13285 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13286 try { 13287 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13288 } catch (InstallerException ignored) { 13289 } 13290 } 13291 } 13292 } 13293 } 13294 13295 /** 13296 * Logic to handle installation of non-ASEC applications, including copying 13297 * and renaming logic. 13298 */ 13299 class FileInstallArgs extends InstallArgs { 13300 private File codeFile; 13301 private File resourceFile; 13302 13303 // Example topology: 13304 // /data/app/com.example/base.apk 13305 // /data/app/com.example/split_foo.apk 13306 // /data/app/com.example/lib/arm/libfoo.so 13307 // /data/app/com.example/lib/arm64/libfoo.so 13308 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13309 13310 /** New install */ 13311 FileInstallArgs(InstallParams params) { 13312 super(params.origin, params.move, params.observer, params.installFlags, 13313 params.installerPackageName, params.volumeUuid, 13314 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13315 params.grantedRuntimePermissions, 13316 params.traceMethod, params.traceCookie, params.certificates); 13317 if (isFwdLocked()) { 13318 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13319 } 13320 } 13321 13322 /** Existing install */ 13323 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13324 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13325 null, null, null, 0, null /*certificates*/); 13326 this.codeFile = (codePath != null) ? new File(codePath) : null; 13327 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13328 } 13329 13330 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13331 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13332 try { 13333 return doCopyApk(imcs, temp); 13334 } finally { 13335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13336 } 13337 } 13338 13339 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13340 if (origin.staged) { 13341 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13342 codeFile = origin.file; 13343 resourceFile = origin.file; 13344 return PackageManager.INSTALL_SUCCEEDED; 13345 } 13346 13347 try { 13348 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13349 final File tempDir = 13350 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13351 codeFile = tempDir; 13352 resourceFile = tempDir; 13353 } catch (IOException e) { 13354 Slog.w(TAG, "Failed to create copy file: " + e); 13355 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13356 } 13357 13358 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13359 @Override 13360 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13361 if (!FileUtils.isValidExtFilename(name)) { 13362 throw new IllegalArgumentException("Invalid filename: " + name); 13363 } 13364 try { 13365 final File file = new File(codeFile, name); 13366 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13367 O_RDWR | O_CREAT, 0644); 13368 Os.chmod(file.getAbsolutePath(), 0644); 13369 return new ParcelFileDescriptor(fd); 13370 } catch (ErrnoException e) { 13371 throw new RemoteException("Failed to open: " + e.getMessage()); 13372 } 13373 } 13374 }; 13375 13376 int ret = PackageManager.INSTALL_SUCCEEDED; 13377 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13378 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13379 Slog.e(TAG, "Failed to copy package"); 13380 return ret; 13381 } 13382 13383 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13384 NativeLibraryHelper.Handle handle = null; 13385 try { 13386 handle = NativeLibraryHelper.Handle.create(codeFile); 13387 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13388 abiOverride); 13389 } catch (IOException e) { 13390 Slog.e(TAG, "Copying native libraries failed", e); 13391 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13392 } finally { 13393 IoUtils.closeQuietly(handle); 13394 } 13395 13396 return ret; 13397 } 13398 13399 int doPreInstall(int status) { 13400 if (status != PackageManager.INSTALL_SUCCEEDED) { 13401 cleanUp(); 13402 } 13403 return status; 13404 } 13405 13406 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13407 if (status != PackageManager.INSTALL_SUCCEEDED) { 13408 cleanUp(); 13409 return false; 13410 } 13411 13412 final File targetDir = codeFile.getParentFile(); 13413 final File beforeCodeFile = codeFile; 13414 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13415 13416 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13417 try { 13418 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13419 } catch (ErrnoException e) { 13420 Slog.w(TAG, "Failed to rename", e); 13421 return false; 13422 } 13423 13424 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13425 Slog.w(TAG, "Failed to restorecon"); 13426 return false; 13427 } 13428 13429 // Reflect the rename internally 13430 codeFile = afterCodeFile; 13431 resourceFile = afterCodeFile; 13432 13433 // Reflect the rename in scanned details 13434 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13435 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13436 afterCodeFile, pkg.baseCodePath)); 13437 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13438 afterCodeFile, pkg.splitCodePaths)); 13439 13440 // Reflect the rename in app info 13441 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13442 pkg.setApplicationInfoCodePath(pkg.codePath); 13443 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13444 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13445 pkg.setApplicationInfoResourcePath(pkg.codePath); 13446 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13447 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13448 13449 return true; 13450 } 13451 13452 int doPostInstall(int status, int uid) { 13453 if (status != PackageManager.INSTALL_SUCCEEDED) { 13454 cleanUp(); 13455 } 13456 return status; 13457 } 13458 13459 @Override 13460 String getCodePath() { 13461 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13462 } 13463 13464 @Override 13465 String getResourcePath() { 13466 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13467 } 13468 13469 private boolean cleanUp() { 13470 if (codeFile == null || !codeFile.exists()) { 13471 return false; 13472 } 13473 13474 removeCodePathLI(codeFile); 13475 13476 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13477 resourceFile.delete(); 13478 } 13479 13480 return true; 13481 } 13482 13483 void cleanUpResourcesLI() { 13484 // Try enumerating all code paths before deleting 13485 List<String> allCodePaths = Collections.EMPTY_LIST; 13486 if (codeFile != null && codeFile.exists()) { 13487 try { 13488 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13489 allCodePaths = pkg.getAllCodePaths(); 13490 } catch (PackageParserException e) { 13491 // Ignored; we tried our best 13492 } 13493 } 13494 13495 cleanUp(); 13496 removeDexFiles(allCodePaths, instructionSets); 13497 } 13498 13499 boolean doPostDeleteLI(boolean delete) { 13500 // XXX err, shouldn't we respect the delete flag? 13501 cleanUpResourcesLI(); 13502 return true; 13503 } 13504 } 13505 13506 private boolean isAsecExternal(String cid) { 13507 final String asecPath = PackageHelper.getSdFilesystem(cid); 13508 return !asecPath.startsWith(mAsecInternalPath); 13509 } 13510 13511 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13512 PackageManagerException { 13513 if (copyRet < 0) { 13514 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13515 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13516 throw new PackageManagerException(copyRet, message); 13517 } 13518 } 13519 } 13520 13521 /** 13522 * Extract the MountService "container ID" from the full code path of an 13523 * .apk. 13524 */ 13525 static String cidFromCodePath(String fullCodePath) { 13526 int eidx = fullCodePath.lastIndexOf("/"); 13527 String subStr1 = fullCodePath.substring(0, eidx); 13528 int sidx = subStr1.lastIndexOf("/"); 13529 return subStr1.substring(sidx+1, eidx); 13530 } 13531 13532 /** 13533 * Logic to handle installation of ASEC applications, including copying and 13534 * renaming logic. 13535 */ 13536 class AsecInstallArgs extends InstallArgs { 13537 static final String RES_FILE_NAME = "pkg.apk"; 13538 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13539 13540 String cid; 13541 String packagePath; 13542 String resourcePath; 13543 13544 /** New install */ 13545 AsecInstallArgs(InstallParams params) { 13546 super(params.origin, params.move, params.observer, params.installFlags, 13547 params.installerPackageName, params.volumeUuid, 13548 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13549 params.grantedRuntimePermissions, 13550 params.traceMethod, params.traceCookie, params.certificates); 13551 } 13552 13553 /** Existing install */ 13554 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13555 boolean isExternal, boolean isForwardLocked) { 13556 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13557 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13558 instructionSets, null, null, null, 0, null /*certificates*/); 13559 // Hackily pretend we're still looking at a full code path 13560 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13561 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13562 } 13563 13564 // Extract cid from fullCodePath 13565 int eidx = fullCodePath.lastIndexOf("/"); 13566 String subStr1 = fullCodePath.substring(0, eidx); 13567 int sidx = subStr1.lastIndexOf("/"); 13568 cid = subStr1.substring(sidx+1, eidx); 13569 setMountPath(subStr1); 13570 } 13571 13572 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13573 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13574 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13575 instructionSets, null, null, null, 0, null /*certificates*/); 13576 this.cid = cid; 13577 setMountPath(PackageHelper.getSdDir(cid)); 13578 } 13579 13580 void createCopyFile() { 13581 cid = mInstallerService.allocateExternalStageCidLegacy(); 13582 } 13583 13584 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13585 if (origin.staged && origin.cid != null) { 13586 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13587 cid = origin.cid; 13588 setMountPath(PackageHelper.getSdDir(cid)); 13589 return PackageManager.INSTALL_SUCCEEDED; 13590 } 13591 13592 if (temp) { 13593 createCopyFile(); 13594 } else { 13595 /* 13596 * Pre-emptively destroy the container since it's destroyed if 13597 * copying fails due to it existing anyway. 13598 */ 13599 PackageHelper.destroySdDir(cid); 13600 } 13601 13602 final String newMountPath = imcs.copyPackageToContainer( 13603 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13604 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13605 13606 if (newMountPath != null) { 13607 setMountPath(newMountPath); 13608 return PackageManager.INSTALL_SUCCEEDED; 13609 } else { 13610 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13611 } 13612 } 13613 13614 @Override 13615 String getCodePath() { 13616 return packagePath; 13617 } 13618 13619 @Override 13620 String getResourcePath() { 13621 return resourcePath; 13622 } 13623 13624 int doPreInstall(int status) { 13625 if (status != PackageManager.INSTALL_SUCCEEDED) { 13626 // Destroy container 13627 PackageHelper.destroySdDir(cid); 13628 } else { 13629 boolean mounted = PackageHelper.isContainerMounted(cid); 13630 if (!mounted) { 13631 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13632 Process.SYSTEM_UID); 13633 if (newMountPath != null) { 13634 setMountPath(newMountPath); 13635 } else { 13636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13637 } 13638 } 13639 } 13640 return status; 13641 } 13642 13643 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13644 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13645 String newMountPath = null; 13646 if (PackageHelper.isContainerMounted(cid)) { 13647 // Unmount the container 13648 if (!PackageHelper.unMountSdDir(cid)) { 13649 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13650 return false; 13651 } 13652 } 13653 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13654 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13655 " which might be stale. Will try to clean up."); 13656 // Clean up the stale container and proceed to recreate. 13657 if (!PackageHelper.destroySdDir(newCacheId)) { 13658 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13659 return false; 13660 } 13661 // Successfully cleaned up stale container. Try to rename again. 13662 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13663 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13664 + " inspite of cleaning it up."); 13665 return false; 13666 } 13667 } 13668 if (!PackageHelper.isContainerMounted(newCacheId)) { 13669 Slog.w(TAG, "Mounting container " + newCacheId); 13670 newMountPath = PackageHelper.mountSdDir(newCacheId, 13671 getEncryptKey(), Process.SYSTEM_UID); 13672 } else { 13673 newMountPath = PackageHelper.getSdDir(newCacheId); 13674 } 13675 if (newMountPath == null) { 13676 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13677 return false; 13678 } 13679 Log.i(TAG, "Succesfully renamed " + cid + 13680 " to " + newCacheId + 13681 " at new path: " + newMountPath); 13682 cid = newCacheId; 13683 13684 final File beforeCodeFile = new File(packagePath); 13685 setMountPath(newMountPath); 13686 final File afterCodeFile = new File(packagePath); 13687 13688 // Reflect the rename in scanned details 13689 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13690 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13691 afterCodeFile, pkg.baseCodePath)); 13692 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13693 afterCodeFile, pkg.splitCodePaths)); 13694 13695 // Reflect the rename in app info 13696 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13697 pkg.setApplicationInfoCodePath(pkg.codePath); 13698 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13699 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13700 pkg.setApplicationInfoResourcePath(pkg.codePath); 13701 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13702 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13703 13704 return true; 13705 } 13706 13707 private void setMountPath(String mountPath) { 13708 final File mountFile = new File(mountPath); 13709 13710 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13711 if (monolithicFile.exists()) { 13712 packagePath = monolithicFile.getAbsolutePath(); 13713 if (isFwdLocked()) { 13714 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13715 } else { 13716 resourcePath = packagePath; 13717 } 13718 } else { 13719 packagePath = mountFile.getAbsolutePath(); 13720 resourcePath = packagePath; 13721 } 13722 } 13723 13724 int doPostInstall(int status, int uid) { 13725 if (status != PackageManager.INSTALL_SUCCEEDED) { 13726 cleanUp(); 13727 } else { 13728 final int groupOwner; 13729 final String protectedFile; 13730 if (isFwdLocked()) { 13731 groupOwner = UserHandle.getSharedAppGid(uid); 13732 protectedFile = RES_FILE_NAME; 13733 } else { 13734 groupOwner = -1; 13735 protectedFile = null; 13736 } 13737 13738 if (uid < Process.FIRST_APPLICATION_UID 13739 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13740 Slog.e(TAG, "Failed to finalize " + cid); 13741 PackageHelper.destroySdDir(cid); 13742 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13743 } 13744 13745 boolean mounted = PackageHelper.isContainerMounted(cid); 13746 if (!mounted) { 13747 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13748 } 13749 } 13750 return status; 13751 } 13752 13753 private void cleanUp() { 13754 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13755 13756 // Destroy secure container 13757 PackageHelper.destroySdDir(cid); 13758 } 13759 13760 private List<String> getAllCodePaths() { 13761 final File codeFile = new File(getCodePath()); 13762 if (codeFile != null && codeFile.exists()) { 13763 try { 13764 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13765 return pkg.getAllCodePaths(); 13766 } catch (PackageParserException e) { 13767 // Ignored; we tried our best 13768 } 13769 } 13770 return Collections.EMPTY_LIST; 13771 } 13772 13773 void cleanUpResourcesLI() { 13774 // Enumerate all code paths before deleting 13775 cleanUpResourcesLI(getAllCodePaths()); 13776 } 13777 13778 private void cleanUpResourcesLI(List<String> allCodePaths) { 13779 cleanUp(); 13780 removeDexFiles(allCodePaths, instructionSets); 13781 } 13782 13783 String getPackageName() { 13784 return getAsecPackageName(cid); 13785 } 13786 13787 boolean doPostDeleteLI(boolean delete) { 13788 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13789 final List<String> allCodePaths = getAllCodePaths(); 13790 boolean mounted = PackageHelper.isContainerMounted(cid); 13791 if (mounted) { 13792 // Unmount first 13793 if (PackageHelper.unMountSdDir(cid)) { 13794 mounted = false; 13795 } 13796 } 13797 if (!mounted && delete) { 13798 cleanUpResourcesLI(allCodePaths); 13799 } 13800 return !mounted; 13801 } 13802 13803 @Override 13804 int doPreCopy() { 13805 if (isFwdLocked()) { 13806 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13807 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13808 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13809 } 13810 } 13811 13812 return PackageManager.INSTALL_SUCCEEDED; 13813 } 13814 13815 @Override 13816 int doPostCopy(int uid) { 13817 if (isFwdLocked()) { 13818 if (uid < Process.FIRST_APPLICATION_UID 13819 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13820 RES_FILE_NAME)) { 13821 Slog.e(TAG, "Failed to finalize " + cid); 13822 PackageHelper.destroySdDir(cid); 13823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13824 } 13825 } 13826 13827 return PackageManager.INSTALL_SUCCEEDED; 13828 } 13829 } 13830 13831 /** 13832 * Logic to handle movement of existing installed applications. 13833 */ 13834 class MoveInstallArgs extends InstallArgs { 13835 private File codeFile; 13836 private File resourceFile; 13837 13838 /** New install */ 13839 MoveInstallArgs(InstallParams params) { 13840 super(params.origin, params.move, params.observer, params.installFlags, 13841 params.installerPackageName, params.volumeUuid, 13842 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13843 params.grantedRuntimePermissions, 13844 params.traceMethod, params.traceCookie, params.certificates); 13845 } 13846 13847 int copyApk(IMediaContainerService imcs, boolean temp) { 13848 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13849 + move.fromUuid + " to " + move.toUuid); 13850 synchronized (mInstaller) { 13851 try { 13852 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13853 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13854 } catch (InstallerException e) { 13855 Slog.w(TAG, "Failed to move app", e); 13856 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13857 } 13858 } 13859 13860 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13861 resourceFile = codeFile; 13862 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13863 13864 return PackageManager.INSTALL_SUCCEEDED; 13865 } 13866 13867 int doPreInstall(int status) { 13868 if (status != PackageManager.INSTALL_SUCCEEDED) { 13869 cleanUp(move.toUuid); 13870 } 13871 return status; 13872 } 13873 13874 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13875 if (status != PackageManager.INSTALL_SUCCEEDED) { 13876 cleanUp(move.toUuid); 13877 return false; 13878 } 13879 13880 // Reflect the move in app info 13881 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13882 pkg.setApplicationInfoCodePath(pkg.codePath); 13883 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13884 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13885 pkg.setApplicationInfoResourcePath(pkg.codePath); 13886 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13887 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13888 13889 return true; 13890 } 13891 13892 int doPostInstall(int status, int uid) { 13893 if (status == PackageManager.INSTALL_SUCCEEDED) { 13894 cleanUp(move.fromUuid); 13895 } else { 13896 cleanUp(move.toUuid); 13897 } 13898 return status; 13899 } 13900 13901 @Override 13902 String getCodePath() { 13903 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13904 } 13905 13906 @Override 13907 String getResourcePath() { 13908 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13909 } 13910 13911 private boolean cleanUp(String volumeUuid) { 13912 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13913 move.dataAppName); 13914 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13915 final int[] userIds = sUserManager.getUserIds(); 13916 synchronized (mInstallLock) { 13917 // Clean up both app data and code 13918 // All package moves are frozen until finished 13919 for (int userId : userIds) { 13920 try { 13921 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13922 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13923 } catch (InstallerException e) { 13924 Slog.w(TAG, String.valueOf(e)); 13925 } 13926 } 13927 removeCodePathLI(codeFile); 13928 } 13929 return true; 13930 } 13931 13932 void cleanUpResourcesLI() { 13933 throw new UnsupportedOperationException(); 13934 } 13935 13936 boolean doPostDeleteLI(boolean delete) { 13937 throw new UnsupportedOperationException(); 13938 } 13939 } 13940 13941 static String getAsecPackageName(String packageCid) { 13942 int idx = packageCid.lastIndexOf("-"); 13943 if (idx == -1) { 13944 return packageCid; 13945 } 13946 return packageCid.substring(0, idx); 13947 } 13948 13949 // Utility method used to create code paths based on package name and available index. 13950 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13951 String idxStr = ""; 13952 int idx = 1; 13953 // Fall back to default value of idx=1 if prefix is not 13954 // part of oldCodePath 13955 if (oldCodePath != null) { 13956 String subStr = oldCodePath; 13957 // Drop the suffix right away 13958 if (suffix != null && subStr.endsWith(suffix)) { 13959 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13960 } 13961 // If oldCodePath already contains prefix find out the 13962 // ending index to either increment or decrement. 13963 int sidx = subStr.lastIndexOf(prefix); 13964 if (sidx != -1) { 13965 subStr = subStr.substring(sidx + prefix.length()); 13966 if (subStr != null) { 13967 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13968 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13969 } 13970 try { 13971 idx = Integer.parseInt(subStr); 13972 if (idx <= 1) { 13973 idx++; 13974 } else { 13975 idx--; 13976 } 13977 } catch(NumberFormatException e) { 13978 } 13979 } 13980 } 13981 } 13982 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13983 return prefix + idxStr; 13984 } 13985 13986 private File getNextCodePath(File targetDir, String packageName) { 13987 int suffix = 1; 13988 File result; 13989 do { 13990 result = new File(targetDir, packageName + "-" + suffix); 13991 suffix++; 13992 } while (result.exists()); 13993 return result; 13994 } 13995 13996 // Utility method that returns the relative package path with respect 13997 // to the installation directory. Like say for /data/data/com.test-1.apk 13998 // string com.test-1 is returned. 13999 static String deriveCodePathName(String codePath) { 14000 if (codePath == null) { 14001 return null; 14002 } 14003 final File codeFile = new File(codePath); 14004 final String name = codeFile.getName(); 14005 if (codeFile.isDirectory()) { 14006 return name; 14007 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14008 final int lastDot = name.lastIndexOf('.'); 14009 return name.substring(0, lastDot); 14010 } else { 14011 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14012 return null; 14013 } 14014 } 14015 14016 static class PackageInstalledInfo { 14017 String name; 14018 int uid; 14019 // The set of users that originally had this package installed. 14020 int[] origUsers; 14021 // The set of users that now have this package installed. 14022 int[] newUsers; 14023 PackageParser.Package pkg; 14024 int returnCode; 14025 String returnMsg; 14026 PackageRemovedInfo removedInfo; 14027 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14028 14029 public void setError(int code, String msg) { 14030 setReturnCode(code); 14031 setReturnMessage(msg); 14032 Slog.w(TAG, msg); 14033 } 14034 14035 public void setError(String msg, PackageParserException e) { 14036 setReturnCode(e.error); 14037 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14038 Slog.w(TAG, msg, e); 14039 } 14040 14041 public void setError(String msg, PackageManagerException e) { 14042 returnCode = e.error; 14043 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14044 Slog.w(TAG, msg, e); 14045 } 14046 14047 public void setReturnCode(int returnCode) { 14048 this.returnCode = returnCode; 14049 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14050 for (int i = 0; i < childCount; i++) { 14051 addedChildPackages.valueAt(i).returnCode = returnCode; 14052 } 14053 } 14054 14055 private void setReturnMessage(String returnMsg) { 14056 this.returnMsg = returnMsg; 14057 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14058 for (int i = 0; i < childCount; i++) { 14059 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14060 } 14061 } 14062 14063 // In some error cases we want to convey more info back to the observer 14064 String origPackage; 14065 String origPermission; 14066 } 14067 14068 /* 14069 * Install a non-existing package. 14070 */ 14071 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14072 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14073 PackageInstalledInfo res) { 14074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14075 14076 // Remember this for later, in case we need to rollback this install 14077 String pkgName = pkg.packageName; 14078 14079 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14080 14081 synchronized(mPackages) { 14082 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14083 // A package with the same name is already installed, though 14084 // it has been renamed to an older name. The package we 14085 // are trying to install should be installed as an update to 14086 // the existing one, but that has not been requested, so bail. 14087 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14088 + " without first uninstalling package running as " 14089 + mSettings.mRenamedPackages.get(pkgName)); 14090 return; 14091 } 14092 if (mPackages.containsKey(pkgName)) { 14093 // Don't allow installation over an existing package with the same name. 14094 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14095 + " without first uninstalling."); 14096 return; 14097 } 14098 } 14099 14100 try { 14101 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14102 System.currentTimeMillis(), user); 14103 14104 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14105 14106 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14107 prepareAppDataAfterInstallLIF(newPackage); 14108 14109 } else { 14110 // Remove package from internal structures, but keep around any 14111 // data that might have already existed 14112 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14113 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14114 } 14115 } catch (PackageManagerException e) { 14116 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14117 } 14118 14119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14120 } 14121 14122 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14123 // Can't rotate keys during boot or if sharedUser. 14124 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14125 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14126 return false; 14127 } 14128 // app is using upgradeKeySets; make sure all are valid 14129 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14130 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14131 for (int i = 0; i < upgradeKeySets.length; i++) { 14132 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14133 Slog.wtf(TAG, "Package " 14134 + (oldPs.name != null ? oldPs.name : "<null>") 14135 + " contains upgrade-key-set reference to unknown key-set: " 14136 + upgradeKeySets[i] 14137 + " reverting to signatures check."); 14138 return false; 14139 } 14140 } 14141 return true; 14142 } 14143 14144 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14145 // Upgrade keysets are being used. Determine if new package has a superset of the 14146 // required keys. 14147 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14148 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14149 for (int i = 0; i < upgradeKeySets.length; i++) { 14150 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14151 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14152 return true; 14153 } 14154 } 14155 return false; 14156 } 14157 14158 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14159 try (DigestInputStream digestStream = 14160 new DigestInputStream(new FileInputStream(file), digest)) { 14161 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14162 } 14163 } 14164 14165 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14166 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14167 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14168 14169 final PackageParser.Package oldPackage; 14170 final String pkgName = pkg.packageName; 14171 final int[] allUsers; 14172 final int[] installedUsers; 14173 14174 synchronized(mPackages) { 14175 oldPackage = mPackages.get(pkgName); 14176 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14177 14178 // don't allow upgrade to target a release SDK from a pre-release SDK 14179 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14180 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14181 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14182 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14183 if (oldTargetsPreRelease 14184 && !newTargetsPreRelease 14185 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14186 Slog.w(TAG, "Can't install package targeting released sdk"); 14187 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14188 return; 14189 } 14190 14191 // don't allow an upgrade from full to ephemeral 14192 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14193 if (isEphemeral && !oldIsEphemeral) { 14194 // can't downgrade from full to ephemeral 14195 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14196 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14197 return; 14198 } 14199 14200 // verify signatures are valid 14201 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14202 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14203 if (!checkUpgradeKeySetLP(ps, pkg)) { 14204 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14205 "New package not signed by keys specified by upgrade-keysets: " 14206 + pkgName); 14207 return; 14208 } 14209 } else { 14210 // default to original signature matching 14211 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14212 != PackageManager.SIGNATURE_MATCH) { 14213 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14214 "New package has a different signature: " + pkgName); 14215 return; 14216 } 14217 } 14218 14219 // don't allow a system upgrade unless the upgrade hash matches 14220 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14221 byte[] digestBytes = null; 14222 try { 14223 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14224 updateDigest(digest, new File(pkg.baseCodePath)); 14225 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14226 for (String path : pkg.splitCodePaths) { 14227 updateDigest(digest, new File(path)); 14228 } 14229 } 14230 digestBytes = digest.digest(); 14231 } catch (NoSuchAlgorithmException | IOException e) { 14232 res.setError(INSTALL_FAILED_INVALID_APK, 14233 "Could not compute hash: " + pkgName); 14234 return; 14235 } 14236 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14237 res.setError(INSTALL_FAILED_INVALID_APK, 14238 "New package fails restrict-update check: " + pkgName); 14239 return; 14240 } 14241 // retain upgrade restriction 14242 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14243 } 14244 14245 // Check for shared user id changes 14246 String invalidPackageName = 14247 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14248 if (invalidPackageName != null) { 14249 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14250 "Package " + invalidPackageName + " tried to change user " 14251 + oldPackage.mSharedUserId); 14252 return; 14253 } 14254 14255 // In case of rollback, remember per-user/profile install state 14256 allUsers = sUserManager.getUserIds(); 14257 installedUsers = ps.queryInstalledUsers(allUsers, true); 14258 } 14259 14260 // Update what is removed 14261 res.removedInfo = new PackageRemovedInfo(); 14262 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14263 res.removedInfo.removedPackage = oldPackage.packageName; 14264 res.removedInfo.isUpdate = true; 14265 res.removedInfo.origUsers = installedUsers; 14266 final int childCount = (oldPackage.childPackages != null) 14267 ? oldPackage.childPackages.size() : 0; 14268 for (int i = 0; i < childCount; i++) { 14269 boolean childPackageUpdated = false; 14270 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14271 if (res.addedChildPackages != null) { 14272 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14273 if (childRes != null) { 14274 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14275 childRes.removedInfo.removedPackage = childPkg.packageName; 14276 childRes.removedInfo.isUpdate = true; 14277 childPackageUpdated = true; 14278 } 14279 } 14280 if (!childPackageUpdated) { 14281 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14282 childRemovedRes.removedPackage = childPkg.packageName; 14283 childRemovedRes.isUpdate = false; 14284 childRemovedRes.dataRemoved = true; 14285 synchronized (mPackages) { 14286 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14287 if (childPs != null) { 14288 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14289 } 14290 } 14291 if (res.removedInfo.removedChildPackages == null) { 14292 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14293 } 14294 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14295 } 14296 } 14297 14298 boolean sysPkg = (isSystemApp(oldPackage)); 14299 if (sysPkg) { 14300 // Set the system/privileged flags as needed 14301 final boolean privileged = 14302 (oldPackage.applicationInfo.privateFlags 14303 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14304 final int systemPolicyFlags = policyFlags 14305 | PackageParser.PARSE_IS_SYSTEM 14306 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14307 14308 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14309 user, allUsers, installerPackageName, res); 14310 } else { 14311 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14312 user, allUsers, installerPackageName, res); 14313 } 14314 } 14315 14316 public List<String> getPreviousCodePaths(String packageName) { 14317 final PackageSetting ps = mSettings.mPackages.get(packageName); 14318 final List<String> result = new ArrayList<String>(); 14319 if (ps != null && ps.oldCodePaths != null) { 14320 result.addAll(ps.oldCodePaths); 14321 } 14322 return result; 14323 } 14324 14325 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14326 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14327 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14328 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14329 + deletedPackage); 14330 14331 String pkgName = deletedPackage.packageName; 14332 boolean deletedPkg = true; 14333 boolean addedPkg = false; 14334 boolean updatedSettings = false; 14335 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14336 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14337 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14338 14339 final long origUpdateTime = (pkg.mExtras != null) 14340 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14341 14342 // First delete the existing package while retaining the data directory 14343 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14344 res.removedInfo, true, pkg)) { 14345 // If the existing package wasn't successfully deleted 14346 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14347 deletedPkg = false; 14348 } else { 14349 // Successfully deleted the old package; proceed with replace. 14350 14351 // If deleted package lived in a container, give users a chance to 14352 // relinquish resources before killing. 14353 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14354 if (DEBUG_INSTALL) { 14355 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14356 } 14357 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14358 final ArrayList<String> pkgList = new ArrayList<String>(1); 14359 pkgList.add(deletedPackage.applicationInfo.packageName); 14360 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14361 } 14362 14363 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14364 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14365 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14366 14367 try { 14368 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14369 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14370 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14371 14372 // Update the in-memory copy of the previous code paths. 14373 PackageSetting ps = mSettings.mPackages.get(pkgName); 14374 if (!killApp) { 14375 if (ps.oldCodePaths == null) { 14376 ps.oldCodePaths = new ArraySet<>(); 14377 } 14378 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14379 if (deletedPackage.splitCodePaths != null) { 14380 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14381 } 14382 } else { 14383 ps.oldCodePaths = null; 14384 } 14385 if (ps.childPackageNames != null) { 14386 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14387 final String childPkgName = ps.childPackageNames.get(i); 14388 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14389 childPs.oldCodePaths = ps.oldCodePaths; 14390 } 14391 } 14392 prepareAppDataAfterInstallLIF(newPackage); 14393 addedPkg = true; 14394 } catch (PackageManagerException e) { 14395 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14396 } 14397 } 14398 14399 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14400 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14401 14402 // Revert all internal state mutations and added folders for the failed install 14403 if (addedPkg) { 14404 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14405 res.removedInfo, true, null); 14406 } 14407 14408 // Restore the old package 14409 if (deletedPkg) { 14410 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14411 File restoreFile = new File(deletedPackage.codePath); 14412 // Parse old package 14413 boolean oldExternal = isExternal(deletedPackage); 14414 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14415 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14416 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14417 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14418 try { 14419 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14420 null); 14421 } catch (PackageManagerException e) { 14422 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14423 + e.getMessage()); 14424 return; 14425 } 14426 14427 synchronized (mPackages) { 14428 // Ensure the installer package name up to date 14429 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14430 14431 // Update permissions for restored package 14432 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14433 14434 mSettings.writeLPr(); 14435 } 14436 14437 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14438 } 14439 } else { 14440 synchronized (mPackages) { 14441 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14442 if (ps != null) { 14443 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14444 if (res.removedInfo.removedChildPackages != null) { 14445 final int childCount = res.removedInfo.removedChildPackages.size(); 14446 // Iterate in reverse as we may modify the collection 14447 for (int i = childCount - 1; i >= 0; i--) { 14448 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14449 if (res.addedChildPackages.containsKey(childPackageName)) { 14450 res.removedInfo.removedChildPackages.removeAt(i); 14451 } else { 14452 PackageRemovedInfo childInfo = res.removedInfo 14453 .removedChildPackages.valueAt(i); 14454 childInfo.removedForAllUsers = mPackages.get( 14455 childInfo.removedPackage) == null; 14456 } 14457 } 14458 } 14459 } 14460 } 14461 } 14462 } 14463 14464 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14465 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14466 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14467 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14468 + ", old=" + deletedPackage); 14469 14470 final boolean disabledSystem; 14471 14472 // Remove existing system package 14473 removePackageLI(deletedPackage, true); 14474 14475 synchronized (mPackages) { 14476 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14477 } 14478 if (!disabledSystem) { 14479 // We didn't need to disable the .apk as a current system package, 14480 // which means we are replacing another update that is already 14481 // installed. We need to make sure to delete the older one's .apk. 14482 res.removedInfo.args = createInstallArgsForExisting(0, 14483 deletedPackage.applicationInfo.getCodePath(), 14484 deletedPackage.applicationInfo.getResourcePath(), 14485 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14486 } else { 14487 res.removedInfo.args = null; 14488 } 14489 14490 // Successfully disabled the old package. Now proceed with re-installation 14491 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14492 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14493 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14494 14495 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14496 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14497 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14498 14499 PackageParser.Package newPackage = null; 14500 try { 14501 // Add the package to the internal data structures 14502 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14503 14504 // Set the update and install times 14505 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14506 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14507 System.currentTimeMillis()); 14508 14509 // Update the package dynamic state if succeeded 14510 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14511 // Now that the install succeeded make sure we remove data 14512 // directories for any child package the update removed. 14513 final int deletedChildCount = (deletedPackage.childPackages != null) 14514 ? deletedPackage.childPackages.size() : 0; 14515 final int newChildCount = (newPackage.childPackages != null) 14516 ? newPackage.childPackages.size() : 0; 14517 for (int i = 0; i < deletedChildCount; i++) { 14518 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14519 boolean childPackageDeleted = true; 14520 for (int j = 0; j < newChildCount; j++) { 14521 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14522 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14523 childPackageDeleted = false; 14524 break; 14525 } 14526 } 14527 if (childPackageDeleted) { 14528 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14529 deletedChildPkg.packageName); 14530 if (ps != null && res.removedInfo.removedChildPackages != null) { 14531 PackageRemovedInfo removedChildRes = res.removedInfo 14532 .removedChildPackages.get(deletedChildPkg.packageName); 14533 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14534 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14535 } 14536 } 14537 } 14538 14539 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14540 prepareAppDataAfterInstallLIF(newPackage); 14541 } 14542 } catch (PackageManagerException e) { 14543 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14544 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14545 } 14546 14547 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14548 // Re installation failed. Restore old information 14549 // Remove new pkg information 14550 if (newPackage != null) { 14551 removeInstalledPackageLI(newPackage, true); 14552 } 14553 // Add back the old system package 14554 try { 14555 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14556 } catch (PackageManagerException e) { 14557 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14558 } 14559 14560 synchronized (mPackages) { 14561 if (disabledSystem) { 14562 enableSystemPackageLPw(deletedPackage); 14563 } 14564 14565 // Ensure the installer package name up to date 14566 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14567 14568 // Update permissions for restored package 14569 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14570 14571 mSettings.writeLPr(); 14572 } 14573 14574 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14575 + " after failed upgrade"); 14576 } 14577 } 14578 14579 /** 14580 * Checks whether the parent or any of the child packages have a change shared 14581 * user. For a package to be a valid update the shred users of the parent and 14582 * the children should match. We may later support changing child shared users. 14583 * @param oldPkg The updated package. 14584 * @param newPkg The update package. 14585 * @return The shared user that change between the versions. 14586 */ 14587 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14588 PackageParser.Package newPkg) { 14589 // Check parent shared user 14590 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14591 return newPkg.packageName; 14592 } 14593 // Check child shared users 14594 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14595 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14596 for (int i = 0; i < newChildCount; i++) { 14597 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14598 // If this child was present, did it have the same shared user? 14599 for (int j = 0; j < oldChildCount; j++) { 14600 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14601 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14602 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14603 return newChildPkg.packageName; 14604 } 14605 } 14606 } 14607 return null; 14608 } 14609 14610 private void removeNativeBinariesLI(PackageSetting ps) { 14611 // Remove the lib path for the parent package 14612 if (ps != null) { 14613 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14614 // Remove the lib path for the child packages 14615 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14616 for (int i = 0; i < childCount; i++) { 14617 PackageSetting childPs = null; 14618 synchronized (mPackages) { 14619 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14620 } 14621 if (childPs != null) { 14622 NativeLibraryHelper.removeNativeBinariesLI(childPs 14623 .legacyNativeLibraryPathString); 14624 } 14625 } 14626 } 14627 } 14628 14629 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14630 // Enable the parent package 14631 mSettings.enableSystemPackageLPw(pkg.packageName); 14632 // Enable the child packages 14633 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14634 for (int i = 0; i < childCount; i++) { 14635 PackageParser.Package childPkg = pkg.childPackages.get(i); 14636 mSettings.enableSystemPackageLPw(childPkg.packageName); 14637 } 14638 } 14639 14640 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14641 PackageParser.Package newPkg) { 14642 // Disable the parent package (parent always replaced) 14643 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14644 // Disable the child packages 14645 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14646 for (int i = 0; i < childCount; i++) { 14647 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14648 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14649 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14650 } 14651 return disabled; 14652 } 14653 14654 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14655 String installerPackageName) { 14656 // Enable the parent package 14657 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14658 // Enable the child packages 14659 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14660 for (int i = 0; i < childCount; i++) { 14661 PackageParser.Package childPkg = pkg.childPackages.get(i); 14662 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14663 } 14664 } 14665 14666 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14667 // Collect all used permissions in the UID 14668 ArraySet<String> usedPermissions = new ArraySet<>(); 14669 final int packageCount = su.packages.size(); 14670 for (int i = 0; i < packageCount; i++) { 14671 PackageSetting ps = su.packages.valueAt(i); 14672 if (ps.pkg == null) { 14673 continue; 14674 } 14675 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14676 for (int j = 0; j < requestedPermCount; j++) { 14677 String permission = ps.pkg.requestedPermissions.get(j); 14678 BasePermission bp = mSettings.mPermissions.get(permission); 14679 if (bp != null) { 14680 usedPermissions.add(permission); 14681 } 14682 } 14683 } 14684 14685 PermissionsState permissionsState = su.getPermissionsState(); 14686 // Prune install permissions 14687 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14688 final int installPermCount = installPermStates.size(); 14689 for (int i = installPermCount - 1; i >= 0; i--) { 14690 PermissionState permissionState = installPermStates.get(i); 14691 if (!usedPermissions.contains(permissionState.getName())) { 14692 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14693 if (bp != null) { 14694 permissionsState.revokeInstallPermission(bp); 14695 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14696 PackageManager.MASK_PERMISSION_FLAGS, 0); 14697 } 14698 } 14699 } 14700 14701 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14702 14703 // Prune runtime permissions 14704 for (int userId : allUserIds) { 14705 List<PermissionState> runtimePermStates = permissionsState 14706 .getRuntimePermissionStates(userId); 14707 final int runtimePermCount = runtimePermStates.size(); 14708 for (int i = runtimePermCount - 1; i >= 0; i--) { 14709 PermissionState permissionState = runtimePermStates.get(i); 14710 if (!usedPermissions.contains(permissionState.getName())) { 14711 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14712 if (bp != null) { 14713 permissionsState.revokeRuntimePermission(bp, userId); 14714 permissionsState.updatePermissionFlags(bp, userId, 14715 PackageManager.MASK_PERMISSION_FLAGS, 0); 14716 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14717 runtimePermissionChangedUserIds, userId); 14718 } 14719 } 14720 } 14721 } 14722 14723 return runtimePermissionChangedUserIds; 14724 } 14725 14726 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14727 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14728 // Update the parent package setting 14729 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14730 res, user); 14731 // Update the child packages setting 14732 final int childCount = (newPackage.childPackages != null) 14733 ? newPackage.childPackages.size() : 0; 14734 for (int i = 0; i < childCount; i++) { 14735 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14736 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14737 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14738 childRes.origUsers, childRes, user); 14739 } 14740 } 14741 14742 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14743 String installerPackageName, int[] allUsers, int[] installedForUsers, 14744 PackageInstalledInfo res, UserHandle user) { 14745 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14746 14747 String pkgName = newPackage.packageName; 14748 synchronized (mPackages) { 14749 //write settings. the installStatus will be incomplete at this stage. 14750 //note that the new package setting would have already been 14751 //added to mPackages. It hasn't been persisted yet. 14752 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14753 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14754 mSettings.writeLPr(); 14755 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14756 } 14757 14758 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14759 synchronized (mPackages) { 14760 updatePermissionsLPw(newPackage.packageName, newPackage, 14761 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14762 ? UPDATE_PERMISSIONS_ALL : 0)); 14763 // For system-bundled packages, we assume that installing an upgraded version 14764 // of the package implies that the user actually wants to run that new code, 14765 // so we enable the package. 14766 PackageSetting ps = mSettings.mPackages.get(pkgName); 14767 final int userId = user.getIdentifier(); 14768 if (ps != null) { 14769 if (isSystemApp(newPackage)) { 14770 if (DEBUG_INSTALL) { 14771 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14772 } 14773 // Enable system package for requested users 14774 if (res.origUsers != null) { 14775 for (int origUserId : res.origUsers) { 14776 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14777 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14778 origUserId, installerPackageName); 14779 } 14780 } 14781 } 14782 // Also convey the prior install/uninstall state 14783 if (allUsers != null && installedForUsers != null) { 14784 for (int currentUserId : allUsers) { 14785 final boolean installed = ArrayUtils.contains( 14786 installedForUsers, currentUserId); 14787 if (DEBUG_INSTALL) { 14788 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14789 } 14790 ps.setInstalled(installed, currentUserId); 14791 } 14792 // these install state changes will be persisted in the 14793 // upcoming call to mSettings.writeLPr(). 14794 } 14795 } 14796 // It's implied that when a user requests installation, they want the app to be 14797 // installed and enabled. 14798 if (userId != UserHandle.USER_ALL) { 14799 ps.setInstalled(true, userId); 14800 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14801 } 14802 } 14803 res.name = pkgName; 14804 res.uid = newPackage.applicationInfo.uid; 14805 res.pkg = newPackage; 14806 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14807 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14808 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14809 //to update install status 14810 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14811 mSettings.writeLPr(); 14812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14813 } 14814 14815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14816 } 14817 14818 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14819 try { 14820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14821 installPackageLI(args, res); 14822 } finally { 14823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14824 } 14825 } 14826 14827 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14828 final int installFlags = args.installFlags; 14829 final String installerPackageName = args.installerPackageName; 14830 final String volumeUuid = args.volumeUuid; 14831 final File tmpPackageFile = new File(args.getCodePath()); 14832 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14833 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14834 || (args.volumeUuid != null)); 14835 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14836 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14837 boolean replace = false; 14838 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14839 if (args.move != null) { 14840 // moving a complete application; perform an initial scan on the new install location 14841 scanFlags |= SCAN_INITIAL; 14842 } 14843 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14844 scanFlags |= SCAN_DONT_KILL_APP; 14845 } 14846 14847 // Result object to be returned 14848 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14849 14850 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14851 14852 // Sanity check 14853 if (ephemeral && (forwardLocked || onExternal)) { 14854 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14855 + " external=" + onExternal); 14856 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14857 return; 14858 } 14859 14860 // Retrieve PackageSettings and parse package 14861 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14862 | PackageParser.PARSE_ENFORCE_CODE 14863 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14864 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14865 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14866 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14867 PackageParser pp = new PackageParser(); 14868 pp.setSeparateProcesses(mSeparateProcesses); 14869 pp.setDisplayMetrics(mMetrics); 14870 14871 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14872 final PackageParser.Package pkg; 14873 try { 14874 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14875 } catch (PackageParserException e) { 14876 res.setError("Failed parse during installPackageLI", e); 14877 return; 14878 } finally { 14879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14880 } 14881 14882 // If we are installing a clustered package add results for the children 14883 if (pkg.childPackages != null) { 14884 synchronized (mPackages) { 14885 final int childCount = pkg.childPackages.size(); 14886 for (int i = 0; i < childCount; i++) { 14887 PackageParser.Package childPkg = pkg.childPackages.get(i); 14888 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14889 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14890 childRes.pkg = childPkg; 14891 childRes.name = childPkg.packageName; 14892 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14893 if (childPs != null) { 14894 childRes.origUsers = childPs.queryInstalledUsers( 14895 sUserManager.getUserIds(), true); 14896 } 14897 if ((mPackages.containsKey(childPkg.packageName))) { 14898 childRes.removedInfo = new PackageRemovedInfo(); 14899 childRes.removedInfo.removedPackage = childPkg.packageName; 14900 } 14901 if (res.addedChildPackages == null) { 14902 res.addedChildPackages = new ArrayMap<>(); 14903 } 14904 res.addedChildPackages.put(childPkg.packageName, childRes); 14905 } 14906 } 14907 } 14908 14909 // If package doesn't declare API override, mark that we have an install 14910 // time CPU ABI override. 14911 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14912 pkg.cpuAbiOverride = args.abiOverride; 14913 } 14914 14915 String pkgName = res.name = pkg.packageName; 14916 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14917 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14918 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14919 return; 14920 } 14921 } 14922 14923 try { 14924 // either use what we've been given or parse directly from the APK 14925 if (args.certificates != null) { 14926 try { 14927 PackageParser.populateCertificates(pkg, args.certificates); 14928 } catch (PackageParserException e) { 14929 // there was something wrong with the certificates we were given; 14930 // try to pull them from the APK 14931 PackageParser.collectCertificates(pkg, parseFlags); 14932 } 14933 } else { 14934 PackageParser.collectCertificates(pkg, parseFlags); 14935 } 14936 } catch (PackageParserException e) { 14937 res.setError("Failed collect during installPackageLI", e); 14938 return; 14939 } 14940 14941 // Get rid of all references to package scan path via parser. 14942 pp = null; 14943 String oldCodePath = null; 14944 boolean systemApp = false; 14945 synchronized (mPackages) { 14946 // Check if installing already existing package 14947 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14948 String oldName = mSettings.mRenamedPackages.get(pkgName); 14949 if (pkg.mOriginalPackages != null 14950 && pkg.mOriginalPackages.contains(oldName) 14951 && mPackages.containsKey(oldName)) { 14952 // This package is derived from an original package, 14953 // and this device has been updating from that original 14954 // name. We must continue using the original name, so 14955 // rename the new package here. 14956 pkg.setPackageName(oldName); 14957 pkgName = pkg.packageName; 14958 replace = true; 14959 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14960 + oldName + " pkgName=" + pkgName); 14961 } else if (mPackages.containsKey(pkgName)) { 14962 // This package, under its official name, already exists 14963 // on the device; we should replace it. 14964 replace = true; 14965 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14966 } 14967 14968 // Child packages are installed through the parent package 14969 if (pkg.parentPackage != null) { 14970 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14971 "Package " + pkg.packageName + " is child of package " 14972 + pkg.parentPackage.parentPackage + ". Child packages " 14973 + "can be updated only through the parent package."); 14974 return; 14975 } 14976 14977 if (replace) { 14978 // Prevent apps opting out from runtime permissions 14979 PackageParser.Package oldPackage = mPackages.get(pkgName); 14980 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14981 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14982 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14983 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14984 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14985 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14986 + " doesn't support runtime permissions but the old" 14987 + " target SDK " + oldTargetSdk + " does."); 14988 return; 14989 } 14990 14991 // Prevent installing of child packages 14992 if (oldPackage.parentPackage != null) { 14993 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14994 "Package " + pkg.packageName + " is child of package " 14995 + oldPackage.parentPackage + ". Child packages " 14996 + "can be updated only through the parent package."); 14997 return; 14998 } 14999 } 15000 } 15001 15002 PackageSetting ps = mSettings.mPackages.get(pkgName); 15003 if (ps != null) { 15004 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15005 15006 // Quick sanity check that we're signed correctly if updating; 15007 // we'll check this again later when scanning, but we want to 15008 // bail early here before tripping over redefined permissions. 15009 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15010 if (!checkUpgradeKeySetLP(ps, pkg)) { 15011 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15012 + pkg.packageName + " upgrade keys do not match the " 15013 + "previously installed version"); 15014 return; 15015 } 15016 } else { 15017 try { 15018 verifySignaturesLP(ps, pkg); 15019 } catch (PackageManagerException e) { 15020 res.setError(e.error, e.getMessage()); 15021 return; 15022 } 15023 } 15024 15025 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15026 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15027 systemApp = (ps.pkg.applicationInfo.flags & 15028 ApplicationInfo.FLAG_SYSTEM) != 0; 15029 } 15030 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15031 } 15032 15033 // Check whether the newly-scanned package wants to define an already-defined perm 15034 int N = pkg.permissions.size(); 15035 for (int i = N-1; i >= 0; i--) { 15036 PackageParser.Permission perm = pkg.permissions.get(i); 15037 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15038 if (bp != null) { 15039 // If the defining package is signed with our cert, it's okay. This 15040 // also includes the "updating the same package" case, of course. 15041 // "updating same package" could also involve key-rotation. 15042 final boolean sigsOk; 15043 if (bp.sourcePackage.equals(pkg.packageName) 15044 && (bp.packageSetting instanceof PackageSetting) 15045 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15046 scanFlags))) { 15047 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15048 } else { 15049 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15050 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15051 } 15052 if (!sigsOk) { 15053 // If the owning package is the system itself, we log but allow 15054 // install to proceed; we fail the install on all other permission 15055 // redefinitions. 15056 if (!bp.sourcePackage.equals("android")) { 15057 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15058 + pkg.packageName + " attempting to redeclare permission " 15059 + perm.info.name + " already owned by " + bp.sourcePackage); 15060 res.origPermission = perm.info.name; 15061 res.origPackage = bp.sourcePackage; 15062 return; 15063 } else { 15064 Slog.w(TAG, "Package " + pkg.packageName 15065 + " attempting to redeclare system permission " 15066 + perm.info.name + "; ignoring new declaration"); 15067 pkg.permissions.remove(i); 15068 } 15069 } 15070 } 15071 } 15072 } 15073 15074 if (systemApp) { 15075 if (onExternal) { 15076 // Abort update; system app can't be replaced with app on sdcard 15077 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15078 "Cannot install updates to system apps on sdcard"); 15079 return; 15080 } else if (ephemeral) { 15081 // Abort update; system app can't be replaced with an ephemeral app 15082 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15083 "Cannot update a system app with an ephemeral app"); 15084 return; 15085 } 15086 } 15087 15088 if (args.move != null) { 15089 // We did an in-place move, so dex is ready to roll 15090 scanFlags |= SCAN_NO_DEX; 15091 scanFlags |= SCAN_MOVE; 15092 15093 synchronized (mPackages) { 15094 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15095 if (ps == null) { 15096 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15097 "Missing settings for moved package " + pkgName); 15098 } 15099 15100 // We moved the entire application as-is, so bring over the 15101 // previously derived ABI information. 15102 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15103 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15104 } 15105 15106 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15107 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15108 scanFlags |= SCAN_NO_DEX; 15109 15110 try { 15111 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15112 args.abiOverride : pkg.cpuAbiOverride); 15113 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15114 true /* extract libs */); 15115 } catch (PackageManagerException pme) { 15116 Slog.e(TAG, "Error deriving application ABI", pme); 15117 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15118 return; 15119 } 15120 15121 // Shared libraries for the package need to be updated. 15122 synchronized (mPackages) { 15123 try { 15124 updateSharedLibrariesLPw(pkg, null); 15125 } catch (PackageManagerException e) { 15126 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15127 } 15128 } 15129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15130 // Do not run PackageDexOptimizer through the local performDexOpt 15131 // method because `pkg` may not be in `mPackages` yet. 15132 // 15133 // Also, don't fail application installs if the dexopt step fails. 15134 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15135 null /* instructionSets */, false /* checkProfiles */, 15136 getCompilerFilterForReason(REASON_INSTALL), 15137 getOrCreateCompilerPackageStats(pkg)); 15138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15139 15140 // Notify BackgroundDexOptService that the package has been changed. 15141 // If this is an update of a package which used to fail to compile, 15142 // BDOS will remove it from its blacklist. 15143 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15144 } 15145 15146 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15147 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15148 return; 15149 } 15150 15151 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15152 15153 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15154 "installPackageLI")) { 15155 if (replace) { 15156 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15157 installerPackageName, res); 15158 } else { 15159 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15160 args.user, installerPackageName, volumeUuid, res); 15161 } 15162 } 15163 synchronized (mPackages) { 15164 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15165 if (ps != null) { 15166 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15167 } 15168 15169 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15170 for (int i = 0; i < childCount; i++) { 15171 PackageParser.Package childPkg = pkg.childPackages.get(i); 15172 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15173 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15174 if (childPs != null) { 15175 childRes.newUsers = childPs.queryInstalledUsers( 15176 sUserManager.getUserIds(), true); 15177 } 15178 } 15179 } 15180 } 15181 15182 private void startIntentFilterVerifications(int userId, boolean replacing, 15183 PackageParser.Package pkg) { 15184 if (mIntentFilterVerifierComponent == null) { 15185 Slog.w(TAG, "No IntentFilter verification will not be done as " 15186 + "there is no IntentFilterVerifier available!"); 15187 return; 15188 } 15189 15190 final int verifierUid = getPackageUid( 15191 mIntentFilterVerifierComponent.getPackageName(), 15192 MATCH_DEBUG_TRIAGED_MISSING, 15193 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15194 15195 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15196 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15197 mHandler.sendMessage(msg); 15198 15199 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15200 for (int i = 0; i < childCount; i++) { 15201 PackageParser.Package childPkg = pkg.childPackages.get(i); 15202 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15203 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15204 mHandler.sendMessage(msg); 15205 } 15206 } 15207 15208 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15209 PackageParser.Package pkg) { 15210 int size = pkg.activities.size(); 15211 if (size == 0) { 15212 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15213 "No activity, so no need to verify any IntentFilter!"); 15214 return; 15215 } 15216 15217 final boolean hasDomainURLs = hasDomainURLs(pkg); 15218 if (!hasDomainURLs) { 15219 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15220 "No domain URLs, so no need to verify any IntentFilter!"); 15221 return; 15222 } 15223 15224 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15225 + " if any IntentFilter from the " + size 15226 + " Activities needs verification ..."); 15227 15228 int count = 0; 15229 final String packageName = pkg.packageName; 15230 15231 synchronized (mPackages) { 15232 // If this is a new install and we see that we've already run verification for this 15233 // package, we have nothing to do: it means the state was restored from backup. 15234 if (!replacing) { 15235 IntentFilterVerificationInfo ivi = 15236 mSettings.getIntentFilterVerificationLPr(packageName); 15237 if (ivi != null) { 15238 if (DEBUG_DOMAIN_VERIFICATION) { 15239 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15240 + ivi.getStatusString()); 15241 } 15242 return; 15243 } 15244 } 15245 15246 // If any filters need to be verified, then all need to be. 15247 boolean needToVerify = false; 15248 for (PackageParser.Activity a : pkg.activities) { 15249 for (ActivityIntentInfo filter : a.intents) { 15250 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15251 if (DEBUG_DOMAIN_VERIFICATION) { 15252 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15253 } 15254 needToVerify = true; 15255 break; 15256 } 15257 } 15258 } 15259 15260 if (needToVerify) { 15261 final int verificationId = mIntentFilterVerificationToken++; 15262 for (PackageParser.Activity a : pkg.activities) { 15263 for (ActivityIntentInfo filter : a.intents) { 15264 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15265 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15266 "Verification needed for IntentFilter:" + filter.toString()); 15267 mIntentFilterVerifier.addOneIntentFilterVerification( 15268 verifierUid, userId, verificationId, filter, packageName); 15269 count++; 15270 } 15271 } 15272 } 15273 } 15274 } 15275 15276 if (count > 0) { 15277 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15278 + " IntentFilter verification" + (count > 1 ? "s" : "") 15279 + " for userId:" + userId); 15280 mIntentFilterVerifier.startVerifications(userId); 15281 } else { 15282 if (DEBUG_DOMAIN_VERIFICATION) { 15283 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15284 } 15285 } 15286 } 15287 15288 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15289 final ComponentName cn = filter.activity.getComponentName(); 15290 final String packageName = cn.getPackageName(); 15291 15292 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15293 packageName); 15294 if (ivi == null) { 15295 return true; 15296 } 15297 int status = ivi.getStatus(); 15298 switch (status) { 15299 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15300 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15301 return true; 15302 15303 default: 15304 // Nothing to do 15305 return false; 15306 } 15307 } 15308 15309 private static boolean isMultiArch(ApplicationInfo info) { 15310 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15311 } 15312 15313 private static boolean isExternal(PackageParser.Package pkg) { 15314 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15315 } 15316 15317 private static boolean isExternal(PackageSetting ps) { 15318 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15319 } 15320 15321 private static boolean isEphemeral(PackageParser.Package pkg) { 15322 return pkg.applicationInfo.isEphemeralApp(); 15323 } 15324 15325 private static boolean isEphemeral(PackageSetting ps) { 15326 return ps.pkg != null && isEphemeral(ps.pkg); 15327 } 15328 15329 private static boolean isSystemApp(PackageParser.Package pkg) { 15330 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15331 } 15332 15333 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15334 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15335 } 15336 15337 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15338 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15339 } 15340 15341 private static boolean isSystemApp(PackageSetting ps) { 15342 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15343 } 15344 15345 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15346 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15347 } 15348 15349 private int packageFlagsToInstallFlags(PackageSetting ps) { 15350 int installFlags = 0; 15351 if (isEphemeral(ps)) { 15352 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15353 } 15354 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15355 // This existing package was an external ASEC install when we have 15356 // the external flag without a UUID 15357 installFlags |= PackageManager.INSTALL_EXTERNAL; 15358 } 15359 if (ps.isForwardLocked()) { 15360 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15361 } 15362 return installFlags; 15363 } 15364 15365 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15366 if (isExternal(pkg)) { 15367 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15368 return StorageManager.UUID_PRIMARY_PHYSICAL; 15369 } else { 15370 return pkg.volumeUuid; 15371 } 15372 } else { 15373 return StorageManager.UUID_PRIVATE_INTERNAL; 15374 } 15375 } 15376 15377 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15378 if (isExternal(pkg)) { 15379 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15380 return mSettings.getExternalVersion(); 15381 } else { 15382 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15383 } 15384 } else { 15385 return mSettings.getInternalVersion(); 15386 } 15387 } 15388 15389 private void deleteTempPackageFiles() { 15390 final FilenameFilter filter = new FilenameFilter() { 15391 public boolean accept(File dir, String name) { 15392 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15393 } 15394 }; 15395 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15396 file.delete(); 15397 } 15398 } 15399 15400 @Override 15401 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15402 int flags) { 15403 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15404 flags); 15405 } 15406 15407 @Override 15408 public void deletePackage(final String packageName, 15409 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15410 mContext.enforceCallingOrSelfPermission( 15411 android.Manifest.permission.DELETE_PACKAGES, null); 15412 Preconditions.checkNotNull(packageName); 15413 Preconditions.checkNotNull(observer); 15414 final int uid = Binder.getCallingUid(); 15415 if (!isOrphaned(packageName) 15416 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15417 try { 15418 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15419 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15420 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15421 observer.onUserActionRequired(intent); 15422 } catch (RemoteException re) { 15423 } 15424 return; 15425 } 15426 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15427 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15428 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15429 mContext.enforceCallingOrSelfPermission( 15430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15431 "deletePackage for user " + userId); 15432 } 15433 15434 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15435 try { 15436 observer.onPackageDeleted(packageName, 15437 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15438 } catch (RemoteException re) { 15439 } 15440 return; 15441 } 15442 15443 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15444 try { 15445 observer.onPackageDeleted(packageName, 15446 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15447 } catch (RemoteException re) { 15448 } 15449 return; 15450 } 15451 15452 if (DEBUG_REMOVE) { 15453 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15454 + " deleteAllUsers: " + deleteAllUsers ); 15455 } 15456 // Queue up an async operation since the package deletion may take a little while. 15457 mHandler.post(new Runnable() { 15458 public void run() { 15459 mHandler.removeCallbacks(this); 15460 int returnCode; 15461 if (!deleteAllUsers) { 15462 returnCode = deletePackageX(packageName, userId, deleteFlags); 15463 } else { 15464 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15465 // If nobody is blocking uninstall, proceed with delete for all users 15466 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15467 returnCode = deletePackageX(packageName, userId, deleteFlags); 15468 } else { 15469 // Otherwise uninstall individually for users with blockUninstalls=false 15470 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15471 for (int userId : users) { 15472 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15473 returnCode = deletePackageX(packageName, userId, userFlags); 15474 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15475 Slog.w(TAG, "Package delete failed for user " + userId 15476 + ", returnCode " + returnCode); 15477 } 15478 } 15479 } 15480 // The app has only been marked uninstalled for certain users. 15481 // We still need to report that delete was blocked 15482 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15483 } 15484 } 15485 try { 15486 observer.onPackageDeleted(packageName, returnCode, null); 15487 } catch (RemoteException e) { 15488 Log.i(TAG, "Observer no longer exists."); 15489 } //end catch 15490 } //end run 15491 }); 15492 } 15493 15494 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15495 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15496 || callingUid == Process.SYSTEM_UID) { 15497 return true; 15498 } 15499 final int callingUserId = UserHandle.getUserId(callingUid); 15500 // If the caller installed the pkgName, then allow it to silently uninstall. 15501 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15502 return true; 15503 } 15504 15505 // Allow package verifier to silently uninstall. 15506 if (mRequiredVerifierPackage != null && 15507 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15508 return true; 15509 } 15510 15511 // Allow package uninstaller to silently uninstall. 15512 if (mRequiredUninstallerPackage != null && 15513 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15514 return true; 15515 } 15516 return false; 15517 } 15518 15519 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15520 int[] result = EMPTY_INT_ARRAY; 15521 for (int userId : userIds) { 15522 if (getBlockUninstallForUser(packageName, userId)) { 15523 result = ArrayUtils.appendInt(result, userId); 15524 } 15525 } 15526 return result; 15527 } 15528 15529 @Override 15530 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15531 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15532 } 15533 15534 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15535 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15536 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15537 try { 15538 if (dpm != null) { 15539 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15540 /* callingUserOnly =*/ false); 15541 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15542 : deviceOwnerComponentName.getPackageName(); 15543 // Does the package contains the device owner? 15544 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15545 // this check is probably not needed, since DO should be registered as a device 15546 // admin on some user too. (Original bug for this: b/17657954) 15547 if (packageName.equals(deviceOwnerPackageName)) { 15548 return true; 15549 } 15550 // Does it contain a device admin for any user? 15551 int[] users; 15552 if (userId == UserHandle.USER_ALL) { 15553 users = sUserManager.getUserIds(); 15554 } else { 15555 users = new int[]{userId}; 15556 } 15557 for (int i = 0; i < users.length; ++i) { 15558 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15559 return true; 15560 } 15561 } 15562 } 15563 } catch (RemoteException e) { 15564 } 15565 return false; 15566 } 15567 15568 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15569 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15570 } 15571 15572 /** 15573 * This method is an internal method that could be get invoked either 15574 * to delete an installed package or to clean up a failed installation. 15575 * After deleting an installed package, a broadcast is sent to notify any 15576 * listeners that the package has been removed. For cleaning up a failed 15577 * installation, the broadcast is not necessary since the package's 15578 * installation wouldn't have sent the initial broadcast either 15579 * The key steps in deleting a package are 15580 * deleting the package information in internal structures like mPackages, 15581 * deleting the packages base directories through installd 15582 * updating mSettings to reflect current status 15583 * persisting settings for later use 15584 * sending a broadcast if necessary 15585 */ 15586 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15587 final PackageRemovedInfo info = new PackageRemovedInfo(); 15588 final boolean res; 15589 15590 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15591 ? UserHandle.USER_ALL : userId; 15592 15593 if (isPackageDeviceAdmin(packageName, removeUser)) { 15594 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15595 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15596 } 15597 15598 PackageSetting uninstalledPs = null; 15599 15600 // for the uninstall-updates case and restricted profiles, remember the per- 15601 // user handle installed state 15602 int[] allUsers; 15603 synchronized (mPackages) { 15604 uninstalledPs = mSettings.mPackages.get(packageName); 15605 if (uninstalledPs == null) { 15606 Slog.w(TAG, "Not removing non-existent package " + packageName); 15607 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15608 } 15609 allUsers = sUserManager.getUserIds(); 15610 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15611 } 15612 15613 final int freezeUser; 15614 if (isUpdatedSystemApp(uninstalledPs) 15615 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15616 // We're downgrading a system app, which will apply to all users, so 15617 // freeze them all during the downgrade 15618 freezeUser = UserHandle.USER_ALL; 15619 } else { 15620 freezeUser = removeUser; 15621 } 15622 15623 synchronized (mInstallLock) { 15624 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15625 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15626 deleteFlags, "deletePackageX")) { 15627 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15628 deleteFlags | REMOVE_CHATTY, info, true, null); 15629 } 15630 synchronized (mPackages) { 15631 if (res) { 15632 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15633 } 15634 } 15635 } 15636 15637 if (res) { 15638 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15639 info.sendPackageRemovedBroadcasts(killApp); 15640 info.sendSystemPackageUpdatedBroadcasts(); 15641 info.sendSystemPackageAppearedBroadcasts(); 15642 } 15643 // Force a gc here. 15644 Runtime.getRuntime().gc(); 15645 // Delete the resources here after sending the broadcast to let 15646 // other processes clean up before deleting resources. 15647 if (info.args != null) { 15648 synchronized (mInstallLock) { 15649 info.args.doPostDeleteLI(true); 15650 } 15651 } 15652 15653 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15654 } 15655 15656 class PackageRemovedInfo { 15657 String removedPackage; 15658 int uid = -1; 15659 int removedAppId = -1; 15660 int[] origUsers; 15661 int[] removedUsers = null; 15662 boolean isRemovedPackageSystemUpdate = false; 15663 boolean isUpdate; 15664 boolean dataRemoved; 15665 boolean removedForAllUsers; 15666 // Clean up resources deleted packages. 15667 InstallArgs args = null; 15668 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15669 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15670 15671 void sendPackageRemovedBroadcasts(boolean killApp) { 15672 sendPackageRemovedBroadcastInternal(killApp); 15673 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15674 for (int i = 0; i < childCount; i++) { 15675 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15676 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15677 } 15678 } 15679 15680 void sendSystemPackageUpdatedBroadcasts() { 15681 if (isRemovedPackageSystemUpdate) { 15682 sendSystemPackageUpdatedBroadcastsInternal(); 15683 final int childCount = (removedChildPackages != null) 15684 ? removedChildPackages.size() : 0; 15685 for (int i = 0; i < childCount; i++) { 15686 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15687 if (childInfo.isRemovedPackageSystemUpdate) { 15688 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15689 } 15690 } 15691 } 15692 } 15693 15694 void sendSystemPackageAppearedBroadcasts() { 15695 final int packageCount = (appearedChildPackages != null) 15696 ? appearedChildPackages.size() : 0; 15697 for (int i = 0; i < packageCount; i++) { 15698 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15699 for (int userId : installedInfo.newUsers) { 15700 sendPackageAddedForUser(installedInfo.name, true, 15701 UserHandle.getAppId(installedInfo.uid), userId); 15702 } 15703 } 15704 } 15705 15706 private void sendSystemPackageUpdatedBroadcastsInternal() { 15707 Bundle extras = new Bundle(2); 15708 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15709 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15710 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15711 extras, 0, null, null, null); 15712 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15713 extras, 0, null, null, null); 15714 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15715 null, 0, removedPackage, null, null); 15716 } 15717 15718 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15719 Bundle extras = new Bundle(2); 15720 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15721 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15722 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15723 if (isUpdate || isRemovedPackageSystemUpdate) { 15724 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15725 } 15726 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15727 if (removedPackage != null) { 15728 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15729 extras, 0, null, null, removedUsers); 15730 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15731 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15732 removedPackage, extras, 0, null, null, removedUsers); 15733 } 15734 } 15735 if (removedAppId >= 0) { 15736 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15737 removedUsers); 15738 } 15739 } 15740 } 15741 15742 /* 15743 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15744 * flag is not set, the data directory is removed as well. 15745 * make sure this flag is set for partially installed apps. If not its meaningless to 15746 * delete a partially installed application. 15747 */ 15748 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15749 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15750 String packageName = ps.name; 15751 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15752 // Retrieve object to delete permissions for shared user later on 15753 final PackageParser.Package deletedPkg; 15754 final PackageSetting deletedPs; 15755 // reader 15756 synchronized (mPackages) { 15757 deletedPkg = mPackages.get(packageName); 15758 deletedPs = mSettings.mPackages.get(packageName); 15759 if (outInfo != null) { 15760 outInfo.removedPackage = packageName; 15761 outInfo.removedUsers = deletedPs != null 15762 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15763 : null; 15764 } 15765 } 15766 15767 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15768 15769 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15770 final PackageParser.Package resolvedPkg; 15771 if (deletedPkg != null) { 15772 resolvedPkg = deletedPkg; 15773 } else { 15774 // We don't have a parsed package when it lives on an ejected 15775 // adopted storage device, so fake something together 15776 resolvedPkg = new PackageParser.Package(ps.name); 15777 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15778 } 15779 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15780 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15781 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15782 if (outInfo != null) { 15783 outInfo.dataRemoved = true; 15784 } 15785 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15786 } 15787 15788 // writer 15789 synchronized (mPackages) { 15790 if (deletedPs != null) { 15791 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15792 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15793 clearDefaultBrowserIfNeeded(packageName); 15794 if (outInfo != null) { 15795 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15796 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15797 } 15798 updatePermissionsLPw(deletedPs.name, null, 0); 15799 if (deletedPs.sharedUser != null) { 15800 // Remove permissions associated with package. Since runtime 15801 // permissions are per user we have to kill the removed package 15802 // or packages running under the shared user of the removed 15803 // package if revoking the permissions requested only by the removed 15804 // package is successful and this causes a change in gids. 15805 for (int userId : UserManagerService.getInstance().getUserIds()) { 15806 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15807 userId); 15808 if (userIdToKill == UserHandle.USER_ALL 15809 || userIdToKill >= UserHandle.USER_SYSTEM) { 15810 // If gids changed for this user, kill all affected packages. 15811 mHandler.post(new Runnable() { 15812 @Override 15813 public void run() { 15814 // This has to happen with no lock held. 15815 killApplication(deletedPs.name, deletedPs.appId, 15816 KILL_APP_REASON_GIDS_CHANGED); 15817 } 15818 }); 15819 break; 15820 } 15821 } 15822 } 15823 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15824 } 15825 // make sure to preserve per-user disabled state if this removal was just 15826 // a downgrade of a system app to the factory package 15827 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15828 if (DEBUG_REMOVE) { 15829 Slog.d(TAG, "Propagating install state across downgrade"); 15830 } 15831 for (int userId : allUserHandles) { 15832 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15833 if (DEBUG_REMOVE) { 15834 Slog.d(TAG, " user " + userId + " => " + installed); 15835 } 15836 ps.setInstalled(installed, userId); 15837 } 15838 } 15839 } 15840 // can downgrade to reader 15841 if (writeSettings) { 15842 // Save settings now 15843 mSettings.writeLPr(); 15844 } 15845 } 15846 if (outInfo != null) { 15847 // A user ID was deleted here. Go through all users and remove it 15848 // from KeyStore. 15849 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15850 } 15851 } 15852 15853 static boolean locationIsPrivileged(File path) { 15854 try { 15855 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15856 .getCanonicalPath(); 15857 return path.getCanonicalPath().startsWith(privilegedAppDir); 15858 } catch (IOException e) { 15859 Slog.e(TAG, "Unable to access code path " + path); 15860 } 15861 return false; 15862 } 15863 15864 /* 15865 * Tries to delete system package. 15866 */ 15867 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15868 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15869 boolean writeSettings) { 15870 if (deletedPs.parentPackageName != null) { 15871 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15872 return false; 15873 } 15874 15875 final boolean applyUserRestrictions 15876 = (allUserHandles != null) && (outInfo.origUsers != null); 15877 final PackageSetting disabledPs; 15878 // Confirm if the system package has been updated 15879 // An updated system app can be deleted. This will also have to restore 15880 // the system pkg from system partition 15881 // reader 15882 synchronized (mPackages) { 15883 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15884 } 15885 15886 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15887 + " disabledPs=" + disabledPs); 15888 15889 if (disabledPs == null) { 15890 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15891 return false; 15892 } else if (DEBUG_REMOVE) { 15893 Slog.d(TAG, "Deleting system pkg from data partition"); 15894 } 15895 15896 if (DEBUG_REMOVE) { 15897 if (applyUserRestrictions) { 15898 Slog.d(TAG, "Remembering install states:"); 15899 for (int userId : allUserHandles) { 15900 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15901 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15902 } 15903 } 15904 } 15905 15906 // Delete the updated package 15907 outInfo.isRemovedPackageSystemUpdate = true; 15908 if (outInfo.removedChildPackages != null) { 15909 final int childCount = (deletedPs.childPackageNames != null) 15910 ? deletedPs.childPackageNames.size() : 0; 15911 for (int i = 0; i < childCount; i++) { 15912 String childPackageName = deletedPs.childPackageNames.get(i); 15913 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15914 .contains(childPackageName)) { 15915 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15916 childPackageName); 15917 if (childInfo != null) { 15918 childInfo.isRemovedPackageSystemUpdate = true; 15919 } 15920 } 15921 } 15922 } 15923 15924 if (disabledPs.versionCode < deletedPs.versionCode) { 15925 // Delete data for downgrades 15926 flags &= ~PackageManager.DELETE_KEEP_DATA; 15927 } else { 15928 // Preserve data by setting flag 15929 flags |= PackageManager.DELETE_KEEP_DATA; 15930 } 15931 15932 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15933 outInfo, writeSettings, disabledPs.pkg); 15934 if (!ret) { 15935 return false; 15936 } 15937 15938 // writer 15939 synchronized (mPackages) { 15940 // Reinstate the old system package 15941 enableSystemPackageLPw(disabledPs.pkg); 15942 // Remove any native libraries from the upgraded package. 15943 removeNativeBinariesLI(deletedPs); 15944 } 15945 15946 // Install the system package 15947 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15948 int parseFlags = mDefParseFlags 15949 | PackageParser.PARSE_MUST_BE_APK 15950 | PackageParser.PARSE_IS_SYSTEM 15951 | PackageParser.PARSE_IS_SYSTEM_DIR; 15952 if (locationIsPrivileged(disabledPs.codePath)) { 15953 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15954 } 15955 15956 final PackageParser.Package newPkg; 15957 try { 15958 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15959 } catch (PackageManagerException e) { 15960 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15961 + e.getMessage()); 15962 return false; 15963 } 15964 try { 15965 // update shared libraries for the newly re-installed system package 15966 updateSharedLibrariesLPw(newPkg, null); 15967 } catch (PackageManagerException e) { 15968 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 15969 } 15970 15971 prepareAppDataAfterInstallLIF(newPkg); 15972 15973 // writer 15974 synchronized (mPackages) { 15975 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15976 15977 // Propagate the permissions state as we do not want to drop on the floor 15978 // runtime permissions. The update permissions method below will take 15979 // care of removing obsolete permissions and grant install permissions. 15980 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15981 updatePermissionsLPw(newPkg.packageName, newPkg, 15982 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15983 15984 if (applyUserRestrictions) { 15985 if (DEBUG_REMOVE) { 15986 Slog.d(TAG, "Propagating install state across reinstall"); 15987 } 15988 for (int userId : allUserHandles) { 15989 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15990 if (DEBUG_REMOVE) { 15991 Slog.d(TAG, " user " + userId + " => " + installed); 15992 } 15993 ps.setInstalled(installed, userId); 15994 15995 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15996 } 15997 // Regardless of writeSettings we need to ensure that this restriction 15998 // state propagation is persisted 15999 mSettings.writeAllUsersPackageRestrictionsLPr(); 16000 } 16001 // can downgrade to reader here 16002 if (writeSettings) { 16003 mSettings.writeLPr(); 16004 } 16005 } 16006 return true; 16007 } 16008 16009 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16010 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16011 PackageRemovedInfo outInfo, boolean writeSettings, 16012 PackageParser.Package replacingPackage) { 16013 synchronized (mPackages) { 16014 if (outInfo != null) { 16015 outInfo.uid = ps.appId; 16016 } 16017 16018 if (outInfo != null && outInfo.removedChildPackages != null) { 16019 final int childCount = (ps.childPackageNames != null) 16020 ? ps.childPackageNames.size() : 0; 16021 for (int i = 0; i < childCount; i++) { 16022 String childPackageName = ps.childPackageNames.get(i); 16023 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16024 if (childPs == null) { 16025 return false; 16026 } 16027 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16028 childPackageName); 16029 if (childInfo != null) { 16030 childInfo.uid = childPs.appId; 16031 } 16032 } 16033 } 16034 } 16035 16036 // Delete package data from internal structures and also remove data if flag is set 16037 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16038 16039 // Delete the child packages data 16040 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16041 for (int i = 0; i < childCount; i++) { 16042 PackageSetting childPs; 16043 synchronized (mPackages) { 16044 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16045 } 16046 if (childPs != null) { 16047 PackageRemovedInfo childOutInfo = (outInfo != null 16048 && outInfo.removedChildPackages != null) 16049 ? outInfo.removedChildPackages.get(childPs.name) : null; 16050 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16051 && (replacingPackage != null 16052 && !replacingPackage.hasChildPackage(childPs.name)) 16053 ? flags & ~DELETE_KEEP_DATA : flags; 16054 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16055 deleteFlags, writeSettings); 16056 } 16057 } 16058 16059 // Delete application code and resources only for parent packages 16060 if (ps.parentPackageName == null) { 16061 if (deleteCodeAndResources && (outInfo != null)) { 16062 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16063 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16064 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16065 } 16066 } 16067 16068 return true; 16069 } 16070 16071 @Override 16072 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16073 int userId) { 16074 mContext.enforceCallingOrSelfPermission( 16075 android.Manifest.permission.DELETE_PACKAGES, null); 16076 synchronized (mPackages) { 16077 PackageSetting ps = mSettings.mPackages.get(packageName); 16078 if (ps == null) { 16079 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16080 return false; 16081 } 16082 if (!ps.getInstalled(userId)) { 16083 // Can't block uninstall for an app that is not installed or enabled. 16084 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16085 return false; 16086 } 16087 ps.setBlockUninstall(blockUninstall, userId); 16088 mSettings.writePackageRestrictionsLPr(userId); 16089 } 16090 return true; 16091 } 16092 16093 @Override 16094 public boolean getBlockUninstallForUser(String packageName, int userId) { 16095 synchronized (mPackages) { 16096 PackageSetting ps = mSettings.mPackages.get(packageName); 16097 if (ps == null) { 16098 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16099 return false; 16100 } 16101 return ps.getBlockUninstall(userId); 16102 } 16103 } 16104 16105 @Override 16106 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16107 int callingUid = Binder.getCallingUid(); 16108 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16109 throw new SecurityException( 16110 "setRequiredForSystemUser can only be run by the system or root"); 16111 } 16112 synchronized (mPackages) { 16113 PackageSetting ps = mSettings.mPackages.get(packageName); 16114 if (ps == null) { 16115 Log.w(TAG, "Package doesn't exist: " + packageName); 16116 return false; 16117 } 16118 if (systemUserApp) { 16119 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16120 } else { 16121 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16122 } 16123 mSettings.writeLPr(); 16124 } 16125 return true; 16126 } 16127 16128 /* 16129 * This method handles package deletion in general 16130 */ 16131 private boolean deletePackageLIF(String packageName, UserHandle user, 16132 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16133 PackageRemovedInfo outInfo, boolean writeSettings, 16134 PackageParser.Package replacingPackage) { 16135 if (packageName == null) { 16136 Slog.w(TAG, "Attempt to delete null packageName."); 16137 return false; 16138 } 16139 16140 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16141 16142 PackageSetting ps; 16143 16144 synchronized (mPackages) { 16145 ps = mSettings.mPackages.get(packageName); 16146 if (ps == null) { 16147 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16148 return false; 16149 } 16150 16151 if (ps.parentPackageName != null && (!isSystemApp(ps) 16152 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16153 if (DEBUG_REMOVE) { 16154 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16155 + ((user == null) ? UserHandle.USER_ALL : user)); 16156 } 16157 final int removedUserId = (user != null) ? user.getIdentifier() 16158 : UserHandle.USER_ALL; 16159 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16160 return false; 16161 } 16162 markPackageUninstalledForUserLPw(ps, user); 16163 scheduleWritePackageRestrictionsLocked(user); 16164 return true; 16165 } 16166 } 16167 16168 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16169 && user.getIdentifier() != UserHandle.USER_ALL)) { 16170 // The caller is asking that the package only be deleted for a single 16171 // user. To do this, we just mark its uninstalled state and delete 16172 // its data. If this is a system app, we only allow this to happen if 16173 // they have set the special DELETE_SYSTEM_APP which requests different 16174 // semantics than normal for uninstalling system apps. 16175 markPackageUninstalledForUserLPw(ps, user); 16176 16177 if (!isSystemApp(ps)) { 16178 // Do not uninstall the APK if an app should be cached 16179 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16180 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16181 // Other user still have this package installed, so all 16182 // we need to do is clear this user's data and save that 16183 // it is uninstalled. 16184 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16185 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16186 return false; 16187 } 16188 scheduleWritePackageRestrictionsLocked(user); 16189 return true; 16190 } else { 16191 // We need to set it back to 'installed' so the uninstall 16192 // broadcasts will be sent correctly. 16193 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16194 ps.setInstalled(true, user.getIdentifier()); 16195 } 16196 } else { 16197 // This is a system app, so we assume that the 16198 // other users still have this package installed, so all 16199 // we need to do is clear this user's data and save that 16200 // it is uninstalled. 16201 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16202 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16203 return false; 16204 } 16205 scheduleWritePackageRestrictionsLocked(user); 16206 return true; 16207 } 16208 } 16209 16210 // If we are deleting a composite package for all users, keep track 16211 // of result for each child. 16212 if (ps.childPackageNames != null && outInfo != null) { 16213 synchronized (mPackages) { 16214 final int childCount = ps.childPackageNames.size(); 16215 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16216 for (int i = 0; i < childCount; i++) { 16217 String childPackageName = ps.childPackageNames.get(i); 16218 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16219 childInfo.removedPackage = childPackageName; 16220 outInfo.removedChildPackages.put(childPackageName, childInfo); 16221 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16222 if (childPs != null) { 16223 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16224 } 16225 } 16226 } 16227 } 16228 16229 boolean ret = false; 16230 if (isSystemApp(ps)) { 16231 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16232 // When an updated system application is deleted we delete the existing resources 16233 // as well and fall back to existing code in system partition 16234 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16235 } else { 16236 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16237 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16238 outInfo, writeSettings, replacingPackage); 16239 } 16240 16241 // Take a note whether we deleted the package for all users 16242 if (outInfo != null) { 16243 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16244 if (outInfo.removedChildPackages != null) { 16245 synchronized (mPackages) { 16246 final int childCount = outInfo.removedChildPackages.size(); 16247 for (int i = 0; i < childCount; i++) { 16248 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16249 if (childInfo != null) { 16250 childInfo.removedForAllUsers = mPackages.get( 16251 childInfo.removedPackage) == null; 16252 } 16253 } 16254 } 16255 } 16256 // If we uninstalled an update to a system app there may be some 16257 // child packages that appeared as they are declared in the system 16258 // app but were not declared in the update. 16259 if (isSystemApp(ps)) { 16260 synchronized (mPackages) { 16261 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16262 final int childCount = (updatedPs.childPackageNames != null) 16263 ? updatedPs.childPackageNames.size() : 0; 16264 for (int i = 0; i < childCount; i++) { 16265 String childPackageName = updatedPs.childPackageNames.get(i); 16266 if (outInfo.removedChildPackages == null 16267 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16268 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16269 if (childPs == null) { 16270 continue; 16271 } 16272 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16273 installRes.name = childPackageName; 16274 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16275 installRes.pkg = mPackages.get(childPackageName); 16276 installRes.uid = childPs.pkg.applicationInfo.uid; 16277 if (outInfo.appearedChildPackages == null) { 16278 outInfo.appearedChildPackages = new ArrayMap<>(); 16279 } 16280 outInfo.appearedChildPackages.put(childPackageName, installRes); 16281 } 16282 } 16283 } 16284 } 16285 } 16286 16287 return ret; 16288 } 16289 16290 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16291 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16292 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16293 for (int nextUserId : userIds) { 16294 if (DEBUG_REMOVE) { 16295 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16296 } 16297 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16298 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16299 false /*hidden*/, false /*suspended*/, null, null, null, 16300 false /*blockUninstall*/, 16301 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16302 } 16303 } 16304 16305 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16306 PackageRemovedInfo outInfo) { 16307 final PackageParser.Package pkg; 16308 synchronized (mPackages) { 16309 pkg = mPackages.get(ps.name); 16310 } 16311 16312 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16313 : new int[] {userId}; 16314 for (int nextUserId : userIds) { 16315 if (DEBUG_REMOVE) { 16316 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16317 + nextUserId); 16318 } 16319 16320 destroyAppDataLIF(pkg, userId, 16321 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16322 destroyAppProfilesLIF(pkg, userId); 16323 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16324 schedulePackageCleaning(ps.name, nextUserId, false); 16325 synchronized (mPackages) { 16326 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16327 scheduleWritePackageRestrictionsLocked(nextUserId); 16328 } 16329 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16330 } 16331 } 16332 16333 if (outInfo != null) { 16334 outInfo.removedPackage = ps.name; 16335 outInfo.removedAppId = ps.appId; 16336 outInfo.removedUsers = userIds; 16337 } 16338 16339 return true; 16340 } 16341 16342 private final class ClearStorageConnection implements ServiceConnection { 16343 IMediaContainerService mContainerService; 16344 16345 @Override 16346 public void onServiceConnected(ComponentName name, IBinder service) { 16347 synchronized (this) { 16348 mContainerService = IMediaContainerService.Stub.asInterface(service); 16349 notifyAll(); 16350 } 16351 } 16352 16353 @Override 16354 public void onServiceDisconnected(ComponentName name) { 16355 } 16356 } 16357 16358 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16359 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16360 16361 final boolean mounted; 16362 if (Environment.isExternalStorageEmulated()) { 16363 mounted = true; 16364 } else { 16365 final String status = Environment.getExternalStorageState(); 16366 16367 mounted = status.equals(Environment.MEDIA_MOUNTED) 16368 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16369 } 16370 16371 if (!mounted) { 16372 return; 16373 } 16374 16375 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16376 int[] users; 16377 if (userId == UserHandle.USER_ALL) { 16378 users = sUserManager.getUserIds(); 16379 } else { 16380 users = new int[] { userId }; 16381 } 16382 final ClearStorageConnection conn = new ClearStorageConnection(); 16383 if (mContext.bindServiceAsUser( 16384 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16385 try { 16386 for (int curUser : users) { 16387 long timeout = SystemClock.uptimeMillis() + 5000; 16388 synchronized (conn) { 16389 long now; 16390 while (conn.mContainerService == null && 16391 (now = SystemClock.uptimeMillis()) < timeout) { 16392 try { 16393 conn.wait(timeout - now); 16394 } catch (InterruptedException e) { 16395 } 16396 } 16397 } 16398 if (conn.mContainerService == null) { 16399 return; 16400 } 16401 16402 final UserEnvironment userEnv = new UserEnvironment(curUser); 16403 clearDirectory(conn.mContainerService, 16404 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16405 if (allData) { 16406 clearDirectory(conn.mContainerService, 16407 userEnv.buildExternalStorageAppDataDirs(packageName)); 16408 clearDirectory(conn.mContainerService, 16409 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16410 } 16411 } 16412 } finally { 16413 mContext.unbindService(conn); 16414 } 16415 } 16416 } 16417 16418 @Override 16419 public void clearApplicationProfileData(String packageName) { 16420 enforceSystemOrRoot("Only the system can clear all profile data"); 16421 16422 final PackageParser.Package pkg; 16423 synchronized (mPackages) { 16424 pkg = mPackages.get(packageName); 16425 } 16426 16427 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16428 synchronized (mInstallLock) { 16429 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16430 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16431 true /* removeBaseMarker */); 16432 } 16433 } 16434 } 16435 16436 @Override 16437 public void clearApplicationUserData(final String packageName, 16438 final IPackageDataObserver observer, final int userId) { 16439 mContext.enforceCallingOrSelfPermission( 16440 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16441 16442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16443 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16444 16445 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16446 throw new SecurityException("Cannot clear data for a protected package: " 16447 + packageName); 16448 } 16449 // Queue up an async operation since the package deletion may take a little while. 16450 mHandler.post(new Runnable() { 16451 public void run() { 16452 mHandler.removeCallbacks(this); 16453 final boolean succeeded; 16454 try (PackageFreezer freezer = freezePackage(packageName, 16455 "clearApplicationUserData")) { 16456 synchronized (mInstallLock) { 16457 succeeded = clearApplicationUserDataLIF(packageName, userId); 16458 } 16459 clearExternalStorageDataSync(packageName, userId, true); 16460 } 16461 if (succeeded) { 16462 // invoke DeviceStorageMonitor's update method to clear any notifications 16463 DeviceStorageMonitorInternal dsm = LocalServices 16464 .getService(DeviceStorageMonitorInternal.class); 16465 if (dsm != null) { 16466 dsm.checkMemory(); 16467 } 16468 } 16469 if(observer != null) { 16470 try { 16471 observer.onRemoveCompleted(packageName, succeeded); 16472 } catch (RemoteException e) { 16473 Log.i(TAG, "Observer no longer exists."); 16474 } 16475 } //end if observer 16476 } //end run 16477 }); 16478 } 16479 16480 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16481 if (packageName == null) { 16482 Slog.w(TAG, "Attempt to delete null packageName."); 16483 return false; 16484 } 16485 16486 // Try finding details about the requested package 16487 PackageParser.Package pkg; 16488 synchronized (mPackages) { 16489 pkg = mPackages.get(packageName); 16490 if (pkg == null) { 16491 final PackageSetting ps = mSettings.mPackages.get(packageName); 16492 if (ps != null) { 16493 pkg = ps.pkg; 16494 } 16495 } 16496 16497 if (pkg == null) { 16498 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16499 return false; 16500 } 16501 16502 PackageSetting ps = (PackageSetting) pkg.mExtras; 16503 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16504 } 16505 16506 clearAppDataLIF(pkg, userId, 16507 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16508 16509 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16510 removeKeystoreDataIfNeeded(userId, appId); 16511 16512 UserManagerInternal umInternal = getUserManagerInternal(); 16513 final int flags; 16514 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16515 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16516 } else if (umInternal.isUserRunning(userId)) { 16517 flags = StorageManager.FLAG_STORAGE_DE; 16518 } else { 16519 flags = 0; 16520 } 16521 prepareAppDataContentsLIF(pkg, userId, flags); 16522 16523 return true; 16524 } 16525 16526 /** 16527 * Reverts user permission state changes (permissions and flags) in 16528 * all packages for a given user. 16529 * 16530 * @param userId The device user for which to do a reset. 16531 */ 16532 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16533 final int packageCount = mPackages.size(); 16534 for (int i = 0; i < packageCount; i++) { 16535 PackageParser.Package pkg = mPackages.valueAt(i); 16536 PackageSetting ps = (PackageSetting) pkg.mExtras; 16537 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16538 } 16539 } 16540 16541 private void resetNetworkPolicies(int userId) { 16542 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16543 } 16544 16545 /** 16546 * Reverts user permission state changes (permissions and flags). 16547 * 16548 * @param ps The package for which to reset. 16549 * @param userId The device user for which to do a reset. 16550 */ 16551 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16552 final PackageSetting ps, final int userId) { 16553 if (ps.pkg == null) { 16554 return; 16555 } 16556 16557 // These are flags that can change base on user actions. 16558 final int userSettableMask = FLAG_PERMISSION_USER_SET 16559 | FLAG_PERMISSION_USER_FIXED 16560 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16561 | FLAG_PERMISSION_REVIEW_REQUIRED; 16562 16563 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16564 | FLAG_PERMISSION_POLICY_FIXED; 16565 16566 boolean writeInstallPermissions = false; 16567 boolean writeRuntimePermissions = false; 16568 16569 final int permissionCount = ps.pkg.requestedPermissions.size(); 16570 for (int i = 0; i < permissionCount; i++) { 16571 String permission = ps.pkg.requestedPermissions.get(i); 16572 16573 BasePermission bp = mSettings.mPermissions.get(permission); 16574 if (bp == null) { 16575 continue; 16576 } 16577 16578 // If shared user we just reset the state to which only this app contributed. 16579 if (ps.sharedUser != null) { 16580 boolean used = false; 16581 final int packageCount = ps.sharedUser.packages.size(); 16582 for (int j = 0; j < packageCount; j++) { 16583 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16584 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16585 && pkg.pkg.requestedPermissions.contains(permission)) { 16586 used = true; 16587 break; 16588 } 16589 } 16590 if (used) { 16591 continue; 16592 } 16593 } 16594 16595 PermissionsState permissionsState = ps.getPermissionsState(); 16596 16597 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16598 16599 // Always clear the user settable flags. 16600 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16601 bp.name) != null; 16602 // If permission review is enabled and this is a legacy app, mark the 16603 // permission as requiring a review as this is the initial state. 16604 int flags = 0; 16605 if (Build.PERMISSIONS_REVIEW_REQUIRED 16606 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16607 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16608 } 16609 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16610 if (hasInstallState) { 16611 writeInstallPermissions = true; 16612 } else { 16613 writeRuntimePermissions = true; 16614 } 16615 } 16616 16617 // Below is only runtime permission handling. 16618 if (!bp.isRuntime()) { 16619 continue; 16620 } 16621 16622 // Never clobber system or policy. 16623 if ((oldFlags & policyOrSystemFlags) != 0) { 16624 continue; 16625 } 16626 16627 // If this permission was granted by default, make sure it is. 16628 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16629 if (permissionsState.grantRuntimePermission(bp, userId) 16630 != PERMISSION_OPERATION_FAILURE) { 16631 writeRuntimePermissions = true; 16632 } 16633 // If permission review is enabled the permissions for a legacy apps 16634 // are represented as constantly granted runtime ones, so don't revoke. 16635 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16636 // Otherwise, reset the permission. 16637 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16638 switch (revokeResult) { 16639 case PERMISSION_OPERATION_SUCCESS: 16640 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16641 writeRuntimePermissions = true; 16642 final int appId = ps.appId; 16643 mHandler.post(new Runnable() { 16644 @Override 16645 public void run() { 16646 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16647 } 16648 }); 16649 } break; 16650 } 16651 } 16652 } 16653 16654 // Synchronously write as we are taking permissions away. 16655 if (writeRuntimePermissions) { 16656 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16657 } 16658 16659 // Synchronously write as we are taking permissions away. 16660 if (writeInstallPermissions) { 16661 mSettings.writeLPr(); 16662 } 16663 } 16664 16665 /** 16666 * Remove entries from the keystore daemon. Will only remove it if the 16667 * {@code appId} is valid. 16668 */ 16669 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16670 if (appId < 0) { 16671 return; 16672 } 16673 16674 final KeyStore keyStore = KeyStore.getInstance(); 16675 if (keyStore != null) { 16676 if (userId == UserHandle.USER_ALL) { 16677 for (final int individual : sUserManager.getUserIds()) { 16678 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16679 } 16680 } else { 16681 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16682 } 16683 } else { 16684 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16685 } 16686 } 16687 16688 @Override 16689 public void deleteApplicationCacheFiles(final String packageName, 16690 final IPackageDataObserver observer) { 16691 final int userId = UserHandle.getCallingUserId(); 16692 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16693 } 16694 16695 @Override 16696 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16697 final IPackageDataObserver observer) { 16698 mContext.enforceCallingOrSelfPermission( 16699 android.Manifest.permission.DELETE_CACHE_FILES, null); 16700 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16701 /* requireFullPermission= */ true, /* checkShell= */ false, 16702 "delete application cache files"); 16703 16704 final PackageParser.Package pkg; 16705 synchronized (mPackages) { 16706 pkg = mPackages.get(packageName); 16707 } 16708 16709 // Queue up an async operation since the package deletion may take a little while. 16710 mHandler.post(new Runnable() { 16711 public void run() { 16712 synchronized (mInstallLock) { 16713 final int flags = StorageManager.FLAG_STORAGE_DE 16714 | StorageManager.FLAG_STORAGE_CE; 16715 // We're only clearing cache files, so we don't care if the 16716 // app is unfrozen and still able to run 16717 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16718 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16719 } 16720 clearExternalStorageDataSync(packageName, userId, false); 16721 if (observer != null) { 16722 try { 16723 observer.onRemoveCompleted(packageName, true); 16724 } catch (RemoteException e) { 16725 Log.i(TAG, "Observer no longer exists."); 16726 } 16727 } 16728 } 16729 }); 16730 } 16731 16732 @Override 16733 public void getPackageSizeInfo(final String packageName, int userHandle, 16734 final IPackageStatsObserver observer) { 16735 mContext.enforceCallingOrSelfPermission( 16736 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16737 if (packageName == null) { 16738 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16739 } 16740 16741 PackageStats stats = new PackageStats(packageName, userHandle); 16742 16743 /* 16744 * Queue up an async operation since the package measurement may take a 16745 * little while. 16746 */ 16747 Message msg = mHandler.obtainMessage(INIT_COPY); 16748 msg.obj = new MeasureParams(stats, observer); 16749 mHandler.sendMessage(msg); 16750 } 16751 16752 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16753 final PackageSetting ps; 16754 synchronized (mPackages) { 16755 ps = mSettings.mPackages.get(packageName); 16756 if (ps == null) { 16757 Slog.w(TAG, "Failed to find settings for " + packageName); 16758 return false; 16759 } 16760 } 16761 try { 16762 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16763 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16764 ps.getCeDataInode(userId), ps.codePathString, stats); 16765 } catch (InstallerException e) { 16766 Slog.w(TAG, String.valueOf(e)); 16767 return false; 16768 } 16769 16770 // For now, ignore code size of packages on system partition 16771 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16772 stats.codeSize = 0; 16773 } 16774 16775 return true; 16776 } 16777 16778 private int getUidTargetSdkVersionLockedLPr(int uid) { 16779 Object obj = mSettings.getUserIdLPr(uid); 16780 if (obj instanceof SharedUserSetting) { 16781 final SharedUserSetting sus = (SharedUserSetting) obj; 16782 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16783 final Iterator<PackageSetting> it = sus.packages.iterator(); 16784 while (it.hasNext()) { 16785 final PackageSetting ps = it.next(); 16786 if (ps.pkg != null) { 16787 int v = ps.pkg.applicationInfo.targetSdkVersion; 16788 if (v < vers) vers = v; 16789 } 16790 } 16791 return vers; 16792 } else if (obj instanceof PackageSetting) { 16793 final PackageSetting ps = (PackageSetting) obj; 16794 if (ps.pkg != null) { 16795 return ps.pkg.applicationInfo.targetSdkVersion; 16796 } 16797 } 16798 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16799 } 16800 16801 @Override 16802 public void addPreferredActivity(IntentFilter filter, int match, 16803 ComponentName[] set, ComponentName activity, int userId) { 16804 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16805 "Adding preferred"); 16806 } 16807 16808 private void addPreferredActivityInternal(IntentFilter filter, int match, 16809 ComponentName[] set, ComponentName activity, boolean always, int userId, 16810 String opname) { 16811 // writer 16812 int callingUid = Binder.getCallingUid(); 16813 enforceCrossUserPermission(callingUid, userId, 16814 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16815 if (filter.countActions() == 0) { 16816 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16817 return; 16818 } 16819 synchronized (mPackages) { 16820 if (mContext.checkCallingOrSelfPermission( 16821 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16822 != PackageManager.PERMISSION_GRANTED) { 16823 if (getUidTargetSdkVersionLockedLPr(callingUid) 16824 < Build.VERSION_CODES.FROYO) { 16825 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16826 + callingUid); 16827 return; 16828 } 16829 mContext.enforceCallingOrSelfPermission( 16830 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16831 } 16832 16833 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16834 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16835 + userId + ":"); 16836 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16837 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16838 scheduleWritePackageRestrictionsLocked(userId); 16839 postPreferredActivityChangedBroadcast(userId); 16840 } 16841 } 16842 16843 private void postPreferredActivityChangedBroadcast(int userId) { 16844 mHandler.post(() -> { 16845 final IActivityManager am = ActivityManagerNative.getDefault(); 16846 if (am == null) { 16847 return; 16848 } 16849 16850 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16851 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16852 try { 16853 am.broadcastIntent(null, intent, null, null, 16854 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16855 null, false, false, userId); 16856 } catch (RemoteException e) { 16857 } 16858 }); 16859 } 16860 16861 @Override 16862 public void replacePreferredActivity(IntentFilter filter, int match, 16863 ComponentName[] set, ComponentName activity, int userId) { 16864 if (filter.countActions() != 1) { 16865 throw new IllegalArgumentException( 16866 "replacePreferredActivity expects filter to have only 1 action."); 16867 } 16868 if (filter.countDataAuthorities() != 0 16869 || filter.countDataPaths() != 0 16870 || filter.countDataSchemes() > 1 16871 || filter.countDataTypes() != 0) { 16872 throw new IllegalArgumentException( 16873 "replacePreferredActivity expects filter to have no data authorities, " + 16874 "paths, or types; and at most one scheme."); 16875 } 16876 16877 final int callingUid = Binder.getCallingUid(); 16878 enforceCrossUserPermission(callingUid, userId, 16879 true /* requireFullPermission */, false /* checkShell */, 16880 "replace preferred activity"); 16881 synchronized (mPackages) { 16882 if (mContext.checkCallingOrSelfPermission( 16883 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16884 != PackageManager.PERMISSION_GRANTED) { 16885 if (getUidTargetSdkVersionLockedLPr(callingUid) 16886 < Build.VERSION_CODES.FROYO) { 16887 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16888 + Binder.getCallingUid()); 16889 return; 16890 } 16891 mContext.enforceCallingOrSelfPermission( 16892 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16893 } 16894 16895 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16896 if (pir != null) { 16897 // Get all of the existing entries that exactly match this filter. 16898 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16899 if (existing != null && existing.size() == 1) { 16900 PreferredActivity cur = existing.get(0); 16901 if (DEBUG_PREFERRED) { 16902 Slog.i(TAG, "Checking replace of preferred:"); 16903 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16904 if (!cur.mPref.mAlways) { 16905 Slog.i(TAG, " -- CUR; not mAlways!"); 16906 } else { 16907 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16908 Slog.i(TAG, " -- CUR: mSet=" 16909 + Arrays.toString(cur.mPref.mSetComponents)); 16910 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16911 Slog.i(TAG, " -- NEW: mMatch=" 16912 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16913 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16914 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16915 } 16916 } 16917 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16918 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16919 && cur.mPref.sameSet(set)) { 16920 // Setting the preferred activity to what it happens to be already 16921 if (DEBUG_PREFERRED) { 16922 Slog.i(TAG, "Replacing with same preferred activity " 16923 + cur.mPref.mShortComponent + " for user " 16924 + userId + ":"); 16925 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16926 } 16927 return; 16928 } 16929 } 16930 16931 if (existing != null) { 16932 if (DEBUG_PREFERRED) { 16933 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16934 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16935 } 16936 for (int i = 0; i < existing.size(); i++) { 16937 PreferredActivity pa = existing.get(i); 16938 if (DEBUG_PREFERRED) { 16939 Slog.i(TAG, "Removing existing preferred activity " 16940 + pa.mPref.mComponent + ":"); 16941 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16942 } 16943 pir.removeFilter(pa); 16944 } 16945 } 16946 } 16947 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16948 "Replacing preferred"); 16949 } 16950 } 16951 16952 @Override 16953 public void clearPackagePreferredActivities(String packageName) { 16954 final int uid = Binder.getCallingUid(); 16955 // writer 16956 synchronized (mPackages) { 16957 PackageParser.Package pkg = mPackages.get(packageName); 16958 if (pkg == null || pkg.applicationInfo.uid != uid) { 16959 if (mContext.checkCallingOrSelfPermission( 16960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16961 != PackageManager.PERMISSION_GRANTED) { 16962 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16963 < Build.VERSION_CODES.FROYO) { 16964 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16965 + Binder.getCallingUid()); 16966 return; 16967 } 16968 mContext.enforceCallingOrSelfPermission( 16969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16970 } 16971 } 16972 16973 int user = UserHandle.getCallingUserId(); 16974 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16975 scheduleWritePackageRestrictionsLocked(user); 16976 } 16977 } 16978 } 16979 16980 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16981 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16982 ArrayList<PreferredActivity> removed = null; 16983 boolean changed = false; 16984 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16985 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16986 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16987 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16988 continue; 16989 } 16990 Iterator<PreferredActivity> it = pir.filterIterator(); 16991 while (it.hasNext()) { 16992 PreferredActivity pa = it.next(); 16993 // Mark entry for removal only if it matches the package name 16994 // and the entry is of type "always". 16995 if (packageName == null || 16996 (pa.mPref.mComponent.getPackageName().equals(packageName) 16997 && pa.mPref.mAlways)) { 16998 if (removed == null) { 16999 removed = new ArrayList<PreferredActivity>(); 17000 } 17001 removed.add(pa); 17002 } 17003 } 17004 if (removed != null) { 17005 for (int j=0; j<removed.size(); j++) { 17006 PreferredActivity pa = removed.get(j); 17007 pir.removeFilter(pa); 17008 } 17009 changed = true; 17010 } 17011 } 17012 if (changed) { 17013 postPreferredActivityChangedBroadcast(userId); 17014 } 17015 return changed; 17016 } 17017 17018 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17019 private void clearIntentFilterVerificationsLPw(int userId) { 17020 final int packageCount = mPackages.size(); 17021 for (int i = 0; i < packageCount; i++) { 17022 PackageParser.Package pkg = mPackages.valueAt(i); 17023 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17024 } 17025 } 17026 17027 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17028 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17029 if (userId == UserHandle.USER_ALL) { 17030 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17031 sUserManager.getUserIds())) { 17032 for (int oneUserId : sUserManager.getUserIds()) { 17033 scheduleWritePackageRestrictionsLocked(oneUserId); 17034 } 17035 } 17036 } else { 17037 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17038 scheduleWritePackageRestrictionsLocked(userId); 17039 } 17040 } 17041 } 17042 17043 void clearDefaultBrowserIfNeeded(String packageName) { 17044 for (int oneUserId : sUserManager.getUserIds()) { 17045 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17046 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17047 if (packageName.equals(defaultBrowserPackageName)) { 17048 setDefaultBrowserPackageName(null, oneUserId); 17049 } 17050 } 17051 } 17052 17053 @Override 17054 public void resetApplicationPreferences(int userId) { 17055 mContext.enforceCallingOrSelfPermission( 17056 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17057 final long identity = Binder.clearCallingIdentity(); 17058 // writer 17059 try { 17060 synchronized (mPackages) { 17061 clearPackagePreferredActivitiesLPw(null, userId); 17062 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17063 // TODO: We have to reset the default SMS and Phone. This requires 17064 // significant refactoring to keep all default apps in the package 17065 // manager (cleaner but more work) or have the services provide 17066 // callbacks to the package manager to request a default app reset. 17067 applyFactoryDefaultBrowserLPw(userId); 17068 clearIntentFilterVerificationsLPw(userId); 17069 primeDomainVerificationsLPw(userId); 17070 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17071 scheduleWritePackageRestrictionsLocked(userId); 17072 } 17073 resetNetworkPolicies(userId); 17074 } finally { 17075 Binder.restoreCallingIdentity(identity); 17076 } 17077 } 17078 17079 @Override 17080 public int getPreferredActivities(List<IntentFilter> outFilters, 17081 List<ComponentName> outActivities, String packageName) { 17082 17083 int num = 0; 17084 final int userId = UserHandle.getCallingUserId(); 17085 // reader 17086 synchronized (mPackages) { 17087 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17088 if (pir != null) { 17089 final Iterator<PreferredActivity> it = pir.filterIterator(); 17090 while (it.hasNext()) { 17091 final PreferredActivity pa = it.next(); 17092 if (packageName == null 17093 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17094 && pa.mPref.mAlways)) { 17095 if (outFilters != null) { 17096 outFilters.add(new IntentFilter(pa)); 17097 } 17098 if (outActivities != null) { 17099 outActivities.add(pa.mPref.mComponent); 17100 } 17101 } 17102 } 17103 } 17104 } 17105 17106 return num; 17107 } 17108 17109 @Override 17110 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17111 int userId) { 17112 int callingUid = Binder.getCallingUid(); 17113 if (callingUid != Process.SYSTEM_UID) { 17114 throw new SecurityException( 17115 "addPersistentPreferredActivity can only be run by the system"); 17116 } 17117 if (filter.countActions() == 0) { 17118 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17119 return; 17120 } 17121 synchronized (mPackages) { 17122 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17123 ":"); 17124 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17125 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17126 new PersistentPreferredActivity(filter, activity)); 17127 scheduleWritePackageRestrictionsLocked(userId); 17128 postPreferredActivityChangedBroadcast(userId); 17129 } 17130 } 17131 17132 @Override 17133 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17134 int callingUid = Binder.getCallingUid(); 17135 if (callingUid != Process.SYSTEM_UID) { 17136 throw new SecurityException( 17137 "clearPackagePersistentPreferredActivities can only be run by the system"); 17138 } 17139 ArrayList<PersistentPreferredActivity> removed = null; 17140 boolean changed = false; 17141 synchronized (mPackages) { 17142 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17143 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17144 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17145 .valueAt(i); 17146 if (userId != thisUserId) { 17147 continue; 17148 } 17149 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17150 while (it.hasNext()) { 17151 PersistentPreferredActivity ppa = it.next(); 17152 // Mark entry for removal only if it matches the package name. 17153 if (ppa.mComponent.getPackageName().equals(packageName)) { 17154 if (removed == null) { 17155 removed = new ArrayList<PersistentPreferredActivity>(); 17156 } 17157 removed.add(ppa); 17158 } 17159 } 17160 if (removed != null) { 17161 for (int j=0; j<removed.size(); j++) { 17162 PersistentPreferredActivity ppa = removed.get(j); 17163 ppir.removeFilter(ppa); 17164 } 17165 changed = true; 17166 } 17167 } 17168 17169 if (changed) { 17170 scheduleWritePackageRestrictionsLocked(userId); 17171 postPreferredActivityChangedBroadcast(userId); 17172 } 17173 } 17174 } 17175 17176 /** 17177 * Common machinery for picking apart a restored XML blob and passing 17178 * it to a caller-supplied functor to be applied to the running system. 17179 */ 17180 private void restoreFromXml(XmlPullParser parser, int userId, 17181 String expectedStartTag, BlobXmlRestorer functor) 17182 throws IOException, XmlPullParserException { 17183 int type; 17184 while ((type = parser.next()) != XmlPullParser.START_TAG 17185 && type != XmlPullParser.END_DOCUMENT) { 17186 } 17187 if (type != XmlPullParser.START_TAG) { 17188 // oops didn't find a start tag?! 17189 if (DEBUG_BACKUP) { 17190 Slog.e(TAG, "Didn't find start tag during restore"); 17191 } 17192 return; 17193 } 17194Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17195 // this is supposed to be TAG_PREFERRED_BACKUP 17196 if (!expectedStartTag.equals(parser.getName())) { 17197 if (DEBUG_BACKUP) { 17198 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17199 } 17200 return; 17201 } 17202 17203 // skip interfering stuff, then we're aligned with the backing implementation 17204 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17205Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17206 functor.apply(parser, userId); 17207 } 17208 17209 private interface BlobXmlRestorer { 17210 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17211 } 17212 17213 /** 17214 * Non-Binder method, support for the backup/restore mechanism: write the 17215 * full set of preferred activities in its canonical XML format. Returns the 17216 * XML output as a byte array, or null if there is none. 17217 */ 17218 @Override 17219 public byte[] getPreferredActivityBackup(int userId) { 17220 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17221 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17222 } 17223 17224 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17225 try { 17226 final XmlSerializer serializer = new FastXmlSerializer(); 17227 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17228 serializer.startDocument(null, true); 17229 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17230 17231 synchronized (mPackages) { 17232 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17233 } 17234 17235 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17236 serializer.endDocument(); 17237 serializer.flush(); 17238 } catch (Exception e) { 17239 if (DEBUG_BACKUP) { 17240 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17241 } 17242 return null; 17243 } 17244 17245 return dataStream.toByteArray(); 17246 } 17247 17248 @Override 17249 public void restorePreferredActivities(byte[] backup, int userId) { 17250 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17251 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17252 } 17253 17254 try { 17255 final XmlPullParser parser = Xml.newPullParser(); 17256 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17257 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17258 new BlobXmlRestorer() { 17259 @Override 17260 public void apply(XmlPullParser parser, int userId) 17261 throws XmlPullParserException, IOException { 17262 synchronized (mPackages) { 17263 mSettings.readPreferredActivitiesLPw(parser, userId); 17264 } 17265 } 17266 } ); 17267 } catch (Exception e) { 17268 if (DEBUG_BACKUP) { 17269 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17270 } 17271 } 17272 } 17273 17274 /** 17275 * Non-Binder method, support for the backup/restore mechanism: write the 17276 * default browser (etc) settings in its canonical XML format. Returns the default 17277 * browser XML representation as a byte array, or null if there is none. 17278 */ 17279 @Override 17280 public byte[] getDefaultAppsBackup(int userId) { 17281 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17282 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17283 } 17284 17285 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17286 try { 17287 final XmlSerializer serializer = new FastXmlSerializer(); 17288 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17289 serializer.startDocument(null, true); 17290 serializer.startTag(null, TAG_DEFAULT_APPS); 17291 17292 synchronized (mPackages) { 17293 mSettings.writeDefaultAppsLPr(serializer, userId); 17294 } 17295 17296 serializer.endTag(null, TAG_DEFAULT_APPS); 17297 serializer.endDocument(); 17298 serializer.flush(); 17299 } catch (Exception e) { 17300 if (DEBUG_BACKUP) { 17301 Slog.e(TAG, "Unable to write default apps for backup", e); 17302 } 17303 return null; 17304 } 17305 17306 return dataStream.toByteArray(); 17307 } 17308 17309 @Override 17310 public void restoreDefaultApps(byte[] backup, int userId) { 17311 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17312 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17313 } 17314 17315 try { 17316 final XmlPullParser parser = Xml.newPullParser(); 17317 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17318 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17319 new BlobXmlRestorer() { 17320 @Override 17321 public void apply(XmlPullParser parser, int userId) 17322 throws XmlPullParserException, IOException { 17323 synchronized (mPackages) { 17324 mSettings.readDefaultAppsLPw(parser, userId); 17325 } 17326 } 17327 } ); 17328 } catch (Exception e) { 17329 if (DEBUG_BACKUP) { 17330 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17331 } 17332 } 17333 } 17334 17335 @Override 17336 public byte[] getIntentFilterVerificationBackup(int userId) { 17337 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17338 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17339 } 17340 17341 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17342 try { 17343 final XmlSerializer serializer = new FastXmlSerializer(); 17344 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17345 serializer.startDocument(null, true); 17346 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17347 17348 synchronized (mPackages) { 17349 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17350 } 17351 17352 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17353 serializer.endDocument(); 17354 serializer.flush(); 17355 } catch (Exception e) { 17356 if (DEBUG_BACKUP) { 17357 Slog.e(TAG, "Unable to write default apps for backup", e); 17358 } 17359 return null; 17360 } 17361 17362 return dataStream.toByteArray(); 17363 } 17364 17365 @Override 17366 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17367 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17368 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17369 } 17370 17371 try { 17372 final XmlPullParser parser = Xml.newPullParser(); 17373 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17374 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17375 new BlobXmlRestorer() { 17376 @Override 17377 public void apply(XmlPullParser parser, int userId) 17378 throws XmlPullParserException, IOException { 17379 synchronized (mPackages) { 17380 mSettings.readAllDomainVerificationsLPr(parser, userId); 17381 mSettings.writeLPr(); 17382 } 17383 } 17384 } ); 17385 } catch (Exception e) { 17386 if (DEBUG_BACKUP) { 17387 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17388 } 17389 } 17390 } 17391 17392 @Override 17393 public byte[] getPermissionGrantBackup(int userId) { 17394 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17395 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17396 } 17397 17398 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17399 try { 17400 final XmlSerializer serializer = new FastXmlSerializer(); 17401 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17402 serializer.startDocument(null, true); 17403 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17404 17405 synchronized (mPackages) { 17406 serializeRuntimePermissionGrantsLPr(serializer, userId); 17407 } 17408 17409 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17410 serializer.endDocument(); 17411 serializer.flush(); 17412 } catch (Exception e) { 17413 if (DEBUG_BACKUP) { 17414 Slog.e(TAG, "Unable to write default apps for backup", e); 17415 } 17416 return null; 17417 } 17418 17419 return dataStream.toByteArray(); 17420 } 17421 17422 @Override 17423 public void restorePermissionGrants(byte[] backup, int userId) { 17424 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17425 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17426 } 17427 17428 try { 17429 final XmlPullParser parser = Xml.newPullParser(); 17430 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17431 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17432 new BlobXmlRestorer() { 17433 @Override 17434 public void apply(XmlPullParser parser, int userId) 17435 throws XmlPullParserException, IOException { 17436 synchronized (mPackages) { 17437 processRestoredPermissionGrantsLPr(parser, userId); 17438 } 17439 } 17440 } ); 17441 } catch (Exception e) { 17442 if (DEBUG_BACKUP) { 17443 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17444 } 17445 } 17446 } 17447 17448 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17449 throws IOException { 17450 serializer.startTag(null, TAG_ALL_GRANTS); 17451 17452 final int N = mSettings.mPackages.size(); 17453 for (int i = 0; i < N; i++) { 17454 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17455 boolean pkgGrantsKnown = false; 17456 17457 PermissionsState packagePerms = ps.getPermissionsState(); 17458 17459 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17460 final int grantFlags = state.getFlags(); 17461 // only look at grants that are not system/policy fixed 17462 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17463 final boolean isGranted = state.isGranted(); 17464 // And only back up the user-twiddled state bits 17465 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17466 final String packageName = mSettings.mPackages.keyAt(i); 17467 if (!pkgGrantsKnown) { 17468 serializer.startTag(null, TAG_GRANT); 17469 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17470 pkgGrantsKnown = true; 17471 } 17472 17473 final boolean userSet = 17474 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17475 final boolean userFixed = 17476 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17477 final boolean revoke = 17478 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17479 17480 serializer.startTag(null, TAG_PERMISSION); 17481 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17482 if (isGranted) { 17483 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17484 } 17485 if (userSet) { 17486 serializer.attribute(null, ATTR_USER_SET, "true"); 17487 } 17488 if (userFixed) { 17489 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17490 } 17491 if (revoke) { 17492 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17493 } 17494 serializer.endTag(null, TAG_PERMISSION); 17495 } 17496 } 17497 } 17498 17499 if (pkgGrantsKnown) { 17500 serializer.endTag(null, TAG_GRANT); 17501 } 17502 } 17503 17504 serializer.endTag(null, TAG_ALL_GRANTS); 17505 } 17506 17507 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17508 throws XmlPullParserException, IOException { 17509 String pkgName = null; 17510 int outerDepth = parser.getDepth(); 17511 int type; 17512 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17513 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17514 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17515 continue; 17516 } 17517 17518 final String tagName = parser.getName(); 17519 if (tagName.equals(TAG_GRANT)) { 17520 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17521 if (DEBUG_BACKUP) { 17522 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17523 } 17524 } else if (tagName.equals(TAG_PERMISSION)) { 17525 17526 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17527 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17528 17529 int newFlagSet = 0; 17530 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17531 newFlagSet |= FLAG_PERMISSION_USER_SET; 17532 } 17533 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17534 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17535 } 17536 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17537 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17538 } 17539 if (DEBUG_BACKUP) { 17540 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17541 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17542 } 17543 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17544 if (ps != null) { 17545 // Already installed so we apply the grant immediately 17546 if (DEBUG_BACKUP) { 17547 Slog.v(TAG, " + already installed; applying"); 17548 } 17549 PermissionsState perms = ps.getPermissionsState(); 17550 BasePermission bp = mSettings.mPermissions.get(permName); 17551 if (bp != null) { 17552 if (isGranted) { 17553 perms.grantRuntimePermission(bp, userId); 17554 } 17555 if (newFlagSet != 0) { 17556 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17557 } 17558 } 17559 } else { 17560 // Need to wait for post-restore install to apply the grant 17561 if (DEBUG_BACKUP) { 17562 Slog.v(TAG, " - not yet installed; saving for later"); 17563 } 17564 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17565 isGranted, newFlagSet, userId); 17566 } 17567 } else { 17568 PackageManagerService.reportSettingsProblem(Log.WARN, 17569 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17570 XmlUtils.skipCurrentTag(parser); 17571 } 17572 } 17573 17574 scheduleWriteSettingsLocked(); 17575 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17576 } 17577 17578 @Override 17579 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17580 int sourceUserId, int targetUserId, int flags) { 17581 mContext.enforceCallingOrSelfPermission( 17582 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17583 int callingUid = Binder.getCallingUid(); 17584 enforceOwnerRights(ownerPackage, callingUid); 17585 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17586 if (intentFilter.countActions() == 0) { 17587 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17588 return; 17589 } 17590 synchronized (mPackages) { 17591 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17592 ownerPackage, targetUserId, flags); 17593 CrossProfileIntentResolver resolver = 17594 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17595 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17596 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17597 if (existing != null) { 17598 int size = existing.size(); 17599 for (int i = 0; i < size; i++) { 17600 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17601 return; 17602 } 17603 } 17604 } 17605 resolver.addFilter(newFilter); 17606 scheduleWritePackageRestrictionsLocked(sourceUserId); 17607 } 17608 } 17609 17610 @Override 17611 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17612 mContext.enforceCallingOrSelfPermission( 17613 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17614 int callingUid = Binder.getCallingUid(); 17615 enforceOwnerRights(ownerPackage, callingUid); 17616 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17617 synchronized (mPackages) { 17618 CrossProfileIntentResolver resolver = 17619 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17620 ArraySet<CrossProfileIntentFilter> set = 17621 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17622 for (CrossProfileIntentFilter filter : set) { 17623 if (filter.getOwnerPackage().equals(ownerPackage)) { 17624 resolver.removeFilter(filter); 17625 } 17626 } 17627 scheduleWritePackageRestrictionsLocked(sourceUserId); 17628 } 17629 } 17630 17631 // Enforcing that callingUid is owning pkg on userId 17632 private void enforceOwnerRights(String pkg, int callingUid) { 17633 // The system owns everything. 17634 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17635 return; 17636 } 17637 int callingUserId = UserHandle.getUserId(callingUid); 17638 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17639 if (pi == null) { 17640 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17641 + callingUserId); 17642 } 17643 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17644 throw new SecurityException("Calling uid " + callingUid 17645 + " does not own package " + pkg); 17646 } 17647 } 17648 17649 @Override 17650 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17651 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17652 } 17653 17654 private Intent getHomeIntent() { 17655 Intent intent = new Intent(Intent.ACTION_MAIN); 17656 intent.addCategory(Intent.CATEGORY_HOME); 17657 intent.addCategory(Intent.CATEGORY_DEFAULT); 17658 return intent; 17659 } 17660 17661 private IntentFilter getHomeFilter() { 17662 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17663 filter.addCategory(Intent.CATEGORY_HOME); 17664 filter.addCategory(Intent.CATEGORY_DEFAULT); 17665 return filter; 17666 } 17667 17668 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17669 int userId) { 17670 Intent intent = getHomeIntent(); 17671 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17672 PackageManager.GET_META_DATA, userId); 17673 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17674 true, false, false, userId); 17675 17676 allHomeCandidates.clear(); 17677 if (list != null) { 17678 for (ResolveInfo ri : list) { 17679 allHomeCandidates.add(ri); 17680 } 17681 } 17682 return (preferred == null || preferred.activityInfo == null) 17683 ? null 17684 : new ComponentName(preferred.activityInfo.packageName, 17685 preferred.activityInfo.name); 17686 } 17687 17688 @Override 17689 public void setHomeActivity(ComponentName comp, int userId) { 17690 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17691 getHomeActivitiesAsUser(homeActivities, userId); 17692 17693 boolean found = false; 17694 17695 final int size = homeActivities.size(); 17696 final ComponentName[] set = new ComponentName[size]; 17697 for (int i = 0; i < size; i++) { 17698 final ResolveInfo candidate = homeActivities.get(i); 17699 final ActivityInfo info = candidate.activityInfo; 17700 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17701 set[i] = activityName; 17702 if (!found && activityName.equals(comp)) { 17703 found = true; 17704 } 17705 } 17706 if (!found) { 17707 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17708 + userId); 17709 } 17710 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17711 set, comp, userId); 17712 } 17713 17714 private @Nullable String getSetupWizardPackageName() { 17715 final Intent intent = new Intent(Intent.ACTION_MAIN); 17716 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17717 17718 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17719 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17720 | MATCH_DISABLED_COMPONENTS, 17721 UserHandle.myUserId()); 17722 if (matches.size() == 1) { 17723 return matches.get(0).getComponentInfo().packageName; 17724 } else { 17725 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17726 + ": matches=" + matches); 17727 return null; 17728 } 17729 } 17730 17731 @Override 17732 public void setApplicationEnabledSetting(String appPackageName, 17733 int newState, int flags, int userId, String callingPackage) { 17734 if (!sUserManager.exists(userId)) return; 17735 if (callingPackage == null) { 17736 callingPackage = Integer.toString(Binder.getCallingUid()); 17737 } 17738 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17739 } 17740 17741 @Override 17742 public void setComponentEnabledSetting(ComponentName componentName, 17743 int newState, int flags, int userId) { 17744 if (!sUserManager.exists(userId)) return; 17745 setEnabledSetting(componentName.getPackageName(), 17746 componentName.getClassName(), newState, flags, userId, null); 17747 } 17748 17749 private void setEnabledSetting(final String packageName, String className, int newState, 17750 final int flags, int userId, String callingPackage) { 17751 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17752 || newState == COMPONENT_ENABLED_STATE_ENABLED 17753 || newState == COMPONENT_ENABLED_STATE_DISABLED 17754 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17755 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17756 throw new IllegalArgumentException("Invalid new component state: " 17757 + newState); 17758 } 17759 PackageSetting pkgSetting; 17760 final int uid = Binder.getCallingUid(); 17761 final int permission; 17762 if (uid == Process.SYSTEM_UID) { 17763 permission = PackageManager.PERMISSION_GRANTED; 17764 } else { 17765 permission = mContext.checkCallingOrSelfPermission( 17766 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17767 } 17768 enforceCrossUserPermission(uid, userId, 17769 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17770 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17771 boolean sendNow = false; 17772 boolean isApp = (className == null); 17773 String componentName = isApp ? packageName : className; 17774 int packageUid = -1; 17775 ArrayList<String> components; 17776 17777 // writer 17778 synchronized (mPackages) { 17779 pkgSetting = mSettings.mPackages.get(packageName); 17780 if (pkgSetting == null) { 17781 if (className == null) { 17782 throw new IllegalArgumentException("Unknown package: " + packageName); 17783 } 17784 throw new IllegalArgumentException( 17785 "Unknown component: " + packageName + "/" + className); 17786 } 17787 } 17788 17789 // Limit who can change which apps 17790 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17791 // Don't allow apps that don't have permission to modify other apps 17792 if (!allowedByPermission) { 17793 throw new SecurityException( 17794 "Permission Denial: attempt to change component state from pid=" 17795 + Binder.getCallingPid() 17796 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17797 } 17798 // Don't allow changing protected packages. 17799 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17800 throw new SecurityException("Cannot disable a protected package: " + packageName); 17801 } 17802 } 17803 17804 synchronized (mPackages) { 17805 if (uid == Process.SHELL_UID) { 17806 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17807 int oldState = pkgSetting.getEnabled(userId); 17808 if (className == null 17809 && 17810 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17811 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17812 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17813 && 17814 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17815 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17816 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17817 // ok 17818 } else { 17819 throw new SecurityException( 17820 "Shell cannot change component state for " + packageName + "/" 17821 + className + " to " + newState); 17822 } 17823 } 17824 if (className == null) { 17825 // We're dealing with an application/package level state change 17826 if (pkgSetting.getEnabled(userId) == newState) { 17827 // Nothing to do 17828 return; 17829 } 17830 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17831 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17832 // Don't care about who enables an app. 17833 callingPackage = null; 17834 } 17835 pkgSetting.setEnabled(newState, userId, callingPackage); 17836 // pkgSetting.pkg.mSetEnabled = newState; 17837 } else { 17838 // We're dealing with a component level state change 17839 // First, verify that this is a valid class name. 17840 PackageParser.Package pkg = pkgSetting.pkg; 17841 if (pkg == null || !pkg.hasComponentClassName(className)) { 17842 if (pkg != null && 17843 pkg.applicationInfo.targetSdkVersion >= 17844 Build.VERSION_CODES.JELLY_BEAN) { 17845 throw new IllegalArgumentException("Component class " + className 17846 + " does not exist in " + packageName); 17847 } else { 17848 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17849 + className + " does not exist in " + packageName); 17850 } 17851 } 17852 switch (newState) { 17853 case COMPONENT_ENABLED_STATE_ENABLED: 17854 if (!pkgSetting.enableComponentLPw(className, userId)) { 17855 return; 17856 } 17857 break; 17858 case COMPONENT_ENABLED_STATE_DISABLED: 17859 if (!pkgSetting.disableComponentLPw(className, userId)) { 17860 return; 17861 } 17862 break; 17863 case COMPONENT_ENABLED_STATE_DEFAULT: 17864 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17865 return; 17866 } 17867 break; 17868 default: 17869 Slog.e(TAG, "Invalid new component state: " + newState); 17870 return; 17871 } 17872 } 17873 scheduleWritePackageRestrictionsLocked(userId); 17874 components = mPendingBroadcasts.get(userId, packageName); 17875 final boolean newPackage = components == null; 17876 if (newPackage) { 17877 components = new ArrayList<String>(); 17878 } 17879 if (!components.contains(componentName)) { 17880 components.add(componentName); 17881 } 17882 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17883 sendNow = true; 17884 // Purge entry from pending broadcast list if another one exists already 17885 // since we are sending one right away. 17886 mPendingBroadcasts.remove(userId, packageName); 17887 } else { 17888 if (newPackage) { 17889 mPendingBroadcasts.put(userId, packageName, components); 17890 } 17891 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17892 // Schedule a message 17893 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17894 } 17895 } 17896 } 17897 17898 long callingId = Binder.clearCallingIdentity(); 17899 try { 17900 if (sendNow) { 17901 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17902 sendPackageChangedBroadcast(packageName, 17903 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17904 } 17905 } finally { 17906 Binder.restoreCallingIdentity(callingId); 17907 } 17908 } 17909 17910 @Override 17911 public void flushPackageRestrictionsAsUser(int userId) { 17912 if (!sUserManager.exists(userId)) { 17913 return; 17914 } 17915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17916 false /* checkShell */, "flushPackageRestrictions"); 17917 synchronized (mPackages) { 17918 mSettings.writePackageRestrictionsLPr(userId); 17919 mDirtyUsers.remove(userId); 17920 if (mDirtyUsers.isEmpty()) { 17921 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17922 } 17923 } 17924 } 17925 17926 private void sendPackageChangedBroadcast(String packageName, 17927 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17928 if (DEBUG_INSTALL) 17929 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17930 + componentNames); 17931 Bundle extras = new Bundle(4); 17932 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17933 String nameList[] = new String[componentNames.size()]; 17934 componentNames.toArray(nameList); 17935 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17936 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17937 extras.putInt(Intent.EXTRA_UID, packageUid); 17938 // If this is not reporting a change of the overall package, then only send it 17939 // to registered receivers. We don't want to launch a swath of apps for every 17940 // little component state change. 17941 final int flags = !componentNames.contains(packageName) 17942 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17943 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17944 new int[] {UserHandle.getUserId(packageUid)}); 17945 } 17946 17947 @Override 17948 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17949 if (!sUserManager.exists(userId)) return; 17950 final int uid = Binder.getCallingUid(); 17951 final int permission = mContext.checkCallingOrSelfPermission( 17952 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17953 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17954 enforceCrossUserPermission(uid, userId, 17955 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17956 // writer 17957 synchronized (mPackages) { 17958 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17959 allowedByPermission, uid, userId)) { 17960 scheduleWritePackageRestrictionsLocked(userId); 17961 } 17962 } 17963 } 17964 17965 @Override 17966 public String getInstallerPackageName(String packageName) { 17967 // reader 17968 synchronized (mPackages) { 17969 return mSettings.getInstallerPackageNameLPr(packageName); 17970 } 17971 } 17972 17973 public boolean isOrphaned(String packageName) { 17974 // reader 17975 synchronized (mPackages) { 17976 return mSettings.isOrphaned(packageName); 17977 } 17978 } 17979 17980 @Override 17981 public int getApplicationEnabledSetting(String packageName, int userId) { 17982 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17983 int uid = Binder.getCallingUid(); 17984 enforceCrossUserPermission(uid, userId, 17985 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17986 // reader 17987 synchronized (mPackages) { 17988 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17989 } 17990 } 17991 17992 @Override 17993 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17994 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17995 int uid = Binder.getCallingUid(); 17996 enforceCrossUserPermission(uid, userId, 17997 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17998 // reader 17999 synchronized (mPackages) { 18000 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18001 } 18002 } 18003 18004 @Override 18005 public void enterSafeMode() { 18006 enforceSystemOrRoot("Only the system can request entering safe mode"); 18007 18008 if (!mSystemReady) { 18009 mSafeMode = true; 18010 } 18011 } 18012 18013 @Override 18014 public void systemReady() { 18015 mSystemReady = true; 18016 18017 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18018 // disabled after already being started. 18019 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18020 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18021 18022 // Read the compatibilty setting when the system is ready. 18023 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18024 mContext.getContentResolver(), 18025 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18026 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18027 if (DEBUG_SETTINGS) { 18028 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18029 } 18030 18031 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18032 18033 synchronized (mPackages) { 18034 // Verify that all of the preferred activity components actually 18035 // exist. It is possible for applications to be updated and at 18036 // that point remove a previously declared activity component that 18037 // had been set as a preferred activity. We try to clean this up 18038 // the next time we encounter that preferred activity, but it is 18039 // possible for the user flow to never be able to return to that 18040 // situation so here we do a sanity check to make sure we haven't 18041 // left any junk around. 18042 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18043 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18044 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18045 removed.clear(); 18046 for (PreferredActivity pa : pir.filterSet()) { 18047 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18048 removed.add(pa); 18049 } 18050 } 18051 if (removed.size() > 0) { 18052 for (int r=0; r<removed.size(); r++) { 18053 PreferredActivity pa = removed.get(r); 18054 Slog.w(TAG, "Removing dangling preferred activity: " 18055 + pa.mPref.mComponent); 18056 pir.removeFilter(pa); 18057 } 18058 mSettings.writePackageRestrictionsLPr( 18059 mSettings.mPreferredActivities.keyAt(i)); 18060 } 18061 } 18062 18063 for (int userId : UserManagerService.getInstance().getUserIds()) { 18064 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18065 grantPermissionsUserIds = ArrayUtils.appendInt( 18066 grantPermissionsUserIds, userId); 18067 } 18068 } 18069 } 18070 sUserManager.systemReady(); 18071 18072 // If we upgraded grant all default permissions before kicking off. 18073 for (int userId : grantPermissionsUserIds) { 18074 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18075 } 18076 18077 // If we did not grant default permissions, we preload from this the 18078 // default permission exceptions lazily to ensure we don't hit the 18079 // disk on a new user creation. 18080 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18081 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18082 } 18083 18084 // Kick off any messages waiting for system ready 18085 if (mPostSystemReadyMessages != null) { 18086 for (Message msg : mPostSystemReadyMessages) { 18087 msg.sendToTarget(); 18088 } 18089 mPostSystemReadyMessages = null; 18090 } 18091 18092 // Watch for external volumes that come and go over time 18093 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18094 storage.registerListener(mStorageListener); 18095 18096 mInstallerService.systemReady(); 18097 mPackageDexOptimizer.systemReady(); 18098 18099 MountServiceInternal mountServiceInternal = LocalServices.getService( 18100 MountServiceInternal.class); 18101 mountServiceInternal.addExternalStoragePolicy( 18102 new MountServiceInternal.ExternalStorageMountPolicy() { 18103 @Override 18104 public int getMountMode(int uid, String packageName) { 18105 if (Process.isIsolated(uid)) { 18106 return Zygote.MOUNT_EXTERNAL_NONE; 18107 } 18108 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18109 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18110 } 18111 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18112 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18113 } 18114 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18115 return Zygote.MOUNT_EXTERNAL_READ; 18116 } 18117 return Zygote.MOUNT_EXTERNAL_WRITE; 18118 } 18119 18120 @Override 18121 public boolean hasExternalStorage(int uid, String packageName) { 18122 return true; 18123 } 18124 }); 18125 18126 // Now that we're mostly running, clean up stale users and apps 18127 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18128 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18129 } 18130 18131 @Override 18132 public boolean isSafeMode() { 18133 return mSafeMode; 18134 } 18135 18136 @Override 18137 public boolean hasSystemUidErrors() { 18138 return mHasSystemUidErrors; 18139 } 18140 18141 static String arrayToString(int[] array) { 18142 StringBuffer buf = new StringBuffer(128); 18143 buf.append('['); 18144 if (array != null) { 18145 for (int i=0; i<array.length; i++) { 18146 if (i > 0) buf.append(", "); 18147 buf.append(array[i]); 18148 } 18149 } 18150 buf.append(']'); 18151 return buf.toString(); 18152 } 18153 18154 static class DumpState { 18155 public static final int DUMP_LIBS = 1 << 0; 18156 public static final int DUMP_FEATURES = 1 << 1; 18157 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18158 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18159 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18160 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18161 public static final int DUMP_PERMISSIONS = 1 << 6; 18162 public static final int DUMP_PACKAGES = 1 << 7; 18163 public static final int DUMP_SHARED_USERS = 1 << 8; 18164 public static final int DUMP_MESSAGES = 1 << 9; 18165 public static final int DUMP_PROVIDERS = 1 << 10; 18166 public static final int DUMP_VERIFIERS = 1 << 11; 18167 public static final int DUMP_PREFERRED = 1 << 12; 18168 public static final int DUMP_PREFERRED_XML = 1 << 13; 18169 public static final int DUMP_KEYSETS = 1 << 14; 18170 public static final int DUMP_VERSION = 1 << 15; 18171 public static final int DUMP_INSTALLS = 1 << 16; 18172 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18173 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18174 public static final int DUMP_FROZEN = 1 << 19; 18175 public static final int DUMP_DEXOPT = 1 << 20; 18176 public static final int DUMP_COMPILER_STATS = 1 << 21; 18177 18178 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18179 18180 private int mTypes; 18181 18182 private int mOptions; 18183 18184 private boolean mTitlePrinted; 18185 18186 private SharedUserSetting mSharedUser; 18187 18188 public boolean isDumping(int type) { 18189 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18190 return true; 18191 } 18192 18193 return (mTypes & type) != 0; 18194 } 18195 18196 public void setDump(int type) { 18197 mTypes |= type; 18198 } 18199 18200 public boolean isOptionEnabled(int option) { 18201 return (mOptions & option) != 0; 18202 } 18203 18204 public void setOptionEnabled(int option) { 18205 mOptions |= option; 18206 } 18207 18208 public boolean onTitlePrinted() { 18209 final boolean printed = mTitlePrinted; 18210 mTitlePrinted = true; 18211 return printed; 18212 } 18213 18214 public boolean getTitlePrinted() { 18215 return mTitlePrinted; 18216 } 18217 18218 public void setTitlePrinted(boolean enabled) { 18219 mTitlePrinted = enabled; 18220 } 18221 18222 public SharedUserSetting getSharedUser() { 18223 return mSharedUser; 18224 } 18225 18226 public void setSharedUser(SharedUserSetting user) { 18227 mSharedUser = user; 18228 } 18229 } 18230 18231 @Override 18232 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18233 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18234 (new PackageManagerShellCommand(this)).exec( 18235 this, in, out, err, args, resultReceiver); 18236 } 18237 18238 @Override 18239 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18240 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18241 != PackageManager.PERMISSION_GRANTED) { 18242 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18243 + Binder.getCallingPid() 18244 + ", uid=" + Binder.getCallingUid() 18245 + " without permission " 18246 + android.Manifest.permission.DUMP); 18247 return; 18248 } 18249 18250 DumpState dumpState = new DumpState(); 18251 boolean fullPreferred = false; 18252 boolean checkin = false; 18253 18254 String packageName = null; 18255 ArraySet<String> permissionNames = null; 18256 18257 int opti = 0; 18258 while (opti < args.length) { 18259 String opt = args[opti]; 18260 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18261 break; 18262 } 18263 opti++; 18264 18265 if ("-a".equals(opt)) { 18266 // Right now we only know how to print all. 18267 } else if ("-h".equals(opt)) { 18268 pw.println("Package manager dump options:"); 18269 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18270 pw.println(" --checkin: dump for a checkin"); 18271 pw.println(" -f: print details of intent filters"); 18272 pw.println(" -h: print this help"); 18273 pw.println(" cmd may be one of:"); 18274 pw.println(" l[ibraries]: list known shared libraries"); 18275 pw.println(" f[eatures]: list device features"); 18276 pw.println(" k[eysets]: print known keysets"); 18277 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18278 pw.println(" perm[issions]: dump permissions"); 18279 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18280 pw.println(" pref[erred]: print preferred package settings"); 18281 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18282 pw.println(" prov[iders]: dump content providers"); 18283 pw.println(" p[ackages]: dump installed packages"); 18284 pw.println(" s[hared-users]: dump shared user IDs"); 18285 pw.println(" m[essages]: print collected runtime messages"); 18286 pw.println(" v[erifiers]: print package verifier info"); 18287 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18288 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18289 pw.println(" version: print database version info"); 18290 pw.println(" write: write current settings now"); 18291 pw.println(" installs: details about install sessions"); 18292 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18293 pw.println(" dexopt: dump dexopt state"); 18294 pw.println(" compiler-stats: dump compiler statistics"); 18295 pw.println(" <package.name>: info about given package"); 18296 return; 18297 } else if ("--checkin".equals(opt)) { 18298 checkin = true; 18299 } else if ("-f".equals(opt)) { 18300 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18301 } else { 18302 pw.println("Unknown argument: " + opt + "; use -h for help"); 18303 } 18304 } 18305 18306 // Is the caller requesting to dump a particular piece of data? 18307 if (opti < args.length) { 18308 String cmd = args[opti]; 18309 opti++; 18310 // Is this a package name? 18311 if ("android".equals(cmd) || cmd.contains(".")) { 18312 packageName = cmd; 18313 // When dumping a single package, we always dump all of its 18314 // filter information since the amount of data will be reasonable. 18315 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18316 } else if ("check-permission".equals(cmd)) { 18317 if (opti >= args.length) { 18318 pw.println("Error: check-permission missing permission argument"); 18319 return; 18320 } 18321 String perm = args[opti]; 18322 opti++; 18323 if (opti >= args.length) { 18324 pw.println("Error: check-permission missing package argument"); 18325 return; 18326 } 18327 String pkg = args[opti]; 18328 opti++; 18329 int user = UserHandle.getUserId(Binder.getCallingUid()); 18330 if (opti < args.length) { 18331 try { 18332 user = Integer.parseInt(args[opti]); 18333 } catch (NumberFormatException e) { 18334 pw.println("Error: check-permission user argument is not a number: " 18335 + args[opti]); 18336 return; 18337 } 18338 } 18339 pw.println(checkPermission(perm, pkg, user)); 18340 return; 18341 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18342 dumpState.setDump(DumpState.DUMP_LIBS); 18343 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18344 dumpState.setDump(DumpState.DUMP_FEATURES); 18345 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18346 if (opti >= args.length) { 18347 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18348 | DumpState.DUMP_SERVICE_RESOLVERS 18349 | DumpState.DUMP_RECEIVER_RESOLVERS 18350 | DumpState.DUMP_CONTENT_RESOLVERS); 18351 } else { 18352 while (opti < args.length) { 18353 String name = args[opti]; 18354 if ("a".equals(name) || "activity".equals(name)) { 18355 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18356 } else if ("s".equals(name) || "service".equals(name)) { 18357 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18358 } else if ("r".equals(name) || "receiver".equals(name)) { 18359 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18360 } else if ("c".equals(name) || "content".equals(name)) { 18361 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18362 } else { 18363 pw.println("Error: unknown resolver table type: " + name); 18364 return; 18365 } 18366 opti++; 18367 } 18368 } 18369 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18370 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18371 } else if ("permission".equals(cmd)) { 18372 if (opti >= args.length) { 18373 pw.println("Error: permission requires permission name"); 18374 return; 18375 } 18376 permissionNames = new ArraySet<>(); 18377 while (opti < args.length) { 18378 permissionNames.add(args[opti]); 18379 opti++; 18380 } 18381 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18382 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18383 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18384 dumpState.setDump(DumpState.DUMP_PREFERRED); 18385 } else if ("preferred-xml".equals(cmd)) { 18386 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18387 if (opti < args.length && "--full".equals(args[opti])) { 18388 fullPreferred = true; 18389 opti++; 18390 } 18391 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18392 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18393 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18394 dumpState.setDump(DumpState.DUMP_PACKAGES); 18395 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18396 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18397 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18398 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18399 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18400 dumpState.setDump(DumpState.DUMP_MESSAGES); 18401 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18402 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18403 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18404 || "intent-filter-verifiers".equals(cmd)) { 18405 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18406 } else if ("version".equals(cmd)) { 18407 dumpState.setDump(DumpState.DUMP_VERSION); 18408 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18409 dumpState.setDump(DumpState.DUMP_KEYSETS); 18410 } else if ("installs".equals(cmd)) { 18411 dumpState.setDump(DumpState.DUMP_INSTALLS); 18412 } else if ("frozen".equals(cmd)) { 18413 dumpState.setDump(DumpState.DUMP_FROZEN); 18414 } else if ("dexopt".equals(cmd)) { 18415 dumpState.setDump(DumpState.DUMP_DEXOPT); 18416 } else if ("compiler-stats".equals(cmd)) { 18417 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18418 } else if ("write".equals(cmd)) { 18419 synchronized (mPackages) { 18420 mSettings.writeLPr(); 18421 pw.println("Settings written."); 18422 return; 18423 } 18424 } 18425 } 18426 18427 if (checkin) { 18428 pw.println("vers,1"); 18429 } 18430 18431 // reader 18432 synchronized (mPackages) { 18433 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18434 if (!checkin) { 18435 if (dumpState.onTitlePrinted()) 18436 pw.println(); 18437 pw.println("Database versions:"); 18438 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18439 } 18440 } 18441 18442 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18443 if (!checkin) { 18444 if (dumpState.onTitlePrinted()) 18445 pw.println(); 18446 pw.println("Verifiers:"); 18447 pw.print(" Required: "); 18448 pw.print(mRequiredVerifierPackage); 18449 pw.print(" (uid="); 18450 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18451 UserHandle.USER_SYSTEM)); 18452 pw.println(")"); 18453 } else if (mRequiredVerifierPackage != null) { 18454 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18455 pw.print(","); 18456 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18457 UserHandle.USER_SYSTEM)); 18458 } 18459 } 18460 18461 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18462 packageName == null) { 18463 if (mIntentFilterVerifierComponent != null) { 18464 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18465 if (!checkin) { 18466 if (dumpState.onTitlePrinted()) 18467 pw.println(); 18468 pw.println("Intent Filter Verifier:"); 18469 pw.print(" Using: "); 18470 pw.print(verifierPackageName); 18471 pw.print(" (uid="); 18472 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18473 UserHandle.USER_SYSTEM)); 18474 pw.println(")"); 18475 } else if (verifierPackageName != null) { 18476 pw.print("ifv,"); pw.print(verifierPackageName); 18477 pw.print(","); 18478 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18479 UserHandle.USER_SYSTEM)); 18480 } 18481 } else { 18482 pw.println(); 18483 pw.println("No Intent Filter Verifier available!"); 18484 } 18485 } 18486 18487 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18488 boolean printedHeader = false; 18489 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18490 while (it.hasNext()) { 18491 String name = it.next(); 18492 SharedLibraryEntry ent = mSharedLibraries.get(name); 18493 if (!checkin) { 18494 if (!printedHeader) { 18495 if (dumpState.onTitlePrinted()) 18496 pw.println(); 18497 pw.println("Libraries:"); 18498 printedHeader = true; 18499 } 18500 pw.print(" "); 18501 } else { 18502 pw.print("lib,"); 18503 } 18504 pw.print(name); 18505 if (!checkin) { 18506 pw.print(" -> "); 18507 } 18508 if (ent.path != null) { 18509 if (!checkin) { 18510 pw.print("(jar) "); 18511 pw.print(ent.path); 18512 } else { 18513 pw.print(",jar,"); 18514 pw.print(ent.path); 18515 } 18516 } else { 18517 if (!checkin) { 18518 pw.print("(apk) "); 18519 pw.print(ent.apk); 18520 } else { 18521 pw.print(",apk,"); 18522 pw.print(ent.apk); 18523 } 18524 } 18525 pw.println(); 18526 } 18527 } 18528 18529 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18530 if (dumpState.onTitlePrinted()) 18531 pw.println(); 18532 if (!checkin) { 18533 pw.println("Features:"); 18534 } 18535 18536 for (FeatureInfo feat : mAvailableFeatures.values()) { 18537 if (checkin) { 18538 pw.print("feat,"); 18539 pw.print(feat.name); 18540 pw.print(","); 18541 pw.println(feat.version); 18542 } else { 18543 pw.print(" "); 18544 pw.print(feat.name); 18545 if (feat.version > 0) { 18546 pw.print(" version="); 18547 pw.print(feat.version); 18548 } 18549 pw.println(); 18550 } 18551 } 18552 } 18553 18554 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18555 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18556 : "Activity Resolver Table:", " ", packageName, 18557 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18558 dumpState.setTitlePrinted(true); 18559 } 18560 } 18561 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18562 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18563 : "Receiver Resolver Table:", " ", packageName, 18564 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18565 dumpState.setTitlePrinted(true); 18566 } 18567 } 18568 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18569 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18570 : "Service Resolver Table:", " ", packageName, 18571 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18572 dumpState.setTitlePrinted(true); 18573 } 18574 } 18575 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18576 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18577 : "Provider Resolver Table:", " ", packageName, 18578 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18579 dumpState.setTitlePrinted(true); 18580 } 18581 } 18582 18583 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18584 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18585 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18586 int user = mSettings.mPreferredActivities.keyAt(i); 18587 if (pir.dump(pw, 18588 dumpState.getTitlePrinted() 18589 ? "\nPreferred Activities User " + user + ":" 18590 : "Preferred Activities User " + user + ":", " ", 18591 packageName, true, false)) { 18592 dumpState.setTitlePrinted(true); 18593 } 18594 } 18595 } 18596 18597 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18598 pw.flush(); 18599 FileOutputStream fout = new FileOutputStream(fd); 18600 BufferedOutputStream str = new BufferedOutputStream(fout); 18601 XmlSerializer serializer = new FastXmlSerializer(); 18602 try { 18603 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18604 serializer.startDocument(null, true); 18605 serializer.setFeature( 18606 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18607 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18608 serializer.endDocument(); 18609 serializer.flush(); 18610 } catch (IllegalArgumentException e) { 18611 pw.println("Failed writing: " + e); 18612 } catch (IllegalStateException e) { 18613 pw.println("Failed writing: " + e); 18614 } catch (IOException e) { 18615 pw.println("Failed writing: " + e); 18616 } 18617 } 18618 18619 if (!checkin 18620 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18621 && packageName == null) { 18622 pw.println(); 18623 int count = mSettings.mPackages.size(); 18624 if (count == 0) { 18625 pw.println("No applications!"); 18626 pw.println(); 18627 } else { 18628 final String prefix = " "; 18629 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18630 if (allPackageSettings.size() == 0) { 18631 pw.println("No domain preferred apps!"); 18632 pw.println(); 18633 } else { 18634 pw.println("App verification status:"); 18635 pw.println(); 18636 count = 0; 18637 for (PackageSetting ps : allPackageSettings) { 18638 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18639 if (ivi == null || ivi.getPackageName() == null) continue; 18640 pw.println(prefix + "Package: " + ivi.getPackageName()); 18641 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18642 pw.println(prefix + "Status: " + ivi.getStatusString()); 18643 pw.println(); 18644 count++; 18645 } 18646 if (count == 0) { 18647 pw.println(prefix + "No app verification established."); 18648 pw.println(); 18649 } 18650 for (int userId : sUserManager.getUserIds()) { 18651 pw.println("App linkages for user " + userId + ":"); 18652 pw.println(); 18653 count = 0; 18654 for (PackageSetting ps : allPackageSettings) { 18655 final long status = ps.getDomainVerificationStatusForUser(userId); 18656 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18657 continue; 18658 } 18659 pw.println(prefix + "Package: " + ps.name); 18660 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18661 String statusStr = IntentFilterVerificationInfo. 18662 getStatusStringFromValue(status); 18663 pw.println(prefix + "Status: " + statusStr); 18664 pw.println(); 18665 count++; 18666 } 18667 if (count == 0) { 18668 pw.println(prefix + "No configured app linkages."); 18669 pw.println(); 18670 } 18671 } 18672 } 18673 } 18674 } 18675 18676 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18677 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18678 if (packageName == null && permissionNames == null) { 18679 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18680 if (iperm == 0) { 18681 if (dumpState.onTitlePrinted()) 18682 pw.println(); 18683 pw.println("AppOp Permissions:"); 18684 } 18685 pw.print(" AppOp Permission "); 18686 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18687 pw.println(":"); 18688 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18689 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18690 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18691 } 18692 } 18693 } 18694 } 18695 18696 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18697 boolean printedSomething = false; 18698 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18699 if (packageName != null && !packageName.equals(p.info.packageName)) { 18700 continue; 18701 } 18702 if (!printedSomething) { 18703 if (dumpState.onTitlePrinted()) 18704 pw.println(); 18705 pw.println("Registered ContentProviders:"); 18706 printedSomething = true; 18707 } 18708 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18709 pw.print(" "); pw.println(p.toString()); 18710 } 18711 printedSomething = false; 18712 for (Map.Entry<String, PackageParser.Provider> entry : 18713 mProvidersByAuthority.entrySet()) { 18714 PackageParser.Provider p = entry.getValue(); 18715 if (packageName != null && !packageName.equals(p.info.packageName)) { 18716 continue; 18717 } 18718 if (!printedSomething) { 18719 if (dumpState.onTitlePrinted()) 18720 pw.println(); 18721 pw.println("ContentProvider Authorities:"); 18722 printedSomething = true; 18723 } 18724 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18725 pw.print(" "); pw.println(p.toString()); 18726 if (p.info != null && p.info.applicationInfo != null) { 18727 final String appInfo = p.info.applicationInfo.toString(); 18728 pw.print(" applicationInfo="); pw.println(appInfo); 18729 } 18730 } 18731 } 18732 18733 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18734 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18735 } 18736 18737 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18738 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18739 } 18740 18741 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18742 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18743 } 18744 18745 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18746 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18747 } 18748 18749 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18750 // XXX should handle packageName != null by dumping only install data that 18751 // the given package is involved with. 18752 if (dumpState.onTitlePrinted()) pw.println(); 18753 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18754 } 18755 18756 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18757 // XXX should handle packageName != null by dumping only install data that 18758 // the given package is involved with. 18759 if (dumpState.onTitlePrinted()) pw.println(); 18760 18761 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18762 ipw.println(); 18763 ipw.println("Frozen packages:"); 18764 ipw.increaseIndent(); 18765 if (mFrozenPackages.size() == 0) { 18766 ipw.println("(none)"); 18767 } else { 18768 for (int i = 0; i < mFrozenPackages.size(); i++) { 18769 ipw.println(mFrozenPackages.valueAt(i)); 18770 } 18771 } 18772 ipw.decreaseIndent(); 18773 } 18774 18775 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18776 if (dumpState.onTitlePrinted()) pw.println(); 18777 dumpDexoptStateLPr(pw, packageName); 18778 } 18779 18780 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18781 if (dumpState.onTitlePrinted()) pw.println(); 18782 dumpCompilerStatsLPr(pw, packageName); 18783 } 18784 18785 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18786 if (dumpState.onTitlePrinted()) pw.println(); 18787 mSettings.dumpReadMessagesLPr(pw, dumpState); 18788 18789 pw.println(); 18790 pw.println("Package warning messages:"); 18791 BufferedReader in = null; 18792 String line = null; 18793 try { 18794 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18795 while ((line = in.readLine()) != null) { 18796 if (line.contains("ignored: updated version")) continue; 18797 pw.println(line); 18798 } 18799 } catch (IOException ignored) { 18800 } finally { 18801 IoUtils.closeQuietly(in); 18802 } 18803 } 18804 18805 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18806 BufferedReader in = null; 18807 String line = null; 18808 try { 18809 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18810 while ((line = in.readLine()) != null) { 18811 if (line.contains("ignored: updated version")) continue; 18812 pw.print("msg,"); 18813 pw.println(line); 18814 } 18815 } catch (IOException ignored) { 18816 } finally { 18817 IoUtils.closeQuietly(in); 18818 } 18819 } 18820 } 18821 } 18822 18823 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18824 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18825 ipw.println(); 18826 ipw.println("Dexopt state:"); 18827 ipw.increaseIndent(); 18828 Collection<PackageParser.Package> packages = null; 18829 if (packageName != null) { 18830 PackageParser.Package targetPackage = mPackages.get(packageName); 18831 if (targetPackage != null) { 18832 packages = Collections.singletonList(targetPackage); 18833 } else { 18834 ipw.println("Unable to find package: " + packageName); 18835 return; 18836 } 18837 } else { 18838 packages = mPackages.values(); 18839 } 18840 18841 for (PackageParser.Package pkg : packages) { 18842 ipw.println("[" + pkg.packageName + "]"); 18843 ipw.increaseIndent(); 18844 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18845 ipw.decreaseIndent(); 18846 } 18847 } 18848 18849 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18850 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18851 ipw.println(); 18852 ipw.println("Compiler stats:"); 18853 ipw.increaseIndent(); 18854 Collection<PackageParser.Package> packages = null; 18855 if (packageName != null) { 18856 PackageParser.Package targetPackage = mPackages.get(packageName); 18857 if (targetPackage != null) { 18858 packages = Collections.singletonList(targetPackage); 18859 } else { 18860 ipw.println("Unable to find package: " + packageName); 18861 return; 18862 } 18863 } else { 18864 packages = mPackages.values(); 18865 } 18866 18867 for (PackageParser.Package pkg : packages) { 18868 ipw.println("[" + pkg.packageName + "]"); 18869 ipw.increaseIndent(); 18870 18871 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18872 if (stats == null) { 18873 ipw.println("(No recorded stats)"); 18874 } else { 18875 stats.dump(ipw); 18876 } 18877 ipw.decreaseIndent(); 18878 } 18879 } 18880 18881 private String dumpDomainString(String packageName) { 18882 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18883 .getList(); 18884 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18885 18886 ArraySet<String> result = new ArraySet<>(); 18887 if (iviList.size() > 0) { 18888 for (IntentFilterVerificationInfo ivi : iviList) { 18889 for (String host : ivi.getDomains()) { 18890 result.add(host); 18891 } 18892 } 18893 } 18894 if (filters != null && filters.size() > 0) { 18895 for (IntentFilter filter : filters) { 18896 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18897 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18898 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18899 result.addAll(filter.getHostsList()); 18900 } 18901 } 18902 } 18903 18904 StringBuilder sb = new StringBuilder(result.size() * 16); 18905 for (String domain : result) { 18906 if (sb.length() > 0) sb.append(" "); 18907 sb.append(domain); 18908 } 18909 return sb.toString(); 18910 } 18911 18912 // ------- apps on sdcard specific code ------- 18913 static final boolean DEBUG_SD_INSTALL = false; 18914 18915 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18916 18917 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18918 18919 private boolean mMediaMounted = false; 18920 18921 static String getEncryptKey() { 18922 try { 18923 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18924 SD_ENCRYPTION_KEYSTORE_NAME); 18925 if (sdEncKey == null) { 18926 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18927 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18928 if (sdEncKey == null) { 18929 Slog.e(TAG, "Failed to create encryption keys"); 18930 return null; 18931 } 18932 } 18933 return sdEncKey; 18934 } catch (NoSuchAlgorithmException nsae) { 18935 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18936 return null; 18937 } catch (IOException ioe) { 18938 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18939 return null; 18940 } 18941 } 18942 18943 /* 18944 * Update media status on PackageManager. 18945 */ 18946 @Override 18947 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18948 int callingUid = Binder.getCallingUid(); 18949 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18950 throw new SecurityException("Media status can only be updated by the system"); 18951 } 18952 // reader; this apparently protects mMediaMounted, but should probably 18953 // be a different lock in that case. 18954 synchronized (mPackages) { 18955 Log.i(TAG, "Updating external media status from " 18956 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18957 + (mediaStatus ? "mounted" : "unmounted")); 18958 if (DEBUG_SD_INSTALL) 18959 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18960 + ", mMediaMounted=" + mMediaMounted); 18961 if (mediaStatus == mMediaMounted) { 18962 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18963 : 0, -1); 18964 mHandler.sendMessage(msg); 18965 return; 18966 } 18967 mMediaMounted = mediaStatus; 18968 } 18969 // Queue up an async operation since the package installation may take a 18970 // little while. 18971 mHandler.post(new Runnable() { 18972 public void run() { 18973 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18974 } 18975 }); 18976 } 18977 18978 /** 18979 * Called by MountService when the initial ASECs to scan are available. 18980 * Should block until all the ASEC containers are finished being scanned. 18981 */ 18982 public void scanAvailableAsecs() { 18983 updateExternalMediaStatusInner(true, false, false); 18984 } 18985 18986 /* 18987 * Collect information of applications on external media, map them against 18988 * existing containers and update information based on current mount status. 18989 * Please note that we always have to report status if reportStatus has been 18990 * set to true especially when unloading packages. 18991 */ 18992 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18993 boolean externalStorage) { 18994 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18995 int[] uidArr = EmptyArray.INT; 18996 18997 final String[] list = PackageHelper.getSecureContainerList(); 18998 if (ArrayUtils.isEmpty(list)) { 18999 Log.i(TAG, "No secure containers found"); 19000 } else { 19001 // Process list of secure containers and categorize them 19002 // as active or stale based on their package internal state. 19003 19004 // reader 19005 synchronized (mPackages) { 19006 for (String cid : list) { 19007 // Leave stages untouched for now; installer service owns them 19008 if (PackageInstallerService.isStageName(cid)) continue; 19009 19010 if (DEBUG_SD_INSTALL) 19011 Log.i(TAG, "Processing container " + cid); 19012 String pkgName = getAsecPackageName(cid); 19013 if (pkgName == null) { 19014 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19015 continue; 19016 } 19017 if (DEBUG_SD_INSTALL) 19018 Log.i(TAG, "Looking for pkg : " + pkgName); 19019 19020 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19021 if (ps == null) { 19022 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19023 continue; 19024 } 19025 19026 /* 19027 * Skip packages that are not external if we're unmounting 19028 * external storage. 19029 */ 19030 if (externalStorage && !isMounted && !isExternal(ps)) { 19031 continue; 19032 } 19033 19034 final AsecInstallArgs args = new AsecInstallArgs(cid, 19035 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19036 // The package status is changed only if the code path 19037 // matches between settings and the container id. 19038 if (ps.codePathString != null 19039 && ps.codePathString.startsWith(args.getCodePath())) { 19040 if (DEBUG_SD_INSTALL) { 19041 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19042 + " at code path: " + ps.codePathString); 19043 } 19044 19045 // We do have a valid package installed on sdcard 19046 processCids.put(args, ps.codePathString); 19047 final int uid = ps.appId; 19048 if (uid != -1) { 19049 uidArr = ArrayUtils.appendInt(uidArr, uid); 19050 } 19051 } else { 19052 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19053 + ps.codePathString); 19054 } 19055 } 19056 } 19057 19058 Arrays.sort(uidArr); 19059 } 19060 19061 // Process packages with valid entries. 19062 if (isMounted) { 19063 if (DEBUG_SD_INSTALL) 19064 Log.i(TAG, "Loading packages"); 19065 loadMediaPackages(processCids, uidArr, externalStorage); 19066 startCleaningPackages(); 19067 mInstallerService.onSecureContainersAvailable(); 19068 } else { 19069 if (DEBUG_SD_INSTALL) 19070 Log.i(TAG, "Unloading packages"); 19071 unloadMediaPackages(processCids, uidArr, reportStatus); 19072 } 19073 } 19074 19075 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19076 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19077 final int size = infos.size(); 19078 final String[] packageNames = new String[size]; 19079 final int[] packageUids = new int[size]; 19080 for (int i = 0; i < size; i++) { 19081 final ApplicationInfo info = infos.get(i); 19082 packageNames[i] = info.packageName; 19083 packageUids[i] = info.uid; 19084 } 19085 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19086 finishedReceiver); 19087 } 19088 19089 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19090 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19091 sendResourcesChangedBroadcast(mediaStatus, replacing, 19092 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19093 } 19094 19095 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19096 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19097 int size = pkgList.length; 19098 if (size > 0) { 19099 // Send broadcasts here 19100 Bundle extras = new Bundle(); 19101 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19102 if (uidArr != null) { 19103 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19104 } 19105 if (replacing) { 19106 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19107 } 19108 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19109 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19110 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19111 } 19112 } 19113 19114 /* 19115 * Look at potentially valid container ids from processCids If package 19116 * information doesn't match the one on record or package scanning fails, 19117 * the cid is added to list of removeCids. We currently don't delete stale 19118 * containers. 19119 */ 19120 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19121 boolean externalStorage) { 19122 ArrayList<String> pkgList = new ArrayList<String>(); 19123 Set<AsecInstallArgs> keys = processCids.keySet(); 19124 19125 for (AsecInstallArgs args : keys) { 19126 String codePath = processCids.get(args); 19127 if (DEBUG_SD_INSTALL) 19128 Log.i(TAG, "Loading container : " + args.cid); 19129 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19130 try { 19131 // Make sure there are no container errors first. 19132 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19133 Slog.e(TAG, "Failed to mount cid : " + args.cid 19134 + " when installing from sdcard"); 19135 continue; 19136 } 19137 // Check code path here. 19138 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19139 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19140 + " does not match one in settings " + codePath); 19141 continue; 19142 } 19143 // Parse package 19144 int parseFlags = mDefParseFlags; 19145 if (args.isExternalAsec()) { 19146 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19147 } 19148 if (args.isFwdLocked()) { 19149 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19150 } 19151 19152 synchronized (mInstallLock) { 19153 PackageParser.Package pkg = null; 19154 try { 19155 // Sadly we don't know the package name yet to freeze it 19156 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19157 SCAN_IGNORE_FROZEN, 0, null); 19158 } catch (PackageManagerException e) { 19159 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19160 } 19161 // Scan the package 19162 if (pkg != null) { 19163 /* 19164 * TODO why is the lock being held? doPostInstall is 19165 * called in other places without the lock. This needs 19166 * to be straightened out. 19167 */ 19168 // writer 19169 synchronized (mPackages) { 19170 retCode = PackageManager.INSTALL_SUCCEEDED; 19171 pkgList.add(pkg.packageName); 19172 // Post process args 19173 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19174 pkg.applicationInfo.uid); 19175 } 19176 } else { 19177 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19178 } 19179 } 19180 19181 } finally { 19182 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19183 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19184 } 19185 } 19186 } 19187 // writer 19188 synchronized (mPackages) { 19189 // If the platform SDK has changed since the last time we booted, 19190 // we need to re-grant app permission to catch any new ones that 19191 // appear. This is really a hack, and means that apps can in some 19192 // cases get permissions that the user didn't initially explicitly 19193 // allow... it would be nice to have some better way to handle 19194 // this situation. 19195 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19196 : mSettings.getInternalVersion(); 19197 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19198 : StorageManager.UUID_PRIVATE_INTERNAL; 19199 19200 int updateFlags = UPDATE_PERMISSIONS_ALL; 19201 if (ver.sdkVersion != mSdkVersion) { 19202 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19203 + mSdkVersion + "; regranting permissions for external"); 19204 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19205 } 19206 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19207 19208 // Yay, everything is now upgraded 19209 ver.forceCurrent(); 19210 19211 // can downgrade to reader 19212 // Persist settings 19213 mSettings.writeLPr(); 19214 } 19215 // Send a broadcast to let everyone know we are done processing 19216 if (pkgList.size() > 0) { 19217 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19218 } 19219 } 19220 19221 /* 19222 * Utility method to unload a list of specified containers 19223 */ 19224 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19225 // Just unmount all valid containers. 19226 for (AsecInstallArgs arg : cidArgs) { 19227 synchronized (mInstallLock) { 19228 arg.doPostDeleteLI(false); 19229 } 19230 } 19231 } 19232 19233 /* 19234 * Unload packages mounted on external media. This involves deleting package 19235 * data from internal structures, sending broadcasts about disabled packages, 19236 * gc'ing to free up references, unmounting all secure containers 19237 * corresponding to packages on external media, and posting a 19238 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19239 * that we always have to post this message if status has been requested no 19240 * matter what. 19241 */ 19242 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19243 final boolean reportStatus) { 19244 if (DEBUG_SD_INSTALL) 19245 Log.i(TAG, "unloading media packages"); 19246 ArrayList<String> pkgList = new ArrayList<String>(); 19247 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19248 final Set<AsecInstallArgs> keys = processCids.keySet(); 19249 for (AsecInstallArgs args : keys) { 19250 String pkgName = args.getPackageName(); 19251 if (DEBUG_SD_INSTALL) 19252 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19253 // Delete package internally 19254 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19255 synchronized (mInstallLock) { 19256 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19257 final boolean res; 19258 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19259 "unloadMediaPackages")) { 19260 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19261 null); 19262 } 19263 if (res) { 19264 pkgList.add(pkgName); 19265 } else { 19266 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19267 failedList.add(args); 19268 } 19269 } 19270 } 19271 19272 // reader 19273 synchronized (mPackages) { 19274 // We didn't update the settings after removing each package; 19275 // write them now for all packages. 19276 mSettings.writeLPr(); 19277 } 19278 19279 // We have to absolutely send UPDATED_MEDIA_STATUS only 19280 // after confirming that all the receivers processed the ordered 19281 // broadcast when packages get disabled, force a gc to clean things up. 19282 // and unload all the containers. 19283 if (pkgList.size() > 0) { 19284 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19285 new IIntentReceiver.Stub() { 19286 public void performReceive(Intent intent, int resultCode, String data, 19287 Bundle extras, boolean ordered, boolean sticky, 19288 int sendingUser) throws RemoteException { 19289 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19290 reportStatus ? 1 : 0, 1, keys); 19291 mHandler.sendMessage(msg); 19292 } 19293 }); 19294 } else { 19295 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19296 keys); 19297 mHandler.sendMessage(msg); 19298 } 19299 } 19300 19301 private void loadPrivatePackages(final VolumeInfo vol) { 19302 mHandler.post(new Runnable() { 19303 @Override 19304 public void run() { 19305 loadPrivatePackagesInner(vol); 19306 } 19307 }); 19308 } 19309 19310 private void loadPrivatePackagesInner(VolumeInfo vol) { 19311 final String volumeUuid = vol.fsUuid; 19312 if (TextUtils.isEmpty(volumeUuid)) { 19313 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19314 return; 19315 } 19316 19317 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19318 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19319 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19320 19321 final VersionInfo ver; 19322 final List<PackageSetting> packages; 19323 synchronized (mPackages) { 19324 ver = mSettings.findOrCreateVersion(volumeUuid); 19325 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19326 } 19327 19328 for (PackageSetting ps : packages) { 19329 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19330 synchronized (mInstallLock) { 19331 final PackageParser.Package pkg; 19332 try { 19333 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19334 loaded.add(pkg.applicationInfo); 19335 19336 } catch (PackageManagerException e) { 19337 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19338 } 19339 19340 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19341 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19342 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19343 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19344 } 19345 } 19346 } 19347 19348 // Reconcile app data for all started/unlocked users 19349 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19350 final UserManager um = mContext.getSystemService(UserManager.class); 19351 UserManagerInternal umInternal = getUserManagerInternal(); 19352 for (UserInfo user : um.getUsers()) { 19353 final int flags; 19354 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19355 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19356 } else if (umInternal.isUserRunning(user.id)) { 19357 flags = StorageManager.FLAG_STORAGE_DE; 19358 } else { 19359 continue; 19360 } 19361 19362 try { 19363 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19364 synchronized (mInstallLock) { 19365 reconcileAppsDataLI(volumeUuid, user.id, flags); 19366 } 19367 } catch (IllegalStateException e) { 19368 // Device was probably ejected, and we'll process that event momentarily 19369 Slog.w(TAG, "Failed to prepare storage: " + e); 19370 } 19371 } 19372 19373 synchronized (mPackages) { 19374 int updateFlags = UPDATE_PERMISSIONS_ALL; 19375 if (ver.sdkVersion != mSdkVersion) { 19376 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19377 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19378 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19379 } 19380 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19381 19382 // Yay, everything is now upgraded 19383 ver.forceCurrent(); 19384 19385 mSettings.writeLPr(); 19386 } 19387 19388 for (PackageFreezer freezer : freezers) { 19389 freezer.close(); 19390 } 19391 19392 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19393 sendResourcesChangedBroadcast(true, false, loaded, null); 19394 } 19395 19396 private void unloadPrivatePackages(final VolumeInfo vol) { 19397 mHandler.post(new Runnable() { 19398 @Override 19399 public void run() { 19400 unloadPrivatePackagesInner(vol); 19401 } 19402 }); 19403 } 19404 19405 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19406 final String volumeUuid = vol.fsUuid; 19407 if (TextUtils.isEmpty(volumeUuid)) { 19408 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19409 return; 19410 } 19411 19412 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19413 synchronized (mInstallLock) { 19414 synchronized (mPackages) { 19415 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19416 for (PackageSetting ps : packages) { 19417 if (ps.pkg == null) continue; 19418 19419 final ApplicationInfo info = ps.pkg.applicationInfo; 19420 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19421 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19422 19423 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19424 "unloadPrivatePackagesInner")) { 19425 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19426 false, null)) { 19427 unloaded.add(info); 19428 } else { 19429 Slog.w(TAG, "Failed to unload " + ps.codePath); 19430 } 19431 } 19432 19433 // Try very hard to release any references to this package 19434 // so we don't risk the system server being killed due to 19435 // open FDs 19436 AttributeCache.instance().removePackage(ps.name); 19437 } 19438 19439 mSettings.writeLPr(); 19440 } 19441 } 19442 19443 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19444 sendResourcesChangedBroadcast(false, false, unloaded, null); 19445 19446 // Try very hard to release any references to this path so we don't risk 19447 // the system server being killed due to open FDs 19448 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19449 19450 for (int i = 0; i < 3; i++) { 19451 System.gc(); 19452 System.runFinalization(); 19453 } 19454 } 19455 19456 /** 19457 * Prepare storage areas for given user on all mounted devices. 19458 */ 19459 void prepareUserData(int userId, int userSerial, int flags) { 19460 synchronized (mInstallLock) { 19461 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19462 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19463 final String volumeUuid = vol.getFsUuid(); 19464 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19465 } 19466 } 19467 } 19468 19469 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19470 boolean allowRecover) { 19471 // Prepare storage and verify that serial numbers are consistent; if 19472 // there's a mismatch we need to destroy to avoid leaking data 19473 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19474 try { 19475 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19476 19477 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19478 UserManagerService.enforceSerialNumber( 19479 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19480 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19481 UserManagerService.enforceSerialNumber( 19482 Environment.getDataSystemDeDirectory(userId), userSerial); 19483 } 19484 } 19485 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19486 UserManagerService.enforceSerialNumber( 19487 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19488 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19489 UserManagerService.enforceSerialNumber( 19490 Environment.getDataSystemCeDirectory(userId), userSerial); 19491 } 19492 } 19493 19494 synchronized (mInstallLock) { 19495 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19496 } 19497 } catch (Exception e) { 19498 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19499 + " because we failed to prepare: " + e); 19500 destroyUserDataLI(volumeUuid, userId, 19501 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19502 19503 if (allowRecover) { 19504 // Try one last time; if we fail again we're really in trouble 19505 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19506 } 19507 } 19508 } 19509 19510 /** 19511 * Destroy storage areas for given user on all mounted devices. 19512 */ 19513 void destroyUserData(int userId, int flags) { 19514 synchronized (mInstallLock) { 19515 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19516 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19517 final String volumeUuid = vol.getFsUuid(); 19518 destroyUserDataLI(volumeUuid, userId, flags); 19519 } 19520 } 19521 } 19522 19523 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19524 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19525 try { 19526 // Clean up app data, profile data, and media data 19527 mInstaller.destroyUserData(volumeUuid, userId, flags); 19528 19529 // Clean up system data 19530 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19531 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19532 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19533 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19534 } 19535 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19536 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19537 } 19538 } 19539 19540 // Data with special labels is now gone, so finish the job 19541 storage.destroyUserStorage(volumeUuid, userId, flags); 19542 19543 } catch (Exception e) { 19544 logCriticalInfo(Log.WARN, 19545 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19546 } 19547 } 19548 19549 /** 19550 * Examine all users present on given mounted volume, and destroy data 19551 * belonging to users that are no longer valid, or whose user ID has been 19552 * recycled. 19553 */ 19554 private void reconcileUsers(String volumeUuid) { 19555 final List<File> files = new ArrayList<>(); 19556 Collections.addAll(files, FileUtils 19557 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19558 Collections.addAll(files, FileUtils 19559 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19560 Collections.addAll(files, FileUtils 19561 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19562 Collections.addAll(files, FileUtils 19563 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19564 for (File file : files) { 19565 if (!file.isDirectory()) continue; 19566 19567 final int userId; 19568 final UserInfo info; 19569 try { 19570 userId = Integer.parseInt(file.getName()); 19571 info = sUserManager.getUserInfo(userId); 19572 } catch (NumberFormatException e) { 19573 Slog.w(TAG, "Invalid user directory " + file); 19574 continue; 19575 } 19576 19577 boolean destroyUser = false; 19578 if (info == null) { 19579 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19580 + " because no matching user was found"); 19581 destroyUser = true; 19582 } else if (!mOnlyCore) { 19583 try { 19584 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19585 } catch (IOException e) { 19586 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19587 + " because we failed to enforce serial number: " + e); 19588 destroyUser = true; 19589 } 19590 } 19591 19592 if (destroyUser) { 19593 synchronized (mInstallLock) { 19594 destroyUserDataLI(volumeUuid, userId, 19595 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19596 } 19597 } 19598 } 19599 } 19600 19601 private void assertPackageKnown(String volumeUuid, String packageName) 19602 throws PackageManagerException { 19603 synchronized (mPackages) { 19604 final PackageSetting ps = mSettings.mPackages.get(packageName); 19605 if (ps == null) { 19606 throw new PackageManagerException("Package " + packageName + " is unknown"); 19607 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19608 throw new PackageManagerException( 19609 "Package " + packageName + " found on unknown volume " + volumeUuid 19610 + "; expected volume " + ps.volumeUuid); 19611 } 19612 } 19613 } 19614 19615 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19616 throws PackageManagerException { 19617 synchronized (mPackages) { 19618 final PackageSetting ps = mSettings.mPackages.get(packageName); 19619 if (ps == null) { 19620 throw new PackageManagerException("Package " + packageName + " is unknown"); 19621 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19622 throw new PackageManagerException( 19623 "Package " + packageName + " found on unknown volume " + volumeUuid 19624 + "; expected volume " + ps.volumeUuid); 19625 } else if (!ps.getInstalled(userId)) { 19626 throw new PackageManagerException( 19627 "Package " + packageName + " not installed for user " + userId); 19628 } 19629 } 19630 } 19631 19632 /** 19633 * Examine all apps present on given mounted volume, and destroy apps that 19634 * aren't expected, either due to uninstallation or reinstallation on 19635 * another volume. 19636 */ 19637 private void reconcileApps(String volumeUuid) { 19638 final File[] files = FileUtils 19639 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19640 for (File file : files) { 19641 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19642 && !PackageInstallerService.isStageName(file.getName()); 19643 if (!isPackage) { 19644 // Ignore entries which are not packages 19645 continue; 19646 } 19647 19648 try { 19649 final PackageLite pkg = PackageParser.parsePackageLite(file, 19650 PackageParser.PARSE_MUST_BE_APK); 19651 assertPackageKnown(volumeUuid, pkg.packageName); 19652 19653 } catch (PackageParserException | PackageManagerException e) { 19654 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19655 synchronized (mInstallLock) { 19656 removeCodePathLI(file); 19657 } 19658 } 19659 } 19660 } 19661 19662 /** 19663 * Reconcile all app data for the given user. 19664 * <p> 19665 * Verifies that directories exist and that ownership and labeling is 19666 * correct for all installed apps on all mounted volumes. 19667 */ 19668 void reconcileAppsData(int userId, int flags) { 19669 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19670 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19671 final String volumeUuid = vol.getFsUuid(); 19672 synchronized (mInstallLock) { 19673 reconcileAppsDataLI(volumeUuid, userId, flags); 19674 } 19675 } 19676 } 19677 19678 /** 19679 * Reconcile all app data on given mounted volume. 19680 * <p> 19681 * Destroys app data that isn't expected, either due to uninstallation or 19682 * reinstallation on another volume. 19683 * <p> 19684 * Verifies that directories exist and that ownership and labeling is 19685 * correct for all installed apps. 19686 */ 19687 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19688 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19689 + Integer.toHexString(flags)); 19690 19691 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19692 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19693 19694 boolean restoreconNeeded = false; 19695 19696 // First look for stale data that doesn't belong, and check if things 19697 // have changed since we did our last restorecon 19698 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19699 if (StorageManager.isFileEncryptedNativeOrEmulated() 19700 && !StorageManager.isUserKeyUnlocked(userId)) { 19701 throw new RuntimeException( 19702 "Yikes, someone asked us to reconcile CE storage while " + userId 19703 + " was still locked; this would have caused massive data loss!"); 19704 } 19705 19706 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19707 19708 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19709 for (File file : files) { 19710 final String packageName = file.getName(); 19711 try { 19712 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19713 } catch (PackageManagerException e) { 19714 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19715 try { 19716 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19717 StorageManager.FLAG_STORAGE_CE, 0); 19718 } catch (InstallerException e2) { 19719 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19720 } 19721 } 19722 } 19723 } 19724 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19725 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19726 19727 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19728 for (File file : files) { 19729 final String packageName = file.getName(); 19730 try { 19731 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19732 } catch (PackageManagerException e) { 19733 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19734 try { 19735 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19736 StorageManager.FLAG_STORAGE_DE, 0); 19737 } catch (InstallerException e2) { 19738 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19739 } 19740 } 19741 } 19742 } 19743 19744 // Ensure that data directories are ready to roll for all packages 19745 // installed for this volume and user 19746 final List<PackageSetting> packages; 19747 synchronized (mPackages) { 19748 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19749 } 19750 int preparedCount = 0; 19751 for (PackageSetting ps : packages) { 19752 final String packageName = ps.name; 19753 if (ps.pkg == null) { 19754 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19755 // TODO: might be due to legacy ASEC apps; we should circle back 19756 // and reconcile again once they're scanned 19757 continue; 19758 } 19759 19760 if (ps.getInstalled(userId)) { 19761 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19762 19763 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19764 // We may have just shuffled around app data directories, so 19765 // prepare them one more time 19766 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19767 } 19768 19769 preparedCount++; 19770 } 19771 } 19772 19773 if (restoreconNeeded) { 19774 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19775 SELinuxMMAC.setRestoreconDone(ceDir); 19776 } 19777 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19778 SELinuxMMAC.setRestoreconDone(deDir); 19779 } 19780 } 19781 19782 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19783 + " packages; restoreconNeeded was " + restoreconNeeded); 19784 } 19785 19786 /** 19787 * Prepare app data for the given app just after it was installed or 19788 * upgraded. This method carefully only touches users that it's installed 19789 * for, and it forces a restorecon to handle any seinfo changes. 19790 * <p> 19791 * Verifies that directories exist and that ownership and labeling is 19792 * correct for all installed apps. If there is an ownership mismatch, it 19793 * will try recovering system apps by wiping data; third-party app data is 19794 * left intact. 19795 * <p> 19796 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19797 */ 19798 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19799 final PackageSetting ps; 19800 synchronized (mPackages) { 19801 ps = mSettings.mPackages.get(pkg.packageName); 19802 mSettings.writeKernelMappingLPr(ps); 19803 } 19804 19805 final UserManager um = mContext.getSystemService(UserManager.class); 19806 UserManagerInternal umInternal = getUserManagerInternal(); 19807 for (UserInfo user : um.getUsers()) { 19808 final int flags; 19809 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19810 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19811 } else if (umInternal.isUserRunning(user.id)) { 19812 flags = StorageManager.FLAG_STORAGE_DE; 19813 } else { 19814 continue; 19815 } 19816 19817 if (ps.getInstalled(user.id)) { 19818 // Whenever an app changes, force a restorecon of its data 19819 // TODO: when user data is locked, mark that we're still dirty 19820 prepareAppDataLIF(pkg, user.id, flags, true); 19821 } 19822 } 19823 } 19824 19825 /** 19826 * Prepare app data for the given app. 19827 * <p> 19828 * Verifies that directories exist and that ownership and labeling is 19829 * correct for all installed apps. If there is an ownership mismatch, this 19830 * will try recovering system apps by wiping data; third-party app data is 19831 * left intact. 19832 */ 19833 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19834 boolean restoreconNeeded) { 19835 if (pkg == null) { 19836 Slog.wtf(TAG, "Package was null!", new Throwable()); 19837 return; 19838 } 19839 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19840 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19841 for (int i = 0; i < childCount; i++) { 19842 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19843 } 19844 } 19845 19846 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19847 boolean restoreconNeeded) { 19848 if (DEBUG_APP_DATA) { 19849 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19850 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19851 } 19852 19853 final String volumeUuid = pkg.volumeUuid; 19854 final String packageName = pkg.packageName; 19855 final ApplicationInfo app = pkg.applicationInfo; 19856 final int appId = UserHandle.getAppId(app.uid); 19857 19858 Preconditions.checkNotNull(app.seinfo); 19859 19860 try { 19861 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19862 appId, app.seinfo, app.targetSdkVersion); 19863 } catch (InstallerException e) { 19864 if (app.isSystemApp()) { 19865 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19866 + ", but trying to recover: " + e); 19867 destroyAppDataLeafLIF(pkg, userId, flags); 19868 try { 19869 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19870 appId, app.seinfo, app.targetSdkVersion); 19871 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19872 } catch (InstallerException e2) { 19873 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19874 } 19875 } else { 19876 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19877 } 19878 } 19879 19880 if (restoreconNeeded) { 19881 try { 19882 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19883 app.seinfo); 19884 } catch (InstallerException e) { 19885 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19886 } 19887 } 19888 19889 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19890 try { 19891 // CE storage is unlocked right now, so read out the inode and 19892 // remember for use later when it's locked 19893 // TODO: mark this structure as dirty so we persist it! 19894 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19895 StorageManager.FLAG_STORAGE_CE); 19896 synchronized (mPackages) { 19897 final PackageSetting ps = mSettings.mPackages.get(packageName); 19898 if (ps != null) { 19899 ps.setCeDataInode(ceDataInode, userId); 19900 } 19901 } 19902 } catch (InstallerException e) { 19903 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19904 } 19905 } 19906 19907 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19908 } 19909 19910 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19911 if (pkg == null) { 19912 Slog.wtf(TAG, "Package was null!", new Throwable()); 19913 return; 19914 } 19915 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19916 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19917 for (int i = 0; i < childCount; i++) { 19918 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19919 } 19920 } 19921 19922 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19923 final String volumeUuid = pkg.volumeUuid; 19924 final String packageName = pkg.packageName; 19925 final ApplicationInfo app = pkg.applicationInfo; 19926 19927 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19928 // Create a native library symlink only if we have native libraries 19929 // and if the native libraries are 32 bit libraries. We do not provide 19930 // this symlink for 64 bit libraries. 19931 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19932 final String nativeLibPath = app.nativeLibraryDir; 19933 try { 19934 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19935 nativeLibPath, userId); 19936 } catch (InstallerException e) { 19937 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19938 } 19939 } 19940 } 19941 } 19942 19943 /** 19944 * For system apps on non-FBE devices, this method migrates any existing 19945 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19946 * requested by the app. 19947 */ 19948 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19949 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19950 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19951 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19952 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19953 try { 19954 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19955 storageTarget); 19956 } catch (InstallerException e) { 19957 logCriticalInfo(Log.WARN, 19958 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19959 } 19960 return true; 19961 } else { 19962 return false; 19963 } 19964 } 19965 19966 public PackageFreezer freezePackage(String packageName, String killReason) { 19967 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19968 } 19969 19970 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19971 return new PackageFreezer(packageName, userId, killReason); 19972 } 19973 19974 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19975 String killReason) { 19976 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19977 } 19978 19979 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19980 String killReason) { 19981 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19982 return new PackageFreezer(); 19983 } else { 19984 return freezePackage(packageName, userId, killReason); 19985 } 19986 } 19987 19988 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19989 String killReason) { 19990 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19991 } 19992 19993 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19994 String killReason) { 19995 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19996 return new PackageFreezer(); 19997 } else { 19998 return freezePackage(packageName, userId, killReason); 19999 } 20000 } 20001 20002 /** 20003 * Class that freezes and kills the given package upon creation, and 20004 * unfreezes it upon closing. This is typically used when doing surgery on 20005 * app code/data to prevent the app from running while you're working. 20006 */ 20007 private class PackageFreezer implements AutoCloseable { 20008 private final String mPackageName; 20009 private final PackageFreezer[] mChildren; 20010 20011 private final boolean mWeFroze; 20012 20013 private final AtomicBoolean mClosed = new AtomicBoolean(); 20014 private final CloseGuard mCloseGuard = CloseGuard.get(); 20015 20016 /** 20017 * Create and return a stub freezer that doesn't actually do anything, 20018 * typically used when someone requested 20019 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20020 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20021 */ 20022 public PackageFreezer() { 20023 mPackageName = null; 20024 mChildren = null; 20025 mWeFroze = false; 20026 mCloseGuard.open("close"); 20027 } 20028 20029 public PackageFreezer(String packageName, int userId, String killReason) { 20030 synchronized (mPackages) { 20031 mPackageName = packageName; 20032 mWeFroze = mFrozenPackages.add(mPackageName); 20033 20034 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20035 if (ps != null) { 20036 killApplication(ps.name, ps.appId, userId, killReason); 20037 } 20038 20039 final PackageParser.Package p = mPackages.get(packageName); 20040 if (p != null && p.childPackages != null) { 20041 final int N = p.childPackages.size(); 20042 mChildren = new PackageFreezer[N]; 20043 for (int i = 0; i < N; i++) { 20044 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20045 userId, killReason); 20046 } 20047 } else { 20048 mChildren = null; 20049 } 20050 } 20051 mCloseGuard.open("close"); 20052 } 20053 20054 @Override 20055 protected void finalize() throws Throwable { 20056 try { 20057 mCloseGuard.warnIfOpen(); 20058 close(); 20059 } finally { 20060 super.finalize(); 20061 } 20062 } 20063 20064 @Override 20065 public void close() { 20066 mCloseGuard.close(); 20067 if (mClosed.compareAndSet(false, true)) { 20068 synchronized (mPackages) { 20069 if (mWeFroze) { 20070 mFrozenPackages.remove(mPackageName); 20071 } 20072 20073 if (mChildren != null) { 20074 for (PackageFreezer freezer : mChildren) { 20075 freezer.close(); 20076 } 20077 } 20078 } 20079 } 20080 } 20081 } 20082 20083 /** 20084 * Verify that given package is currently frozen. 20085 */ 20086 private void checkPackageFrozen(String packageName) { 20087 synchronized (mPackages) { 20088 if (!mFrozenPackages.contains(packageName)) { 20089 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20090 } 20091 } 20092 } 20093 20094 @Override 20095 public int movePackage(final String packageName, final String volumeUuid) { 20096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20097 20098 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20099 final int moveId = mNextMoveId.getAndIncrement(); 20100 mHandler.post(new Runnable() { 20101 @Override 20102 public void run() { 20103 try { 20104 movePackageInternal(packageName, volumeUuid, moveId, user); 20105 } catch (PackageManagerException e) { 20106 Slog.w(TAG, "Failed to move " + packageName, e); 20107 mMoveCallbacks.notifyStatusChanged(moveId, 20108 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20109 } 20110 } 20111 }); 20112 return moveId; 20113 } 20114 20115 private void movePackageInternal(final String packageName, final String volumeUuid, 20116 final int moveId, UserHandle user) throws PackageManagerException { 20117 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20118 final PackageManager pm = mContext.getPackageManager(); 20119 20120 final boolean currentAsec; 20121 final String currentVolumeUuid; 20122 final File codeFile; 20123 final String installerPackageName; 20124 final String packageAbiOverride; 20125 final int appId; 20126 final String seinfo; 20127 final String label; 20128 final int targetSdkVersion; 20129 final PackageFreezer freezer; 20130 final int[] installedUserIds; 20131 20132 // reader 20133 synchronized (mPackages) { 20134 final PackageParser.Package pkg = mPackages.get(packageName); 20135 final PackageSetting ps = mSettings.mPackages.get(packageName); 20136 if (pkg == null || ps == null) { 20137 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20138 } 20139 20140 if (pkg.applicationInfo.isSystemApp()) { 20141 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20142 "Cannot move system application"); 20143 } 20144 20145 if (pkg.applicationInfo.isExternalAsec()) { 20146 currentAsec = true; 20147 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20148 } else if (pkg.applicationInfo.isForwardLocked()) { 20149 currentAsec = true; 20150 currentVolumeUuid = "forward_locked"; 20151 } else { 20152 currentAsec = false; 20153 currentVolumeUuid = ps.volumeUuid; 20154 20155 final File probe = new File(pkg.codePath); 20156 final File probeOat = new File(probe, "oat"); 20157 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20158 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20159 "Move only supported for modern cluster style installs"); 20160 } 20161 } 20162 20163 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20164 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20165 "Package already moved to " + volumeUuid); 20166 } 20167 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20168 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20169 "Device admin cannot be moved"); 20170 } 20171 20172 if (mFrozenPackages.contains(packageName)) { 20173 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20174 "Failed to move already frozen package"); 20175 } 20176 20177 codeFile = new File(pkg.codePath); 20178 installerPackageName = ps.installerPackageName; 20179 packageAbiOverride = ps.cpuAbiOverrideString; 20180 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20181 seinfo = pkg.applicationInfo.seinfo; 20182 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20183 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20184 freezer = freezePackage(packageName, "movePackageInternal"); 20185 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20186 } 20187 20188 final Bundle extras = new Bundle(); 20189 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20190 extras.putString(Intent.EXTRA_TITLE, label); 20191 mMoveCallbacks.notifyCreated(moveId, extras); 20192 20193 int installFlags; 20194 final boolean moveCompleteApp; 20195 final File measurePath; 20196 20197 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20198 installFlags = INSTALL_INTERNAL; 20199 moveCompleteApp = !currentAsec; 20200 measurePath = Environment.getDataAppDirectory(volumeUuid); 20201 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20202 installFlags = INSTALL_EXTERNAL; 20203 moveCompleteApp = false; 20204 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20205 } else { 20206 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20207 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20208 || !volume.isMountedWritable()) { 20209 freezer.close(); 20210 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20211 "Move location not mounted private volume"); 20212 } 20213 20214 Preconditions.checkState(!currentAsec); 20215 20216 installFlags = INSTALL_INTERNAL; 20217 moveCompleteApp = true; 20218 measurePath = Environment.getDataAppDirectory(volumeUuid); 20219 } 20220 20221 final PackageStats stats = new PackageStats(null, -1); 20222 synchronized (mInstaller) { 20223 for (int userId : installedUserIds) { 20224 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20225 freezer.close(); 20226 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20227 "Failed to measure package size"); 20228 } 20229 } 20230 } 20231 20232 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20233 + stats.dataSize); 20234 20235 final long startFreeBytes = measurePath.getFreeSpace(); 20236 final long sizeBytes; 20237 if (moveCompleteApp) { 20238 sizeBytes = stats.codeSize + stats.dataSize; 20239 } else { 20240 sizeBytes = stats.codeSize; 20241 } 20242 20243 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20244 freezer.close(); 20245 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20246 "Not enough free space to move"); 20247 } 20248 20249 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20250 20251 final CountDownLatch installedLatch = new CountDownLatch(1); 20252 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20253 @Override 20254 public void onUserActionRequired(Intent intent) throws RemoteException { 20255 throw new IllegalStateException(); 20256 } 20257 20258 @Override 20259 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20260 Bundle extras) throws RemoteException { 20261 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20262 + PackageManager.installStatusToString(returnCode, msg)); 20263 20264 installedLatch.countDown(); 20265 freezer.close(); 20266 20267 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20268 switch (status) { 20269 case PackageInstaller.STATUS_SUCCESS: 20270 mMoveCallbacks.notifyStatusChanged(moveId, 20271 PackageManager.MOVE_SUCCEEDED); 20272 break; 20273 case PackageInstaller.STATUS_FAILURE_STORAGE: 20274 mMoveCallbacks.notifyStatusChanged(moveId, 20275 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20276 break; 20277 default: 20278 mMoveCallbacks.notifyStatusChanged(moveId, 20279 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20280 break; 20281 } 20282 } 20283 }; 20284 20285 final MoveInfo move; 20286 if (moveCompleteApp) { 20287 // Kick off a thread to report progress estimates 20288 new Thread() { 20289 @Override 20290 public void run() { 20291 while (true) { 20292 try { 20293 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20294 break; 20295 } 20296 } catch (InterruptedException ignored) { 20297 } 20298 20299 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20300 final int progress = 10 + (int) MathUtils.constrain( 20301 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20302 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20303 } 20304 } 20305 }.start(); 20306 20307 final String dataAppName = codeFile.getName(); 20308 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20309 dataAppName, appId, seinfo, targetSdkVersion); 20310 } else { 20311 move = null; 20312 } 20313 20314 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20315 20316 final Message msg = mHandler.obtainMessage(INIT_COPY); 20317 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20318 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20319 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20320 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20321 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20322 msg.obj = params; 20323 20324 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20325 System.identityHashCode(msg.obj)); 20326 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20327 System.identityHashCode(msg.obj)); 20328 20329 mHandler.sendMessage(msg); 20330 } 20331 20332 @Override 20333 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20335 20336 final int realMoveId = mNextMoveId.getAndIncrement(); 20337 final Bundle extras = new Bundle(); 20338 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20339 mMoveCallbacks.notifyCreated(realMoveId, extras); 20340 20341 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20342 @Override 20343 public void onCreated(int moveId, Bundle extras) { 20344 // Ignored 20345 } 20346 20347 @Override 20348 public void onStatusChanged(int moveId, int status, long estMillis) { 20349 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20350 } 20351 }; 20352 20353 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20354 storage.setPrimaryStorageUuid(volumeUuid, callback); 20355 return realMoveId; 20356 } 20357 20358 @Override 20359 public int getMoveStatus(int moveId) { 20360 mContext.enforceCallingOrSelfPermission( 20361 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20362 return mMoveCallbacks.mLastStatus.get(moveId); 20363 } 20364 20365 @Override 20366 public void registerMoveCallback(IPackageMoveObserver callback) { 20367 mContext.enforceCallingOrSelfPermission( 20368 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20369 mMoveCallbacks.register(callback); 20370 } 20371 20372 @Override 20373 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20374 mContext.enforceCallingOrSelfPermission( 20375 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20376 mMoveCallbacks.unregister(callback); 20377 } 20378 20379 @Override 20380 public boolean setInstallLocation(int loc) { 20381 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20382 null); 20383 if (getInstallLocation() == loc) { 20384 return true; 20385 } 20386 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20387 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20388 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20389 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20390 return true; 20391 } 20392 return false; 20393 } 20394 20395 @Override 20396 public int getInstallLocation() { 20397 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20398 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20399 PackageHelper.APP_INSTALL_AUTO); 20400 } 20401 20402 /** Called by UserManagerService */ 20403 void cleanUpUser(UserManagerService userManager, int userHandle) { 20404 synchronized (mPackages) { 20405 mDirtyUsers.remove(userHandle); 20406 mUserNeedsBadging.delete(userHandle); 20407 mSettings.removeUserLPw(userHandle); 20408 mPendingBroadcasts.remove(userHandle); 20409 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20410 removeUnusedPackagesLPw(userManager, userHandle); 20411 } 20412 } 20413 20414 /** 20415 * We're removing userHandle and would like to remove any downloaded packages 20416 * that are no longer in use by any other user. 20417 * @param userHandle the user being removed 20418 */ 20419 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20420 final boolean DEBUG_CLEAN_APKS = false; 20421 int [] users = userManager.getUserIds(); 20422 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20423 while (psit.hasNext()) { 20424 PackageSetting ps = psit.next(); 20425 if (ps.pkg == null) { 20426 continue; 20427 } 20428 final String packageName = ps.pkg.packageName; 20429 // Skip over if system app 20430 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20431 continue; 20432 } 20433 if (DEBUG_CLEAN_APKS) { 20434 Slog.i(TAG, "Checking package " + packageName); 20435 } 20436 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20437 if (keep) { 20438 if (DEBUG_CLEAN_APKS) { 20439 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20440 } 20441 } else { 20442 for (int i = 0; i < users.length; i++) { 20443 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20444 keep = true; 20445 if (DEBUG_CLEAN_APKS) { 20446 Slog.i(TAG, " Keeping package " + packageName + " for user " 20447 + users[i]); 20448 } 20449 break; 20450 } 20451 } 20452 } 20453 if (!keep) { 20454 if (DEBUG_CLEAN_APKS) { 20455 Slog.i(TAG, " Removing package " + packageName); 20456 } 20457 mHandler.post(new Runnable() { 20458 public void run() { 20459 deletePackageX(packageName, userHandle, 0); 20460 } //end run 20461 }); 20462 } 20463 } 20464 } 20465 20466 /** Called by UserManagerService */ 20467 void createNewUser(int userId) { 20468 synchronized (mInstallLock) { 20469 mSettings.createNewUserLI(this, mInstaller, userId); 20470 } 20471 synchronized (mPackages) { 20472 scheduleWritePackageRestrictionsLocked(userId); 20473 scheduleWritePackageListLocked(userId); 20474 applyFactoryDefaultBrowserLPw(userId); 20475 primeDomainVerificationsLPw(userId); 20476 } 20477 } 20478 20479 void onNewUserCreated(final int userId) { 20480 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20481 // If permission review for legacy apps is required, we represent 20482 // dagerous permissions for such apps as always granted runtime 20483 // permissions to keep per user flag state whether review is needed. 20484 // Hence, if a new user is added we have to propagate dangerous 20485 // permission grants for these legacy apps. 20486 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20487 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20488 | UPDATE_PERMISSIONS_REPLACE_ALL); 20489 } 20490 } 20491 20492 @Override 20493 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20494 mContext.enforceCallingOrSelfPermission( 20495 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20496 "Only package verification agents can read the verifier device identity"); 20497 20498 synchronized (mPackages) { 20499 return mSettings.getVerifierDeviceIdentityLPw(); 20500 } 20501 } 20502 20503 @Override 20504 public void setPermissionEnforced(String permission, boolean enforced) { 20505 // TODO: Now that we no longer change GID for storage, this should to away. 20506 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20507 "setPermissionEnforced"); 20508 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20509 synchronized (mPackages) { 20510 if (mSettings.mReadExternalStorageEnforced == null 20511 || mSettings.mReadExternalStorageEnforced != enforced) { 20512 mSettings.mReadExternalStorageEnforced = enforced; 20513 mSettings.writeLPr(); 20514 } 20515 } 20516 // kill any non-foreground processes so we restart them and 20517 // grant/revoke the GID. 20518 final IActivityManager am = ActivityManagerNative.getDefault(); 20519 if (am != null) { 20520 final long token = Binder.clearCallingIdentity(); 20521 try { 20522 am.killProcessesBelowForeground("setPermissionEnforcement"); 20523 } catch (RemoteException e) { 20524 } finally { 20525 Binder.restoreCallingIdentity(token); 20526 } 20527 } 20528 } else { 20529 throw new IllegalArgumentException("No selective enforcement for " + permission); 20530 } 20531 } 20532 20533 @Override 20534 @Deprecated 20535 public boolean isPermissionEnforced(String permission) { 20536 return true; 20537 } 20538 20539 @Override 20540 public boolean isStorageLow() { 20541 final long token = Binder.clearCallingIdentity(); 20542 try { 20543 final DeviceStorageMonitorInternal 20544 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20545 if (dsm != null) { 20546 return dsm.isMemoryLow(); 20547 } else { 20548 return false; 20549 } 20550 } finally { 20551 Binder.restoreCallingIdentity(token); 20552 } 20553 } 20554 20555 @Override 20556 public IPackageInstaller getPackageInstaller() { 20557 return mInstallerService; 20558 } 20559 20560 private boolean userNeedsBadging(int userId) { 20561 int index = mUserNeedsBadging.indexOfKey(userId); 20562 if (index < 0) { 20563 final UserInfo userInfo; 20564 final long token = Binder.clearCallingIdentity(); 20565 try { 20566 userInfo = sUserManager.getUserInfo(userId); 20567 } finally { 20568 Binder.restoreCallingIdentity(token); 20569 } 20570 final boolean b; 20571 if (userInfo != null && userInfo.isManagedProfile()) { 20572 b = true; 20573 } else { 20574 b = false; 20575 } 20576 mUserNeedsBadging.put(userId, b); 20577 return b; 20578 } 20579 return mUserNeedsBadging.valueAt(index); 20580 } 20581 20582 @Override 20583 public KeySet getKeySetByAlias(String packageName, String alias) { 20584 if (packageName == null || alias == null) { 20585 return null; 20586 } 20587 synchronized(mPackages) { 20588 final PackageParser.Package pkg = mPackages.get(packageName); 20589 if (pkg == null) { 20590 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20591 throw new IllegalArgumentException("Unknown package: " + packageName); 20592 } 20593 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20594 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20595 } 20596 } 20597 20598 @Override 20599 public KeySet getSigningKeySet(String packageName) { 20600 if (packageName == null) { 20601 return null; 20602 } 20603 synchronized(mPackages) { 20604 final PackageParser.Package pkg = mPackages.get(packageName); 20605 if (pkg == null) { 20606 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20607 throw new IllegalArgumentException("Unknown package: " + packageName); 20608 } 20609 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20610 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20611 throw new SecurityException("May not access signing KeySet of other apps."); 20612 } 20613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20614 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20615 } 20616 } 20617 20618 @Override 20619 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20620 if (packageName == null || ks == null) { 20621 return false; 20622 } 20623 synchronized(mPackages) { 20624 final PackageParser.Package pkg = mPackages.get(packageName); 20625 if (pkg == null) { 20626 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20627 throw new IllegalArgumentException("Unknown package: " + packageName); 20628 } 20629 IBinder ksh = ks.getToken(); 20630 if (ksh instanceof KeySetHandle) { 20631 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20632 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20633 } 20634 return false; 20635 } 20636 } 20637 20638 @Override 20639 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20640 if (packageName == null || ks == null) { 20641 return false; 20642 } 20643 synchronized(mPackages) { 20644 final PackageParser.Package pkg = mPackages.get(packageName); 20645 if (pkg == null) { 20646 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20647 throw new IllegalArgumentException("Unknown package: " + packageName); 20648 } 20649 IBinder ksh = ks.getToken(); 20650 if (ksh instanceof KeySetHandle) { 20651 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20652 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20653 } 20654 return false; 20655 } 20656 } 20657 20658 private void deletePackageIfUnusedLPr(final String packageName) { 20659 PackageSetting ps = mSettings.mPackages.get(packageName); 20660 if (ps == null) { 20661 return; 20662 } 20663 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20664 // TODO Implement atomic delete if package is unused 20665 // It is currently possible that the package will be deleted even if it is installed 20666 // after this method returns. 20667 mHandler.post(new Runnable() { 20668 public void run() { 20669 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20670 } 20671 }); 20672 } 20673 } 20674 20675 /** 20676 * Check and throw if the given before/after packages would be considered a 20677 * downgrade. 20678 */ 20679 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20680 throws PackageManagerException { 20681 if (after.versionCode < before.mVersionCode) { 20682 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20683 "Update version code " + after.versionCode + " is older than current " 20684 + before.mVersionCode); 20685 } else if (after.versionCode == before.mVersionCode) { 20686 if (after.baseRevisionCode < before.baseRevisionCode) { 20687 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20688 "Update base revision code " + after.baseRevisionCode 20689 + " is older than current " + before.baseRevisionCode); 20690 } 20691 20692 if (!ArrayUtils.isEmpty(after.splitNames)) { 20693 for (int i = 0; i < after.splitNames.length; i++) { 20694 final String splitName = after.splitNames[i]; 20695 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20696 if (j != -1) { 20697 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20698 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20699 "Update split " + splitName + " revision code " 20700 + after.splitRevisionCodes[i] + " is older than current " 20701 + before.splitRevisionCodes[j]); 20702 } 20703 } 20704 } 20705 } 20706 } 20707 } 20708 20709 private static class MoveCallbacks extends Handler { 20710 private static final int MSG_CREATED = 1; 20711 private static final int MSG_STATUS_CHANGED = 2; 20712 20713 private final RemoteCallbackList<IPackageMoveObserver> 20714 mCallbacks = new RemoteCallbackList<>(); 20715 20716 private final SparseIntArray mLastStatus = new SparseIntArray(); 20717 20718 public MoveCallbacks(Looper looper) { 20719 super(looper); 20720 } 20721 20722 public void register(IPackageMoveObserver callback) { 20723 mCallbacks.register(callback); 20724 } 20725 20726 public void unregister(IPackageMoveObserver callback) { 20727 mCallbacks.unregister(callback); 20728 } 20729 20730 @Override 20731 public void handleMessage(Message msg) { 20732 final SomeArgs args = (SomeArgs) msg.obj; 20733 final int n = mCallbacks.beginBroadcast(); 20734 for (int i = 0; i < n; i++) { 20735 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20736 try { 20737 invokeCallback(callback, msg.what, args); 20738 } catch (RemoteException ignored) { 20739 } 20740 } 20741 mCallbacks.finishBroadcast(); 20742 args.recycle(); 20743 } 20744 20745 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20746 throws RemoteException { 20747 switch (what) { 20748 case MSG_CREATED: { 20749 callback.onCreated(args.argi1, (Bundle) args.arg2); 20750 break; 20751 } 20752 case MSG_STATUS_CHANGED: { 20753 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20754 break; 20755 } 20756 } 20757 } 20758 20759 private void notifyCreated(int moveId, Bundle extras) { 20760 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20761 20762 final SomeArgs args = SomeArgs.obtain(); 20763 args.argi1 = moveId; 20764 args.arg2 = extras; 20765 obtainMessage(MSG_CREATED, args).sendToTarget(); 20766 } 20767 20768 private void notifyStatusChanged(int moveId, int status) { 20769 notifyStatusChanged(moveId, status, -1); 20770 } 20771 20772 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20773 Slog.v(TAG, "Move " + moveId + " status " + status); 20774 20775 final SomeArgs args = SomeArgs.obtain(); 20776 args.argi1 = moveId; 20777 args.argi2 = status; 20778 args.arg3 = estMillis; 20779 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20780 20781 synchronized (mLastStatus) { 20782 mLastStatus.put(moveId, status); 20783 } 20784 } 20785 } 20786 20787 private final static class OnPermissionChangeListeners extends Handler { 20788 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20789 20790 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20791 new RemoteCallbackList<>(); 20792 20793 public OnPermissionChangeListeners(Looper looper) { 20794 super(looper); 20795 } 20796 20797 @Override 20798 public void handleMessage(Message msg) { 20799 switch (msg.what) { 20800 case MSG_ON_PERMISSIONS_CHANGED: { 20801 final int uid = msg.arg1; 20802 handleOnPermissionsChanged(uid); 20803 } break; 20804 } 20805 } 20806 20807 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20808 mPermissionListeners.register(listener); 20809 20810 } 20811 20812 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20813 mPermissionListeners.unregister(listener); 20814 } 20815 20816 public void onPermissionsChanged(int uid) { 20817 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20818 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20819 } 20820 } 20821 20822 private void handleOnPermissionsChanged(int uid) { 20823 final int count = mPermissionListeners.beginBroadcast(); 20824 try { 20825 for (int i = 0; i < count; i++) { 20826 IOnPermissionsChangeListener callback = mPermissionListeners 20827 .getBroadcastItem(i); 20828 try { 20829 callback.onPermissionsChanged(uid); 20830 } catch (RemoteException e) { 20831 Log.e(TAG, "Permission listener is dead", e); 20832 } 20833 } 20834 } finally { 20835 mPermissionListeners.finishBroadcast(); 20836 } 20837 } 20838 } 20839 20840 private class PackageManagerInternalImpl extends PackageManagerInternal { 20841 @Override 20842 public void setLocationPackagesProvider(PackagesProvider provider) { 20843 synchronized (mPackages) { 20844 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20845 } 20846 } 20847 20848 @Override 20849 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20850 synchronized (mPackages) { 20851 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20852 } 20853 } 20854 20855 @Override 20856 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20857 synchronized (mPackages) { 20858 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20859 } 20860 } 20861 20862 @Override 20863 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20864 synchronized (mPackages) { 20865 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20866 } 20867 } 20868 20869 @Override 20870 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20871 synchronized (mPackages) { 20872 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20873 } 20874 } 20875 20876 @Override 20877 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20878 synchronized (mPackages) { 20879 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20880 } 20881 } 20882 20883 @Override 20884 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20885 synchronized (mPackages) { 20886 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20887 packageName, userId); 20888 } 20889 } 20890 20891 @Override 20892 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20893 synchronized (mPackages) { 20894 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20895 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20896 packageName, userId); 20897 } 20898 } 20899 20900 @Override 20901 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20902 synchronized (mPackages) { 20903 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20904 packageName, userId); 20905 } 20906 } 20907 20908 @Override 20909 public void setKeepUninstalledPackages(final List<String> packageList) { 20910 Preconditions.checkNotNull(packageList); 20911 List<String> removedFromList = null; 20912 synchronized (mPackages) { 20913 if (mKeepUninstalledPackages != null) { 20914 final int packagesCount = mKeepUninstalledPackages.size(); 20915 for (int i = 0; i < packagesCount; i++) { 20916 String oldPackage = mKeepUninstalledPackages.get(i); 20917 if (packageList != null && packageList.contains(oldPackage)) { 20918 continue; 20919 } 20920 if (removedFromList == null) { 20921 removedFromList = new ArrayList<>(); 20922 } 20923 removedFromList.add(oldPackage); 20924 } 20925 } 20926 mKeepUninstalledPackages = new ArrayList<>(packageList); 20927 if (removedFromList != null) { 20928 final int removedCount = removedFromList.size(); 20929 for (int i = 0; i < removedCount; i++) { 20930 deletePackageIfUnusedLPr(removedFromList.get(i)); 20931 } 20932 } 20933 } 20934 } 20935 20936 @Override 20937 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20938 synchronized (mPackages) { 20939 // If we do not support permission review, done. 20940 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20941 return false; 20942 } 20943 20944 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20945 if (packageSetting == null) { 20946 return false; 20947 } 20948 20949 // Permission review applies only to apps not supporting the new permission model. 20950 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20951 return false; 20952 } 20953 20954 // Legacy apps have the permission and get user consent on launch. 20955 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20956 return permissionsState.isPermissionReviewRequired(userId); 20957 } 20958 } 20959 20960 @Override 20961 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20962 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20963 } 20964 20965 @Override 20966 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20967 int userId) { 20968 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20969 } 20970 20971 @Override 20972 public void setDeviceAndProfileOwnerPackages( 20973 int deviceOwnerUserId, String deviceOwnerPackage, 20974 SparseArray<String> profileOwnerPackages) { 20975 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20976 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20977 } 20978 20979 @Override 20980 public boolean isPackageDataProtected(int userId, String packageName) { 20981 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20982 } 20983 } 20984 20985 @Override 20986 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20987 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20988 synchronized (mPackages) { 20989 final long identity = Binder.clearCallingIdentity(); 20990 try { 20991 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20992 packageNames, userId); 20993 } finally { 20994 Binder.restoreCallingIdentity(identity); 20995 } 20996 } 20997 } 20998 20999 private static void enforceSystemOrPhoneCaller(String tag) { 21000 int callingUid = Binder.getCallingUid(); 21001 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21002 throw new SecurityException( 21003 "Cannot call " + tag + " from UID " + callingUid); 21004 } 21005 } 21006 21007 boolean isHistoricalPackageUsageAvailable() { 21008 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21009 } 21010 21011 /** 21012 * Return a <b>copy</b> of the collection of packages known to the package manager. 21013 * @return A copy of the values of mPackages. 21014 */ 21015 Collection<PackageParser.Package> getPackages() { 21016 synchronized (mPackages) { 21017 return new ArrayList<>(mPackages.values()); 21018 } 21019 } 21020 21021 /** 21022 * Logs process start information (including base APK hash) to the security log. 21023 * @hide 21024 */ 21025 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21026 String apkFile, int pid) { 21027 if (!SecurityLog.isLoggingEnabled()) { 21028 return; 21029 } 21030 Bundle data = new Bundle(); 21031 data.putLong("startTimestamp", System.currentTimeMillis()); 21032 data.putString("processName", processName); 21033 data.putInt("uid", uid); 21034 data.putString("seinfo", seinfo); 21035 data.putString("apkFile", apkFile); 21036 data.putInt("pid", pid); 21037 Message msg = mProcessLoggingHandler.obtainMessage( 21038 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21039 msg.setData(data); 21040 mProcessLoggingHandler.sendMessage(msg); 21041 } 21042 21043 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21044 return mCompilerStats.getPackageStats(pkgName); 21045 } 21046 21047 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21048 return getOrCreateCompilerPackageStats(pkg.packageName); 21049 } 21050 21051 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21052 return mCompilerStats.getOrCreatePackageStats(pkgName); 21053 } 21054 21055 public void deleteCompilerPackageStats(String pkgName) { 21056 mCompilerStats.deletePackageStats(pkgName); 21057 } 21058} 21059