PackageManagerService.java revision 94ae1e739fd84a308609fff3b913d0963900ed6e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 80import static android.system.OsConstants.O_CREAT; 81import static android.system.OsConstants.O_RDWR; 82 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.annotation.UserIdInt; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 369 370 private static final int RADIO_UID = Process.PHONE_UID; 371 private static final int LOG_UID = Process.LOG_UID; 372 private static final int NFC_UID = Process.NFC_UID; 373 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 374 private static final int SHELL_UID = Process.SHELL_UID; 375 376 // Cap the size of permission trees that 3rd party apps can define 377 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 378 379 // Suffix used during package installation when copying/moving 380 // package apks to install directory. 381 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 382 383 static final int SCAN_NO_DEX = 1<<1; 384 static final int SCAN_FORCE_DEX = 1<<2; 385 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 386 static final int SCAN_NEW_INSTALL = 1<<4; 387 static final int SCAN_NO_PATHS = 1<<5; 388 static final int SCAN_UPDATE_TIME = 1<<6; 389 static final int SCAN_DEFER_DEX = 1<<7; 390 static final int SCAN_BOOTING = 1<<8; 391 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 392 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 393 static final int SCAN_REPLACING = 1<<11; 394 static final int SCAN_REQUIRE_KNOWN = 1<<12; 395 static final int SCAN_MOVE = 1<<13; 396 static final int SCAN_INITIAL = 1<<14; 397 static final int SCAN_CHECK_ONLY = 1<<15; 398 static final int SCAN_DONT_KILL_APP = 1<<17; 399 static final int SCAN_IGNORE_FROZEN = 1<<18; 400 401 static final int REMOVE_CHATTY = 1<<16; 402 403 private static final int[] EMPTY_INT_ARRAY = new int[0]; 404 405 /** 406 * Timeout (in milliseconds) after which the watchdog should declare that 407 * our handler thread is wedged. The usual default for such things is one 408 * minute but we sometimes do very lengthy I/O operations on this thread, 409 * such as installing multi-gigabyte applications, so ours needs to be longer. 410 */ 411 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 412 413 /** 414 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 415 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 416 * settings entry if available, otherwise we use the hardcoded default. If it's been 417 * more than this long since the last fstrim, we force one during the boot sequence. 418 * 419 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 420 * one gets run at the next available charging+idle time. This final mandatory 421 * no-fstrim check kicks in only of the other scheduling criteria is never met. 422 */ 423 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 424 425 /** 426 * Whether verification is enabled by default. 427 */ 428 private static final boolean DEFAULT_VERIFY_ENABLE = true; 429 430 /** 431 * The default maximum time to wait for the verification agent to return in 432 * milliseconds. 433 */ 434 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 435 436 /** 437 * The default response for package verification timeout. 438 * 439 * This can be either PackageManager.VERIFICATION_ALLOW or 440 * PackageManager.VERIFICATION_REJECT. 441 */ 442 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 443 444 static final String PLATFORM_PACKAGE_NAME = "android"; 445 446 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 447 448 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 449 DEFAULT_CONTAINER_PACKAGE, 450 "com.android.defcontainer.DefaultContainerService"); 451 452 private static final String KILL_APP_REASON_GIDS_CHANGED = 453 "permission grant or revoke changed gids"; 454 455 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 456 "permissions revoked"; 457 458 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 459 460 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 461 462 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 463 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 public static final int REASON_CORE_APP = 8; 508 509 public static final int REASON_LAST = REASON_CORE_APP; 510 511 /** Special library name that skips shared libraries check during compilation. */ 512 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 513 514 final ServiceThread mHandlerThread; 515 516 final PackageHandler mHandler; 517 518 private final ProcessLoggingHandler mProcessLoggingHandler; 519 520 /** 521 * Messages for {@link #mHandler} that need to wait for system ready before 522 * being dispatched. 523 */ 524 private ArrayList<Message> mPostSystemReadyMessages; 525 526 final int mSdkVersion = Build.VERSION.SDK_INT; 527 528 final Context mContext; 529 final boolean mFactoryTest; 530 final boolean mOnlyCore; 531 final DisplayMetrics mMetrics; 532 final int mDefParseFlags; 533 final String[] mSeparateProcesses; 534 final boolean mIsUpgrade; 535 final boolean mIsPreNUpgrade; 536 537 /** The location for ASEC container files on internal storage. */ 538 final String mAsecInternalPath; 539 540 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 541 // LOCK HELD. Can be called with mInstallLock held. 542 @GuardedBy("mInstallLock") 543 final Installer mInstaller; 544 545 /** Directory where installed third-party apps stored */ 546 final File mAppInstallDir; 547 final File mEphemeralInstallDir; 548 549 /** 550 * Directory to which applications installed internally have their 551 * 32 bit native libraries copied. 552 */ 553 private File mAppLib32InstallDir; 554 555 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 556 // apps. 557 final File mDrmAppPrivateInstallDir; 558 559 // ---------------------------------------------------------------- 560 561 // Lock for state used when installing and doing other long running 562 // operations. Methods that must be called with this lock held have 563 // the suffix "LI". 564 final Object mInstallLock = new Object(); 565 566 // ---------------------------------------------------------------- 567 568 // Keys are String (package name), values are Package. This also serves 569 // as the lock for the global state. Methods that must be called with 570 // this lock held have the prefix "LP". 571 @GuardedBy("mPackages") 572 final ArrayMap<String, PackageParser.Package> mPackages = 573 new ArrayMap<String, PackageParser.Package>(); 574 575 final ArrayMap<String, Set<String>> mKnownCodebase = 576 new ArrayMap<String, Set<String>>(); 577 578 // Tracks available target package names -> overlay package paths. 579 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 580 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 581 582 /** 583 * Tracks new system packages [received in an OTA] that we expect to 584 * find updated user-installed versions. Keys are package name, values 585 * are package location. 586 */ 587 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 588 /** 589 * Tracks high priority intent filters for protected actions. During boot, certain 590 * filter actions are protected and should never be allowed to have a high priority 591 * intent filter for them. However, there is one, and only one exception -- the 592 * setup wizard. It must be able to define a high priority intent filter for these 593 * actions to ensure there are no escapes from the wizard. We need to delay processing 594 * of these during boot as we need to look at all of the system packages in order 595 * to know which component is the setup wizard. 596 */ 597 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 598 /** 599 * Whether or not processing protected filters should be deferred. 600 */ 601 private boolean mDeferProtectedFilters = true; 602 603 /** 604 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 605 */ 606 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 607 /** 608 * Whether or not system app permissions should be promoted from install to runtime. 609 */ 610 boolean mPromoteSystemApps; 611 612 @GuardedBy("mPackages") 613 final Settings mSettings; 614 615 /** 616 * Set of package names that are currently "frozen", which means active 617 * surgery is being done on the code/data for that package. The platform 618 * will refuse to launch frozen packages to avoid race conditions. 619 * 620 * @see PackageFreezer 621 */ 622 @GuardedBy("mPackages") 623 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 624 625 final ProtectedPackages mProtectedPackages; 626 627 boolean mFirstBoot; 628 629 // System configuration read by SystemConfig. 630 final int[] mGlobalGids; 631 final SparseArray<ArraySet<String>> mSystemPermissions; 632 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 633 634 // If mac_permissions.xml was found for seinfo labeling. 635 boolean mFoundPolicyFile; 636 637 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 638 639 public static final class SharedLibraryEntry { 640 public final String path; 641 public final String apk; 642 643 SharedLibraryEntry(String _path, String _apk) { 644 path = _path; 645 apk = _apk; 646 } 647 } 648 649 // Currently known shared libraries. 650 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 651 new ArrayMap<String, SharedLibraryEntry>(); 652 653 // All available activities, for your resolving pleasure. 654 final ActivityIntentResolver mActivities = 655 new ActivityIntentResolver(); 656 657 // All available receivers, for your resolving pleasure. 658 final ActivityIntentResolver mReceivers = 659 new ActivityIntentResolver(); 660 661 // All available services, for your resolving pleasure. 662 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 663 664 // All available providers, for your resolving pleasure. 665 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 666 667 // Mapping from provider base names (first directory in content URI codePath) 668 // to the provider information. 669 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 670 new ArrayMap<String, PackageParser.Provider>(); 671 672 // Mapping from instrumentation class names to info about them. 673 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 674 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 675 676 // Mapping from permission names to info about them. 677 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 678 new ArrayMap<String, PackageParser.PermissionGroup>(); 679 680 // Packages whose data we have transfered into another package, thus 681 // should no longer exist. 682 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 683 684 // Broadcast actions that are only available to the system. 685 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 686 687 /** List of packages waiting for verification. */ 688 final SparseArray<PackageVerificationState> mPendingVerification 689 = new SparseArray<PackageVerificationState>(); 690 691 /** Set of packages associated with each app op permission. */ 692 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 693 694 final PackageInstallerService mInstallerService; 695 696 private final PackageDexOptimizer mPackageDexOptimizer; 697 698 private AtomicInteger mNextMoveId = new AtomicInteger(); 699 private final MoveCallbacks mMoveCallbacks; 700 701 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 702 703 // Cache of users who need badging. 704 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 705 706 /** Token for keys in mPendingVerification. */ 707 private int mPendingVerificationToken = 0; 708 709 volatile boolean mSystemReady; 710 volatile boolean mSafeMode; 711 volatile boolean mHasSystemUidErrors; 712 713 ApplicationInfo mAndroidApplication; 714 final ActivityInfo mResolveActivity = new ActivityInfo(); 715 final ResolveInfo mResolveInfo = new ResolveInfo(); 716 ComponentName mResolveComponentName; 717 PackageParser.Package mPlatformPackage; 718 ComponentName mCustomResolverComponentName; 719 720 boolean mResolverReplaced = false; 721 722 private final @Nullable ComponentName mIntentFilterVerifierComponent; 723 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 724 725 private int mIntentFilterVerificationToken = 0; 726 727 /** Component that knows whether or not an ephemeral application exists */ 728 final ComponentName mEphemeralResolverComponent; 729 /** The service connection to the ephemeral resolver */ 730 final EphemeralResolverConnection mEphemeralResolverConnection; 731 732 /** Component used to install ephemeral applications */ 733 final ComponentName mEphemeralInstallerComponent; 734 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 735 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 736 737 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 738 = new SparseArray<IntentFilterVerificationState>(); 739 740 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 741 new DefaultPermissionGrantPolicy(this); 742 743 // List of packages names to keep cached, even if they are uninstalled for all users 744 private List<String> mKeepUninstalledPackages; 745 746 private UserManagerInternal mUserManagerInternal; 747 748 private static class IFVerificationParams { 749 PackageParser.Package pkg; 750 boolean replacing; 751 int userId; 752 int verifierUid; 753 754 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 755 int _userId, int _verifierUid) { 756 pkg = _pkg; 757 replacing = _replacing; 758 userId = _userId; 759 replacing = _replacing; 760 verifierUid = _verifierUid; 761 } 762 } 763 764 private interface IntentFilterVerifier<T extends IntentFilter> { 765 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 766 T filter, String packageName); 767 void startVerifications(int userId); 768 void receiveVerificationResponse(int verificationId); 769 } 770 771 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 772 private Context mContext; 773 private ComponentName mIntentFilterVerifierComponent; 774 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 775 776 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 777 mContext = context; 778 mIntentFilterVerifierComponent = verifierComponent; 779 } 780 781 private String getDefaultScheme() { 782 return IntentFilter.SCHEME_HTTPS; 783 } 784 785 @Override 786 public void startVerifications(int userId) { 787 // Launch verifications requests 788 int count = mCurrentIntentFilterVerifications.size(); 789 for (int n=0; n<count; n++) { 790 int verificationId = mCurrentIntentFilterVerifications.get(n); 791 final IntentFilterVerificationState ivs = 792 mIntentFilterVerificationStates.get(verificationId); 793 794 String packageName = ivs.getPackageName(); 795 796 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 797 final int filterCount = filters.size(); 798 ArraySet<String> domainsSet = new ArraySet<>(); 799 for (int m=0; m<filterCount; m++) { 800 PackageParser.ActivityIntentInfo filter = filters.get(m); 801 domainsSet.addAll(filter.getHostsList()); 802 } 803 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 804 synchronized (mPackages) { 805 if (mSettings.createIntentFilterVerificationIfNeededLPw( 806 packageName, domainsList) != null) { 807 scheduleWriteSettingsLocked(); 808 } 809 } 810 sendVerificationRequest(userId, verificationId, ivs); 811 } 812 mCurrentIntentFilterVerifications.clear(); 813 } 814 815 private void sendVerificationRequest(int userId, int verificationId, 816 IntentFilterVerificationState ivs) { 817 818 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 821 verificationId); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 824 getDefaultScheme()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 827 ivs.getHostsString()); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 830 ivs.getPackageName()); 831 verificationIntent.setComponent(mIntentFilterVerifierComponent); 832 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 833 834 UserHandle user = new UserHandle(userId); 835 mContext.sendBroadcastAsUser(verificationIntent, user); 836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 837 "Sending IntentFilter verification broadcast"); 838 } 839 840 public void receiveVerificationResponse(int verificationId) { 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 843 final boolean verified = ivs.isVerified(); 844 845 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 846 final int count = filters.size(); 847 if (DEBUG_DOMAIN_VERIFICATION) { 848 Slog.i(TAG, "Received verification response " + verificationId 849 + " for " + count + " filters, verified=" + verified); 850 } 851 for (int n=0; n<count; n++) { 852 PackageParser.ActivityIntentInfo filter = filters.get(n); 853 filter.setVerified(verified); 854 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 856 + " verified with result:" + verified + " and hosts:" 857 + ivs.getHostsString()); 858 } 859 860 mIntentFilterVerificationStates.remove(verificationId); 861 862 final String packageName = ivs.getPackageName(); 863 IntentFilterVerificationInfo ivi = null; 864 865 synchronized (mPackages) { 866 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 867 } 868 if (ivi == null) { 869 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 870 + verificationId + " packageName:" + packageName); 871 return; 872 } 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 874 "Updating IntentFilterVerificationInfo for package " + packageName 875 +" verificationId:" + verificationId); 876 877 synchronized (mPackages) { 878 if (verified) { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 880 } else { 881 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 882 } 883 scheduleWriteSettingsLocked(); 884 885 final int userId = ivs.getUserId(); 886 if (userId != UserHandle.USER_ALL) { 887 final int userStatus = 888 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 889 890 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 891 boolean needUpdate = false; 892 893 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 894 // already been set by the User thru the Disambiguation dialog 895 switch (userStatus) { 896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 897 if (verified) { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 899 } else { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 901 } 902 needUpdate = true; 903 break; 904 905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 906 if (verified) { 907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 908 needUpdate = true; 909 } 910 break; 911 912 default: 913 // Nothing to do 914 } 915 916 if (needUpdate) { 917 mSettings.updateIntentFilterVerificationStatusLPw( 918 packageName, updatedStatus, userId); 919 scheduleWritePackageRestrictionsLocked(userId); 920 } 921 } 922 } 923 } 924 925 @Override 926 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 927 ActivityIntentInfo filter, String packageName) { 928 if (!hasValidDomains(filter)) { 929 return false; 930 } 931 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 932 if (ivs == null) { 933 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 934 packageName); 935 } 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 938 } 939 ivs.addFilter(filter); 940 return true; 941 } 942 943 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 944 int userId, int verificationId, String packageName) { 945 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 946 verifierUid, userId, packageName); 947 ivs.setPendingState(); 948 synchronized (mPackages) { 949 mIntentFilterVerificationStates.append(verificationId, ivs); 950 mCurrentIntentFilterVerifications.add(verificationId); 951 } 952 return ivs; 953 } 954 } 955 956 private static boolean hasValidDomains(ActivityIntentInfo filter) { 957 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 960 } 961 962 // Set of pending broadcasts for aggregating enable/disable of components. 963 static class PendingPackageBroadcasts { 964 // for each user id, a map of <package name -> components within that package> 965 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 966 967 public PendingPackageBroadcasts() { 968 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 969 } 970 971 public ArrayList<String> get(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 return packages.get(packageName); 974 } 975 976 public void put(int userId, String packageName, ArrayList<String> components) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 packages.put(packageName, components); 979 } 980 981 public void remove(int userId, String packageName) { 982 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 983 if (packages != null) { 984 packages.remove(packageName); 985 } 986 } 987 988 public void remove(int userId) { 989 mUidMap.remove(userId); 990 } 991 992 public int userIdCount() { 993 return mUidMap.size(); 994 } 995 996 public int userIdAt(int n) { 997 return mUidMap.keyAt(n); 998 } 999 1000 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1001 return mUidMap.get(userId); 1002 } 1003 1004 public int size() { 1005 // total number of pending broadcast entries across all userIds 1006 int num = 0; 1007 for (int i = 0; i< mUidMap.size(); i++) { 1008 num += mUidMap.valueAt(i).size(); 1009 } 1010 return num; 1011 } 1012 1013 public void clear() { 1014 mUidMap.clear(); 1015 } 1016 1017 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1018 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1019 if (map == null) { 1020 map = new ArrayMap<String, ArrayList<String>>(); 1021 mUidMap.put(userId, map); 1022 } 1023 return map; 1024 } 1025 } 1026 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1027 1028 // Service Connection to remote media container service to copy 1029 // package uri's from external media onto secure containers 1030 // or internal storage. 1031 private IMediaContainerService mContainerService = null; 1032 1033 static final int SEND_PENDING_BROADCAST = 1; 1034 static final int MCS_BOUND = 3; 1035 static final int END_COPY = 4; 1036 static final int INIT_COPY = 5; 1037 static final int MCS_UNBIND = 6; 1038 static final int START_CLEANING_PACKAGE = 7; 1039 static final int FIND_INSTALL_LOC = 8; 1040 static final int POST_INSTALL = 9; 1041 static final int MCS_RECONNECT = 10; 1042 static final int MCS_GIVE_UP = 11; 1043 static final int UPDATED_MEDIA_STATUS = 12; 1044 static final int WRITE_SETTINGS = 13; 1045 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1046 static final int PACKAGE_VERIFIED = 15; 1047 static final int CHECK_PENDING_VERIFICATION = 16; 1048 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1049 static final int INTENT_FILTER_VERIFIED = 18; 1050 static final int WRITE_PACKAGE_LIST = 19; 1051 1052 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1053 1054 // Delay time in millisecs 1055 static final int BROADCAST_DELAY = 10 * 1000; 1056 1057 static UserManagerService sUserManager; 1058 1059 // Stores a list of users whose package restrictions file needs to be updated 1060 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1061 1062 final private DefaultContainerConnection mDefContainerConn = 1063 new DefaultContainerConnection(); 1064 class DefaultContainerConnection implements ServiceConnection { 1065 public void onServiceConnected(ComponentName name, IBinder service) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1067 IMediaContainerService imcs = 1068 IMediaContainerService.Stub.asInterface(service); 1069 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1070 } 1071 1072 public void onServiceDisconnected(ComponentName name) { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1074 } 1075 } 1076 1077 // Recordkeeping of restore-after-install operations that are currently in flight 1078 // between the Package Manager and the Backup Manager 1079 static class PostInstallData { 1080 public InstallArgs args; 1081 public PackageInstalledInfo res; 1082 1083 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1084 args = _a; 1085 res = _r; 1086 } 1087 } 1088 1089 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1090 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1091 1092 // XML tags for backup/restore of various bits of state 1093 private static final String TAG_PREFERRED_BACKUP = "pa"; 1094 private static final String TAG_DEFAULT_APPS = "da"; 1095 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1096 1097 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1098 private static final String TAG_ALL_GRANTS = "rt-grants"; 1099 private static final String TAG_GRANT = "grant"; 1100 private static final String ATTR_PACKAGE_NAME = "pkg"; 1101 1102 private static final String TAG_PERMISSION = "perm"; 1103 private static final String ATTR_PERMISSION_NAME = "name"; 1104 private static final String ATTR_IS_GRANTED = "g"; 1105 private static final String ATTR_USER_SET = "set"; 1106 private static final String ATTR_USER_FIXED = "fixed"; 1107 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1108 1109 // System/policy permission grants are not backed up 1110 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1111 FLAG_PERMISSION_POLICY_FIXED 1112 | FLAG_PERMISSION_SYSTEM_FIXED 1113 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1114 1115 // And we back up these user-adjusted states 1116 private static final int USER_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_USER_SET 1118 | FLAG_PERMISSION_USER_FIXED 1119 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1120 1121 final @Nullable String mRequiredVerifierPackage; 1122 final @NonNull String mRequiredInstallerPackage; 1123 final @Nullable String mSetupWizardPackage; 1124 final @NonNull String mServicesSystemSharedLibraryPackageName; 1125 final @NonNull String mSharedSystemSharedLibraryPackageName; 1126 1127 private final PackageUsage mPackageUsage = new PackageUsage(); 1128 private final CompilerStats mCompilerStats = new CompilerStats(); 1129 1130 class PackageHandler extends Handler { 1131 private boolean mBound = false; 1132 final ArrayList<HandlerParams> mPendingInstalls = 1133 new ArrayList<HandlerParams>(); 1134 1135 private boolean connectToService() { 1136 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1137 " DefaultContainerService"); 1138 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1141 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1143 mBound = true; 1144 return true; 1145 } 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1147 return false; 1148 } 1149 1150 private void disconnectService() { 1151 mContainerService = null; 1152 mBound = false; 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1154 mContext.unbindService(mDefContainerConn); 1155 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1156 } 1157 1158 PackageHandler(Looper looper) { 1159 super(looper); 1160 } 1161 1162 public void handleMessage(Message msg) { 1163 try { 1164 doHandleMessage(msg); 1165 } finally { 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 } 1168 } 1169 1170 void doHandleMessage(Message msg) { 1171 switch (msg.what) { 1172 case INIT_COPY: { 1173 HandlerParams params = (HandlerParams) msg.obj; 1174 int idx = mPendingInstalls.size(); 1175 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1176 // If a bind was already initiated we dont really 1177 // need to do anything. The pending install 1178 // will be processed later on. 1179 if (!mBound) { 1180 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1181 System.identityHashCode(mHandler)); 1182 // If this is the only one pending we might 1183 // have to bind to the service again. 1184 if (!connectToService()) { 1185 Slog.e(TAG, "Failed to bind to media container service"); 1186 params.serviceError(); 1187 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1188 System.identityHashCode(mHandler)); 1189 if (params.traceMethod != null) { 1190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1191 params.traceCookie); 1192 } 1193 return; 1194 } else { 1195 // Once we bind to the service, the first 1196 // pending request will be processed. 1197 mPendingInstalls.add(idx, params); 1198 } 1199 } else { 1200 mPendingInstalls.add(idx, params); 1201 // Already bound to the service. Just make 1202 // sure we trigger off processing the first request. 1203 if (idx == 0) { 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 break; 1208 } 1209 case MCS_BOUND: { 1210 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1211 if (msg.obj != null) { 1212 mContainerService = (IMediaContainerService) msg.obj; 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1214 System.identityHashCode(mHandler)); 1215 } 1216 if (mContainerService == null) { 1217 if (!mBound) { 1218 // Something seriously wrong since we are not bound and we are not 1219 // waiting for connection. Bail out. 1220 Slog.e(TAG, "Cannot bind to media container service"); 1221 for (HandlerParams params : mPendingInstalls) { 1222 // Indicate service bind error 1223 params.serviceError(); 1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1225 System.identityHashCode(params)); 1226 if (params.traceMethod != null) { 1227 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1228 params.traceMethod, params.traceCookie); 1229 } 1230 return; 1231 } 1232 mPendingInstalls.clear(); 1233 } else { 1234 Slog.w(TAG, "Waiting to connect to media container service"); 1235 } 1236 } else if (mPendingInstalls.size() > 0) { 1237 HandlerParams params = mPendingInstalls.get(0); 1238 if (params != null) { 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1240 System.identityHashCode(params)); 1241 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1242 if (params.startCopy()) { 1243 // We are done... look for more work or to 1244 // go idle. 1245 if (DEBUG_SD_INSTALL) Log.i(TAG, 1246 "Checking for more work or unbind..."); 1247 // Delete pending install 1248 if (mPendingInstalls.size() > 0) { 1249 mPendingInstalls.remove(0); 1250 } 1251 if (mPendingInstalls.size() == 0) { 1252 if (mBound) { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, 1254 "Posting delayed MCS_UNBIND"); 1255 removeMessages(MCS_UNBIND); 1256 Message ubmsg = obtainMessage(MCS_UNBIND); 1257 // Unbind after a little delay, to avoid 1258 // continual thrashing. 1259 sendMessageDelayed(ubmsg, 10000); 1260 } 1261 } else { 1262 // There are more pending requests in queue. 1263 // Just post MCS_BOUND message to trigger processing 1264 // of next pending install. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Posting MCS_BOUND for next work"); 1267 mHandler.sendEmptyMessage(MCS_BOUND); 1268 } 1269 } 1270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1271 } 1272 } else { 1273 // Should never happen ideally. 1274 Slog.w(TAG, "Empty queue"); 1275 } 1276 break; 1277 } 1278 case MCS_RECONNECT: { 1279 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1280 if (mPendingInstalls.size() > 0) { 1281 if (mBound) { 1282 disconnectService(); 1283 } 1284 if (!connectToService()) { 1285 Slog.e(TAG, "Failed to bind to media container service"); 1286 for (HandlerParams params : mPendingInstalls) { 1287 // Indicate service bind error 1288 params.serviceError(); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 } 1292 mPendingInstalls.clear(); 1293 } 1294 } 1295 break; 1296 } 1297 case MCS_UNBIND: { 1298 // If there is no actual work left, then time to unbind. 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1300 1301 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1302 if (mBound) { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1304 1305 disconnectService(); 1306 } 1307 } else if (mPendingInstalls.size() > 0) { 1308 // There are more pending requests in queue. 1309 // Just post MCS_BOUND message to trigger processing 1310 // of next pending install. 1311 mHandler.sendEmptyMessage(MCS_BOUND); 1312 } 1313 1314 break; 1315 } 1316 case MCS_GIVE_UP: { 1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1318 HandlerParams params = mPendingInstalls.remove(0); 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 break; 1322 } 1323 case SEND_PENDING_BROADCAST: { 1324 String packages[]; 1325 ArrayList<String> components[]; 1326 int size = 0; 1327 int uids[]; 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1329 synchronized (mPackages) { 1330 if (mPendingBroadcasts == null) { 1331 return; 1332 } 1333 size = mPendingBroadcasts.size(); 1334 if (size <= 0) { 1335 // Nothing to be done. Just return 1336 return; 1337 } 1338 packages = new String[size]; 1339 components = new ArrayList[size]; 1340 uids = new int[size]; 1341 int i = 0; // filling out the above arrays 1342 1343 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1344 int packageUserId = mPendingBroadcasts.userIdAt(n); 1345 Iterator<Map.Entry<String, ArrayList<String>>> it 1346 = mPendingBroadcasts.packagesForUserId(packageUserId) 1347 .entrySet().iterator(); 1348 while (it.hasNext() && i < size) { 1349 Map.Entry<String, ArrayList<String>> ent = it.next(); 1350 packages[i] = ent.getKey(); 1351 components[i] = ent.getValue(); 1352 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1353 uids[i] = (ps != null) 1354 ? UserHandle.getUid(packageUserId, ps.appId) 1355 : -1; 1356 i++; 1357 } 1358 } 1359 size = i; 1360 mPendingBroadcasts.clear(); 1361 } 1362 // Send broadcasts 1363 for (int i = 0; i < size; i++) { 1364 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1365 } 1366 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1367 break; 1368 } 1369 case START_CLEANING_PACKAGE: { 1370 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1371 final String packageName = (String)msg.obj; 1372 final int userId = msg.arg1; 1373 final boolean andCode = msg.arg2 != 0; 1374 synchronized (mPackages) { 1375 if (userId == UserHandle.USER_ALL) { 1376 int[] users = sUserManager.getUserIds(); 1377 for (int user : users) { 1378 mSettings.addPackageToCleanLPw( 1379 new PackageCleanItem(user, packageName, andCode)); 1380 } 1381 } else { 1382 mSettings.addPackageToCleanLPw( 1383 new PackageCleanItem(userId, packageName, andCode)); 1384 } 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 startCleaningPackages(); 1388 } break; 1389 case POST_INSTALL: { 1390 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1391 1392 PostInstallData data = mRunningInstalls.get(msg.arg1); 1393 final boolean didRestore = (msg.arg2 != 0); 1394 mRunningInstalls.delete(msg.arg1); 1395 1396 if (data != null) { 1397 InstallArgs args = data.args; 1398 PackageInstalledInfo parentRes = data.res; 1399 1400 final boolean grantPermissions = (args.installFlags 1401 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1402 final boolean killApp = (args.installFlags 1403 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1404 final String[] grantedPermissions = args.installGrantPermissions; 1405 1406 // Handle the parent package 1407 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1408 grantedPermissions, didRestore, args.installerPackageName, 1409 args.observer); 1410 1411 // Handle the child packages 1412 final int childCount = (parentRes.addedChildPackages != null) 1413 ? parentRes.addedChildPackages.size() : 0; 1414 for (int i = 0; i < childCount; i++) { 1415 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1416 handlePackagePostInstall(childRes, grantPermissions, killApp, 1417 grantedPermissions, false, args.installerPackageName, 1418 args.observer); 1419 } 1420 1421 // Log tracing if needed 1422 if (args.traceMethod != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1424 args.traceCookie); 1425 } 1426 } else { 1427 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1428 } 1429 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1431 } break; 1432 case UPDATED_MEDIA_STATUS: { 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1434 boolean reportStatus = msg.arg1 == 1; 1435 boolean doGc = msg.arg2 == 1; 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1437 if (doGc) { 1438 // Force a gc to clear up stale containers. 1439 Runtime.getRuntime().gc(); 1440 } 1441 if (msg.obj != null) { 1442 @SuppressWarnings("unchecked") 1443 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1445 // Unload containers 1446 unloadAllContainers(args); 1447 } 1448 if (reportStatus) { 1449 try { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1451 PackageHelper.getMountService().finishMediaUpdate(); 1452 } catch (RemoteException e) { 1453 Log.e(TAG, "MountService not running?"); 1454 } 1455 } 1456 } break; 1457 case WRITE_SETTINGS: { 1458 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1459 synchronized (mPackages) { 1460 removeMessages(WRITE_SETTINGS); 1461 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1462 mSettings.writeLPr(); 1463 mDirtyUsers.clear(); 1464 } 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1466 } break; 1467 case WRITE_PACKAGE_RESTRICTIONS: { 1468 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1469 synchronized (mPackages) { 1470 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1471 for (int userId : mDirtyUsers) { 1472 mSettings.writePackageRestrictionsLPr(userId); 1473 } 1474 mDirtyUsers.clear(); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 } break; 1478 case WRITE_PACKAGE_LIST: { 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1480 synchronized (mPackages) { 1481 removeMessages(WRITE_PACKAGE_LIST); 1482 mSettings.writePackageListLPr(msg.arg1); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 } break; 1486 case CHECK_PENDING_VERIFICATION: { 1487 final int verificationId = msg.arg1; 1488 final PackageVerificationState state = mPendingVerification.get(verificationId); 1489 1490 if ((state != null) && !state.timeoutExtended()) { 1491 final InstallArgs args = state.getInstallArgs(); 1492 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1493 1494 Slog.i(TAG, "Verification timed out for " + originUri); 1495 mPendingVerification.remove(verificationId); 1496 1497 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1498 1499 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1500 Slog.i(TAG, "Continuing with installation of " + originUri); 1501 state.setVerifierResponse(Binder.getCallingUid(), 1502 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1503 broadcastPackageVerified(verificationId, originUri, 1504 PackageManager.VERIFICATION_ALLOW, 1505 state.getInstallArgs().getUser()); 1506 try { 1507 ret = args.copyApk(mContainerService, true); 1508 } catch (RemoteException e) { 1509 Slog.e(TAG, "Could not contact the ContainerService"); 1510 } 1511 } else { 1512 broadcastPackageVerified(verificationId, originUri, 1513 PackageManager.VERIFICATION_REJECT, 1514 state.getInstallArgs().getUser()); 1515 } 1516 1517 Trace.asyncTraceEnd( 1518 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1519 1520 processPendingInstall(args, ret); 1521 mHandler.sendEmptyMessage(MCS_UNBIND); 1522 } 1523 break; 1524 } 1525 case PACKAGE_VERIFIED: { 1526 final int verificationId = msg.arg1; 1527 1528 final PackageVerificationState state = mPendingVerification.get(verificationId); 1529 if (state == null) { 1530 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1531 break; 1532 } 1533 1534 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1535 1536 state.setVerifierResponse(response.callerUid, response.code); 1537 1538 if (state.isVerificationComplete()) { 1539 mPendingVerification.remove(verificationId); 1540 1541 final InstallArgs args = state.getInstallArgs(); 1542 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1543 1544 int ret; 1545 if (state.isInstallAllowed()) { 1546 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1547 broadcastPackageVerified(verificationId, originUri, 1548 response.code, state.getInstallArgs().getUser()); 1549 try { 1550 ret = args.copyApk(mContainerService, true); 1551 } catch (RemoteException e) { 1552 Slog.e(TAG, "Could not contact the ContainerService"); 1553 } 1554 } else { 1555 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1556 } 1557 1558 Trace.asyncTraceEnd( 1559 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1560 1561 processPendingInstall(args, ret); 1562 mHandler.sendEmptyMessage(MCS_UNBIND); 1563 } 1564 1565 break; 1566 } 1567 case START_INTENT_FILTER_VERIFICATIONS: { 1568 IFVerificationParams params = (IFVerificationParams) msg.obj; 1569 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1570 params.replacing, params.pkg); 1571 break; 1572 } 1573 case INTENT_FILTER_VERIFIED: { 1574 final int verificationId = msg.arg1; 1575 1576 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1577 verificationId); 1578 if (state == null) { 1579 Slog.w(TAG, "Invalid IntentFilter verification token " 1580 + verificationId + " received"); 1581 break; 1582 } 1583 1584 final int userId = state.getUserId(); 1585 1586 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1587 "Processing IntentFilter verification with token:" 1588 + verificationId + " and userId:" + userId); 1589 1590 final IntentFilterVerificationResponse response = 1591 (IntentFilterVerificationResponse) msg.obj; 1592 1593 state.setVerifierResponse(response.callerUid, response.code); 1594 1595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1596 "IntentFilter verification with token:" + verificationId 1597 + " and userId:" + userId 1598 + " is settings verifier response with response code:" 1599 + response.code); 1600 1601 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1603 + response.getFailedDomainsString()); 1604 } 1605 1606 if (state.isVerificationComplete()) { 1607 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1608 } else { 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " was not said to be complete"); 1612 } 1613 1614 break; 1615 } 1616 } 1617 } 1618 } 1619 1620 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1621 boolean killApp, String[] grantedPermissions, 1622 boolean launchedForRestore, String installerPackage, 1623 IPackageInstallObserver2 installObserver) { 1624 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1625 // Send the removed broadcasts 1626 if (res.removedInfo != null) { 1627 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1628 } 1629 1630 // Now that we successfully installed the package, grant runtime 1631 // permissions if requested before broadcasting the install. 1632 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1633 >= Build.VERSION_CODES.M) { 1634 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1635 } 1636 1637 final boolean update = res.removedInfo != null 1638 && res.removedInfo.removedPackage != null; 1639 1640 // If this is the first time we have child packages for a disabled privileged 1641 // app that had no children, we grant requested runtime permissions to the new 1642 // children if the parent on the system image had them already granted. 1643 if (res.pkg.parentPackage != null) { 1644 synchronized (mPackages) { 1645 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1646 } 1647 } 1648 1649 synchronized (mPackages) { 1650 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1651 } 1652 1653 final String packageName = res.pkg.applicationInfo.packageName; 1654 Bundle extras = new Bundle(1); 1655 extras.putInt(Intent.EXTRA_UID, res.uid); 1656 1657 // Determine the set of users who are adding this package for 1658 // the first time vs. those who are seeing an update. 1659 int[] firstUsers = EMPTY_INT_ARRAY; 1660 int[] updateUsers = EMPTY_INT_ARRAY; 1661 if (res.origUsers == null || res.origUsers.length == 0) { 1662 firstUsers = res.newUsers; 1663 } else { 1664 for (int newUser : res.newUsers) { 1665 boolean isNew = true; 1666 for (int origUser : res.origUsers) { 1667 if (origUser == newUser) { 1668 isNew = false; 1669 break; 1670 } 1671 } 1672 if (isNew) { 1673 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1674 } else { 1675 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1676 } 1677 } 1678 } 1679 1680 // Send installed broadcasts if the install/update is not ephemeral 1681 if (!isEphemeral(res.pkg)) { 1682 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1683 1684 // Send added for users that see the package for the first time 1685 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1686 extras, 0 /*flags*/, null /*targetPackage*/, 1687 null /*finishedReceiver*/, firstUsers); 1688 1689 // Send added for users that don't see the package for the first time 1690 if (update) { 1691 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1692 } 1693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1694 extras, 0 /*flags*/, null /*targetPackage*/, 1695 null /*finishedReceiver*/, updateUsers); 1696 1697 // Send replaced for users that don't see the package for the first time 1698 if (update) { 1699 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1700 packageName, extras, 0 /*flags*/, 1701 null /*targetPackage*/, null /*finishedReceiver*/, 1702 updateUsers); 1703 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1704 null /*package*/, null /*extras*/, 0 /*flags*/, 1705 packageName /*targetPackage*/, 1706 null /*finishedReceiver*/, updateUsers); 1707 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1708 // First-install and we did a restore, so we're responsible for the 1709 // first-launch broadcast. 1710 if (DEBUG_BACKUP) { 1711 Slog.i(TAG, "Post-restore of " + packageName 1712 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1713 } 1714 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1715 } 1716 1717 // Send broadcast package appeared if forward locked/external for all users 1718 // treat asec-hosted packages like removable media on upgrade 1719 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1720 if (DEBUG_INSTALL) { 1721 Slog.i(TAG, "upgrading pkg " + res.pkg 1722 + " is ASEC-hosted -> AVAILABLE"); 1723 } 1724 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1725 ArrayList<String> pkgList = new ArrayList<>(1); 1726 pkgList.add(packageName); 1727 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1728 } 1729 } 1730 1731 // Work that needs to happen on first install within each user 1732 if (firstUsers != null && firstUsers.length > 0) { 1733 synchronized (mPackages) { 1734 for (int userId : firstUsers) { 1735 // If this app is a browser and it's newly-installed for some 1736 // users, clear any default-browser state in those users. The 1737 // app's nature doesn't depend on the user, so we can just check 1738 // its browser nature in any user and generalize. 1739 if (packageIsBrowser(packageName, userId)) { 1740 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1741 } 1742 1743 // We may also need to apply pending (restored) runtime 1744 // permission grants within these users. 1745 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1746 } 1747 } 1748 } 1749 1750 // Log current value of "unknown sources" setting 1751 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1752 getUnknownSourcesSettings()); 1753 1754 // Force a gc to clear up things 1755 Runtime.getRuntime().gc(); 1756 1757 // Remove the replaced package's older resources safely now 1758 // We delete after a gc for applications on sdcard. 1759 if (res.removedInfo != null && res.removedInfo.args != null) { 1760 synchronized (mInstallLock) { 1761 res.removedInfo.args.doPostDeleteLI(true); 1762 } 1763 } 1764 } 1765 1766 // If someone is watching installs - notify them 1767 if (installObserver != null) { 1768 try { 1769 Bundle extras = extrasForInstallResult(res); 1770 installObserver.onPackageInstalled(res.name, res.returnCode, 1771 res.returnMsg, extras); 1772 } catch (RemoteException e) { 1773 Slog.i(TAG, "Observer no longer exists."); 1774 } 1775 } 1776 } 1777 1778 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1779 PackageParser.Package pkg) { 1780 if (pkg.parentPackage == null) { 1781 return; 1782 } 1783 if (pkg.requestedPermissions == null) { 1784 return; 1785 } 1786 final PackageSetting disabledSysParentPs = mSettings 1787 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1788 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1789 || !disabledSysParentPs.isPrivileged() 1790 || (disabledSysParentPs.childPackageNames != null 1791 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1792 return; 1793 } 1794 final int[] allUserIds = sUserManager.getUserIds(); 1795 final int permCount = pkg.requestedPermissions.size(); 1796 for (int i = 0; i < permCount; i++) { 1797 String permission = pkg.requestedPermissions.get(i); 1798 BasePermission bp = mSettings.mPermissions.get(permission); 1799 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1800 continue; 1801 } 1802 for (int userId : allUserIds) { 1803 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1804 permission, userId)) { 1805 grantRuntimePermission(pkg.packageName, permission, userId); 1806 } 1807 } 1808 } 1809 } 1810 1811 private StorageEventListener mStorageListener = new StorageEventListener() { 1812 @Override 1813 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1814 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1815 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1816 final String volumeUuid = vol.getFsUuid(); 1817 1818 // Clean up any users or apps that were removed or recreated 1819 // while this volume was missing 1820 reconcileUsers(volumeUuid); 1821 reconcileApps(volumeUuid); 1822 1823 // Clean up any install sessions that expired or were 1824 // cancelled while this volume was missing 1825 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1826 1827 loadPrivatePackages(vol); 1828 1829 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1830 unloadPrivatePackages(vol); 1831 } 1832 } 1833 1834 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1835 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1836 updateExternalMediaStatus(true, false); 1837 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1838 updateExternalMediaStatus(false, false); 1839 } 1840 } 1841 } 1842 1843 @Override 1844 public void onVolumeForgotten(String fsUuid) { 1845 if (TextUtils.isEmpty(fsUuid)) { 1846 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1847 return; 1848 } 1849 1850 // Remove any apps installed on the forgotten volume 1851 synchronized (mPackages) { 1852 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1853 for (PackageSetting ps : packages) { 1854 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1855 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1856 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1857 } 1858 1859 mSettings.onVolumeForgotten(fsUuid); 1860 mSettings.writeLPr(); 1861 } 1862 } 1863 }; 1864 1865 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1866 String[] grantedPermissions) { 1867 for (int userId : userIds) { 1868 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1869 } 1870 1871 // We could have touched GID membership, so flush out packages.list 1872 synchronized (mPackages) { 1873 mSettings.writePackageListLPr(); 1874 } 1875 } 1876 1877 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1878 String[] grantedPermissions) { 1879 SettingBase sb = (SettingBase) pkg.mExtras; 1880 if (sb == null) { 1881 return; 1882 } 1883 1884 PermissionsState permissionsState = sb.getPermissionsState(); 1885 1886 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1887 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1888 1889 for (String permission : pkg.requestedPermissions) { 1890 final BasePermission bp; 1891 synchronized (mPackages) { 1892 bp = mSettings.mPermissions.get(permission); 1893 } 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 1906 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1907 Bundle extras = null; 1908 switch (res.returnCode) { 1909 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1910 extras = new Bundle(); 1911 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1912 res.origPermission); 1913 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1914 res.origPackage); 1915 break; 1916 } 1917 case PackageManager.INSTALL_SUCCEEDED: { 1918 extras = new Bundle(); 1919 extras.putBoolean(Intent.EXTRA_REPLACING, 1920 res.removedInfo != null && res.removedInfo.removedPackage != null); 1921 break; 1922 } 1923 } 1924 return extras; 1925 } 1926 1927 void scheduleWriteSettingsLocked() { 1928 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1929 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1930 } 1931 } 1932 1933 void scheduleWritePackageListLocked(int userId) { 1934 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1935 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1936 msg.arg1 = userId; 1937 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1938 } 1939 } 1940 1941 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1942 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1943 scheduleWritePackageRestrictionsLocked(userId); 1944 } 1945 1946 void scheduleWritePackageRestrictionsLocked(int userId) { 1947 final int[] userIds = (userId == UserHandle.USER_ALL) 1948 ? sUserManager.getUserIds() : new int[]{userId}; 1949 for (int nextUserId : userIds) { 1950 if (!sUserManager.exists(nextUserId)) return; 1951 mDirtyUsers.add(nextUserId); 1952 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1953 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1954 } 1955 } 1956 } 1957 1958 public static PackageManagerService main(Context context, Installer installer, 1959 boolean factoryTest, boolean onlyCore) { 1960 // Self-check for initial settings. 1961 PackageManagerServiceCompilerMapping.checkProperties(); 1962 1963 PackageManagerService m = new PackageManagerService(context, installer, 1964 factoryTest, onlyCore); 1965 m.enableSystemUserPackages(); 1966 ServiceManager.addService("package", m); 1967 return m; 1968 } 1969 1970 private void enableSystemUserPackages() { 1971 if (!UserManager.isSplitSystemUser()) { 1972 return; 1973 } 1974 // For system user, enable apps based on the following conditions: 1975 // - app is whitelisted or belong to one of these groups: 1976 // -- system app which has no launcher icons 1977 // -- system app which has INTERACT_ACROSS_USERS permission 1978 // -- system IME app 1979 // - app is not in the blacklist 1980 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1981 Set<String> enableApps = new ArraySet<>(); 1982 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1983 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1984 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1985 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1986 enableApps.addAll(wlApps); 1987 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1988 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1989 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1990 enableApps.removeAll(blApps); 1991 Log.i(TAG, "Applications installed for system user: " + enableApps); 1992 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1993 UserHandle.SYSTEM); 1994 final int allAppsSize = allAps.size(); 1995 synchronized (mPackages) { 1996 for (int i = 0; i < allAppsSize; i++) { 1997 String pName = allAps.get(i); 1998 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1999 // Should not happen, but we shouldn't be failing if it does 2000 if (pkgSetting == null) { 2001 continue; 2002 } 2003 boolean install = enableApps.contains(pName); 2004 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2005 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2006 + " for system user"); 2007 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2008 } 2009 } 2010 } 2011 } 2012 2013 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2014 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2015 Context.DISPLAY_SERVICE); 2016 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2017 } 2018 2019 /** 2020 * Requests that files preopted on a secondary system partition be copied to the data partition 2021 * if possible. Note that the actual copying of the files is accomplished by init for security 2022 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2023 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2024 */ 2025 private static void requestCopyPreoptedFiles() { 2026 final int WAIT_TIME_MS = 100; 2027 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2028 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2029 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2030 // We will wait for up to 100 seconds. 2031 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2032 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2033 try { 2034 Thread.sleep(WAIT_TIME_MS); 2035 } catch (InterruptedException e) { 2036 // Do nothing 2037 } 2038 if (SystemClock.uptimeMillis() > timeEnd) { 2039 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2040 Slog.wtf(TAG, "cppreopt did not finish!"); 2041 break; 2042 } 2043 } 2044 } 2045 } 2046 2047 public PackageManagerService(Context context, Installer installer, 2048 boolean factoryTest, boolean onlyCore) { 2049 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2050 SystemClock.uptimeMillis()); 2051 2052 if (mSdkVersion <= 0) { 2053 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2054 } 2055 2056 mContext = context; 2057 mFactoryTest = factoryTest; 2058 mOnlyCore = onlyCore; 2059 mMetrics = new DisplayMetrics(); 2060 mSettings = new Settings(mPackages); 2061 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2062 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2063 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2064 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2065 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2066 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2067 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2068 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2069 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2070 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2071 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2072 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2073 2074 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2075 if (separateProcesses != null && separateProcesses.length() > 0) { 2076 if ("*".equals(separateProcesses)) { 2077 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2078 mSeparateProcesses = null; 2079 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2080 } else { 2081 mDefParseFlags = 0; 2082 mSeparateProcesses = separateProcesses.split(","); 2083 Slog.w(TAG, "Running with debug.separate_processes: " 2084 + separateProcesses); 2085 } 2086 } else { 2087 mDefParseFlags = 0; 2088 mSeparateProcesses = null; 2089 } 2090 2091 mInstaller = installer; 2092 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2093 "*dexopt*"); 2094 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2095 2096 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2097 FgThread.get().getLooper()); 2098 2099 getDefaultDisplayMetrics(context, mMetrics); 2100 2101 SystemConfig systemConfig = SystemConfig.getInstance(); 2102 mGlobalGids = systemConfig.getGlobalGids(); 2103 mSystemPermissions = systemConfig.getSystemPermissions(); 2104 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2105 2106 mProtectedPackages = new ProtectedPackages(mContext); 2107 2108 synchronized (mInstallLock) { 2109 // writer 2110 synchronized (mPackages) { 2111 mHandlerThread = new ServiceThread(TAG, 2112 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2113 mHandlerThread.start(); 2114 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2115 mProcessLoggingHandler = new ProcessLoggingHandler(); 2116 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2117 2118 File dataDir = Environment.getDataDirectory(); 2119 mAppInstallDir = new File(dataDir, "app"); 2120 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2121 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2122 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2123 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2124 2125 sUserManager = new UserManagerService(context, this, mPackages); 2126 2127 // Propagate permission configuration in to package manager. 2128 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2129 = systemConfig.getPermissions(); 2130 for (int i=0; i<permConfig.size(); i++) { 2131 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2132 BasePermission bp = mSettings.mPermissions.get(perm.name); 2133 if (bp == null) { 2134 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2135 mSettings.mPermissions.put(perm.name, bp); 2136 } 2137 if (perm.gids != null) { 2138 bp.setGids(perm.gids, perm.perUser); 2139 } 2140 } 2141 2142 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2143 for (int i=0; i<libConfig.size(); i++) { 2144 mSharedLibraries.put(libConfig.keyAt(i), 2145 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2146 } 2147 2148 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2149 2150 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2151 2152 if (mFirstBoot) { 2153 requestCopyPreoptedFiles(); 2154 } 2155 2156 String customResolverActivity = Resources.getSystem().getString( 2157 R.string.config_customResolverActivity); 2158 if (TextUtils.isEmpty(customResolverActivity)) { 2159 customResolverActivity = null; 2160 } else { 2161 mCustomResolverComponentName = ComponentName.unflattenFromString( 2162 customResolverActivity); 2163 } 2164 2165 long startTime = SystemClock.uptimeMillis(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2168 startTime); 2169 2170 // Set flag to monitor and not change apk file paths when 2171 // scanning install directories. 2172 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2173 2174 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2175 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2176 2177 if (bootClassPath == null) { 2178 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2179 } 2180 2181 if (systemServerClassPath == null) { 2182 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2183 } 2184 2185 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2186 final String[] dexCodeInstructionSets = 2187 getDexCodeInstructionSets( 2188 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2189 2190 /** 2191 * Ensure all external libraries have had dexopt run on them. 2192 */ 2193 if (mSharedLibraries.size() > 0) { 2194 // NOTE: For now, we're compiling these system "shared libraries" 2195 // (and framework jars) into all available architectures. It's possible 2196 // to compile them only when we come across an app that uses them (there's 2197 // already logic for that in scanPackageLI) but that adds some complexity. 2198 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2199 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2200 final String lib = libEntry.path; 2201 if (lib == null) { 2202 continue; 2203 } 2204 2205 try { 2206 // Shared libraries do not have profiles so we perform a full 2207 // AOT compilation (if needed). 2208 int dexoptNeeded = DexFile.getDexOptNeeded( 2209 lib, dexCodeInstructionSet, 2210 getCompilerFilterForReason(REASON_SHARED_APK), 2211 false /* newProfile */); 2212 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2213 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2214 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2215 getCompilerFilterForReason(REASON_SHARED_APK), 2216 StorageManager.UUID_PRIVATE_INTERNAL, 2217 SKIP_SHARED_LIBRARY_CHECK); 2218 } 2219 } catch (FileNotFoundException e) { 2220 Slog.w(TAG, "Library not found: " + lib); 2221 } catch (IOException | InstallerException e) { 2222 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2223 + e.getMessage()); 2224 } 2225 } 2226 } 2227 } 2228 2229 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2230 2231 final VersionInfo ver = mSettings.getInternalVersion(); 2232 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2233 2234 // when upgrading from pre-M, promote system app permissions from install to runtime 2235 mPromoteSystemApps = 2236 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2237 2238 // When upgrading from pre-N, we need to handle package extraction like first boot, 2239 // as there is no profiling data available. 2240 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2241 2242 // save off the names of pre-existing system packages prior to scanning; we don't 2243 // want to automatically grant runtime permissions for new system apps 2244 if (mPromoteSystemApps) { 2245 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2246 while (pkgSettingIter.hasNext()) { 2247 PackageSetting ps = pkgSettingIter.next(); 2248 if (isSystemApp(ps)) { 2249 mExistingSystemPackages.add(ps.name); 2250 } 2251 } 2252 } 2253 2254 // Collect vendor overlay packages. 2255 // (Do this before scanning any apps.) 2256 // For security and version matching reason, only consider 2257 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2258 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2259 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2260 | PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR 2262 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2263 2264 // Find base frameworks (resource packages without code). 2265 scanDirTracedLI(frameworkDir, mDefParseFlags 2266 | PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR 2268 | PackageParser.PARSE_IS_PRIVILEGED, 2269 scanFlags | SCAN_NO_DEX, 0); 2270 2271 // Collected privileged system packages. 2272 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2273 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2274 | PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR 2276 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2277 2278 // Collect ordinary system packages. 2279 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2280 scanDirTracedLI(systemAppDir, mDefParseFlags 2281 | PackageParser.PARSE_IS_SYSTEM 2282 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2283 2284 // Collect all vendor packages. 2285 File vendorAppDir = new File("/vendor/app"); 2286 try { 2287 vendorAppDir = vendorAppDir.getCanonicalFile(); 2288 } catch (IOException e) { 2289 // failed to look up canonical path, continue with original one 2290 } 2291 scanDirTracedLI(vendorAppDir, mDefParseFlags 2292 | PackageParser.PARSE_IS_SYSTEM 2293 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2294 2295 // Collect all OEM packages. 2296 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2297 scanDirTracedLI(oemAppDir, mDefParseFlags 2298 | PackageParser.PARSE_IS_SYSTEM 2299 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2300 2301 // Prune any system packages that no longer exist. 2302 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2303 if (!mOnlyCore) { 2304 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2305 while (psit.hasNext()) { 2306 PackageSetting ps = psit.next(); 2307 2308 /* 2309 * If this is not a system app, it can't be a 2310 * disable system app. 2311 */ 2312 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2313 continue; 2314 } 2315 2316 /* 2317 * If the package is scanned, it's not erased. 2318 */ 2319 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2320 if (scannedPkg != null) { 2321 /* 2322 * If the system app is both scanned and in the 2323 * disabled packages list, then it must have been 2324 * added via OTA. Remove it from the currently 2325 * scanned package so the previously user-installed 2326 * application can be scanned. 2327 */ 2328 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2329 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2330 + ps.name + "; removing system app. Last known codePath=" 2331 + ps.codePathString + ", installStatus=" + ps.installStatus 2332 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2333 + scannedPkg.mVersionCode); 2334 removePackageLI(scannedPkg, true); 2335 mExpectingBetter.put(ps.name, ps.codePath); 2336 } 2337 2338 continue; 2339 } 2340 2341 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2342 psit.remove(); 2343 logCriticalInfo(Log.WARN, "System package " + ps.name 2344 + " no longer exists; it's data will be wiped"); 2345 // Actual deletion of code and data will be handled by later 2346 // reconciliation step 2347 } else { 2348 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2349 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2350 possiblyDeletedUpdatedSystemApps.add(ps.name); 2351 } 2352 } 2353 } 2354 } 2355 2356 //look for any incomplete package installations 2357 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2358 for (int i = 0; i < deletePkgsList.size(); i++) { 2359 // Actual deletion of code and data will be handled by later 2360 // reconciliation step 2361 final String packageName = deletePkgsList.get(i).name; 2362 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2363 synchronized (mPackages) { 2364 mSettings.removePackageLPw(packageName); 2365 } 2366 } 2367 2368 //delete tmp files 2369 deleteTempPackageFiles(); 2370 2371 // Remove any shared userIDs that have no associated packages 2372 mSettings.pruneSharedUsersLPw(); 2373 2374 if (!mOnlyCore) { 2375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2376 SystemClock.uptimeMillis()); 2377 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2378 2379 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2380 | PackageParser.PARSE_FORWARD_LOCK, 2381 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2382 2383 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2384 | PackageParser.PARSE_IS_EPHEMERAL, 2385 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2386 2387 /** 2388 * Remove disable package settings for any updated system 2389 * apps that were removed via an OTA. If they're not a 2390 * previously-updated app, remove them completely. 2391 * Otherwise, just revoke their system-level permissions. 2392 */ 2393 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2394 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2395 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2396 2397 String msg; 2398 if (deletedPkg == null) { 2399 msg = "Updated system package " + deletedAppName 2400 + " no longer exists; it's data will be wiped"; 2401 // Actual deletion of code and data will be handled by later 2402 // reconciliation step 2403 } else { 2404 msg = "Updated system app + " + deletedAppName 2405 + " no longer present; removing system privileges for " 2406 + deletedAppName; 2407 2408 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2409 2410 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2411 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2412 } 2413 logCriticalInfo(Log.WARN, msg); 2414 } 2415 2416 /** 2417 * Make sure all system apps that we expected to appear on 2418 * the userdata partition actually showed up. If they never 2419 * appeared, crawl back and revive the system version. 2420 */ 2421 for (int i = 0; i < mExpectingBetter.size(); i++) { 2422 final String packageName = mExpectingBetter.keyAt(i); 2423 if (!mPackages.containsKey(packageName)) { 2424 final File scanFile = mExpectingBetter.valueAt(i); 2425 2426 logCriticalInfo(Log.WARN, "Expected better " + packageName 2427 + " but never showed up; reverting to system"); 2428 2429 int reparseFlags = mDefParseFlags; 2430 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2431 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR 2433 | PackageParser.PARSE_IS_PRIVILEGED; 2434 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2435 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR; 2437 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2438 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2439 | PackageParser.PARSE_IS_SYSTEM_DIR; 2440 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2441 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2442 | PackageParser.PARSE_IS_SYSTEM_DIR; 2443 } else { 2444 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2445 continue; 2446 } 2447 2448 mSettings.enableSystemPackageLPw(packageName); 2449 2450 try { 2451 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2452 } catch (PackageManagerException e) { 2453 Slog.e(TAG, "Failed to parse original system package: " 2454 + e.getMessage()); 2455 } 2456 } 2457 } 2458 } 2459 mExpectingBetter.clear(); 2460 2461 // Resolve protected action filters. Only the setup wizard is allowed to 2462 // have a high priority filter for these actions. 2463 mSetupWizardPackage = getSetupWizardPackageName(); 2464 if (mProtectedFilters.size() > 0) { 2465 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2466 Slog.i(TAG, "No setup wizard;" 2467 + " All protected intents capped to priority 0"); 2468 } 2469 for (ActivityIntentInfo filter : mProtectedFilters) { 2470 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2471 if (DEBUG_FILTERS) { 2472 Slog.i(TAG, "Found setup wizard;" 2473 + " allow priority " + filter.getPriority() + ";" 2474 + " package: " + filter.activity.info.packageName 2475 + " activity: " + filter.activity.className 2476 + " priority: " + filter.getPriority()); 2477 } 2478 // skip setup wizard; allow it to keep the high priority filter 2479 continue; 2480 } 2481 Slog.w(TAG, "Protected action; cap priority to 0;" 2482 + " package: " + filter.activity.info.packageName 2483 + " activity: " + filter.activity.className 2484 + " origPrio: " + filter.getPriority()); 2485 filter.setPriority(0); 2486 } 2487 } 2488 mDeferProtectedFilters = false; 2489 mProtectedFilters.clear(); 2490 2491 // Now that we know all of the shared libraries, update all clients to have 2492 // the correct library paths. 2493 updateAllSharedLibrariesLPw(); 2494 2495 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2496 // NOTE: We ignore potential failures here during a system scan (like 2497 // the rest of the commands above) because there's precious little we 2498 // can do about it. A settings error is reported, though. 2499 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2500 false /* boot complete */); 2501 } 2502 2503 // Now that we know all the packages we are keeping, 2504 // read and update their last usage times. 2505 mPackageUsage.read(mPackages); 2506 mCompilerStats.read(); 2507 2508 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2509 SystemClock.uptimeMillis()); 2510 Slog.i(TAG, "Time to scan packages: " 2511 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2512 + " seconds"); 2513 2514 // If the platform SDK has changed since the last time we booted, 2515 // we need to re-grant app permission to catch any new ones that 2516 // appear. This is really a hack, and means that apps can in some 2517 // cases get permissions that the user didn't initially explicitly 2518 // allow... it would be nice to have some better way to handle 2519 // this situation. 2520 int updateFlags = UPDATE_PERMISSIONS_ALL; 2521 if (ver.sdkVersion != mSdkVersion) { 2522 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2523 + mSdkVersion + "; regranting permissions for internal storage"); 2524 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2525 } 2526 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2527 ver.sdkVersion = mSdkVersion; 2528 2529 // If this is the first boot or an update from pre-M, and it is a normal 2530 // boot, then we need to initialize the default preferred apps across 2531 // all defined users. 2532 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2533 for (UserInfo user : sUserManager.getUsers(true)) { 2534 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2535 applyFactoryDefaultBrowserLPw(user.id); 2536 primeDomainVerificationsLPw(user.id); 2537 } 2538 } 2539 2540 // Prepare storage for system user really early during boot, 2541 // since core system apps like SettingsProvider and SystemUI 2542 // can't wait for user to start 2543 final int storageFlags; 2544 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2545 storageFlags = StorageManager.FLAG_STORAGE_DE; 2546 } else { 2547 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2548 } 2549 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2550 storageFlags); 2551 2552 // If this is first boot after an OTA, and a normal boot, then 2553 // we need to clear code cache directories. 2554 // Note that we do *not* clear the application profiles. These remain valid 2555 // across OTAs and are used to drive profile verification (post OTA) and 2556 // profile compilation (without waiting to collect a fresh set of profiles). 2557 if (mIsUpgrade && !onlyCore) { 2558 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2559 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2560 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2561 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2562 // No apps are running this early, so no need to freeze 2563 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2564 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2565 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2566 } 2567 } 2568 ver.fingerprint = Build.FINGERPRINT; 2569 } 2570 2571 checkDefaultBrowser(); 2572 2573 // clear only after permissions and other defaults have been updated 2574 mExistingSystemPackages.clear(); 2575 mPromoteSystemApps = false; 2576 2577 // All the changes are done during package scanning. 2578 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2579 2580 // can downgrade to reader 2581 mSettings.writeLPr(); 2582 2583 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2584 // early on (before the package manager declares itself as early) because other 2585 // components in the system server might ask for package contexts for these apps. 2586 // 2587 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2588 // (i.e, that the data partition is unavailable). 2589 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2590 long start = System.nanoTime(); 2591 List<PackageParser.Package> coreApps = new ArrayList<>(); 2592 for (PackageParser.Package pkg : mPackages.values()) { 2593 if (pkg.coreApp) { 2594 coreApps.add(pkg); 2595 } 2596 } 2597 2598 int[] stats = performDexOptUpgrade(coreApps, false, 2599 getCompilerFilterForReason(REASON_CORE_APP)); 2600 2601 final int elapsedTimeSeconds = 2602 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2603 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2604 2605 if (DEBUG_DEXOPT) { 2606 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2607 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2608 } 2609 2610 2611 // TODO: Should we log these stats to tron too ? 2612 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2613 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2614 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2615 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2616 } 2617 2618 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2619 SystemClock.uptimeMillis()); 2620 2621 if (!mOnlyCore) { 2622 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2623 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2624 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2625 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2626 mIntentFilterVerifierComponent); 2627 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2628 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2629 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2630 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2631 } else { 2632 mRequiredVerifierPackage = null; 2633 mRequiredInstallerPackage = null; 2634 mIntentFilterVerifierComponent = null; 2635 mIntentFilterVerifier = null; 2636 mServicesSystemSharedLibraryPackageName = null; 2637 mSharedSystemSharedLibraryPackageName = null; 2638 } 2639 2640 mInstallerService = new PackageInstallerService(context, this); 2641 2642 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2643 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2644 // both the installer and resolver must be present to enable ephemeral 2645 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2646 if (DEBUG_EPHEMERAL) { 2647 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2648 + " installer:" + ephemeralInstallerComponent); 2649 } 2650 mEphemeralResolverComponent = ephemeralResolverComponent; 2651 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2652 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2653 mEphemeralResolverConnection = 2654 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2655 } else { 2656 if (DEBUG_EPHEMERAL) { 2657 final String missingComponent = 2658 (ephemeralResolverComponent == null) 2659 ? (ephemeralInstallerComponent == null) 2660 ? "resolver and installer" 2661 : "resolver" 2662 : "installer"; 2663 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2664 } 2665 mEphemeralResolverComponent = null; 2666 mEphemeralInstallerComponent = null; 2667 mEphemeralResolverConnection = null; 2668 } 2669 2670 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2671 } // synchronized (mPackages) 2672 } // synchronized (mInstallLock) 2673 2674 // Now after opening every single application zip, make sure they 2675 // are all flushed. Not really needed, but keeps things nice and 2676 // tidy. 2677 Runtime.getRuntime().gc(); 2678 2679 // The initial scanning above does many calls into installd while 2680 // holding the mPackages lock, but we're mostly interested in yelling 2681 // once we have a booted system. 2682 mInstaller.setWarnIfHeld(mPackages); 2683 2684 // Expose private service for system components to use. 2685 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2686 } 2687 2688 @Override 2689 public boolean isFirstBoot() { 2690 return mFirstBoot; 2691 } 2692 2693 @Override 2694 public boolean isOnlyCoreApps() { 2695 return mOnlyCore; 2696 } 2697 2698 @Override 2699 public boolean isUpgrade() { 2700 return mIsUpgrade; 2701 } 2702 2703 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2704 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2705 2706 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2707 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2708 UserHandle.USER_SYSTEM); 2709 if (matches.size() == 1) { 2710 return matches.get(0).getComponentInfo().packageName; 2711 } else { 2712 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2713 return null; 2714 } 2715 } 2716 2717 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2718 synchronized (mPackages) { 2719 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2720 if (libraryEntry == null) { 2721 throw new IllegalStateException("Missing required shared library:" + libraryName); 2722 } 2723 return libraryEntry.apk; 2724 } 2725 } 2726 2727 private @NonNull String getRequiredInstallerLPr() { 2728 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2729 intent.addCategory(Intent.CATEGORY_DEFAULT); 2730 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2731 2732 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2733 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2734 UserHandle.USER_SYSTEM); 2735 if (matches.size() == 1) { 2736 ResolveInfo resolveInfo = matches.get(0); 2737 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2738 throw new RuntimeException("The installer must be a privileged app"); 2739 } 2740 return matches.get(0).getComponentInfo().packageName; 2741 } else { 2742 throw new RuntimeException("There must be exactly one installer; found " + matches); 2743 } 2744 } 2745 2746 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2747 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2748 2749 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2750 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2751 UserHandle.USER_SYSTEM); 2752 ResolveInfo best = null; 2753 final int N = matches.size(); 2754 for (int i = 0; i < N; i++) { 2755 final ResolveInfo cur = matches.get(i); 2756 final String packageName = cur.getComponentInfo().packageName; 2757 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2758 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2759 continue; 2760 } 2761 2762 if (best == null || cur.priority > best.priority) { 2763 best = cur; 2764 } 2765 } 2766 2767 if (best != null) { 2768 return best.getComponentInfo().getComponentName(); 2769 } else { 2770 throw new RuntimeException("There must be at least one intent filter verifier"); 2771 } 2772 } 2773 2774 private @Nullable ComponentName getEphemeralResolverLPr() { 2775 final String[] packageArray = 2776 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2777 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2778 if (DEBUG_EPHEMERAL) { 2779 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2780 } 2781 return null; 2782 } 2783 2784 final int resolveFlags = 2785 MATCH_DIRECT_BOOT_AWARE 2786 | MATCH_DIRECT_BOOT_UNAWARE 2787 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2788 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2789 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2790 resolveFlags, UserHandle.USER_SYSTEM); 2791 2792 final int N = resolvers.size(); 2793 if (N == 0) { 2794 if (DEBUG_EPHEMERAL) { 2795 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2796 } 2797 return null; 2798 } 2799 2800 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2801 for (int i = 0; i < N; i++) { 2802 final ResolveInfo info = resolvers.get(i); 2803 2804 if (info.serviceInfo == null) { 2805 continue; 2806 } 2807 2808 final String packageName = info.serviceInfo.packageName; 2809 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2810 if (DEBUG_EPHEMERAL) { 2811 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2812 + " pkg: " + packageName + ", info:" + info); 2813 } 2814 continue; 2815 } 2816 2817 if (DEBUG_EPHEMERAL) { 2818 Slog.v(TAG, "Ephemeral resolver found;" 2819 + " pkg: " + packageName + ", info:" + info); 2820 } 2821 return new ComponentName(packageName, info.serviceInfo.name); 2822 } 2823 if (DEBUG_EPHEMERAL) { 2824 Slog.v(TAG, "Ephemeral resolver NOT found"); 2825 } 2826 return null; 2827 } 2828 2829 private @Nullable ComponentName getEphemeralInstallerLPr() { 2830 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2831 intent.addCategory(Intent.CATEGORY_DEFAULT); 2832 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2833 2834 final int resolveFlags = 2835 MATCH_DIRECT_BOOT_AWARE 2836 | MATCH_DIRECT_BOOT_UNAWARE 2837 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2838 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2839 resolveFlags, UserHandle.USER_SYSTEM); 2840 if (matches.size() == 0) { 2841 return null; 2842 } else if (matches.size() == 1) { 2843 return matches.get(0).getComponentInfo().getComponentName(); 2844 } else { 2845 throw new RuntimeException( 2846 "There must be at most one ephemeral installer; found " + matches); 2847 } 2848 } 2849 2850 private void primeDomainVerificationsLPw(int userId) { 2851 if (DEBUG_DOMAIN_VERIFICATION) { 2852 Slog.d(TAG, "Priming domain verifications in user " + userId); 2853 } 2854 2855 SystemConfig systemConfig = SystemConfig.getInstance(); 2856 ArraySet<String> packages = systemConfig.getLinkedApps(); 2857 ArraySet<String> domains = new ArraySet<String>(); 2858 2859 for (String packageName : packages) { 2860 PackageParser.Package pkg = mPackages.get(packageName); 2861 if (pkg != null) { 2862 if (!pkg.isSystemApp()) { 2863 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2864 continue; 2865 } 2866 2867 domains.clear(); 2868 for (PackageParser.Activity a : pkg.activities) { 2869 for (ActivityIntentInfo filter : a.intents) { 2870 if (hasValidDomains(filter)) { 2871 domains.addAll(filter.getHostsList()); 2872 } 2873 } 2874 } 2875 2876 if (domains.size() > 0) { 2877 if (DEBUG_DOMAIN_VERIFICATION) { 2878 Slog.v(TAG, " + " + packageName); 2879 } 2880 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2881 // state w.r.t. the formal app-linkage "no verification attempted" state; 2882 // and then 'always' in the per-user state actually used for intent resolution. 2883 final IntentFilterVerificationInfo ivi; 2884 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2885 new ArrayList<String>(domains)); 2886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2887 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2888 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2889 } else { 2890 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2891 + "' does not handle web links"); 2892 } 2893 } else { 2894 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2895 } 2896 } 2897 2898 scheduleWritePackageRestrictionsLocked(userId); 2899 scheduleWriteSettingsLocked(); 2900 } 2901 2902 private void applyFactoryDefaultBrowserLPw(int userId) { 2903 // The default browser app's package name is stored in a string resource, 2904 // with a product-specific overlay used for vendor customization. 2905 String browserPkg = mContext.getResources().getString( 2906 com.android.internal.R.string.default_browser); 2907 if (!TextUtils.isEmpty(browserPkg)) { 2908 // non-empty string => required to be a known package 2909 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2910 if (ps == null) { 2911 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2912 browserPkg = null; 2913 } else { 2914 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2915 } 2916 } 2917 2918 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2919 // default. If there's more than one, just leave everything alone. 2920 if (browserPkg == null) { 2921 calculateDefaultBrowserLPw(userId); 2922 } 2923 } 2924 2925 private void calculateDefaultBrowserLPw(int userId) { 2926 List<String> allBrowsers = resolveAllBrowserApps(userId); 2927 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2928 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2929 } 2930 2931 private List<String> resolveAllBrowserApps(int userId) { 2932 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2933 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2934 PackageManager.MATCH_ALL, userId); 2935 2936 final int count = list.size(); 2937 List<String> result = new ArrayList<String>(count); 2938 for (int i=0; i<count; i++) { 2939 ResolveInfo info = list.get(i); 2940 if (info.activityInfo == null 2941 || !info.handleAllWebDataURI 2942 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2943 || result.contains(info.activityInfo.packageName)) { 2944 continue; 2945 } 2946 result.add(info.activityInfo.packageName); 2947 } 2948 2949 return result; 2950 } 2951 2952 private boolean packageIsBrowser(String packageName, int userId) { 2953 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2954 PackageManager.MATCH_ALL, userId); 2955 final int N = list.size(); 2956 for (int i = 0; i < N; i++) { 2957 ResolveInfo info = list.get(i); 2958 if (packageName.equals(info.activityInfo.packageName)) { 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 2965 private void checkDefaultBrowser() { 2966 final int myUserId = UserHandle.myUserId(); 2967 final String packageName = getDefaultBrowserPackageName(myUserId); 2968 if (packageName != null) { 2969 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2970 if (info == null) { 2971 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2972 synchronized (mPackages) { 2973 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2974 } 2975 } 2976 } 2977 } 2978 2979 @Override 2980 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2981 throws RemoteException { 2982 try { 2983 return super.onTransact(code, data, reply, flags); 2984 } catch (RuntimeException e) { 2985 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2986 Slog.wtf(TAG, "Package Manager Crash", e); 2987 } 2988 throw e; 2989 } 2990 } 2991 2992 static int[] appendInts(int[] cur, int[] add) { 2993 if (add == null) return cur; 2994 if (cur == null) return add; 2995 final int N = add.length; 2996 for (int i=0; i<N; i++) { 2997 cur = appendInt(cur, add[i]); 2998 } 2999 return cur; 3000 } 3001 3002 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3003 if (!sUserManager.exists(userId)) return null; 3004 if (ps == null) { 3005 return null; 3006 } 3007 final PackageParser.Package p = ps.pkg; 3008 if (p == null) { 3009 return null; 3010 } 3011 3012 final PermissionsState permissionsState = ps.getPermissionsState(); 3013 3014 // Compute GIDs only if requested 3015 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3016 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3017 // Compute granted permissions only if package has requested permissions 3018 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3019 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3020 final PackageUserState state = ps.readUserState(userId); 3021 3022 return PackageParser.generatePackageInfo(p, gids, flags, 3023 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3024 } 3025 3026 @Override 3027 public void checkPackageStartable(String packageName, int userId) { 3028 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3029 3030 synchronized (mPackages) { 3031 final PackageSetting ps = mSettings.mPackages.get(packageName); 3032 if (ps == null) { 3033 throw new SecurityException("Package " + packageName + " was not found!"); 3034 } 3035 3036 if (!ps.getInstalled(userId)) { 3037 throw new SecurityException( 3038 "Package " + packageName + " was not installed for user " + userId + "!"); 3039 } 3040 3041 if (mSafeMode && !ps.isSystem()) { 3042 throw new SecurityException("Package " + packageName + " not a system app!"); 3043 } 3044 3045 if (mFrozenPackages.contains(packageName)) { 3046 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3047 } 3048 3049 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3050 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3051 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3052 } 3053 } 3054 } 3055 3056 @Override 3057 public boolean isPackageAvailable(String packageName, int userId) { 3058 if (!sUserManager.exists(userId)) return false; 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3060 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3061 synchronized (mPackages) { 3062 PackageParser.Package p = mPackages.get(packageName); 3063 if (p != null) { 3064 final PackageSetting ps = (PackageSetting) p.mExtras; 3065 if (ps != null) { 3066 final PackageUserState state = ps.readUserState(userId); 3067 if (state != null) { 3068 return PackageParser.isAvailable(state); 3069 } 3070 } 3071 } 3072 } 3073 return false; 3074 } 3075 3076 @Override 3077 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 flags = updateFlagsForPackage(flags, userId, packageName); 3080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3081 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3082 // reader 3083 synchronized (mPackages) { 3084 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3085 PackageParser.Package p = null; 3086 if (matchFactoryOnly) { 3087 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3088 if (ps != null) { 3089 return generatePackageInfo(ps, flags, userId); 3090 } 3091 } 3092 if (p == null) { 3093 p = mPackages.get(packageName); 3094 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3095 return null; 3096 } 3097 } 3098 if (DEBUG_PACKAGE_INFO) 3099 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3100 if (p != null) { 3101 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3102 } 3103 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3104 final PackageSetting ps = mSettings.mPackages.get(packageName); 3105 return generatePackageInfo(ps, flags, userId); 3106 } 3107 } 3108 return null; 3109 } 3110 3111 @Override 3112 public String[] currentToCanonicalPackageNames(String[] names) { 3113 String[] out = new String[names.length]; 3114 // reader 3115 synchronized (mPackages) { 3116 for (int i=names.length-1; i>=0; i--) { 3117 PackageSetting ps = mSettings.mPackages.get(names[i]); 3118 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3119 } 3120 } 3121 return out; 3122 } 3123 3124 @Override 3125 public String[] canonicalToCurrentPackageNames(String[] names) { 3126 String[] out = new String[names.length]; 3127 // reader 3128 synchronized (mPackages) { 3129 for (int i=names.length-1; i>=0; i--) { 3130 String cur = mSettings.mRenamedPackages.get(names[i]); 3131 out[i] = cur != null ? cur : names[i]; 3132 } 3133 } 3134 return out; 3135 } 3136 3137 @Override 3138 public int getPackageUid(String packageName, int flags, int userId) { 3139 if (!sUserManager.exists(userId)) return -1; 3140 flags = updateFlagsForPackage(flags, userId, packageName); 3141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3142 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3143 3144 // reader 3145 synchronized (mPackages) { 3146 final PackageParser.Package p = mPackages.get(packageName); 3147 if (p != null && p.isMatch(flags)) { 3148 return UserHandle.getUid(userId, p.applicationInfo.uid); 3149 } 3150 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3151 final PackageSetting ps = mSettings.mPackages.get(packageName); 3152 if (ps != null && ps.isMatch(flags)) { 3153 return UserHandle.getUid(userId, ps.appId); 3154 } 3155 } 3156 } 3157 3158 return -1; 3159 } 3160 3161 @Override 3162 public int[] getPackageGids(String packageName, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 flags = updateFlagsForPackage(flags, userId, packageName); 3165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3166 false /* requireFullPermission */, false /* checkShell */, 3167 "getPackageGids"); 3168 3169 // reader 3170 synchronized (mPackages) { 3171 final PackageParser.Package p = mPackages.get(packageName); 3172 if (p != null && p.isMatch(flags)) { 3173 PackageSetting ps = (PackageSetting) p.mExtras; 3174 return ps.getPermissionsState().computeGids(userId); 3175 } 3176 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3177 final PackageSetting ps = mSettings.mPackages.get(packageName); 3178 if (ps != null && ps.isMatch(flags)) { 3179 return ps.getPermissionsState().computeGids(userId); 3180 } 3181 } 3182 } 3183 3184 return null; 3185 } 3186 3187 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3188 if (bp.perm != null) { 3189 return PackageParser.generatePermissionInfo(bp.perm, flags); 3190 } 3191 PermissionInfo pi = new PermissionInfo(); 3192 pi.name = bp.name; 3193 pi.packageName = bp.sourcePackage; 3194 pi.nonLocalizedLabel = bp.name; 3195 pi.protectionLevel = bp.protectionLevel; 3196 return pi; 3197 } 3198 3199 @Override 3200 public PermissionInfo getPermissionInfo(String name, int flags) { 3201 // reader 3202 synchronized (mPackages) { 3203 final BasePermission p = mSettings.mPermissions.get(name); 3204 if (p != null) { 3205 return generatePermissionInfo(p, flags); 3206 } 3207 return null; 3208 } 3209 } 3210 3211 @Override 3212 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3213 int flags) { 3214 // reader 3215 synchronized (mPackages) { 3216 if (group != null && !mPermissionGroups.containsKey(group)) { 3217 // This is thrown as NameNotFoundException 3218 return null; 3219 } 3220 3221 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3222 for (BasePermission p : mSettings.mPermissions.values()) { 3223 if (group == null) { 3224 if (p.perm == null || p.perm.info.group == null) { 3225 out.add(generatePermissionInfo(p, flags)); 3226 } 3227 } else { 3228 if (p.perm != null && group.equals(p.perm.info.group)) { 3229 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3230 } 3231 } 3232 } 3233 return new ParceledListSlice<>(out); 3234 } 3235 } 3236 3237 @Override 3238 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3239 // reader 3240 synchronized (mPackages) { 3241 return PackageParser.generatePermissionGroupInfo( 3242 mPermissionGroups.get(name), flags); 3243 } 3244 } 3245 3246 @Override 3247 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3248 // reader 3249 synchronized (mPackages) { 3250 final int N = mPermissionGroups.size(); 3251 ArrayList<PermissionGroupInfo> out 3252 = new ArrayList<PermissionGroupInfo>(N); 3253 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3254 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3255 } 3256 return new ParceledListSlice<>(out); 3257 } 3258 } 3259 3260 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3261 int userId) { 3262 if (!sUserManager.exists(userId)) return null; 3263 PackageSetting ps = mSettings.mPackages.get(packageName); 3264 if (ps != null) { 3265 if (ps.pkg == null) { 3266 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3267 if (pInfo != null) { 3268 return pInfo.applicationInfo; 3269 } 3270 return null; 3271 } 3272 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3273 ps.readUserState(userId), userId); 3274 } 3275 return null; 3276 } 3277 3278 @Override 3279 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3280 if (!sUserManager.exists(userId)) return null; 3281 flags = updateFlagsForApplication(flags, userId, packageName); 3282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3283 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3284 // writer 3285 synchronized (mPackages) { 3286 PackageParser.Package p = mPackages.get(packageName); 3287 if (DEBUG_PACKAGE_INFO) Log.v( 3288 TAG, "getApplicationInfo " + packageName 3289 + ": " + p); 3290 if (p != null) { 3291 PackageSetting ps = mSettings.mPackages.get(packageName); 3292 if (ps == null) return null; 3293 // Note: isEnabledLP() does not apply here - always return info 3294 return PackageParser.generateApplicationInfo( 3295 p, flags, ps.readUserState(userId), userId); 3296 } 3297 if ("android".equals(packageName)||"system".equals(packageName)) { 3298 return mAndroidApplication; 3299 } 3300 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3301 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3302 } 3303 } 3304 return null; 3305 } 3306 3307 @Override 3308 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3309 final IPackageDataObserver observer) { 3310 mContext.enforceCallingOrSelfPermission( 3311 android.Manifest.permission.CLEAR_APP_CACHE, null); 3312 // Queue up an async operation since clearing cache may take a little while. 3313 mHandler.post(new Runnable() { 3314 public void run() { 3315 mHandler.removeCallbacks(this); 3316 boolean success = true; 3317 synchronized (mInstallLock) { 3318 try { 3319 mInstaller.freeCache(volumeUuid, freeStorageSize); 3320 } catch (InstallerException e) { 3321 Slog.w(TAG, "Couldn't clear application caches: " + e); 3322 success = false; 3323 } 3324 } 3325 if (observer != null) { 3326 try { 3327 observer.onRemoveCompleted(null, success); 3328 } catch (RemoteException e) { 3329 Slog.w(TAG, "RemoveException when invoking call back"); 3330 } 3331 } 3332 } 3333 }); 3334 } 3335 3336 @Override 3337 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3338 final IntentSender pi) { 3339 mContext.enforceCallingOrSelfPermission( 3340 android.Manifest.permission.CLEAR_APP_CACHE, null); 3341 // Queue up an async operation since clearing cache may take a little while. 3342 mHandler.post(new Runnable() { 3343 public void run() { 3344 mHandler.removeCallbacks(this); 3345 boolean success = true; 3346 synchronized (mInstallLock) { 3347 try { 3348 mInstaller.freeCache(volumeUuid, freeStorageSize); 3349 } catch (InstallerException e) { 3350 Slog.w(TAG, "Couldn't clear application caches: " + e); 3351 success = false; 3352 } 3353 } 3354 if(pi != null) { 3355 try { 3356 // Callback via pending intent 3357 int code = success ? 1 : 0; 3358 pi.sendIntent(null, code, null, 3359 null, null); 3360 } catch (SendIntentException e1) { 3361 Slog.i(TAG, "Failed to send pending intent"); 3362 } 3363 } 3364 } 3365 }); 3366 } 3367 3368 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3369 synchronized (mInstallLock) { 3370 try { 3371 mInstaller.freeCache(volumeUuid, freeStorageSize); 3372 } catch (InstallerException e) { 3373 throw new IOException("Failed to free enough space", e); 3374 } 3375 } 3376 } 3377 3378 /** 3379 * Update given flags based on encryption status of current user. 3380 */ 3381 private int updateFlags(int flags, int userId) { 3382 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3383 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3384 // Caller expressed an explicit opinion about what encryption 3385 // aware/unaware components they want to see, so fall through and 3386 // give them what they want 3387 } else { 3388 // Caller expressed no opinion, so match based on user state 3389 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3390 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3391 } else { 3392 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3393 } 3394 } 3395 return flags; 3396 } 3397 3398 private UserManagerInternal getUserManagerInternal() { 3399 if (mUserManagerInternal == null) { 3400 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3401 } 3402 return mUserManagerInternal; 3403 } 3404 3405 /** 3406 * Update given flags when being used to request {@link PackageInfo}. 3407 */ 3408 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3409 boolean triaged = true; 3410 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3411 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3412 // Caller is asking for component details, so they'd better be 3413 // asking for specific encryption matching behavior, or be triaged 3414 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3415 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3416 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3417 triaged = false; 3418 } 3419 } 3420 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3421 | PackageManager.MATCH_SYSTEM_ONLY 3422 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3423 triaged = false; 3424 } 3425 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3426 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3427 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3428 } 3429 return updateFlags(flags, userId); 3430 } 3431 3432 /** 3433 * Update given flags when being used to request {@link ApplicationInfo}. 3434 */ 3435 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3436 return updateFlagsForPackage(flags, userId, cookie); 3437 } 3438 3439 /** 3440 * Update given flags when being used to request {@link ComponentInfo}. 3441 */ 3442 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3443 if (cookie instanceof Intent) { 3444 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3445 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3446 } 3447 } 3448 3449 boolean triaged = true; 3450 // Caller is asking for component details, so they'd better be 3451 // asking for specific encryption matching behavior, or be triaged 3452 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3453 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3454 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3455 triaged = false; 3456 } 3457 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3458 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3459 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3460 } 3461 3462 return updateFlags(flags, userId); 3463 } 3464 3465 /** 3466 * Update given flags when being used to request {@link ResolveInfo}. 3467 */ 3468 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3469 // Safe mode means we shouldn't match any third-party components 3470 if (mSafeMode) { 3471 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3472 } 3473 3474 return updateFlagsForComponent(flags, userId, cookie); 3475 } 3476 3477 @Override 3478 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3479 if (!sUserManager.exists(userId)) return null; 3480 flags = updateFlagsForComponent(flags, userId, component); 3481 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3482 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3483 synchronized (mPackages) { 3484 PackageParser.Activity a = mActivities.mActivities.get(component); 3485 3486 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3487 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3488 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3489 if (ps == null) return null; 3490 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3491 userId); 3492 } 3493 if (mResolveComponentName.equals(component)) { 3494 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3495 new PackageUserState(), userId); 3496 } 3497 } 3498 return null; 3499 } 3500 3501 @Override 3502 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3503 String resolvedType) { 3504 synchronized (mPackages) { 3505 if (component.equals(mResolveComponentName)) { 3506 // The resolver supports EVERYTHING! 3507 return true; 3508 } 3509 PackageParser.Activity a = mActivities.mActivities.get(component); 3510 if (a == null) { 3511 return false; 3512 } 3513 for (int i=0; i<a.intents.size(); i++) { 3514 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3515 intent.getData(), intent.getCategories(), TAG) >= 0) { 3516 return true; 3517 } 3518 } 3519 return false; 3520 } 3521 } 3522 3523 @Override 3524 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3525 if (!sUserManager.exists(userId)) return null; 3526 flags = updateFlagsForComponent(flags, userId, component); 3527 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3528 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3529 synchronized (mPackages) { 3530 PackageParser.Activity a = mReceivers.mActivities.get(component); 3531 if (DEBUG_PACKAGE_INFO) Log.v( 3532 TAG, "getReceiverInfo " + component + ": " + a); 3533 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3534 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3535 if (ps == null) return null; 3536 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3537 userId); 3538 } 3539 } 3540 return null; 3541 } 3542 3543 @Override 3544 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3545 if (!sUserManager.exists(userId)) return null; 3546 flags = updateFlagsForComponent(flags, userId, component); 3547 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3548 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3549 synchronized (mPackages) { 3550 PackageParser.Service s = mServices.mServices.get(component); 3551 if (DEBUG_PACKAGE_INFO) Log.v( 3552 TAG, "getServiceInfo " + component + ": " + s); 3553 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3554 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3555 if (ps == null) return null; 3556 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3557 userId); 3558 } 3559 } 3560 return null; 3561 } 3562 3563 @Override 3564 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return null; 3566 flags = updateFlagsForComponent(flags, userId, component); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3569 synchronized (mPackages) { 3570 PackageParser.Provider p = mProviders.mProviders.get(component); 3571 if (DEBUG_PACKAGE_INFO) Log.v( 3572 TAG, "getProviderInfo " + component + ": " + p); 3573 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3574 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3575 if (ps == null) return null; 3576 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3577 userId); 3578 } 3579 } 3580 return null; 3581 } 3582 3583 @Override 3584 public String[] getSystemSharedLibraryNames() { 3585 Set<String> libSet; 3586 synchronized (mPackages) { 3587 libSet = mSharedLibraries.keySet(); 3588 int size = libSet.size(); 3589 if (size > 0) { 3590 String[] libs = new String[size]; 3591 libSet.toArray(libs); 3592 return libs; 3593 } 3594 } 3595 return null; 3596 } 3597 3598 @Override 3599 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3600 synchronized (mPackages) { 3601 return mServicesSystemSharedLibraryPackageName; 3602 } 3603 } 3604 3605 @Override 3606 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3607 synchronized (mPackages) { 3608 return mSharedSystemSharedLibraryPackageName; 3609 } 3610 } 3611 3612 @Override 3613 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3614 synchronized (mPackages) { 3615 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3616 3617 final FeatureInfo fi = new FeatureInfo(); 3618 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3619 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3620 res.add(fi); 3621 3622 return new ParceledListSlice<>(res); 3623 } 3624 } 3625 3626 @Override 3627 public boolean hasSystemFeature(String name, int version) { 3628 synchronized (mPackages) { 3629 final FeatureInfo feat = mAvailableFeatures.get(name); 3630 if (feat == null) { 3631 return false; 3632 } else { 3633 return feat.version >= version; 3634 } 3635 } 3636 } 3637 3638 @Override 3639 public int checkPermission(String permName, String pkgName, int userId) { 3640 if (!sUserManager.exists(userId)) { 3641 return PackageManager.PERMISSION_DENIED; 3642 } 3643 3644 synchronized (mPackages) { 3645 final PackageParser.Package p = mPackages.get(pkgName); 3646 if (p != null && p.mExtras != null) { 3647 final PackageSetting ps = (PackageSetting) p.mExtras; 3648 final PermissionsState permissionsState = ps.getPermissionsState(); 3649 if (permissionsState.hasPermission(permName, userId)) { 3650 return PackageManager.PERMISSION_GRANTED; 3651 } 3652 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3653 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3654 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3655 return PackageManager.PERMISSION_GRANTED; 3656 } 3657 } 3658 } 3659 3660 return PackageManager.PERMISSION_DENIED; 3661 } 3662 3663 @Override 3664 public int checkUidPermission(String permName, int uid) { 3665 final int userId = UserHandle.getUserId(uid); 3666 3667 if (!sUserManager.exists(userId)) { 3668 return PackageManager.PERMISSION_DENIED; 3669 } 3670 3671 synchronized (mPackages) { 3672 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3673 if (obj != null) { 3674 final SettingBase ps = (SettingBase) obj; 3675 final PermissionsState permissionsState = ps.getPermissionsState(); 3676 if (permissionsState.hasPermission(permName, userId)) { 3677 return PackageManager.PERMISSION_GRANTED; 3678 } 3679 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3680 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3681 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3682 return PackageManager.PERMISSION_GRANTED; 3683 } 3684 } else { 3685 ArraySet<String> perms = mSystemPermissions.get(uid); 3686 if (perms != null) { 3687 if (perms.contains(permName)) { 3688 return PackageManager.PERMISSION_GRANTED; 3689 } 3690 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3691 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3692 return PackageManager.PERMISSION_GRANTED; 3693 } 3694 } 3695 } 3696 } 3697 3698 return PackageManager.PERMISSION_DENIED; 3699 } 3700 3701 @Override 3702 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3703 if (UserHandle.getCallingUserId() != userId) { 3704 mContext.enforceCallingPermission( 3705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3706 "isPermissionRevokedByPolicy for user " + userId); 3707 } 3708 3709 if (checkPermission(permission, packageName, userId) 3710 == PackageManager.PERMISSION_GRANTED) { 3711 return false; 3712 } 3713 3714 final long identity = Binder.clearCallingIdentity(); 3715 try { 3716 final int flags = getPermissionFlags(permission, packageName, userId); 3717 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3718 } finally { 3719 Binder.restoreCallingIdentity(identity); 3720 } 3721 } 3722 3723 @Override 3724 public String getPermissionControllerPackageName() { 3725 synchronized (mPackages) { 3726 return mRequiredInstallerPackage; 3727 } 3728 } 3729 3730 /** 3731 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3732 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3733 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3734 * @param message the message to log on security exception 3735 */ 3736 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3737 boolean checkShell, String message) { 3738 if (userId < 0) { 3739 throw new IllegalArgumentException("Invalid userId " + userId); 3740 } 3741 if (checkShell) { 3742 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3743 } 3744 if (userId == UserHandle.getUserId(callingUid)) return; 3745 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3746 if (requireFullPermission) { 3747 mContext.enforceCallingOrSelfPermission( 3748 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3749 } else { 3750 try { 3751 mContext.enforceCallingOrSelfPermission( 3752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3753 } catch (SecurityException se) { 3754 mContext.enforceCallingOrSelfPermission( 3755 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3756 } 3757 } 3758 } 3759 } 3760 3761 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3762 if (callingUid == Process.SHELL_UID) { 3763 if (userHandle >= 0 3764 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3765 throw new SecurityException("Shell does not have permission to access user " 3766 + userHandle); 3767 } else if (userHandle < 0) { 3768 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3769 + Debug.getCallers(3)); 3770 } 3771 } 3772 } 3773 3774 private BasePermission findPermissionTreeLP(String permName) { 3775 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3776 if (permName.startsWith(bp.name) && 3777 permName.length() > bp.name.length() && 3778 permName.charAt(bp.name.length()) == '.') { 3779 return bp; 3780 } 3781 } 3782 return null; 3783 } 3784 3785 private BasePermission checkPermissionTreeLP(String permName) { 3786 if (permName != null) { 3787 BasePermission bp = findPermissionTreeLP(permName); 3788 if (bp != null) { 3789 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3790 return bp; 3791 } 3792 throw new SecurityException("Calling uid " 3793 + Binder.getCallingUid() 3794 + " is not allowed to add to permission tree " 3795 + bp.name + " owned by uid " + bp.uid); 3796 } 3797 } 3798 throw new SecurityException("No permission tree found for " + permName); 3799 } 3800 3801 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3802 if (s1 == null) { 3803 return s2 == null; 3804 } 3805 if (s2 == null) { 3806 return false; 3807 } 3808 if (s1.getClass() != s2.getClass()) { 3809 return false; 3810 } 3811 return s1.equals(s2); 3812 } 3813 3814 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3815 if (pi1.icon != pi2.icon) return false; 3816 if (pi1.logo != pi2.logo) return false; 3817 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3818 if (!compareStrings(pi1.name, pi2.name)) return false; 3819 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3820 // We'll take care of setting this one. 3821 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3822 // These are not currently stored in settings. 3823 //if (!compareStrings(pi1.group, pi2.group)) return false; 3824 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3825 //if (pi1.labelRes != pi2.labelRes) return false; 3826 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3827 return true; 3828 } 3829 3830 int permissionInfoFootprint(PermissionInfo info) { 3831 int size = info.name.length(); 3832 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3833 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3834 return size; 3835 } 3836 3837 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3838 int size = 0; 3839 for (BasePermission perm : mSettings.mPermissions.values()) { 3840 if (perm.uid == tree.uid) { 3841 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3842 } 3843 } 3844 return size; 3845 } 3846 3847 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3848 // We calculate the max size of permissions defined by this uid and throw 3849 // if that plus the size of 'info' would exceed our stated maximum. 3850 if (tree.uid != Process.SYSTEM_UID) { 3851 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3852 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3853 throw new SecurityException("Permission tree size cap exceeded"); 3854 } 3855 } 3856 } 3857 3858 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3859 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3860 throw new SecurityException("Label must be specified in permission"); 3861 } 3862 BasePermission tree = checkPermissionTreeLP(info.name); 3863 BasePermission bp = mSettings.mPermissions.get(info.name); 3864 boolean added = bp == null; 3865 boolean changed = true; 3866 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3867 if (added) { 3868 enforcePermissionCapLocked(info, tree); 3869 bp = new BasePermission(info.name, tree.sourcePackage, 3870 BasePermission.TYPE_DYNAMIC); 3871 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3872 throw new SecurityException( 3873 "Not allowed to modify non-dynamic permission " 3874 + info.name); 3875 } else { 3876 if (bp.protectionLevel == fixedLevel 3877 && bp.perm.owner.equals(tree.perm.owner) 3878 && bp.uid == tree.uid 3879 && comparePermissionInfos(bp.perm.info, info)) { 3880 changed = false; 3881 } 3882 } 3883 bp.protectionLevel = fixedLevel; 3884 info = new PermissionInfo(info); 3885 info.protectionLevel = fixedLevel; 3886 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3887 bp.perm.info.packageName = tree.perm.info.packageName; 3888 bp.uid = tree.uid; 3889 if (added) { 3890 mSettings.mPermissions.put(info.name, bp); 3891 } 3892 if (changed) { 3893 if (!async) { 3894 mSettings.writeLPr(); 3895 } else { 3896 scheduleWriteSettingsLocked(); 3897 } 3898 } 3899 return added; 3900 } 3901 3902 @Override 3903 public boolean addPermission(PermissionInfo info) { 3904 synchronized (mPackages) { 3905 return addPermissionLocked(info, false); 3906 } 3907 } 3908 3909 @Override 3910 public boolean addPermissionAsync(PermissionInfo info) { 3911 synchronized (mPackages) { 3912 return addPermissionLocked(info, true); 3913 } 3914 } 3915 3916 @Override 3917 public void removePermission(String name) { 3918 synchronized (mPackages) { 3919 checkPermissionTreeLP(name); 3920 BasePermission bp = mSettings.mPermissions.get(name); 3921 if (bp != null) { 3922 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3923 throw new SecurityException( 3924 "Not allowed to modify non-dynamic permission " 3925 + name); 3926 } 3927 mSettings.mPermissions.remove(name); 3928 mSettings.writeLPr(); 3929 } 3930 } 3931 } 3932 3933 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3934 BasePermission bp) { 3935 int index = pkg.requestedPermissions.indexOf(bp.name); 3936 if (index == -1) { 3937 throw new SecurityException("Package " + pkg.packageName 3938 + " has not requested permission " + bp.name); 3939 } 3940 if (!bp.isRuntime() && !bp.isDevelopment()) { 3941 throw new SecurityException("Permission " + bp.name 3942 + " is not a changeable permission type"); 3943 } 3944 } 3945 3946 @Override 3947 public void grantRuntimePermission(String packageName, String name, final int userId) { 3948 if (!sUserManager.exists(userId)) { 3949 Log.e(TAG, "No such user:" + userId); 3950 return; 3951 } 3952 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3955 "grantRuntimePermission"); 3956 3957 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3958 true /* requireFullPermission */, true /* checkShell */, 3959 "grantRuntimePermission"); 3960 3961 final int uid; 3962 final SettingBase sb; 3963 3964 synchronized (mPackages) { 3965 final PackageParser.Package pkg = mPackages.get(packageName); 3966 if (pkg == null) { 3967 throw new IllegalArgumentException("Unknown package: " + packageName); 3968 } 3969 3970 final BasePermission bp = mSettings.mPermissions.get(name); 3971 if (bp == null) { 3972 throw new IllegalArgumentException("Unknown permission: " + name); 3973 } 3974 3975 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3976 3977 // If a permission review is required for legacy apps we represent 3978 // their permissions as always granted runtime ones since we need 3979 // to keep the review required permission flag per user while an 3980 // install permission's state is shared across all users. 3981 if (Build.PERMISSIONS_REVIEW_REQUIRED 3982 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3983 && bp.isRuntime()) { 3984 return; 3985 } 3986 3987 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3988 sb = (SettingBase) pkg.mExtras; 3989 if (sb == null) { 3990 throw new IllegalArgumentException("Unknown package: " + packageName); 3991 } 3992 3993 final PermissionsState permissionsState = sb.getPermissionsState(); 3994 3995 final int flags = permissionsState.getPermissionFlags(name, userId); 3996 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3997 throw new SecurityException("Cannot grant system fixed permission " 3998 + name + " for package " + packageName); 3999 } 4000 4001 if (bp.isDevelopment()) { 4002 // Development permissions must be handled specially, since they are not 4003 // normal runtime permissions. For now they apply to all users. 4004 if (permissionsState.grantInstallPermission(bp) != 4005 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4006 scheduleWriteSettingsLocked(); 4007 } 4008 return; 4009 } 4010 4011 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4012 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4013 return; 4014 } 4015 4016 final int result = permissionsState.grantRuntimePermission(bp, userId); 4017 switch (result) { 4018 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4019 return; 4020 } 4021 4022 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4023 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4024 mHandler.post(new Runnable() { 4025 @Override 4026 public void run() { 4027 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4028 } 4029 }); 4030 } 4031 break; 4032 } 4033 4034 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4035 4036 // Not critical if that is lost - app has to request again. 4037 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4038 } 4039 4040 // Only need to do this if user is initialized. Otherwise it's a new user 4041 // and there are no processes running as the user yet and there's no need 4042 // to make an expensive call to remount processes for the changed permissions. 4043 if (READ_EXTERNAL_STORAGE.equals(name) 4044 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4045 final long token = Binder.clearCallingIdentity(); 4046 try { 4047 if (sUserManager.isInitialized(userId)) { 4048 MountServiceInternal mountServiceInternal = LocalServices.getService( 4049 MountServiceInternal.class); 4050 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4051 } 4052 } finally { 4053 Binder.restoreCallingIdentity(token); 4054 } 4055 } 4056 } 4057 4058 @Override 4059 public void revokeRuntimePermission(String packageName, String name, int userId) { 4060 if (!sUserManager.exists(userId)) { 4061 Log.e(TAG, "No such user:" + userId); 4062 return; 4063 } 4064 4065 mContext.enforceCallingOrSelfPermission( 4066 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4067 "revokeRuntimePermission"); 4068 4069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4070 true /* requireFullPermission */, true /* checkShell */, 4071 "revokeRuntimePermission"); 4072 4073 final int appId; 4074 4075 synchronized (mPackages) { 4076 final PackageParser.Package pkg = mPackages.get(packageName); 4077 if (pkg == null) { 4078 throw new IllegalArgumentException("Unknown package: " + packageName); 4079 } 4080 4081 final BasePermission bp = mSettings.mPermissions.get(name); 4082 if (bp == null) { 4083 throw new IllegalArgumentException("Unknown permission: " + name); 4084 } 4085 4086 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4087 4088 // If a permission review is required for legacy apps we represent 4089 // their permissions as always granted runtime ones since we need 4090 // to keep the review required permission flag per user while an 4091 // install permission's state is shared across all users. 4092 if (Build.PERMISSIONS_REVIEW_REQUIRED 4093 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4094 && bp.isRuntime()) { 4095 return; 4096 } 4097 4098 SettingBase sb = (SettingBase) pkg.mExtras; 4099 if (sb == null) { 4100 throw new IllegalArgumentException("Unknown package: " + packageName); 4101 } 4102 4103 final PermissionsState permissionsState = sb.getPermissionsState(); 4104 4105 final int flags = permissionsState.getPermissionFlags(name, userId); 4106 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4107 throw new SecurityException("Cannot revoke system fixed permission " 4108 + name + " for package " + packageName); 4109 } 4110 4111 if (bp.isDevelopment()) { 4112 // Development permissions must be handled specially, since they are not 4113 // normal runtime permissions. For now they apply to all users. 4114 if (permissionsState.revokeInstallPermission(bp) != 4115 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4116 scheduleWriteSettingsLocked(); 4117 } 4118 return; 4119 } 4120 4121 if (permissionsState.revokeRuntimePermission(bp, userId) == 4122 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4123 return; 4124 } 4125 4126 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4127 4128 // Critical, after this call app should never have the permission. 4129 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4130 4131 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4132 } 4133 4134 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4135 } 4136 4137 @Override 4138 public void resetRuntimePermissions() { 4139 mContext.enforceCallingOrSelfPermission( 4140 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4141 "revokeRuntimePermission"); 4142 4143 int callingUid = Binder.getCallingUid(); 4144 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4145 mContext.enforceCallingOrSelfPermission( 4146 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4147 "resetRuntimePermissions"); 4148 } 4149 4150 synchronized (mPackages) { 4151 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4152 for (int userId : UserManagerService.getInstance().getUserIds()) { 4153 final int packageCount = mPackages.size(); 4154 for (int i = 0; i < packageCount; i++) { 4155 PackageParser.Package pkg = mPackages.valueAt(i); 4156 if (!(pkg.mExtras instanceof PackageSetting)) { 4157 continue; 4158 } 4159 PackageSetting ps = (PackageSetting) pkg.mExtras; 4160 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4161 } 4162 } 4163 } 4164 } 4165 4166 @Override 4167 public int getPermissionFlags(String name, String packageName, int userId) { 4168 if (!sUserManager.exists(userId)) { 4169 return 0; 4170 } 4171 4172 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4173 4174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4175 true /* requireFullPermission */, false /* checkShell */, 4176 "getPermissionFlags"); 4177 4178 synchronized (mPackages) { 4179 final PackageParser.Package pkg = mPackages.get(packageName); 4180 if (pkg == null) { 4181 return 0; 4182 } 4183 4184 final BasePermission bp = mSettings.mPermissions.get(name); 4185 if (bp == null) { 4186 return 0; 4187 } 4188 4189 SettingBase sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 return 0; 4192 } 4193 4194 PermissionsState permissionsState = sb.getPermissionsState(); 4195 return permissionsState.getPermissionFlags(name, userId); 4196 } 4197 } 4198 4199 @Override 4200 public void updatePermissionFlags(String name, String packageName, int flagMask, 4201 int flagValues, int userId) { 4202 if (!sUserManager.exists(userId)) { 4203 return; 4204 } 4205 4206 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4207 4208 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4209 true /* requireFullPermission */, true /* checkShell */, 4210 "updatePermissionFlags"); 4211 4212 // Only the system can change these flags and nothing else. 4213 if (getCallingUid() != Process.SYSTEM_UID) { 4214 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4215 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4216 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4217 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4218 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4219 } 4220 4221 synchronized (mPackages) { 4222 final PackageParser.Package pkg = mPackages.get(packageName); 4223 if (pkg == null) { 4224 throw new IllegalArgumentException("Unknown package: " + packageName); 4225 } 4226 4227 final BasePermission bp = mSettings.mPermissions.get(name); 4228 if (bp == null) { 4229 throw new IllegalArgumentException("Unknown permission: " + name); 4230 } 4231 4232 SettingBase sb = (SettingBase) pkg.mExtras; 4233 if (sb == null) { 4234 throw new IllegalArgumentException("Unknown package: " + packageName); 4235 } 4236 4237 PermissionsState permissionsState = sb.getPermissionsState(); 4238 4239 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4240 4241 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4242 // Install and runtime permissions are stored in different places, 4243 // so figure out what permission changed and persist the change. 4244 if (permissionsState.getInstallPermissionState(name) != null) { 4245 scheduleWriteSettingsLocked(); 4246 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4247 || hadState) { 4248 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4249 } 4250 } 4251 } 4252 } 4253 4254 /** 4255 * Update the permission flags for all packages and runtime permissions of a user in order 4256 * to allow device or profile owner to remove POLICY_FIXED. 4257 */ 4258 @Override 4259 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4260 if (!sUserManager.exists(userId)) { 4261 return; 4262 } 4263 4264 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4265 4266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4267 true /* requireFullPermission */, true /* checkShell */, 4268 "updatePermissionFlagsForAllApps"); 4269 4270 // Only the system can change system fixed flags. 4271 if (getCallingUid() != Process.SYSTEM_UID) { 4272 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4273 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4274 } 4275 4276 synchronized (mPackages) { 4277 boolean changed = false; 4278 final int packageCount = mPackages.size(); 4279 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4280 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4281 SettingBase sb = (SettingBase) pkg.mExtras; 4282 if (sb == null) { 4283 continue; 4284 } 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4287 userId, flagMask, flagValues); 4288 } 4289 if (changed) { 4290 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4291 } 4292 } 4293 } 4294 4295 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4296 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4297 != PackageManager.PERMISSION_GRANTED 4298 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4299 != PackageManager.PERMISSION_GRANTED) { 4300 throw new SecurityException(message + " requires " 4301 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4302 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4303 } 4304 } 4305 4306 @Override 4307 public boolean shouldShowRequestPermissionRationale(String permissionName, 4308 String packageName, int userId) { 4309 if (UserHandle.getCallingUserId() != userId) { 4310 mContext.enforceCallingPermission( 4311 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4312 "canShowRequestPermissionRationale for user " + userId); 4313 } 4314 4315 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4316 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4317 return false; 4318 } 4319 4320 if (checkPermission(permissionName, packageName, userId) 4321 == PackageManager.PERMISSION_GRANTED) { 4322 return false; 4323 } 4324 4325 final int flags; 4326 4327 final long identity = Binder.clearCallingIdentity(); 4328 try { 4329 flags = getPermissionFlags(permissionName, 4330 packageName, userId); 4331 } finally { 4332 Binder.restoreCallingIdentity(identity); 4333 } 4334 4335 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4336 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4337 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4338 4339 if ((flags & fixedFlags) != 0) { 4340 return false; 4341 } 4342 4343 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4344 } 4345 4346 @Override 4347 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4348 mContext.enforceCallingOrSelfPermission( 4349 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4350 "addOnPermissionsChangeListener"); 4351 4352 synchronized (mPackages) { 4353 mOnPermissionChangeListeners.addListenerLocked(listener); 4354 } 4355 } 4356 4357 @Override 4358 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4359 synchronized (mPackages) { 4360 mOnPermissionChangeListeners.removeListenerLocked(listener); 4361 } 4362 } 4363 4364 @Override 4365 public boolean isProtectedBroadcast(String actionName) { 4366 synchronized (mPackages) { 4367 if (mProtectedBroadcasts.contains(actionName)) { 4368 return true; 4369 } else if (actionName != null) { 4370 // TODO: remove these terrible hacks 4371 if (actionName.startsWith("android.net.netmon.lingerExpired") 4372 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4373 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4374 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4375 return true; 4376 } 4377 } 4378 } 4379 return false; 4380 } 4381 4382 @Override 4383 public int checkSignatures(String pkg1, String pkg2) { 4384 synchronized (mPackages) { 4385 final PackageParser.Package p1 = mPackages.get(pkg1); 4386 final PackageParser.Package p2 = mPackages.get(pkg2); 4387 if (p1 == null || p1.mExtras == null 4388 || p2 == null || p2.mExtras == null) { 4389 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4390 } 4391 return compareSignatures(p1.mSignatures, p2.mSignatures); 4392 } 4393 } 4394 4395 @Override 4396 public int checkUidSignatures(int uid1, int uid2) { 4397 // Map to base uids. 4398 uid1 = UserHandle.getAppId(uid1); 4399 uid2 = UserHandle.getAppId(uid2); 4400 // reader 4401 synchronized (mPackages) { 4402 Signature[] s1; 4403 Signature[] s2; 4404 Object obj = mSettings.getUserIdLPr(uid1); 4405 if (obj != null) { 4406 if (obj instanceof SharedUserSetting) { 4407 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4408 } else if (obj instanceof PackageSetting) { 4409 s1 = ((PackageSetting)obj).signatures.mSignatures; 4410 } else { 4411 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4412 } 4413 } else { 4414 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4415 } 4416 obj = mSettings.getUserIdLPr(uid2); 4417 if (obj != null) { 4418 if (obj instanceof SharedUserSetting) { 4419 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4420 } else if (obj instanceof PackageSetting) { 4421 s2 = ((PackageSetting)obj).signatures.mSignatures; 4422 } else { 4423 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4424 } 4425 } else { 4426 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4427 } 4428 return compareSignatures(s1, s2); 4429 } 4430 } 4431 4432 /** 4433 * This method should typically only be used when granting or revoking 4434 * permissions, since the app may immediately restart after this call. 4435 * <p> 4436 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4437 * guard your work against the app being relaunched. 4438 */ 4439 private void killUid(int appId, int userId, String reason) { 4440 final long identity = Binder.clearCallingIdentity(); 4441 try { 4442 IActivityManager am = ActivityManagerNative.getDefault(); 4443 if (am != null) { 4444 try { 4445 am.killUid(appId, userId, reason); 4446 } catch (RemoteException e) { 4447 /* ignore - same process */ 4448 } 4449 } 4450 } finally { 4451 Binder.restoreCallingIdentity(identity); 4452 } 4453 } 4454 4455 /** 4456 * Compares two sets of signatures. Returns: 4457 * <br /> 4458 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4459 * <br /> 4460 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4461 * <br /> 4462 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4463 * <br /> 4464 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4465 * <br /> 4466 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4467 */ 4468 static int compareSignatures(Signature[] s1, Signature[] s2) { 4469 if (s1 == null) { 4470 return s2 == null 4471 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4472 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4473 } 4474 4475 if (s2 == null) { 4476 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4477 } 4478 4479 if (s1.length != s2.length) { 4480 return PackageManager.SIGNATURE_NO_MATCH; 4481 } 4482 4483 // Since both signature sets are of size 1, we can compare without HashSets. 4484 if (s1.length == 1) { 4485 return s1[0].equals(s2[0]) ? 4486 PackageManager.SIGNATURE_MATCH : 4487 PackageManager.SIGNATURE_NO_MATCH; 4488 } 4489 4490 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4491 for (Signature sig : s1) { 4492 set1.add(sig); 4493 } 4494 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4495 for (Signature sig : s2) { 4496 set2.add(sig); 4497 } 4498 // Make sure s2 contains all signatures in s1. 4499 if (set1.equals(set2)) { 4500 return PackageManager.SIGNATURE_MATCH; 4501 } 4502 return PackageManager.SIGNATURE_NO_MATCH; 4503 } 4504 4505 /** 4506 * If the database version for this type of package (internal storage or 4507 * external storage) is less than the version where package signatures 4508 * were updated, return true. 4509 */ 4510 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4511 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4512 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4513 } 4514 4515 /** 4516 * Used for backward compatibility to make sure any packages with 4517 * certificate chains get upgraded to the new style. {@code existingSigs} 4518 * will be in the old format (since they were stored on disk from before the 4519 * system upgrade) and {@code scannedSigs} will be in the newer format. 4520 */ 4521 private int compareSignaturesCompat(PackageSignatures existingSigs, 4522 PackageParser.Package scannedPkg) { 4523 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4524 return PackageManager.SIGNATURE_NO_MATCH; 4525 } 4526 4527 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4528 for (Signature sig : existingSigs.mSignatures) { 4529 existingSet.add(sig); 4530 } 4531 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4532 for (Signature sig : scannedPkg.mSignatures) { 4533 try { 4534 Signature[] chainSignatures = sig.getChainSignatures(); 4535 for (Signature chainSig : chainSignatures) { 4536 scannedCompatSet.add(chainSig); 4537 } 4538 } catch (CertificateEncodingException e) { 4539 scannedCompatSet.add(sig); 4540 } 4541 } 4542 /* 4543 * Make sure the expanded scanned set contains all signatures in the 4544 * existing one. 4545 */ 4546 if (scannedCompatSet.equals(existingSet)) { 4547 // Migrate the old signatures to the new scheme. 4548 existingSigs.assignSignatures(scannedPkg.mSignatures); 4549 // The new KeySets will be re-added later in the scanning process. 4550 synchronized (mPackages) { 4551 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4552 } 4553 return PackageManager.SIGNATURE_MATCH; 4554 } 4555 return PackageManager.SIGNATURE_NO_MATCH; 4556 } 4557 4558 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4559 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4560 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4561 } 4562 4563 private int compareSignaturesRecover(PackageSignatures existingSigs, 4564 PackageParser.Package scannedPkg) { 4565 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 String msg = null; 4570 try { 4571 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4572 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4573 + scannedPkg.packageName); 4574 return PackageManager.SIGNATURE_MATCH; 4575 } 4576 } catch (CertificateException e) { 4577 msg = e.getMessage(); 4578 } 4579 4580 logCriticalInfo(Log.INFO, 4581 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4582 return PackageManager.SIGNATURE_NO_MATCH; 4583 } 4584 4585 @Override 4586 public List<String> getAllPackages() { 4587 synchronized (mPackages) { 4588 return new ArrayList<String>(mPackages.keySet()); 4589 } 4590 } 4591 4592 @Override 4593 public String[] getPackagesForUid(int uid) { 4594 uid = UserHandle.getAppId(uid); 4595 // reader 4596 synchronized (mPackages) { 4597 Object obj = mSettings.getUserIdLPr(uid); 4598 if (obj instanceof SharedUserSetting) { 4599 final SharedUserSetting sus = (SharedUserSetting) obj; 4600 final int N = sus.packages.size(); 4601 final String[] res = new String[N]; 4602 for (int i = 0; i < N; i++) { 4603 res[i] = sus.packages.valueAt(i).name; 4604 } 4605 return res; 4606 } else if (obj instanceof PackageSetting) { 4607 final PackageSetting ps = (PackageSetting) obj; 4608 return new String[] { ps.name }; 4609 } 4610 } 4611 return null; 4612 } 4613 4614 @Override 4615 public String getNameForUid(int uid) { 4616 // reader 4617 synchronized (mPackages) { 4618 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4619 if (obj instanceof SharedUserSetting) { 4620 final SharedUserSetting sus = (SharedUserSetting) obj; 4621 return sus.name + ":" + sus.userId; 4622 } else if (obj instanceof PackageSetting) { 4623 final PackageSetting ps = (PackageSetting) obj; 4624 return ps.name; 4625 } 4626 } 4627 return null; 4628 } 4629 4630 @Override 4631 public int getUidForSharedUser(String sharedUserName) { 4632 if(sharedUserName == null) { 4633 return -1; 4634 } 4635 // reader 4636 synchronized (mPackages) { 4637 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4638 if (suid == null) { 4639 return -1; 4640 } 4641 return suid.userId; 4642 } 4643 } 4644 4645 @Override 4646 public int getFlagsForUid(int uid) { 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.pkgFlags; 4652 } else if (obj instanceof PackageSetting) { 4653 final PackageSetting ps = (PackageSetting) obj; 4654 return ps.pkgFlags; 4655 } 4656 } 4657 return 0; 4658 } 4659 4660 @Override 4661 public int getPrivateFlagsForUid(int uid) { 4662 synchronized (mPackages) { 4663 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4664 if (obj instanceof SharedUserSetting) { 4665 final SharedUserSetting sus = (SharedUserSetting) obj; 4666 return sus.pkgPrivateFlags; 4667 } else if (obj instanceof PackageSetting) { 4668 final PackageSetting ps = (PackageSetting) obj; 4669 return ps.pkgPrivateFlags; 4670 } 4671 } 4672 return 0; 4673 } 4674 4675 @Override 4676 public boolean isUidPrivileged(int uid) { 4677 uid = UserHandle.getAppId(uid); 4678 // reader 4679 synchronized (mPackages) { 4680 Object obj = mSettings.getUserIdLPr(uid); 4681 if (obj instanceof SharedUserSetting) { 4682 final SharedUserSetting sus = (SharedUserSetting) obj; 4683 final Iterator<PackageSetting> it = sus.packages.iterator(); 4684 while (it.hasNext()) { 4685 if (it.next().isPrivileged()) { 4686 return true; 4687 } 4688 } 4689 } else if (obj instanceof PackageSetting) { 4690 final PackageSetting ps = (PackageSetting) obj; 4691 return ps.isPrivileged(); 4692 } 4693 } 4694 return false; 4695 } 4696 4697 @Override 4698 public String[] getAppOpPermissionPackages(String permissionName) { 4699 synchronized (mPackages) { 4700 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4701 if (pkgs == null) { 4702 return null; 4703 } 4704 return pkgs.toArray(new String[pkgs.size()]); 4705 } 4706 } 4707 4708 @Override 4709 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4710 int flags, int userId) { 4711 try { 4712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4713 4714 if (!sUserManager.exists(userId)) return null; 4715 flags = updateFlagsForResolve(flags, userId, intent); 4716 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4717 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4718 4719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4720 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4721 flags, userId); 4722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4723 4724 final ResolveInfo bestChoice = 4725 chooseBestActivity(intent, resolvedType, flags, query, userId); 4726 4727 if (isEphemeralAllowed(intent, query, userId)) { 4728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4729 final EphemeralResolveInfo ai = 4730 getEphemeralResolveInfo(intent, resolvedType, userId); 4731 if (ai != null) { 4732 if (DEBUG_EPHEMERAL) { 4733 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4734 } 4735 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4736 bestChoice.ephemeralResolveInfo = ai; 4737 } 4738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4739 } 4740 return bestChoice; 4741 } finally { 4742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4743 } 4744 } 4745 4746 @Override 4747 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4748 IntentFilter filter, int match, ComponentName activity) { 4749 final int userId = UserHandle.getCallingUserId(); 4750 if (DEBUG_PREFERRED) { 4751 Log.v(TAG, "setLastChosenActivity intent=" + intent 4752 + " resolvedType=" + resolvedType 4753 + " flags=" + flags 4754 + " filter=" + filter 4755 + " match=" + match 4756 + " activity=" + activity); 4757 filter.dump(new PrintStreamPrinter(System.out), " "); 4758 } 4759 intent.setComponent(null); 4760 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4761 userId); 4762 // Find any earlier preferred or last chosen entries and nuke them 4763 findPreferredActivity(intent, resolvedType, 4764 flags, query, 0, false, true, false, userId); 4765 // Add the new activity as the last chosen for this filter 4766 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4767 "Setting last chosen"); 4768 } 4769 4770 @Override 4771 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4772 final int userId = UserHandle.getCallingUserId(); 4773 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4774 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4775 userId); 4776 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4777 false, false, false, userId); 4778 } 4779 4780 4781 private boolean isEphemeralAllowed( 4782 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4783 // Short circuit and return early if possible. 4784 if (DISABLE_EPHEMERAL_APPS) { 4785 return false; 4786 } 4787 final int callingUser = UserHandle.getCallingUserId(); 4788 if (callingUser != UserHandle.USER_SYSTEM) { 4789 return false; 4790 } 4791 if (mEphemeralResolverConnection == null) { 4792 return false; 4793 } 4794 if (intent.getComponent() != null) { 4795 return false; 4796 } 4797 if (intent.getPackage() != null) { 4798 return false; 4799 } 4800 final boolean isWebUri = hasWebURI(intent); 4801 if (!isWebUri) { 4802 return false; 4803 } 4804 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4805 synchronized (mPackages) { 4806 final int count = resolvedActivites.size(); 4807 for (int n = 0; n < count; n++) { 4808 ResolveInfo info = resolvedActivites.get(n); 4809 String packageName = info.activityInfo.packageName; 4810 PackageSetting ps = mSettings.mPackages.get(packageName); 4811 if (ps != null) { 4812 // Try to get the status from User settings first 4813 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4814 int status = (int) (packedStatus >> 32); 4815 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4816 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4817 if (DEBUG_EPHEMERAL) { 4818 Slog.v(TAG, "DENY ephemeral apps;" 4819 + " pkg: " + packageName + ", status: " + status); 4820 } 4821 return false; 4822 } 4823 } 4824 } 4825 } 4826 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4827 return true; 4828 } 4829 4830 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4831 int userId) { 4832 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4833 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4834 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 4835 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4836 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4837 ephemeralPrefixCount); 4838 final int[] shaPrefix = digest.getDigestPrefix(); 4839 final byte[][] digestBytes = digest.getDigestBytes(); 4840 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4841 mEphemeralResolverConnection.getEphemeralResolveInfoList( 4842 shaPrefix, ephemeralPrefixMask); 4843 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4844 // No hash prefix match; there are no ephemeral apps for this domain. 4845 return null; 4846 } 4847 4848 // Go in reverse order so we match the narrowest scope first. 4849 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4850 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4851 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4852 continue; 4853 } 4854 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4855 // No filters; this should never happen. 4856 if (filters.isEmpty()) { 4857 continue; 4858 } 4859 // We have a domain match; resolve the filters to see if anything matches. 4860 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4861 for (int j = filters.size() - 1; j >= 0; --j) { 4862 final EphemeralResolveIntentInfo intentInfo = 4863 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4864 ephemeralResolver.addFilter(intentInfo); 4865 } 4866 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4867 intent, resolvedType, false /*defaultOnly*/, userId); 4868 if (!matchedResolveInfoList.isEmpty()) { 4869 return matchedResolveInfoList.get(0); 4870 } 4871 } 4872 } 4873 // Hash or filter mis-match; no ephemeral apps for this domain. 4874 return null; 4875 } 4876 4877 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4878 int flags, List<ResolveInfo> query, int userId) { 4879 if (query != null) { 4880 final int N = query.size(); 4881 if (N == 1) { 4882 return query.get(0); 4883 } else if (N > 1) { 4884 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4885 // If there is more than one activity with the same priority, 4886 // then let the user decide between them. 4887 ResolveInfo r0 = query.get(0); 4888 ResolveInfo r1 = query.get(1); 4889 if (DEBUG_INTENT_MATCHING || debug) { 4890 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4891 + r1.activityInfo.name + "=" + r1.priority); 4892 } 4893 // If the first activity has a higher priority, or a different 4894 // default, then it is always desirable to pick it. 4895 if (r0.priority != r1.priority 4896 || r0.preferredOrder != r1.preferredOrder 4897 || r0.isDefault != r1.isDefault) { 4898 return query.get(0); 4899 } 4900 // If we have saved a preference for a preferred activity for 4901 // this Intent, use that. 4902 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4903 flags, query, r0.priority, true, false, debug, userId); 4904 if (ri != null) { 4905 return ri; 4906 } 4907 ri = new ResolveInfo(mResolveInfo); 4908 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4909 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4910 // If all of the options come from the same package, show the application's 4911 // label and icon instead of the generic resolver's. 4912 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4913 // and then throw away the ResolveInfo itself, meaning that the caller loses 4914 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4915 // a fallback for this case; we only set the target package's resources on 4916 // the ResolveInfo, not the ActivityInfo. 4917 final String intentPackage = intent.getPackage(); 4918 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4919 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4920 ri.resolvePackageName = intentPackage; 4921 if (userNeedsBadging(userId)) { 4922 ri.noResourceId = true; 4923 } else { 4924 ri.icon = appi.icon; 4925 } 4926 ri.iconResourceId = appi.icon; 4927 ri.labelRes = appi.labelRes; 4928 } 4929 ri.activityInfo.applicationInfo = new ApplicationInfo( 4930 ri.activityInfo.applicationInfo); 4931 if (userId != 0) { 4932 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4933 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4934 } 4935 // Make sure that the resolver is displayable in car mode 4936 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4937 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4938 return ri; 4939 } 4940 } 4941 return null; 4942 } 4943 4944 /** 4945 * Return true if the given list is not empty and all of its contents have 4946 * an activityInfo with the given package name. 4947 */ 4948 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4949 if (ArrayUtils.isEmpty(list)) { 4950 return false; 4951 } 4952 for (int i = 0, N = list.size(); i < N; i++) { 4953 final ResolveInfo ri = list.get(i); 4954 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4955 if (ai == null || !packageName.equals(ai.packageName)) { 4956 return false; 4957 } 4958 } 4959 return true; 4960 } 4961 4962 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4963 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4964 final int N = query.size(); 4965 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4966 .get(userId); 4967 // Get the list of persistent preferred activities that handle the intent 4968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4969 List<PersistentPreferredActivity> pprefs = ppir != null 4970 ? ppir.queryIntent(intent, resolvedType, 4971 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4972 : null; 4973 if (pprefs != null && pprefs.size() > 0) { 4974 final int M = pprefs.size(); 4975 for (int i=0; i<M; i++) { 4976 final PersistentPreferredActivity ppa = pprefs.get(i); 4977 if (DEBUG_PREFERRED || debug) { 4978 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4979 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4980 + "\n component=" + ppa.mComponent); 4981 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4982 } 4983 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4984 flags | MATCH_DISABLED_COMPONENTS, userId); 4985 if (DEBUG_PREFERRED || debug) { 4986 Slog.v(TAG, "Found persistent preferred activity:"); 4987 if (ai != null) { 4988 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4989 } else { 4990 Slog.v(TAG, " null"); 4991 } 4992 } 4993 if (ai == null) { 4994 // This previously registered persistent preferred activity 4995 // component is no longer known. Ignore it and do NOT remove it. 4996 continue; 4997 } 4998 for (int j=0; j<N; j++) { 4999 final ResolveInfo ri = query.get(j); 5000 if (!ri.activityInfo.applicationInfo.packageName 5001 .equals(ai.applicationInfo.packageName)) { 5002 continue; 5003 } 5004 if (!ri.activityInfo.name.equals(ai.name)) { 5005 continue; 5006 } 5007 // Found a persistent preference that can handle the intent. 5008 if (DEBUG_PREFERRED || debug) { 5009 Slog.v(TAG, "Returning persistent preferred activity: " + 5010 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5011 } 5012 return ri; 5013 } 5014 } 5015 } 5016 return null; 5017 } 5018 5019 // TODO: handle preferred activities missing while user has amnesia 5020 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5021 List<ResolveInfo> query, int priority, boolean always, 5022 boolean removeMatches, boolean debug, int userId) { 5023 if (!sUserManager.exists(userId)) return null; 5024 flags = updateFlagsForResolve(flags, userId, intent); 5025 // writer 5026 synchronized (mPackages) { 5027 if (intent.getSelector() != null) { 5028 intent = intent.getSelector(); 5029 } 5030 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5031 5032 // Try to find a matching persistent preferred activity. 5033 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5034 debug, userId); 5035 5036 // If a persistent preferred activity matched, use it. 5037 if (pri != null) { 5038 return pri; 5039 } 5040 5041 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5042 // Get the list of preferred activities that handle the intent 5043 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5044 List<PreferredActivity> prefs = pir != null 5045 ? pir.queryIntent(intent, resolvedType, 5046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5047 : null; 5048 if (prefs != null && prefs.size() > 0) { 5049 boolean changed = false; 5050 try { 5051 // First figure out how good the original match set is. 5052 // We will only allow preferred activities that came 5053 // from the same match quality. 5054 int match = 0; 5055 5056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5057 5058 final int N = query.size(); 5059 for (int j=0; j<N; j++) { 5060 final ResolveInfo ri = query.get(j); 5061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5062 + ": 0x" + Integer.toHexString(match)); 5063 if (ri.match > match) { 5064 match = ri.match; 5065 } 5066 } 5067 5068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5069 + Integer.toHexString(match)); 5070 5071 match &= IntentFilter.MATCH_CATEGORY_MASK; 5072 final int M = prefs.size(); 5073 for (int i=0; i<M; i++) { 5074 final PreferredActivity pa = prefs.get(i); 5075 if (DEBUG_PREFERRED || debug) { 5076 Slog.v(TAG, "Checking PreferredActivity ds=" 5077 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5078 + "\n component=" + pa.mPref.mComponent); 5079 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5080 } 5081 if (pa.mPref.mMatch != match) { 5082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5083 + Integer.toHexString(pa.mPref.mMatch)); 5084 continue; 5085 } 5086 // If it's not an "always" type preferred activity and that's what we're 5087 // looking for, skip it. 5088 if (always && !pa.mPref.mAlways) { 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5090 continue; 5091 } 5092 final ActivityInfo ai = getActivityInfo( 5093 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5094 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5095 userId); 5096 if (DEBUG_PREFERRED || debug) { 5097 Slog.v(TAG, "Found preferred activity:"); 5098 if (ai != null) { 5099 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5100 } else { 5101 Slog.v(TAG, " null"); 5102 } 5103 } 5104 if (ai == null) { 5105 // This previously registered preferred activity 5106 // component is no longer known. Most likely an update 5107 // to the app was installed and in the new version this 5108 // component no longer exists. Clean it up by removing 5109 // it from the preferred activities list, and skip it. 5110 Slog.w(TAG, "Removing dangling preferred activity: " 5111 + pa.mPref.mComponent); 5112 pir.removeFilter(pa); 5113 changed = true; 5114 continue; 5115 } 5116 for (int j=0; j<N; j++) { 5117 final ResolveInfo ri = query.get(j); 5118 if (!ri.activityInfo.applicationInfo.packageName 5119 .equals(ai.applicationInfo.packageName)) { 5120 continue; 5121 } 5122 if (!ri.activityInfo.name.equals(ai.name)) { 5123 continue; 5124 } 5125 5126 if (removeMatches) { 5127 pir.removeFilter(pa); 5128 changed = true; 5129 if (DEBUG_PREFERRED) { 5130 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5131 } 5132 break; 5133 } 5134 5135 // Okay we found a previously set preferred or last chosen app. 5136 // If the result set is different from when this 5137 // was created, we need to clear it and re-ask the 5138 // user their preference, if we're looking for an "always" type entry. 5139 if (always && !pa.mPref.sameSet(query)) { 5140 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5141 + intent + " type " + resolvedType); 5142 if (DEBUG_PREFERRED) { 5143 Slog.v(TAG, "Removing preferred activity since set changed " 5144 + pa.mPref.mComponent); 5145 } 5146 pir.removeFilter(pa); 5147 // Re-add the filter as a "last chosen" entry (!always) 5148 PreferredActivity lastChosen = new PreferredActivity( 5149 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5150 pir.addFilter(lastChosen); 5151 changed = true; 5152 return null; 5153 } 5154 5155 // Yay! Either the set matched or we're looking for the last chosen 5156 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5157 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5158 return ri; 5159 } 5160 } 5161 } finally { 5162 if (changed) { 5163 if (DEBUG_PREFERRED) { 5164 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5165 } 5166 scheduleWritePackageRestrictionsLocked(userId); 5167 } 5168 } 5169 } 5170 } 5171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5172 return null; 5173 } 5174 5175 /* 5176 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5177 */ 5178 @Override 5179 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5180 int targetUserId) { 5181 mContext.enforceCallingOrSelfPermission( 5182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5183 List<CrossProfileIntentFilter> matches = 5184 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5185 if (matches != null) { 5186 int size = matches.size(); 5187 for (int i = 0; i < size; i++) { 5188 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5189 } 5190 } 5191 if (hasWebURI(intent)) { 5192 // cross-profile app linking works only towards the parent. 5193 final UserInfo parent = getProfileParent(sourceUserId); 5194 synchronized(mPackages) { 5195 int flags = updateFlagsForResolve(0, parent.id, intent); 5196 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5197 intent, resolvedType, flags, sourceUserId, parent.id); 5198 return xpDomainInfo != null; 5199 } 5200 } 5201 return false; 5202 } 5203 5204 private UserInfo getProfileParent(int userId) { 5205 final long identity = Binder.clearCallingIdentity(); 5206 try { 5207 return sUserManager.getProfileParent(userId); 5208 } finally { 5209 Binder.restoreCallingIdentity(identity); 5210 } 5211 } 5212 5213 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5214 String resolvedType, int userId) { 5215 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5216 if (resolver != null) { 5217 return resolver.queryIntent(intent, resolvedType, false, userId); 5218 } 5219 return null; 5220 } 5221 5222 @Override 5223 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5224 String resolvedType, int flags, int userId) { 5225 try { 5226 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5227 5228 return new ParceledListSlice<>( 5229 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5230 } finally { 5231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5232 } 5233 } 5234 5235 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5236 String resolvedType, int flags, int userId) { 5237 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5238 flags = updateFlagsForResolve(flags, userId, intent); 5239 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5240 false /* requireFullPermission */, false /* checkShell */, 5241 "query intent activities"); 5242 ComponentName comp = intent.getComponent(); 5243 if (comp == null) { 5244 if (intent.getSelector() != null) { 5245 intent = intent.getSelector(); 5246 comp = intent.getComponent(); 5247 } 5248 } 5249 5250 if (comp != null) { 5251 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5252 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5253 if (ai != null) { 5254 final ResolveInfo ri = new ResolveInfo(); 5255 ri.activityInfo = ai; 5256 list.add(ri); 5257 } 5258 return list; 5259 } 5260 5261 // reader 5262 synchronized (mPackages) { 5263 final String pkgName = intent.getPackage(); 5264 if (pkgName == null) { 5265 List<CrossProfileIntentFilter> matchingFilters = 5266 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5267 // Check for results that need to skip the current profile. 5268 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5269 resolvedType, flags, userId); 5270 if (xpResolveInfo != null) { 5271 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5272 result.add(xpResolveInfo); 5273 return filterIfNotSystemUser(result, userId); 5274 } 5275 5276 // Check for results in the current profile. 5277 List<ResolveInfo> result = mActivities.queryIntent( 5278 intent, resolvedType, flags, userId); 5279 result = filterIfNotSystemUser(result, userId); 5280 5281 // Check for cross profile results. 5282 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5283 xpResolveInfo = queryCrossProfileIntents( 5284 matchingFilters, intent, resolvedType, flags, userId, 5285 hasNonNegativePriorityResult); 5286 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5287 boolean isVisibleToUser = filterIfNotSystemUser( 5288 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5289 if (isVisibleToUser) { 5290 result.add(xpResolveInfo); 5291 Collections.sort(result, mResolvePrioritySorter); 5292 } 5293 } 5294 if (hasWebURI(intent)) { 5295 CrossProfileDomainInfo xpDomainInfo = null; 5296 final UserInfo parent = getProfileParent(userId); 5297 if (parent != null) { 5298 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5299 flags, userId, parent.id); 5300 } 5301 if (xpDomainInfo != null) { 5302 if (xpResolveInfo != null) { 5303 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5304 // in the result. 5305 result.remove(xpResolveInfo); 5306 } 5307 if (result.size() == 0) { 5308 result.add(xpDomainInfo.resolveInfo); 5309 return result; 5310 } 5311 } else if (result.size() <= 1) { 5312 return result; 5313 } 5314 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5315 xpDomainInfo, userId); 5316 Collections.sort(result, mResolvePrioritySorter); 5317 } 5318 return result; 5319 } 5320 final PackageParser.Package pkg = mPackages.get(pkgName); 5321 if (pkg != null) { 5322 return filterIfNotSystemUser( 5323 mActivities.queryIntentForPackage( 5324 intent, resolvedType, flags, pkg.activities, userId), 5325 userId); 5326 } 5327 return new ArrayList<ResolveInfo>(); 5328 } 5329 } 5330 5331 private static class CrossProfileDomainInfo { 5332 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5333 ResolveInfo resolveInfo; 5334 /* Best domain verification status of the activities found in the other profile */ 5335 int bestDomainVerificationStatus; 5336 } 5337 5338 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5339 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5340 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5341 sourceUserId)) { 5342 return null; 5343 } 5344 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5345 resolvedType, flags, parentUserId); 5346 5347 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5348 return null; 5349 } 5350 CrossProfileDomainInfo result = null; 5351 int size = resultTargetUser.size(); 5352 for (int i = 0; i < size; i++) { 5353 ResolveInfo riTargetUser = resultTargetUser.get(i); 5354 // Intent filter verification is only for filters that specify a host. So don't return 5355 // those that handle all web uris. 5356 if (riTargetUser.handleAllWebDataURI) { 5357 continue; 5358 } 5359 String packageName = riTargetUser.activityInfo.packageName; 5360 PackageSetting ps = mSettings.mPackages.get(packageName); 5361 if (ps == null) { 5362 continue; 5363 } 5364 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5365 int status = (int)(verificationState >> 32); 5366 if (result == null) { 5367 result = new CrossProfileDomainInfo(); 5368 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5369 sourceUserId, parentUserId); 5370 result.bestDomainVerificationStatus = status; 5371 } else { 5372 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5373 result.bestDomainVerificationStatus); 5374 } 5375 } 5376 // Don't consider matches with status NEVER across profiles. 5377 if (result != null && result.bestDomainVerificationStatus 5378 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5379 return null; 5380 } 5381 return result; 5382 } 5383 5384 /** 5385 * Verification statuses are ordered from the worse to the best, except for 5386 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5387 */ 5388 private int bestDomainVerificationStatus(int status1, int status2) { 5389 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5390 return status2; 5391 } 5392 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5393 return status1; 5394 } 5395 return (int) MathUtils.max(status1, status2); 5396 } 5397 5398 private boolean isUserEnabled(int userId) { 5399 long callingId = Binder.clearCallingIdentity(); 5400 try { 5401 UserInfo userInfo = sUserManager.getUserInfo(userId); 5402 return userInfo != null && userInfo.isEnabled(); 5403 } finally { 5404 Binder.restoreCallingIdentity(callingId); 5405 } 5406 } 5407 5408 /** 5409 * Filter out activities with systemUserOnly flag set, when current user is not System. 5410 * 5411 * @return filtered list 5412 */ 5413 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5414 if (userId == UserHandle.USER_SYSTEM) { 5415 return resolveInfos; 5416 } 5417 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5418 ResolveInfo info = resolveInfos.get(i); 5419 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5420 resolveInfos.remove(i); 5421 } 5422 } 5423 return resolveInfos; 5424 } 5425 5426 /** 5427 * @param resolveInfos list of resolve infos in descending priority order 5428 * @return if the list contains a resolve info with non-negative priority 5429 */ 5430 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5431 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5432 } 5433 5434 private static boolean hasWebURI(Intent intent) { 5435 if (intent.getData() == null) { 5436 return false; 5437 } 5438 final String scheme = intent.getScheme(); 5439 if (TextUtils.isEmpty(scheme)) { 5440 return false; 5441 } 5442 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5443 } 5444 5445 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5446 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5447 int userId) { 5448 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5449 5450 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5451 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5452 candidates.size()); 5453 } 5454 5455 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5456 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5457 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5458 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5459 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5460 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5461 5462 synchronized (mPackages) { 5463 final int count = candidates.size(); 5464 // First, try to use linked apps. Partition the candidates into four lists: 5465 // one for the final results, one for the "do not use ever", one for "undefined status" 5466 // and finally one for "browser app type". 5467 for (int n=0; n<count; n++) { 5468 ResolveInfo info = candidates.get(n); 5469 String packageName = info.activityInfo.packageName; 5470 PackageSetting ps = mSettings.mPackages.get(packageName); 5471 if (ps != null) { 5472 // Add to the special match all list (Browser use case) 5473 if (info.handleAllWebDataURI) { 5474 matchAllList.add(info); 5475 continue; 5476 } 5477 // Try to get the status from User settings first 5478 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5479 int status = (int)(packedStatus >> 32); 5480 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5481 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5482 if (DEBUG_DOMAIN_VERIFICATION) { 5483 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5484 + " : linkgen=" + linkGeneration); 5485 } 5486 // Use link-enabled generation as preferredOrder, i.e. 5487 // prefer newly-enabled over earlier-enabled. 5488 info.preferredOrder = linkGeneration; 5489 alwaysList.add(info); 5490 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5491 if (DEBUG_DOMAIN_VERIFICATION) { 5492 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5493 } 5494 neverList.add(info); 5495 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5496 if (DEBUG_DOMAIN_VERIFICATION) { 5497 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5498 } 5499 alwaysAskList.add(info); 5500 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5501 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5502 if (DEBUG_DOMAIN_VERIFICATION) { 5503 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5504 } 5505 undefinedList.add(info); 5506 } 5507 } 5508 } 5509 5510 // We'll want to include browser possibilities in a few cases 5511 boolean includeBrowser = false; 5512 5513 // First try to add the "always" resolution(s) for the current user, if any 5514 if (alwaysList.size() > 0) { 5515 result.addAll(alwaysList); 5516 } else { 5517 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5518 result.addAll(undefinedList); 5519 // Maybe add one for the other profile. 5520 if (xpDomainInfo != null && ( 5521 xpDomainInfo.bestDomainVerificationStatus 5522 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5523 result.add(xpDomainInfo.resolveInfo); 5524 } 5525 includeBrowser = true; 5526 } 5527 5528 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5529 // If there were 'always' entries their preferred order has been set, so we also 5530 // back that off to make the alternatives equivalent 5531 if (alwaysAskList.size() > 0) { 5532 for (ResolveInfo i : result) { 5533 i.preferredOrder = 0; 5534 } 5535 result.addAll(alwaysAskList); 5536 includeBrowser = true; 5537 } 5538 5539 if (includeBrowser) { 5540 // Also add browsers (all of them or only the default one) 5541 if (DEBUG_DOMAIN_VERIFICATION) { 5542 Slog.v(TAG, " ...including browsers in candidate set"); 5543 } 5544 if ((matchFlags & MATCH_ALL) != 0) { 5545 result.addAll(matchAllList); 5546 } else { 5547 // Browser/generic handling case. If there's a default browser, go straight 5548 // to that (but only if there is no other higher-priority match). 5549 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5550 int maxMatchPrio = 0; 5551 ResolveInfo defaultBrowserMatch = null; 5552 final int numCandidates = matchAllList.size(); 5553 for (int n = 0; n < numCandidates; n++) { 5554 ResolveInfo info = matchAllList.get(n); 5555 // track the highest overall match priority... 5556 if (info.priority > maxMatchPrio) { 5557 maxMatchPrio = info.priority; 5558 } 5559 // ...and the highest-priority default browser match 5560 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5561 if (defaultBrowserMatch == null 5562 || (defaultBrowserMatch.priority < info.priority)) { 5563 if (debug) { 5564 Slog.v(TAG, "Considering default browser match " + info); 5565 } 5566 defaultBrowserMatch = info; 5567 } 5568 } 5569 } 5570 if (defaultBrowserMatch != null 5571 && defaultBrowserMatch.priority >= maxMatchPrio 5572 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5573 { 5574 if (debug) { 5575 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5576 } 5577 result.add(defaultBrowserMatch); 5578 } else { 5579 result.addAll(matchAllList); 5580 } 5581 } 5582 5583 // If there is nothing selected, add all candidates and remove the ones that the user 5584 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5585 if (result.size() == 0) { 5586 result.addAll(candidates); 5587 result.removeAll(neverList); 5588 } 5589 } 5590 } 5591 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5592 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5593 result.size()); 5594 for (ResolveInfo info : result) { 5595 Slog.v(TAG, " + " + info.activityInfo); 5596 } 5597 } 5598 return result; 5599 } 5600 5601 // Returns a packed value as a long: 5602 // 5603 // high 'int'-sized word: link status: undefined/ask/never/always. 5604 // low 'int'-sized word: relative priority among 'always' results. 5605 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5606 long result = ps.getDomainVerificationStatusForUser(userId); 5607 // if none available, get the master status 5608 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5609 if (ps.getIntentFilterVerificationInfo() != null) { 5610 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5611 } 5612 } 5613 return result; 5614 } 5615 5616 private ResolveInfo querySkipCurrentProfileIntents( 5617 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5618 int flags, int sourceUserId) { 5619 if (matchingFilters != null) { 5620 int size = matchingFilters.size(); 5621 for (int i = 0; i < size; i ++) { 5622 CrossProfileIntentFilter filter = matchingFilters.get(i); 5623 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5624 // Checking if there are activities in the target user that can handle the 5625 // intent. 5626 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5627 resolvedType, flags, sourceUserId); 5628 if (resolveInfo != null) { 5629 return resolveInfo; 5630 } 5631 } 5632 } 5633 } 5634 return null; 5635 } 5636 5637 // Return matching ResolveInfo in target user if any. 5638 private ResolveInfo queryCrossProfileIntents( 5639 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5640 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5641 if (matchingFilters != null) { 5642 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5643 // match the same intent. For performance reasons, it is better not to 5644 // run queryIntent twice for the same userId 5645 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5646 int size = matchingFilters.size(); 5647 for (int i = 0; i < size; i++) { 5648 CrossProfileIntentFilter filter = matchingFilters.get(i); 5649 int targetUserId = filter.getTargetUserId(); 5650 boolean skipCurrentProfile = 5651 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5652 boolean skipCurrentProfileIfNoMatchFound = 5653 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5654 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5655 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5656 // Checking if there are activities in the target user that can handle the 5657 // intent. 5658 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5659 resolvedType, flags, sourceUserId); 5660 if (resolveInfo != null) return resolveInfo; 5661 alreadyTriedUserIds.put(targetUserId, true); 5662 } 5663 } 5664 } 5665 return null; 5666 } 5667 5668 /** 5669 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5670 * will forward the intent to the filter's target user. 5671 * Otherwise, returns null. 5672 */ 5673 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5674 String resolvedType, int flags, int sourceUserId) { 5675 int targetUserId = filter.getTargetUserId(); 5676 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5677 resolvedType, flags, targetUserId); 5678 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5679 // If all the matches in the target profile are suspended, return null. 5680 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5681 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5682 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5683 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5684 targetUserId); 5685 } 5686 } 5687 } 5688 return null; 5689 } 5690 5691 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5692 int sourceUserId, int targetUserId) { 5693 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5694 long ident = Binder.clearCallingIdentity(); 5695 boolean targetIsProfile; 5696 try { 5697 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5698 } finally { 5699 Binder.restoreCallingIdentity(ident); 5700 } 5701 String className; 5702 if (targetIsProfile) { 5703 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5704 } else { 5705 className = FORWARD_INTENT_TO_PARENT; 5706 } 5707 ComponentName forwardingActivityComponentName = new ComponentName( 5708 mAndroidApplication.packageName, className); 5709 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5710 sourceUserId); 5711 if (!targetIsProfile) { 5712 forwardingActivityInfo.showUserIcon = targetUserId; 5713 forwardingResolveInfo.noResourceId = true; 5714 } 5715 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5716 forwardingResolveInfo.priority = 0; 5717 forwardingResolveInfo.preferredOrder = 0; 5718 forwardingResolveInfo.match = 0; 5719 forwardingResolveInfo.isDefault = true; 5720 forwardingResolveInfo.filter = filter; 5721 forwardingResolveInfo.targetUserId = targetUserId; 5722 return forwardingResolveInfo; 5723 } 5724 5725 @Override 5726 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5727 Intent[] specifics, String[] specificTypes, Intent intent, 5728 String resolvedType, int flags, int userId) { 5729 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5730 specificTypes, intent, resolvedType, flags, userId)); 5731 } 5732 5733 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5734 Intent[] specifics, String[] specificTypes, Intent intent, 5735 String resolvedType, int flags, int userId) { 5736 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5737 flags = updateFlagsForResolve(flags, userId, intent); 5738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5739 false /* requireFullPermission */, false /* checkShell */, 5740 "query intent activity options"); 5741 final String resultsAction = intent.getAction(); 5742 5743 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5744 | PackageManager.GET_RESOLVED_FILTER, userId); 5745 5746 if (DEBUG_INTENT_MATCHING) { 5747 Log.v(TAG, "Query " + intent + ": " + results); 5748 } 5749 5750 int specificsPos = 0; 5751 int N; 5752 5753 // todo: note that the algorithm used here is O(N^2). This 5754 // isn't a problem in our current environment, but if we start running 5755 // into situations where we have more than 5 or 10 matches then this 5756 // should probably be changed to something smarter... 5757 5758 // First we go through and resolve each of the specific items 5759 // that were supplied, taking care of removing any corresponding 5760 // duplicate items in the generic resolve list. 5761 if (specifics != null) { 5762 for (int i=0; i<specifics.length; i++) { 5763 final Intent sintent = specifics[i]; 5764 if (sintent == null) { 5765 continue; 5766 } 5767 5768 if (DEBUG_INTENT_MATCHING) { 5769 Log.v(TAG, "Specific #" + i + ": " + sintent); 5770 } 5771 5772 String action = sintent.getAction(); 5773 if (resultsAction != null && resultsAction.equals(action)) { 5774 // If this action was explicitly requested, then don't 5775 // remove things that have it. 5776 action = null; 5777 } 5778 5779 ResolveInfo ri = null; 5780 ActivityInfo ai = null; 5781 5782 ComponentName comp = sintent.getComponent(); 5783 if (comp == null) { 5784 ri = resolveIntent( 5785 sintent, 5786 specificTypes != null ? specificTypes[i] : null, 5787 flags, userId); 5788 if (ri == null) { 5789 continue; 5790 } 5791 if (ri == mResolveInfo) { 5792 // ACK! Must do something better with this. 5793 } 5794 ai = ri.activityInfo; 5795 comp = new ComponentName(ai.applicationInfo.packageName, 5796 ai.name); 5797 } else { 5798 ai = getActivityInfo(comp, flags, userId); 5799 if (ai == null) { 5800 continue; 5801 } 5802 } 5803 5804 // Look for any generic query activities that are duplicates 5805 // of this specific one, and remove them from the results. 5806 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5807 N = results.size(); 5808 int j; 5809 for (j=specificsPos; j<N; j++) { 5810 ResolveInfo sri = results.get(j); 5811 if ((sri.activityInfo.name.equals(comp.getClassName()) 5812 && sri.activityInfo.applicationInfo.packageName.equals( 5813 comp.getPackageName())) 5814 || (action != null && sri.filter.matchAction(action))) { 5815 results.remove(j); 5816 if (DEBUG_INTENT_MATCHING) Log.v( 5817 TAG, "Removing duplicate item from " + j 5818 + " due to specific " + specificsPos); 5819 if (ri == null) { 5820 ri = sri; 5821 } 5822 j--; 5823 N--; 5824 } 5825 } 5826 5827 // Add this specific item to its proper place. 5828 if (ri == null) { 5829 ri = new ResolveInfo(); 5830 ri.activityInfo = ai; 5831 } 5832 results.add(specificsPos, ri); 5833 ri.specificIndex = i; 5834 specificsPos++; 5835 } 5836 } 5837 5838 // Now we go through the remaining generic results and remove any 5839 // duplicate actions that are found here. 5840 N = results.size(); 5841 for (int i=specificsPos; i<N-1; i++) { 5842 final ResolveInfo rii = results.get(i); 5843 if (rii.filter == null) { 5844 continue; 5845 } 5846 5847 // Iterate over all of the actions of this result's intent 5848 // filter... typically this should be just one. 5849 final Iterator<String> it = rii.filter.actionsIterator(); 5850 if (it == null) { 5851 continue; 5852 } 5853 while (it.hasNext()) { 5854 final String action = it.next(); 5855 if (resultsAction != null && resultsAction.equals(action)) { 5856 // If this action was explicitly requested, then don't 5857 // remove things that have it. 5858 continue; 5859 } 5860 for (int j=i+1; j<N; j++) { 5861 final ResolveInfo rij = results.get(j); 5862 if (rij.filter != null && rij.filter.hasAction(action)) { 5863 results.remove(j); 5864 if (DEBUG_INTENT_MATCHING) Log.v( 5865 TAG, "Removing duplicate item from " + j 5866 + " due to action " + action + " at " + i); 5867 j--; 5868 N--; 5869 } 5870 } 5871 } 5872 5873 // If the caller didn't request filter information, drop it now 5874 // so we don't have to marshall/unmarshall it. 5875 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5876 rii.filter = null; 5877 } 5878 } 5879 5880 // Filter out the caller activity if so requested. 5881 if (caller != null) { 5882 N = results.size(); 5883 for (int i=0; i<N; i++) { 5884 ActivityInfo ainfo = results.get(i).activityInfo; 5885 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5886 && caller.getClassName().equals(ainfo.name)) { 5887 results.remove(i); 5888 break; 5889 } 5890 } 5891 } 5892 5893 // If the caller didn't request filter information, 5894 // drop them now so we don't have to 5895 // marshall/unmarshall it. 5896 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5897 N = results.size(); 5898 for (int i=0; i<N; i++) { 5899 results.get(i).filter = null; 5900 } 5901 } 5902 5903 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5904 return results; 5905 } 5906 5907 @Override 5908 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5909 String resolvedType, int flags, int userId) { 5910 return new ParceledListSlice<>( 5911 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5912 } 5913 5914 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5915 String resolvedType, int flags, int userId) { 5916 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5917 flags = updateFlagsForResolve(flags, userId, intent); 5918 ComponentName comp = intent.getComponent(); 5919 if (comp == null) { 5920 if (intent.getSelector() != null) { 5921 intent = intent.getSelector(); 5922 comp = intent.getComponent(); 5923 } 5924 } 5925 if (comp != null) { 5926 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5927 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5928 if (ai != null) { 5929 ResolveInfo ri = new ResolveInfo(); 5930 ri.activityInfo = ai; 5931 list.add(ri); 5932 } 5933 return list; 5934 } 5935 5936 // reader 5937 synchronized (mPackages) { 5938 String pkgName = intent.getPackage(); 5939 if (pkgName == null) { 5940 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5941 } 5942 final PackageParser.Package pkg = mPackages.get(pkgName); 5943 if (pkg != null) { 5944 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5945 userId); 5946 } 5947 return Collections.emptyList(); 5948 } 5949 } 5950 5951 @Override 5952 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5953 if (!sUserManager.exists(userId)) return null; 5954 flags = updateFlagsForResolve(flags, userId, intent); 5955 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5956 if (query != null) { 5957 if (query.size() >= 1) { 5958 // If there is more than one service with the same priority, 5959 // just arbitrarily pick the first one. 5960 return query.get(0); 5961 } 5962 } 5963 return null; 5964 } 5965 5966 @Override 5967 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5968 String resolvedType, int flags, int userId) { 5969 return new ParceledListSlice<>( 5970 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5971 } 5972 5973 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5974 String resolvedType, int flags, int userId) { 5975 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5976 flags = updateFlagsForResolve(flags, userId, intent); 5977 ComponentName comp = intent.getComponent(); 5978 if (comp == null) { 5979 if (intent.getSelector() != null) { 5980 intent = intent.getSelector(); 5981 comp = intent.getComponent(); 5982 } 5983 } 5984 if (comp != null) { 5985 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5986 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5987 if (si != null) { 5988 final ResolveInfo ri = new ResolveInfo(); 5989 ri.serviceInfo = si; 5990 list.add(ri); 5991 } 5992 return list; 5993 } 5994 5995 // reader 5996 synchronized (mPackages) { 5997 String pkgName = intent.getPackage(); 5998 if (pkgName == null) { 5999 return mServices.queryIntent(intent, resolvedType, flags, userId); 6000 } 6001 final PackageParser.Package pkg = mPackages.get(pkgName); 6002 if (pkg != null) { 6003 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6004 userId); 6005 } 6006 return Collections.emptyList(); 6007 } 6008 } 6009 6010 @Override 6011 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6012 String resolvedType, int flags, int userId) { 6013 return new ParceledListSlice<>( 6014 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6015 } 6016 6017 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6018 Intent intent, String resolvedType, int flags, int userId) { 6019 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6020 flags = updateFlagsForResolve(flags, userId, intent); 6021 ComponentName comp = intent.getComponent(); 6022 if (comp == null) { 6023 if (intent.getSelector() != null) { 6024 intent = intent.getSelector(); 6025 comp = intent.getComponent(); 6026 } 6027 } 6028 if (comp != null) { 6029 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6030 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6031 if (pi != null) { 6032 final ResolveInfo ri = new ResolveInfo(); 6033 ri.providerInfo = pi; 6034 list.add(ri); 6035 } 6036 return list; 6037 } 6038 6039 // reader 6040 synchronized (mPackages) { 6041 String pkgName = intent.getPackage(); 6042 if (pkgName == null) { 6043 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6044 } 6045 final PackageParser.Package pkg = mPackages.get(pkgName); 6046 if (pkg != null) { 6047 return mProviders.queryIntentForPackage( 6048 intent, resolvedType, flags, pkg.providers, userId); 6049 } 6050 return Collections.emptyList(); 6051 } 6052 } 6053 6054 @Override 6055 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6056 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6057 flags = updateFlagsForPackage(flags, userId, null); 6058 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6060 true /* requireFullPermission */, false /* checkShell */, 6061 "get installed packages"); 6062 6063 // writer 6064 synchronized (mPackages) { 6065 ArrayList<PackageInfo> list; 6066 if (listUninstalled) { 6067 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6068 for (PackageSetting ps : mSettings.mPackages.values()) { 6069 final PackageInfo pi; 6070 if (ps.pkg != null) { 6071 pi = generatePackageInfo(ps, flags, userId); 6072 } else { 6073 pi = generatePackageInfo(ps, flags, userId); 6074 } 6075 if (pi != null) { 6076 list.add(pi); 6077 } 6078 } 6079 } else { 6080 list = new ArrayList<PackageInfo>(mPackages.size()); 6081 for (PackageParser.Package p : mPackages.values()) { 6082 final PackageInfo pi = 6083 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6084 if (pi != null) { 6085 list.add(pi); 6086 } 6087 } 6088 } 6089 6090 return new ParceledListSlice<PackageInfo>(list); 6091 } 6092 } 6093 6094 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6095 String[] permissions, boolean[] tmp, int flags, int userId) { 6096 int numMatch = 0; 6097 final PermissionsState permissionsState = ps.getPermissionsState(); 6098 for (int i=0; i<permissions.length; i++) { 6099 final String permission = permissions[i]; 6100 if (permissionsState.hasPermission(permission, userId)) { 6101 tmp[i] = true; 6102 numMatch++; 6103 } else { 6104 tmp[i] = false; 6105 } 6106 } 6107 if (numMatch == 0) { 6108 return; 6109 } 6110 final PackageInfo pi; 6111 if (ps.pkg != null) { 6112 pi = generatePackageInfo(ps, flags, userId); 6113 } else { 6114 pi = generatePackageInfo(ps, flags, userId); 6115 } 6116 // The above might return null in cases of uninstalled apps or install-state 6117 // skew across users/profiles. 6118 if (pi != null) { 6119 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6120 if (numMatch == permissions.length) { 6121 pi.requestedPermissions = permissions; 6122 } else { 6123 pi.requestedPermissions = new String[numMatch]; 6124 numMatch = 0; 6125 for (int i=0; i<permissions.length; i++) { 6126 if (tmp[i]) { 6127 pi.requestedPermissions[numMatch] = permissions[i]; 6128 numMatch++; 6129 } 6130 } 6131 } 6132 } 6133 list.add(pi); 6134 } 6135 } 6136 6137 @Override 6138 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6139 String[] permissions, int flags, int userId) { 6140 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6141 flags = updateFlagsForPackage(flags, userId, permissions); 6142 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6143 6144 // writer 6145 synchronized (mPackages) { 6146 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6147 boolean[] tmpBools = new boolean[permissions.length]; 6148 if (listUninstalled) { 6149 for (PackageSetting ps : mSettings.mPackages.values()) { 6150 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6151 } 6152 } else { 6153 for (PackageParser.Package pkg : mPackages.values()) { 6154 PackageSetting ps = (PackageSetting)pkg.mExtras; 6155 if (ps != null) { 6156 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6157 userId); 6158 } 6159 } 6160 } 6161 6162 return new ParceledListSlice<PackageInfo>(list); 6163 } 6164 } 6165 6166 @Override 6167 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6168 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6169 flags = updateFlagsForApplication(flags, userId, null); 6170 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6171 6172 // writer 6173 synchronized (mPackages) { 6174 ArrayList<ApplicationInfo> list; 6175 if (listUninstalled) { 6176 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6177 for (PackageSetting ps : mSettings.mPackages.values()) { 6178 ApplicationInfo ai; 6179 if (ps.pkg != null) { 6180 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6181 ps.readUserState(userId), userId); 6182 } else { 6183 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6184 } 6185 if (ai != null) { 6186 list.add(ai); 6187 } 6188 } 6189 } else { 6190 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6191 for (PackageParser.Package p : mPackages.values()) { 6192 if (p.mExtras != null) { 6193 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6194 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6195 if (ai != null) { 6196 list.add(ai); 6197 } 6198 } 6199 } 6200 } 6201 6202 return new ParceledListSlice<ApplicationInfo>(list); 6203 } 6204 } 6205 6206 @Override 6207 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6208 if (DISABLE_EPHEMERAL_APPS) { 6209 return null; 6210 } 6211 6212 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6213 "getEphemeralApplications"); 6214 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6215 true /* requireFullPermission */, false /* checkShell */, 6216 "getEphemeralApplications"); 6217 synchronized (mPackages) { 6218 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6219 .getEphemeralApplicationsLPw(userId); 6220 if (ephemeralApps != null) { 6221 return new ParceledListSlice<>(ephemeralApps); 6222 } 6223 } 6224 return null; 6225 } 6226 6227 @Override 6228 public boolean isEphemeralApplication(String packageName, int userId) { 6229 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6230 true /* requireFullPermission */, false /* checkShell */, 6231 "isEphemeral"); 6232 if (DISABLE_EPHEMERAL_APPS) { 6233 return false; 6234 } 6235 6236 if (!isCallerSameApp(packageName)) { 6237 return false; 6238 } 6239 synchronized (mPackages) { 6240 PackageParser.Package pkg = mPackages.get(packageName); 6241 if (pkg != null) { 6242 return pkg.applicationInfo.isEphemeralApp(); 6243 } 6244 } 6245 return false; 6246 } 6247 6248 @Override 6249 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6250 if (DISABLE_EPHEMERAL_APPS) { 6251 return null; 6252 } 6253 6254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6255 true /* requireFullPermission */, false /* checkShell */, 6256 "getCookie"); 6257 if (!isCallerSameApp(packageName)) { 6258 return null; 6259 } 6260 synchronized (mPackages) { 6261 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6262 packageName, userId); 6263 } 6264 } 6265 6266 @Override 6267 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6268 if (DISABLE_EPHEMERAL_APPS) { 6269 return true; 6270 } 6271 6272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6273 true /* requireFullPermission */, true /* checkShell */, 6274 "setCookie"); 6275 if (!isCallerSameApp(packageName)) { 6276 return false; 6277 } 6278 synchronized (mPackages) { 6279 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6280 packageName, cookie, userId); 6281 } 6282 } 6283 6284 @Override 6285 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6286 if (DISABLE_EPHEMERAL_APPS) { 6287 return null; 6288 } 6289 6290 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6291 "getEphemeralApplicationIcon"); 6292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6293 true /* requireFullPermission */, false /* checkShell */, 6294 "getEphemeralApplicationIcon"); 6295 synchronized (mPackages) { 6296 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6297 packageName, userId); 6298 } 6299 } 6300 6301 private boolean isCallerSameApp(String packageName) { 6302 PackageParser.Package pkg = mPackages.get(packageName); 6303 return pkg != null 6304 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6305 } 6306 6307 @Override 6308 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6309 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6310 } 6311 6312 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6313 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6314 6315 // reader 6316 synchronized (mPackages) { 6317 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6318 final int userId = UserHandle.getCallingUserId(); 6319 while (i.hasNext()) { 6320 final PackageParser.Package p = i.next(); 6321 if (p.applicationInfo == null) continue; 6322 6323 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6324 && !p.applicationInfo.isDirectBootAware(); 6325 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6326 && p.applicationInfo.isDirectBootAware(); 6327 6328 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6329 && (!mSafeMode || isSystemApp(p)) 6330 && (matchesUnaware || matchesAware)) { 6331 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6332 if (ps != null) { 6333 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6334 ps.readUserState(userId), userId); 6335 if (ai != null) { 6336 finalList.add(ai); 6337 } 6338 } 6339 } 6340 } 6341 } 6342 6343 return finalList; 6344 } 6345 6346 @Override 6347 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6348 if (!sUserManager.exists(userId)) return null; 6349 flags = updateFlagsForComponent(flags, userId, name); 6350 // reader 6351 synchronized (mPackages) { 6352 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6353 PackageSetting ps = provider != null 6354 ? mSettings.mPackages.get(provider.owner.packageName) 6355 : null; 6356 return ps != null 6357 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6358 ? PackageParser.generateProviderInfo(provider, flags, 6359 ps.readUserState(userId), userId) 6360 : null; 6361 } 6362 } 6363 6364 /** 6365 * @deprecated 6366 */ 6367 @Deprecated 6368 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6369 // reader 6370 synchronized (mPackages) { 6371 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6372 .entrySet().iterator(); 6373 final int userId = UserHandle.getCallingUserId(); 6374 while (i.hasNext()) { 6375 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6376 PackageParser.Provider p = entry.getValue(); 6377 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6378 6379 if (ps != null && p.syncable 6380 && (!mSafeMode || (p.info.applicationInfo.flags 6381 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6382 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6383 ps.readUserState(userId), userId); 6384 if (info != null) { 6385 outNames.add(entry.getKey()); 6386 outInfo.add(info); 6387 } 6388 } 6389 } 6390 } 6391 } 6392 6393 @Override 6394 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6395 int uid, int flags) { 6396 final int userId = processName != null ? UserHandle.getUserId(uid) 6397 : UserHandle.getCallingUserId(); 6398 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6399 flags = updateFlagsForComponent(flags, userId, processName); 6400 6401 ArrayList<ProviderInfo> finalList = null; 6402 // reader 6403 synchronized (mPackages) { 6404 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6405 while (i.hasNext()) { 6406 final PackageParser.Provider p = i.next(); 6407 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6408 if (ps != null && p.info.authority != null 6409 && (processName == null 6410 || (p.info.processName.equals(processName) 6411 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6412 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6413 if (finalList == null) { 6414 finalList = new ArrayList<ProviderInfo>(3); 6415 } 6416 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6417 ps.readUserState(userId), userId); 6418 if (info != null) { 6419 finalList.add(info); 6420 } 6421 } 6422 } 6423 } 6424 6425 if (finalList != null) { 6426 Collections.sort(finalList, mProviderInitOrderSorter); 6427 return new ParceledListSlice<ProviderInfo>(finalList); 6428 } 6429 6430 return ParceledListSlice.emptyList(); 6431 } 6432 6433 @Override 6434 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6435 // reader 6436 synchronized (mPackages) { 6437 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6438 return PackageParser.generateInstrumentationInfo(i, flags); 6439 } 6440 } 6441 6442 @Override 6443 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6444 String targetPackage, int flags) { 6445 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6446 } 6447 6448 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6449 int flags) { 6450 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6451 6452 // reader 6453 synchronized (mPackages) { 6454 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6455 while (i.hasNext()) { 6456 final PackageParser.Instrumentation p = i.next(); 6457 if (targetPackage == null 6458 || targetPackage.equals(p.info.targetPackage)) { 6459 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6460 flags); 6461 if (ii != null) { 6462 finalList.add(ii); 6463 } 6464 } 6465 } 6466 } 6467 6468 return finalList; 6469 } 6470 6471 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6472 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6473 if (overlays == null) { 6474 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6475 return; 6476 } 6477 for (PackageParser.Package opkg : overlays.values()) { 6478 // Not much to do if idmap fails: we already logged the error 6479 // and we certainly don't want to abort installation of pkg simply 6480 // because an overlay didn't fit properly. For these reasons, 6481 // ignore the return value of createIdmapForPackagePairLI. 6482 createIdmapForPackagePairLI(pkg, opkg); 6483 } 6484 } 6485 6486 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6487 PackageParser.Package opkg) { 6488 if (!opkg.mTrustedOverlay) { 6489 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6490 opkg.baseCodePath + ": overlay not trusted"); 6491 return false; 6492 } 6493 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6494 if (overlaySet == null) { 6495 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6496 opkg.baseCodePath + " but target package has no known overlays"); 6497 return false; 6498 } 6499 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6500 // TODO: generate idmap for split APKs 6501 try { 6502 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6503 } catch (InstallerException e) { 6504 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6505 + opkg.baseCodePath); 6506 return false; 6507 } 6508 PackageParser.Package[] overlayArray = 6509 overlaySet.values().toArray(new PackageParser.Package[0]); 6510 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6511 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6512 return p1.mOverlayPriority - p2.mOverlayPriority; 6513 } 6514 }; 6515 Arrays.sort(overlayArray, cmp); 6516 6517 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6518 int i = 0; 6519 for (PackageParser.Package p : overlayArray) { 6520 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6521 } 6522 return true; 6523 } 6524 6525 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6527 try { 6528 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6529 } finally { 6530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6531 } 6532 } 6533 6534 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6535 final File[] files = dir.listFiles(); 6536 if (ArrayUtils.isEmpty(files)) { 6537 Log.d(TAG, "No files in app dir " + dir); 6538 return; 6539 } 6540 6541 if (DEBUG_PACKAGE_SCANNING) { 6542 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6543 + " flags=0x" + Integer.toHexString(parseFlags)); 6544 } 6545 6546 for (File file : files) { 6547 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6548 && !PackageInstallerService.isStageName(file.getName()); 6549 if (!isPackage) { 6550 // Ignore entries which are not packages 6551 continue; 6552 } 6553 try { 6554 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6555 scanFlags, currentTime, null); 6556 } catch (PackageManagerException e) { 6557 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6558 6559 // Delete invalid userdata apps 6560 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6561 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6562 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6563 removeCodePathLI(file); 6564 } 6565 } 6566 } 6567 } 6568 6569 private static File getSettingsProblemFile() { 6570 File dataDir = Environment.getDataDirectory(); 6571 File systemDir = new File(dataDir, "system"); 6572 File fname = new File(systemDir, "uiderrors.txt"); 6573 return fname; 6574 } 6575 6576 static void reportSettingsProblem(int priority, String msg) { 6577 logCriticalInfo(priority, msg); 6578 } 6579 6580 static void logCriticalInfo(int priority, String msg) { 6581 Slog.println(priority, TAG, msg); 6582 EventLogTags.writePmCriticalInfo(msg); 6583 try { 6584 File fname = getSettingsProblemFile(); 6585 FileOutputStream out = new FileOutputStream(fname, true); 6586 PrintWriter pw = new FastPrintWriter(out); 6587 SimpleDateFormat formatter = new SimpleDateFormat(); 6588 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6589 pw.println(dateString + ": " + msg); 6590 pw.close(); 6591 FileUtils.setPermissions( 6592 fname.toString(), 6593 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6594 -1, -1); 6595 } catch (java.io.IOException e) { 6596 } 6597 } 6598 6599 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6600 if (srcFile.isDirectory()) { 6601 final File baseFile = new File(pkg.baseCodePath); 6602 long maxModifiedTime = baseFile.lastModified(); 6603 if (pkg.splitCodePaths != null) { 6604 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6605 final File splitFile = new File(pkg.splitCodePaths[i]); 6606 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6607 } 6608 } 6609 return maxModifiedTime; 6610 } 6611 return srcFile.lastModified(); 6612 } 6613 6614 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6615 final int policyFlags) throws PackageManagerException { 6616 if (ps != null 6617 && ps.codePath.equals(srcFile) 6618 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6619 && !isCompatSignatureUpdateNeeded(pkg) 6620 && !isRecoverSignatureUpdateNeeded(pkg)) { 6621 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6622 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6623 ArraySet<PublicKey> signingKs; 6624 synchronized (mPackages) { 6625 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6626 } 6627 if (ps.signatures.mSignatures != null 6628 && ps.signatures.mSignatures.length != 0 6629 && signingKs != null) { 6630 // Optimization: reuse the existing cached certificates 6631 // if the package appears to be unchanged. 6632 pkg.mSignatures = ps.signatures.mSignatures; 6633 pkg.mSigningKeys = signingKs; 6634 return; 6635 } 6636 6637 Slog.w(TAG, "PackageSetting for " + ps.name 6638 + " is missing signatures. Collecting certs again to recover them."); 6639 } else { 6640 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6641 } 6642 6643 try { 6644 PackageParser.collectCertificates(pkg, policyFlags); 6645 } catch (PackageParserException e) { 6646 throw PackageManagerException.from(e); 6647 } 6648 } 6649 6650 /** 6651 * Traces a package scan. 6652 * @see #scanPackageLI(File, int, int, long, UserHandle) 6653 */ 6654 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6655 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6657 try { 6658 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6659 } finally { 6660 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6661 } 6662 } 6663 6664 /** 6665 * Scans a package and returns the newly parsed package. 6666 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6667 */ 6668 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6669 long currentTime, UserHandle user) throws PackageManagerException { 6670 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6671 PackageParser pp = new PackageParser(); 6672 pp.setSeparateProcesses(mSeparateProcesses); 6673 pp.setOnlyCoreApps(mOnlyCore); 6674 pp.setDisplayMetrics(mMetrics); 6675 6676 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6677 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6678 } 6679 6680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6681 final PackageParser.Package pkg; 6682 try { 6683 pkg = pp.parsePackage(scanFile, parseFlags); 6684 } catch (PackageParserException e) { 6685 throw PackageManagerException.from(e); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 6690 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6691 } 6692 6693 /** 6694 * Scans a package and returns the newly parsed package. 6695 * @throws PackageManagerException on a parse error. 6696 */ 6697 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6698 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6699 throws PackageManagerException { 6700 // If the package has children and this is the first dive in the function 6701 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6702 // packages (parent and children) would be successfully scanned before the 6703 // actual scan since scanning mutates internal state and we want to atomically 6704 // install the package and its children. 6705 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6706 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6707 scanFlags |= SCAN_CHECK_ONLY; 6708 } 6709 } else { 6710 scanFlags &= ~SCAN_CHECK_ONLY; 6711 } 6712 6713 // Scan the parent 6714 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6715 scanFlags, currentTime, user); 6716 6717 // Scan the children 6718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6719 for (int i = 0; i < childCount; i++) { 6720 PackageParser.Package childPackage = pkg.childPackages.get(i); 6721 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6722 currentTime, user); 6723 } 6724 6725 6726 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6727 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6728 } 6729 6730 return scannedPkg; 6731 } 6732 6733 /** 6734 * Scans a package and returns the newly parsed package. 6735 * @throws PackageManagerException on a parse error. 6736 */ 6737 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6738 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6739 throws PackageManagerException { 6740 PackageSetting ps = null; 6741 PackageSetting updatedPkg; 6742 // reader 6743 synchronized (mPackages) { 6744 // Look to see if we already know about this package. 6745 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6746 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6747 // This package has been renamed to its original name. Let's 6748 // use that. 6749 ps = mSettings.peekPackageLPr(oldName); 6750 } 6751 // If there was no original package, see one for the real package name. 6752 if (ps == null) { 6753 ps = mSettings.peekPackageLPr(pkg.packageName); 6754 } 6755 // Check to see if this package could be hiding/updating a system 6756 // package. Must look for it either under the original or real 6757 // package name depending on our state. 6758 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6759 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6760 6761 // If this is a package we don't know about on the system partition, we 6762 // may need to remove disabled child packages on the system partition 6763 // or may need to not add child packages if the parent apk is updated 6764 // on the data partition and no longer defines this child package. 6765 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6766 // If this is a parent package for an updated system app and this system 6767 // app got an OTA update which no longer defines some of the child packages 6768 // we have to prune them from the disabled system packages. 6769 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6770 if (disabledPs != null) { 6771 final int scannedChildCount = (pkg.childPackages != null) 6772 ? pkg.childPackages.size() : 0; 6773 final int disabledChildCount = disabledPs.childPackageNames != null 6774 ? disabledPs.childPackageNames.size() : 0; 6775 for (int i = 0; i < disabledChildCount; i++) { 6776 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6777 boolean disabledPackageAvailable = false; 6778 for (int j = 0; j < scannedChildCount; j++) { 6779 PackageParser.Package childPkg = pkg.childPackages.get(j); 6780 if (childPkg.packageName.equals(disabledChildPackageName)) { 6781 disabledPackageAvailable = true; 6782 break; 6783 } 6784 } 6785 if (!disabledPackageAvailable) { 6786 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6787 } 6788 } 6789 } 6790 } 6791 } 6792 6793 boolean updatedPkgBetter = false; 6794 // First check if this is a system package that may involve an update 6795 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6796 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6797 // it needs to drop FLAG_PRIVILEGED. 6798 if (locationIsPrivileged(scanFile)) { 6799 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6800 } else { 6801 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6802 } 6803 6804 if (ps != null && !ps.codePath.equals(scanFile)) { 6805 // The path has changed from what was last scanned... check the 6806 // version of the new path against what we have stored to determine 6807 // what to do. 6808 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6809 if (pkg.mVersionCode <= ps.versionCode) { 6810 // The system package has been updated and the code path does not match 6811 // Ignore entry. Skip it. 6812 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6813 + " ignored: updated version " + ps.versionCode 6814 + " better than this " + pkg.mVersionCode); 6815 if (!updatedPkg.codePath.equals(scanFile)) { 6816 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6817 + ps.name + " changing from " + updatedPkg.codePathString 6818 + " to " + scanFile); 6819 updatedPkg.codePath = scanFile; 6820 updatedPkg.codePathString = scanFile.toString(); 6821 updatedPkg.resourcePath = scanFile; 6822 updatedPkg.resourcePathString = scanFile.toString(); 6823 } 6824 updatedPkg.pkg = pkg; 6825 updatedPkg.versionCode = pkg.mVersionCode; 6826 6827 // Update the disabled system child packages to point to the package too. 6828 final int childCount = updatedPkg.childPackageNames != null 6829 ? updatedPkg.childPackageNames.size() : 0; 6830 for (int i = 0; i < childCount; i++) { 6831 String childPackageName = updatedPkg.childPackageNames.get(i); 6832 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6833 childPackageName); 6834 if (updatedChildPkg != null) { 6835 updatedChildPkg.pkg = pkg; 6836 updatedChildPkg.versionCode = pkg.mVersionCode; 6837 } 6838 } 6839 6840 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6841 + scanFile + " ignored: updated version " + ps.versionCode 6842 + " better than this " + pkg.mVersionCode); 6843 } else { 6844 // The current app on the system partition is better than 6845 // what we have updated to on the data partition; switch 6846 // back to the system partition version. 6847 // At this point, its safely assumed that package installation for 6848 // apps in system partition will go through. If not there won't be a working 6849 // version of the app 6850 // writer 6851 synchronized (mPackages) { 6852 // Just remove the loaded entries from package lists. 6853 mPackages.remove(ps.name); 6854 } 6855 6856 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6857 + " reverting from " + ps.codePathString 6858 + ": new version " + pkg.mVersionCode 6859 + " better than installed " + ps.versionCode); 6860 6861 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6862 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6863 synchronized (mInstallLock) { 6864 args.cleanUpResourcesLI(); 6865 } 6866 synchronized (mPackages) { 6867 mSettings.enableSystemPackageLPw(ps.name); 6868 } 6869 updatedPkgBetter = true; 6870 } 6871 } 6872 } 6873 6874 if (updatedPkg != null) { 6875 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6876 // initially 6877 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6878 6879 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6880 // flag set initially 6881 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6882 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6883 } 6884 } 6885 6886 // Verify certificates against what was last scanned 6887 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6888 6889 /* 6890 * A new system app appeared, but we already had a non-system one of the 6891 * same name installed earlier. 6892 */ 6893 boolean shouldHideSystemApp = false; 6894 if (updatedPkg == null && ps != null 6895 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6896 /* 6897 * Check to make sure the signatures match first. If they don't, 6898 * wipe the installed application and its data. 6899 */ 6900 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6901 != PackageManager.SIGNATURE_MATCH) { 6902 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6903 + " signatures don't match existing userdata copy; removing"); 6904 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6905 "scanPackageInternalLI")) { 6906 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6907 } 6908 ps = null; 6909 } else { 6910 /* 6911 * If the newly-added system app is an older version than the 6912 * already installed version, hide it. It will be scanned later 6913 * and re-added like an update. 6914 */ 6915 if (pkg.mVersionCode <= ps.versionCode) { 6916 shouldHideSystemApp = true; 6917 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6918 + " but new version " + pkg.mVersionCode + " better than installed " 6919 + ps.versionCode + "; hiding system"); 6920 } else { 6921 /* 6922 * The newly found system app is a newer version that the 6923 * one previously installed. Simply remove the 6924 * already-installed application and replace it with our own 6925 * while keeping the application data. 6926 */ 6927 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6928 + " reverting from " + ps.codePathString + ": new version " 6929 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6930 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6931 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6932 synchronized (mInstallLock) { 6933 args.cleanUpResourcesLI(); 6934 } 6935 } 6936 } 6937 } 6938 6939 // The apk is forward locked (not public) if its code and resources 6940 // are kept in different files. (except for app in either system or 6941 // vendor path). 6942 // TODO grab this value from PackageSettings 6943 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6944 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6945 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6946 } 6947 } 6948 6949 // TODO: extend to support forward-locked splits 6950 String resourcePath = null; 6951 String baseResourcePath = null; 6952 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6953 if (ps != null && ps.resourcePathString != null) { 6954 resourcePath = ps.resourcePathString; 6955 baseResourcePath = ps.resourcePathString; 6956 } else { 6957 // Should not happen at all. Just log an error. 6958 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6959 } 6960 } else { 6961 resourcePath = pkg.codePath; 6962 baseResourcePath = pkg.baseCodePath; 6963 } 6964 6965 // Set application objects path explicitly. 6966 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6967 pkg.setApplicationInfoCodePath(pkg.codePath); 6968 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6969 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6970 pkg.setApplicationInfoResourcePath(resourcePath); 6971 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6972 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6973 6974 // Note that we invoke the following method only if we are about to unpack an application 6975 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6976 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6977 6978 /* 6979 * If the system app should be overridden by a previously installed 6980 * data, hide the system app now and let the /data/app scan pick it up 6981 * again. 6982 */ 6983 if (shouldHideSystemApp) { 6984 synchronized (mPackages) { 6985 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6986 } 6987 } 6988 6989 return scannedPkg; 6990 } 6991 6992 private static String fixProcessName(String defProcessName, 6993 String processName, int uid) { 6994 if (processName == null) { 6995 return defProcessName; 6996 } 6997 return processName; 6998 } 6999 7000 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7001 throws PackageManagerException { 7002 if (pkgSetting.signatures.mSignatures != null) { 7003 // Already existing package. Make sure signatures match 7004 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7005 == PackageManager.SIGNATURE_MATCH; 7006 if (!match) { 7007 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7008 == PackageManager.SIGNATURE_MATCH; 7009 } 7010 if (!match) { 7011 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7012 == PackageManager.SIGNATURE_MATCH; 7013 } 7014 if (!match) { 7015 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7016 + pkg.packageName + " signatures do not match the " 7017 + "previously installed version; ignoring!"); 7018 } 7019 } 7020 7021 // Check for shared user signatures 7022 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7023 // Already existing package. Make sure signatures match 7024 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7025 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7026 if (!match) { 7027 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7028 == PackageManager.SIGNATURE_MATCH; 7029 } 7030 if (!match) { 7031 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7032 == PackageManager.SIGNATURE_MATCH; 7033 } 7034 if (!match) { 7035 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7036 "Package " + pkg.packageName 7037 + " has no signatures that match those in shared user " 7038 + pkgSetting.sharedUser.name + "; ignoring!"); 7039 } 7040 } 7041 } 7042 7043 /** 7044 * Enforces that only the system UID or root's UID can call a method exposed 7045 * via Binder. 7046 * 7047 * @param message used as message if SecurityException is thrown 7048 * @throws SecurityException if the caller is not system or root 7049 */ 7050 private static final void enforceSystemOrRoot(String message) { 7051 final int uid = Binder.getCallingUid(); 7052 if (uid != Process.SYSTEM_UID && uid != 0) { 7053 throw new SecurityException(message); 7054 } 7055 } 7056 7057 @Override 7058 public void performFstrimIfNeeded() { 7059 enforceSystemOrRoot("Only the system can request fstrim"); 7060 7061 // Before everything else, see whether we need to fstrim. 7062 try { 7063 IMountService ms = PackageHelper.getMountService(); 7064 if (ms != null) { 7065 boolean doTrim = false; 7066 final long interval = android.provider.Settings.Global.getLong( 7067 mContext.getContentResolver(), 7068 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7069 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7070 if (interval > 0) { 7071 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7072 if (timeSinceLast > interval) { 7073 doTrim = true; 7074 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7075 + "; running immediately"); 7076 } 7077 } 7078 if (doTrim) { 7079 if (!isFirstBoot()) { 7080 try { 7081 ActivityManagerNative.getDefault().showBootMessage( 7082 mContext.getResources().getString( 7083 R.string.android_upgrading_fstrim), true); 7084 } catch (RemoteException e) { 7085 } 7086 } 7087 ms.runMaintenance(); 7088 } 7089 } else { 7090 Slog.e(TAG, "Mount service unavailable!"); 7091 } 7092 } catch (RemoteException e) { 7093 // Can't happen; MountService is local 7094 } 7095 } 7096 7097 @Override 7098 public void updatePackagesIfNeeded() { 7099 enforceSystemOrRoot("Only the system can request package update"); 7100 7101 // We need to re-extract after an OTA. 7102 boolean causeUpgrade = isUpgrade(); 7103 7104 // First boot or factory reset. 7105 // Note: we also handle devices that are upgrading to N right now as if it is their 7106 // first boot, as they do not have profile data. 7107 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7108 7109 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7110 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7111 7112 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7113 return; 7114 } 7115 7116 List<PackageParser.Package> pkgs; 7117 synchronized (mPackages) { 7118 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7119 } 7120 7121 final long startTime = System.nanoTime(); 7122 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7123 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7124 7125 final int elapsedTimeSeconds = 7126 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7127 7128 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7129 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7130 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7131 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7132 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7133 } 7134 7135 /** 7136 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7137 * containing statistics about the invocation. The array consists of three elements, 7138 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7139 * and {@code numberOfPackagesFailed}. 7140 */ 7141 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7142 String compilerFilter) { 7143 7144 int numberOfPackagesVisited = 0; 7145 int numberOfPackagesOptimized = 0; 7146 int numberOfPackagesSkipped = 0; 7147 int numberOfPackagesFailed = 0; 7148 final int numberOfPackagesToDexopt = pkgs.size(); 7149 7150 for (PackageParser.Package pkg : pkgs) { 7151 numberOfPackagesVisited++; 7152 7153 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7154 if (DEBUG_DEXOPT) { 7155 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7156 } 7157 numberOfPackagesSkipped++; 7158 continue; 7159 } 7160 7161 if (DEBUG_DEXOPT) { 7162 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7163 numberOfPackagesToDexopt + ": " + pkg.packageName); 7164 } 7165 7166 if (showDialog) { 7167 try { 7168 ActivityManagerNative.getDefault().showBootMessage( 7169 mContext.getResources().getString(R.string.android_upgrading_apk, 7170 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7171 } catch (RemoteException e) { 7172 } 7173 } 7174 7175 // If the OTA updates a system app which was previously preopted to a non-preopted state 7176 // the app might end up being verified at runtime. That's because by default the apps 7177 // are verify-profile but for preopted apps there's no profile. 7178 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7179 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7180 // filter (by default interpret-only). 7181 // Note that at this stage unused apps are already filtered. 7182 if (isSystemApp(pkg) && 7183 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7184 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7185 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7186 } 7187 7188 // checkProfiles is false to avoid merging profiles during boot which 7189 // might interfere with background compilation (b/28612421). 7190 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7191 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7192 // trade-off worth doing to save boot time work. 7193 int dexOptStatus = performDexOptTraced(pkg.packageName, 7194 false /* checkProfiles */, 7195 compilerFilter, 7196 false /* force */); 7197 switch (dexOptStatus) { 7198 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7199 numberOfPackagesOptimized++; 7200 break; 7201 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7202 numberOfPackagesSkipped++; 7203 break; 7204 case PackageDexOptimizer.DEX_OPT_FAILED: 7205 numberOfPackagesFailed++; 7206 break; 7207 default: 7208 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7209 break; 7210 } 7211 } 7212 7213 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7214 numberOfPackagesFailed }; 7215 } 7216 7217 @Override 7218 public void notifyPackageUse(String packageName, int reason) { 7219 synchronized (mPackages) { 7220 PackageParser.Package p = mPackages.get(packageName); 7221 if (p == null) { 7222 return; 7223 } 7224 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7225 } 7226 } 7227 7228 // TODO: this is not used nor needed. Delete it. 7229 @Override 7230 public boolean performDexOptIfNeeded(String packageName) { 7231 int dexOptStatus = performDexOptTraced(packageName, 7232 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7233 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7234 } 7235 7236 @Override 7237 public boolean performDexOpt(String packageName, 7238 boolean checkProfiles, int compileReason, boolean force) { 7239 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7240 getCompilerFilterForReason(compileReason), force); 7241 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7242 } 7243 7244 @Override 7245 public boolean performDexOptMode(String packageName, 7246 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7247 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7248 targetCompilerFilter, force); 7249 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7250 } 7251 7252 private int performDexOptTraced(String packageName, 7253 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7255 try { 7256 return performDexOptInternal(packageName, checkProfiles, 7257 targetCompilerFilter, force); 7258 } finally { 7259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7260 } 7261 } 7262 7263 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7264 // if the package can now be considered up to date for the given filter. 7265 private int performDexOptInternal(String packageName, 7266 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7267 PackageParser.Package p; 7268 synchronized (mPackages) { 7269 p = mPackages.get(packageName); 7270 if (p == null) { 7271 // Package could not be found. Report failure. 7272 return PackageDexOptimizer.DEX_OPT_FAILED; 7273 } 7274 mPackageUsage.maybeWriteAsync(mPackages); 7275 mCompilerStats.maybeWriteAsync(); 7276 } 7277 long callingId = Binder.clearCallingIdentity(); 7278 try { 7279 synchronized (mInstallLock) { 7280 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7281 targetCompilerFilter, force); 7282 } 7283 } finally { 7284 Binder.restoreCallingIdentity(callingId); 7285 } 7286 } 7287 7288 public ArraySet<String> getOptimizablePackages() { 7289 ArraySet<String> pkgs = new ArraySet<String>(); 7290 synchronized (mPackages) { 7291 for (PackageParser.Package p : mPackages.values()) { 7292 if (PackageDexOptimizer.canOptimizePackage(p)) { 7293 pkgs.add(p.packageName); 7294 } 7295 } 7296 } 7297 return pkgs; 7298 } 7299 7300 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7301 boolean checkProfiles, String targetCompilerFilter, 7302 boolean force) { 7303 // Select the dex optimizer based on the force parameter. 7304 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7305 // allocate an object here. 7306 PackageDexOptimizer pdo = force 7307 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7308 : mPackageDexOptimizer; 7309 7310 // Optimize all dependencies first. Note: we ignore the return value and march on 7311 // on errors. 7312 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7313 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7314 if (!deps.isEmpty()) { 7315 for (PackageParser.Package depPackage : deps) { 7316 // TODO: Analyze and investigate if we (should) profile libraries. 7317 // Currently this will do a full compilation of the library by default. 7318 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7319 false /* checkProfiles */, 7320 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7321 getOrCreateCompilerPackageStats(depPackage)); 7322 } 7323 } 7324 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7325 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7326 } 7327 7328 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7329 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7330 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7331 Set<String> collectedNames = new HashSet<>(); 7332 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7333 7334 retValue.remove(p); 7335 7336 return retValue; 7337 } else { 7338 return Collections.emptyList(); 7339 } 7340 } 7341 7342 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7343 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7344 if (!collectedNames.contains(p.packageName)) { 7345 collectedNames.add(p.packageName); 7346 collected.add(p); 7347 7348 if (p.usesLibraries != null) { 7349 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7350 } 7351 if (p.usesOptionalLibraries != null) { 7352 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7353 collectedNames); 7354 } 7355 } 7356 } 7357 7358 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7359 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7360 for (String libName : libs) { 7361 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7362 if (libPkg != null) { 7363 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7364 } 7365 } 7366 } 7367 7368 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7369 synchronized (mPackages) { 7370 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7371 if (lib != null && lib.apk != null) { 7372 return mPackages.get(lib.apk); 7373 } 7374 } 7375 return null; 7376 } 7377 7378 public void shutdown() { 7379 mPackageUsage.writeNow(mPackages); 7380 mCompilerStats.writeNow(); 7381 } 7382 7383 @Override 7384 public void dumpProfiles(String packageName) { 7385 PackageParser.Package pkg; 7386 synchronized (mPackages) { 7387 pkg = mPackages.get(packageName); 7388 if (pkg == null) { 7389 throw new IllegalArgumentException("Unknown package: " + packageName); 7390 } 7391 } 7392 /* Only the shell, root, or the app user should be able to dump profiles. */ 7393 int callingUid = Binder.getCallingUid(); 7394 if (callingUid != Process.SHELL_UID && 7395 callingUid != Process.ROOT_UID && 7396 callingUid != pkg.applicationInfo.uid) { 7397 throw new SecurityException("dumpProfiles"); 7398 } 7399 7400 synchronized (mInstallLock) { 7401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7402 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7403 try { 7404 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7405 String gid = Integer.toString(sharedGid); 7406 String codePaths = TextUtils.join(";", allCodePaths); 7407 mInstaller.dumpProfiles(gid, packageName, codePaths); 7408 } catch (InstallerException e) { 7409 Slog.w(TAG, "Failed to dump profiles", e); 7410 } 7411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7412 } 7413 } 7414 7415 @Override 7416 public void forceDexOpt(String packageName) { 7417 enforceSystemOrRoot("forceDexOpt"); 7418 7419 PackageParser.Package pkg; 7420 synchronized (mPackages) { 7421 pkg = mPackages.get(packageName); 7422 if (pkg == null) { 7423 throw new IllegalArgumentException("Unknown package: " + packageName); 7424 } 7425 } 7426 7427 synchronized (mInstallLock) { 7428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7429 7430 // Whoever is calling forceDexOpt wants a fully compiled package. 7431 // Don't use profiles since that may cause compilation to be skipped. 7432 final int res = performDexOptInternalWithDependenciesLI(pkg, 7433 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7434 true /* force */); 7435 7436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7437 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7438 throw new IllegalStateException("Failed to dexopt: " + res); 7439 } 7440 } 7441 } 7442 7443 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7444 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7445 Slog.w(TAG, "Unable to update from " + oldPkg.name 7446 + " to " + newPkg.packageName 7447 + ": old package not in system partition"); 7448 return false; 7449 } else if (mPackages.get(oldPkg.name) != null) { 7450 Slog.w(TAG, "Unable to update from " + oldPkg.name 7451 + " to " + newPkg.packageName 7452 + ": old package still exists"); 7453 return false; 7454 } 7455 return true; 7456 } 7457 7458 void removeCodePathLI(File codePath) { 7459 if (codePath.isDirectory()) { 7460 try { 7461 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7462 } catch (InstallerException e) { 7463 Slog.w(TAG, "Failed to remove code path", e); 7464 } 7465 } else { 7466 codePath.delete(); 7467 } 7468 } 7469 7470 private int[] resolveUserIds(int userId) { 7471 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7472 } 7473 7474 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7475 if (pkg == null) { 7476 Slog.wtf(TAG, "Package was null!", new Throwable()); 7477 return; 7478 } 7479 clearAppDataLeafLIF(pkg, userId, flags); 7480 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7481 for (int i = 0; i < childCount; i++) { 7482 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7483 } 7484 } 7485 7486 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7487 final PackageSetting ps; 7488 synchronized (mPackages) { 7489 ps = mSettings.mPackages.get(pkg.packageName); 7490 } 7491 for (int realUserId : resolveUserIds(userId)) { 7492 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7493 try { 7494 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7495 ceDataInode); 7496 } catch (InstallerException e) { 7497 Slog.w(TAG, String.valueOf(e)); 7498 } 7499 } 7500 } 7501 7502 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7503 if (pkg == null) { 7504 Slog.wtf(TAG, "Package was null!", new Throwable()); 7505 return; 7506 } 7507 destroyAppDataLeafLIF(pkg, userId, flags); 7508 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7509 for (int i = 0; i < childCount; i++) { 7510 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7511 } 7512 } 7513 7514 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7515 final PackageSetting ps; 7516 synchronized (mPackages) { 7517 ps = mSettings.mPackages.get(pkg.packageName); 7518 } 7519 for (int realUserId : resolveUserIds(userId)) { 7520 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7521 try { 7522 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7523 ceDataInode); 7524 } catch (InstallerException e) { 7525 Slog.w(TAG, String.valueOf(e)); 7526 } 7527 } 7528 } 7529 7530 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7531 if (pkg == null) { 7532 Slog.wtf(TAG, "Package was null!", new Throwable()); 7533 return; 7534 } 7535 destroyAppProfilesLeafLIF(pkg); 7536 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7537 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7538 for (int i = 0; i < childCount; i++) { 7539 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7540 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7541 true /* removeBaseMarker */); 7542 } 7543 } 7544 7545 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7546 boolean removeBaseMarker) { 7547 if (pkg.isForwardLocked()) { 7548 return; 7549 } 7550 7551 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7552 try { 7553 path = PackageManagerServiceUtils.realpath(new File(path)); 7554 } catch (IOException e) { 7555 // TODO: Should we return early here ? 7556 Slog.w(TAG, "Failed to get canonical path", e); 7557 continue; 7558 } 7559 7560 final String useMarker = path.replace('/', '@'); 7561 for (int realUserId : resolveUserIds(userId)) { 7562 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7563 if (removeBaseMarker) { 7564 File foreignUseMark = new File(profileDir, useMarker); 7565 if (foreignUseMark.exists()) { 7566 if (!foreignUseMark.delete()) { 7567 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7568 + pkg.packageName); 7569 } 7570 } 7571 } 7572 7573 File[] markers = profileDir.listFiles(); 7574 if (markers != null) { 7575 final String searchString = "@" + pkg.packageName + "@"; 7576 // We also delete all markers that contain the package name we're 7577 // uninstalling. These are associated with secondary dex-files belonging 7578 // to the package. Reconstructing the path of these dex files is messy 7579 // in general. 7580 for (File marker : markers) { 7581 if (marker.getName().indexOf(searchString) > 0) { 7582 if (!marker.delete()) { 7583 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7584 + pkg.packageName); 7585 } 7586 } 7587 } 7588 } 7589 } 7590 } 7591 } 7592 7593 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7594 try { 7595 mInstaller.destroyAppProfiles(pkg.packageName); 7596 } catch (InstallerException e) { 7597 Slog.w(TAG, String.valueOf(e)); 7598 } 7599 } 7600 7601 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7602 if (pkg == null) { 7603 Slog.wtf(TAG, "Package was null!", new Throwable()); 7604 return; 7605 } 7606 clearAppProfilesLeafLIF(pkg); 7607 // We don't remove the base foreign use marker when clearing profiles because 7608 // we will rename it when the app is updated. Unlike the actual profile contents, 7609 // the foreign use marker is good across installs. 7610 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7612 for (int i = 0; i < childCount; i++) { 7613 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7614 } 7615 } 7616 7617 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7618 try { 7619 mInstaller.clearAppProfiles(pkg.packageName); 7620 } catch (InstallerException e) { 7621 Slog.w(TAG, String.valueOf(e)); 7622 } 7623 } 7624 7625 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7626 long lastUpdateTime) { 7627 // Set parent install/update time 7628 PackageSetting ps = (PackageSetting) pkg.mExtras; 7629 if (ps != null) { 7630 ps.firstInstallTime = firstInstallTime; 7631 ps.lastUpdateTime = lastUpdateTime; 7632 } 7633 // Set children install/update time 7634 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7635 for (int i = 0; i < childCount; i++) { 7636 PackageParser.Package childPkg = pkg.childPackages.get(i); 7637 ps = (PackageSetting) childPkg.mExtras; 7638 if (ps != null) { 7639 ps.firstInstallTime = firstInstallTime; 7640 ps.lastUpdateTime = lastUpdateTime; 7641 } 7642 } 7643 } 7644 7645 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7646 PackageParser.Package changingLib) { 7647 if (file.path != null) { 7648 usesLibraryFiles.add(file.path); 7649 return; 7650 } 7651 PackageParser.Package p = mPackages.get(file.apk); 7652 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7653 // If we are doing this while in the middle of updating a library apk, 7654 // then we need to make sure to use that new apk for determining the 7655 // dependencies here. (We haven't yet finished committing the new apk 7656 // to the package manager state.) 7657 if (p == null || p.packageName.equals(changingLib.packageName)) { 7658 p = changingLib; 7659 } 7660 } 7661 if (p != null) { 7662 usesLibraryFiles.addAll(p.getAllCodePaths()); 7663 } 7664 } 7665 7666 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7667 PackageParser.Package changingLib) throws PackageManagerException { 7668 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7669 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7670 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7671 for (int i=0; i<N; i++) { 7672 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7673 if (file == null) { 7674 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7675 "Package " + pkg.packageName + " requires unavailable shared library " 7676 + pkg.usesLibraries.get(i) + "; failing!"); 7677 } 7678 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7679 } 7680 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7681 for (int i=0; i<N; i++) { 7682 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7683 if (file == null) { 7684 Slog.w(TAG, "Package " + pkg.packageName 7685 + " desires unavailable shared library " 7686 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7687 } else { 7688 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7689 } 7690 } 7691 N = usesLibraryFiles.size(); 7692 if (N > 0) { 7693 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7694 } else { 7695 pkg.usesLibraryFiles = null; 7696 } 7697 } 7698 } 7699 7700 private static boolean hasString(List<String> list, List<String> which) { 7701 if (list == null) { 7702 return false; 7703 } 7704 for (int i=list.size()-1; i>=0; i--) { 7705 for (int j=which.size()-1; j>=0; j--) { 7706 if (which.get(j).equals(list.get(i))) { 7707 return true; 7708 } 7709 } 7710 } 7711 return false; 7712 } 7713 7714 private void updateAllSharedLibrariesLPw() { 7715 for (PackageParser.Package pkg : mPackages.values()) { 7716 try { 7717 updateSharedLibrariesLPw(pkg, null); 7718 } catch (PackageManagerException e) { 7719 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7720 } 7721 } 7722 } 7723 7724 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7725 PackageParser.Package changingPkg) { 7726 ArrayList<PackageParser.Package> res = null; 7727 for (PackageParser.Package pkg : mPackages.values()) { 7728 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7729 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7730 if (res == null) { 7731 res = new ArrayList<PackageParser.Package>(); 7732 } 7733 res.add(pkg); 7734 try { 7735 updateSharedLibrariesLPw(pkg, changingPkg); 7736 } catch (PackageManagerException e) { 7737 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7738 } 7739 } 7740 } 7741 return res; 7742 } 7743 7744 /** 7745 * Derive the value of the {@code cpuAbiOverride} based on the provided 7746 * value and an optional stored value from the package settings. 7747 */ 7748 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7749 String cpuAbiOverride = null; 7750 7751 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7752 cpuAbiOverride = null; 7753 } else if (abiOverride != null) { 7754 cpuAbiOverride = abiOverride; 7755 } else if (settings != null) { 7756 cpuAbiOverride = settings.cpuAbiOverrideString; 7757 } 7758 7759 return cpuAbiOverride; 7760 } 7761 7762 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7763 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7764 throws PackageManagerException { 7765 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7766 // If the package has children and this is the first dive in the function 7767 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7768 // whether all packages (parent and children) would be successfully scanned 7769 // before the actual scan since scanning mutates internal state and we want 7770 // to atomically install the package and its children. 7771 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7772 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7773 scanFlags |= SCAN_CHECK_ONLY; 7774 } 7775 } else { 7776 scanFlags &= ~SCAN_CHECK_ONLY; 7777 } 7778 7779 final PackageParser.Package scannedPkg; 7780 try { 7781 // Scan the parent 7782 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7783 // Scan the children 7784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7785 for (int i = 0; i < childCount; i++) { 7786 PackageParser.Package childPkg = pkg.childPackages.get(i); 7787 scanPackageLI(childPkg, policyFlags, 7788 scanFlags, currentTime, user); 7789 } 7790 } finally { 7791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7792 } 7793 7794 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7795 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7796 } 7797 7798 return scannedPkg; 7799 } 7800 7801 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7802 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7803 boolean success = false; 7804 try { 7805 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7806 currentTime, user); 7807 success = true; 7808 return res; 7809 } finally { 7810 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7811 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7812 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7813 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7814 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7815 } 7816 } 7817 } 7818 7819 /** 7820 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7821 */ 7822 private static boolean apkHasCode(String fileName) { 7823 StrictJarFile jarFile = null; 7824 try { 7825 jarFile = new StrictJarFile(fileName, 7826 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7827 return jarFile.findEntry("classes.dex") != null; 7828 } catch (IOException ignore) { 7829 } finally { 7830 try { 7831 if (jarFile != null) { 7832 jarFile.close(); 7833 } 7834 } catch (IOException ignore) {} 7835 } 7836 return false; 7837 } 7838 7839 /** 7840 * Enforces code policy for the package. This ensures that if an APK has 7841 * declared hasCode="true" in its manifest that the APK actually contains 7842 * code. 7843 * 7844 * @throws PackageManagerException If bytecode could not be found when it should exist 7845 */ 7846 private static void enforceCodePolicy(PackageParser.Package pkg) 7847 throws PackageManagerException { 7848 final boolean shouldHaveCode = 7849 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7850 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7851 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7852 "Package " + pkg.baseCodePath + " code is missing"); 7853 } 7854 7855 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7856 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7857 final boolean splitShouldHaveCode = 7858 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7859 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7860 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7861 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7862 } 7863 } 7864 } 7865 } 7866 7867 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7868 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7869 throws PackageManagerException { 7870 final File scanFile = new File(pkg.codePath); 7871 if (pkg.applicationInfo.getCodePath() == null || 7872 pkg.applicationInfo.getResourcePath() == null) { 7873 // Bail out. The resource and code paths haven't been set. 7874 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7875 "Code and resource paths haven't been set correctly"); 7876 } 7877 7878 // Apply policy 7879 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7880 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7881 if (pkg.applicationInfo.isDirectBootAware()) { 7882 // we're direct boot aware; set for all components 7883 for (PackageParser.Service s : pkg.services) { 7884 s.info.encryptionAware = s.info.directBootAware = true; 7885 } 7886 for (PackageParser.Provider p : pkg.providers) { 7887 p.info.encryptionAware = p.info.directBootAware = true; 7888 } 7889 for (PackageParser.Activity a : pkg.activities) { 7890 a.info.encryptionAware = a.info.directBootAware = true; 7891 } 7892 for (PackageParser.Activity r : pkg.receivers) { 7893 r.info.encryptionAware = r.info.directBootAware = true; 7894 } 7895 } 7896 } else { 7897 // Only allow system apps to be flagged as core apps. 7898 pkg.coreApp = false; 7899 // clear flags not applicable to regular apps 7900 pkg.applicationInfo.privateFlags &= 7901 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7902 pkg.applicationInfo.privateFlags &= 7903 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7904 } 7905 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7906 7907 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7908 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7909 } 7910 7911 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7912 enforceCodePolicy(pkg); 7913 } 7914 7915 if (mCustomResolverComponentName != null && 7916 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7917 setUpCustomResolverActivity(pkg); 7918 } 7919 7920 if (pkg.packageName.equals("android")) { 7921 synchronized (mPackages) { 7922 if (mAndroidApplication != null) { 7923 Slog.w(TAG, "*************************************************"); 7924 Slog.w(TAG, "Core android package being redefined. Skipping."); 7925 Slog.w(TAG, " file=" + scanFile); 7926 Slog.w(TAG, "*************************************************"); 7927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7928 "Core android package being redefined. Skipping."); 7929 } 7930 7931 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7932 // Set up information for our fall-back user intent resolution activity. 7933 mPlatformPackage = pkg; 7934 pkg.mVersionCode = mSdkVersion; 7935 mAndroidApplication = pkg.applicationInfo; 7936 7937 if (!mResolverReplaced) { 7938 mResolveActivity.applicationInfo = mAndroidApplication; 7939 mResolveActivity.name = ResolverActivity.class.getName(); 7940 mResolveActivity.packageName = mAndroidApplication.packageName; 7941 mResolveActivity.processName = "system:ui"; 7942 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7943 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7944 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7945 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7946 mResolveActivity.exported = true; 7947 mResolveActivity.enabled = true; 7948 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7949 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7950 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7951 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7952 | ActivityInfo.CONFIG_ORIENTATION 7953 | ActivityInfo.CONFIG_KEYBOARD 7954 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7955 mResolveInfo.activityInfo = mResolveActivity; 7956 mResolveInfo.priority = 0; 7957 mResolveInfo.preferredOrder = 0; 7958 mResolveInfo.match = 0; 7959 mResolveComponentName = new ComponentName( 7960 mAndroidApplication.packageName, mResolveActivity.name); 7961 } 7962 } 7963 } 7964 } 7965 7966 if (DEBUG_PACKAGE_SCANNING) { 7967 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7968 Log.d(TAG, "Scanning package " + pkg.packageName); 7969 } 7970 7971 synchronized (mPackages) { 7972 if (mPackages.containsKey(pkg.packageName) 7973 || mSharedLibraries.containsKey(pkg.packageName)) { 7974 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7975 "Application package " + pkg.packageName 7976 + " already installed. Skipping duplicate."); 7977 } 7978 7979 // If we're only installing presumed-existing packages, require that the 7980 // scanned APK is both already known and at the path previously established 7981 // for it. Previously unknown packages we pick up normally, but if we have an 7982 // a priori expectation about this package's install presence, enforce it. 7983 // With a singular exception for new system packages. When an OTA contains 7984 // a new system package, we allow the codepath to change from a system location 7985 // to the user-installed location. If we don't allow this change, any newer, 7986 // user-installed version of the application will be ignored. 7987 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7988 if (mExpectingBetter.containsKey(pkg.packageName)) { 7989 logCriticalInfo(Log.WARN, 7990 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7991 } else { 7992 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7993 if (known != null) { 7994 if (DEBUG_PACKAGE_SCANNING) { 7995 Log.d(TAG, "Examining " + pkg.codePath 7996 + " and requiring known paths " + known.codePathString 7997 + " & " + known.resourcePathString); 7998 } 7999 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8000 || !pkg.applicationInfo.getResourcePath().equals( 8001 known.resourcePathString)) { 8002 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8003 "Application package " + pkg.packageName 8004 + " found at " + pkg.applicationInfo.getCodePath() 8005 + " but expected at " + known.codePathString 8006 + "; ignoring."); 8007 } 8008 } 8009 } 8010 } 8011 } 8012 8013 // Initialize package source and resource directories 8014 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8015 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8016 8017 SharedUserSetting suid = null; 8018 PackageSetting pkgSetting = null; 8019 8020 if (!isSystemApp(pkg)) { 8021 // Only system apps can use these features. 8022 pkg.mOriginalPackages = null; 8023 pkg.mRealPackage = null; 8024 pkg.mAdoptPermissions = null; 8025 } 8026 8027 // Getting the package setting may have a side-effect, so if we 8028 // are only checking if scan would succeed, stash a copy of the 8029 // old setting to restore at the end. 8030 PackageSetting nonMutatedPs = null; 8031 8032 // writer 8033 synchronized (mPackages) { 8034 if (pkg.mSharedUserId != null) { 8035 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8036 if (suid == null) { 8037 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8038 "Creating application package " + pkg.packageName 8039 + " for shared user failed"); 8040 } 8041 if (DEBUG_PACKAGE_SCANNING) { 8042 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8043 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8044 + "): packages=" + suid.packages); 8045 } 8046 } 8047 8048 // Check if we are renaming from an original package name. 8049 PackageSetting origPackage = null; 8050 String realName = null; 8051 if (pkg.mOriginalPackages != null) { 8052 // This package may need to be renamed to a previously 8053 // installed name. Let's check on that... 8054 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8055 if (pkg.mOriginalPackages.contains(renamed)) { 8056 // This package had originally been installed as the 8057 // original name, and we have already taken care of 8058 // transitioning to the new one. Just update the new 8059 // one to continue using the old name. 8060 realName = pkg.mRealPackage; 8061 if (!pkg.packageName.equals(renamed)) { 8062 // Callers into this function may have already taken 8063 // care of renaming the package; only do it here if 8064 // it is not already done. 8065 pkg.setPackageName(renamed); 8066 } 8067 8068 } else { 8069 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8070 if ((origPackage = mSettings.peekPackageLPr( 8071 pkg.mOriginalPackages.get(i))) != null) { 8072 // We do have the package already installed under its 8073 // original name... should we use it? 8074 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8075 // New package is not compatible with original. 8076 origPackage = null; 8077 continue; 8078 } else if (origPackage.sharedUser != null) { 8079 // Make sure uid is compatible between packages. 8080 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8081 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8082 + " to " + pkg.packageName + ": old uid " 8083 + origPackage.sharedUser.name 8084 + " differs from " + pkg.mSharedUserId); 8085 origPackage = null; 8086 continue; 8087 } 8088 // TODO: Add case when shared user id is added [b/28144775] 8089 } else { 8090 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8091 + pkg.packageName + " to old name " + origPackage.name); 8092 } 8093 break; 8094 } 8095 } 8096 } 8097 } 8098 8099 if (mTransferedPackages.contains(pkg.packageName)) { 8100 Slog.w(TAG, "Package " + pkg.packageName 8101 + " was transferred to another, but its .apk remains"); 8102 } 8103 8104 // See comments in nonMutatedPs declaration 8105 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8106 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8107 if (foundPs != null) { 8108 nonMutatedPs = new PackageSetting(foundPs); 8109 } 8110 } 8111 8112 // Just create the setting, don't add it yet. For already existing packages 8113 // the PkgSetting exists already and doesn't have to be created. 8114 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8115 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8116 pkg.applicationInfo.primaryCpuAbi, 8117 pkg.applicationInfo.secondaryCpuAbi, 8118 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8119 user, false); 8120 if (pkgSetting == null) { 8121 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8122 "Creating application package " + pkg.packageName + " failed"); 8123 } 8124 8125 if (pkgSetting.origPackage != null) { 8126 // If we are first transitioning from an original package, 8127 // fix up the new package's name now. We need to do this after 8128 // looking up the package under its new name, so getPackageLP 8129 // can take care of fiddling things correctly. 8130 pkg.setPackageName(origPackage.name); 8131 8132 // File a report about this. 8133 String msg = "New package " + pkgSetting.realName 8134 + " renamed to replace old package " + pkgSetting.name; 8135 reportSettingsProblem(Log.WARN, msg); 8136 8137 // Make a note of it. 8138 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8139 mTransferedPackages.add(origPackage.name); 8140 } 8141 8142 // No longer need to retain this. 8143 pkgSetting.origPackage = null; 8144 } 8145 8146 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8147 // Make a note of it. 8148 mTransferedPackages.add(pkg.packageName); 8149 } 8150 8151 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8152 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8153 } 8154 8155 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8156 // Check all shared libraries and map to their actual file path. 8157 // We only do this here for apps not on a system dir, because those 8158 // are the only ones that can fail an install due to this. We 8159 // will take care of the system apps by updating all of their 8160 // library paths after the scan is done. 8161 updateSharedLibrariesLPw(pkg, null); 8162 } 8163 8164 if (mFoundPolicyFile) { 8165 SELinuxMMAC.assignSeinfoValue(pkg); 8166 } 8167 8168 pkg.applicationInfo.uid = pkgSetting.appId; 8169 pkg.mExtras = pkgSetting; 8170 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8171 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8172 // We just determined the app is signed correctly, so bring 8173 // over the latest parsed certs. 8174 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8175 } else { 8176 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8177 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8178 "Package " + pkg.packageName + " upgrade keys do not match the " 8179 + "previously installed version"); 8180 } else { 8181 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8182 String msg = "System package " + pkg.packageName 8183 + " signature changed; retaining data."; 8184 reportSettingsProblem(Log.WARN, msg); 8185 } 8186 } 8187 } else { 8188 try { 8189 verifySignaturesLP(pkgSetting, pkg); 8190 // We just determined the app is signed correctly, so bring 8191 // over the latest parsed certs. 8192 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8193 } catch (PackageManagerException e) { 8194 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8195 throw e; 8196 } 8197 // The signature has changed, but this package is in the system 8198 // image... let's recover! 8199 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8200 // However... if this package is part of a shared user, but it 8201 // doesn't match the signature of the shared user, let's fail. 8202 // What this means is that you can't change the signatures 8203 // associated with an overall shared user, which doesn't seem all 8204 // that unreasonable. 8205 if (pkgSetting.sharedUser != null) { 8206 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8207 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8208 throw new PackageManagerException( 8209 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8210 "Signature mismatch for shared user: " 8211 + pkgSetting.sharedUser); 8212 } 8213 } 8214 // File a report about this. 8215 String msg = "System package " + pkg.packageName 8216 + " signature changed; retaining data."; 8217 reportSettingsProblem(Log.WARN, msg); 8218 } 8219 } 8220 // Verify that this new package doesn't have any content providers 8221 // that conflict with existing packages. Only do this if the 8222 // package isn't already installed, since we don't want to break 8223 // things that are installed. 8224 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8225 final int N = pkg.providers.size(); 8226 int i; 8227 for (i=0; i<N; i++) { 8228 PackageParser.Provider p = pkg.providers.get(i); 8229 if (p.info.authority != null) { 8230 String names[] = p.info.authority.split(";"); 8231 for (int j = 0; j < names.length; j++) { 8232 if (mProvidersByAuthority.containsKey(names[j])) { 8233 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8234 final String otherPackageName = 8235 ((other != null && other.getComponentName() != null) ? 8236 other.getComponentName().getPackageName() : "?"); 8237 throw new PackageManagerException( 8238 INSTALL_FAILED_CONFLICTING_PROVIDER, 8239 "Can't install because provider name " + names[j] 8240 + " (in package " + pkg.applicationInfo.packageName 8241 + ") is already used by " + otherPackageName); 8242 } 8243 } 8244 } 8245 } 8246 } 8247 8248 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8249 // This package wants to adopt ownership of permissions from 8250 // another package. 8251 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8252 final String origName = pkg.mAdoptPermissions.get(i); 8253 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8254 if (orig != null) { 8255 if (verifyPackageUpdateLPr(orig, pkg)) { 8256 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8257 + pkg.packageName); 8258 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8259 } 8260 } 8261 } 8262 } 8263 } 8264 8265 final String pkgName = pkg.packageName; 8266 8267 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8268 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8269 pkg.applicationInfo.processName = fixProcessName( 8270 pkg.applicationInfo.packageName, 8271 pkg.applicationInfo.processName, 8272 pkg.applicationInfo.uid); 8273 8274 if (pkg != mPlatformPackage) { 8275 // Get all of our default paths setup 8276 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8277 } 8278 8279 final String path = scanFile.getPath(); 8280 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8281 8282 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8283 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8284 8285 // Some system apps still use directory structure for native libraries 8286 // in which case we might end up not detecting abi solely based on apk 8287 // structure. Try to detect abi based on directory structure. 8288 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8289 pkg.applicationInfo.primaryCpuAbi == null) { 8290 setBundledAppAbisAndRoots(pkg, pkgSetting); 8291 setNativeLibraryPaths(pkg); 8292 } 8293 8294 } else { 8295 if ((scanFlags & SCAN_MOVE) != 0) { 8296 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8297 // but we already have this packages package info in the PackageSetting. We just 8298 // use that and derive the native library path based on the new codepath. 8299 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8300 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8301 } 8302 8303 // Set native library paths again. For moves, the path will be updated based on the 8304 // ABIs we've determined above. For non-moves, the path will be updated based on the 8305 // ABIs we determined during compilation, but the path will depend on the final 8306 // package path (after the rename away from the stage path). 8307 setNativeLibraryPaths(pkg); 8308 } 8309 8310 // This is a special case for the "system" package, where the ABI is 8311 // dictated by the zygote configuration (and init.rc). We should keep track 8312 // of this ABI so that we can deal with "normal" applications that run under 8313 // the same UID correctly. 8314 if (mPlatformPackage == pkg) { 8315 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8316 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8317 } 8318 8319 // If there's a mismatch between the abi-override in the package setting 8320 // and the abiOverride specified for the install. Warn about this because we 8321 // would've already compiled the app without taking the package setting into 8322 // account. 8323 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8324 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8325 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8326 " for package " + pkg.packageName); 8327 } 8328 } 8329 8330 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8331 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8332 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8333 8334 // Copy the derived override back to the parsed package, so that we can 8335 // update the package settings accordingly. 8336 pkg.cpuAbiOverride = cpuAbiOverride; 8337 8338 if (DEBUG_ABI_SELECTION) { 8339 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8340 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8341 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8342 } 8343 8344 // Push the derived path down into PackageSettings so we know what to 8345 // clean up at uninstall time. 8346 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8347 8348 if (DEBUG_ABI_SELECTION) { 8349 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8350 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8351 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8352 } 8353 8354 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8355 // We don't do this here during boot because we can do it all 8356 // at once after scanning all existing packages. 8357 // 8358 // We also do this *before* we perform dexopt on this package, so that 8359 // we can avoid redundant dexopts, and also to make sure we've got the 8360 // code and package path correct. 8361 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8362 pkg, true /* boot complete */); 8363 } 8364 8365 if (mFactoryTest && pkg.requestedPermissions.contains( 8366 android.Manifest.permission.FACTORY_TEST)) { 8367 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8368 } 8369 8370 ArrayList<PackageParser.Package> clientLibPkgs = null; 8371 8372 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8373 if (nonMutatedPs != null) { 8374 synchronized (mPackages) { 8375 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8376 } 8377 } 8378 return pkg; 8379 } 8380 8381 // Only privileged apps and updated privileged apps can add child packages. 8382 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8383 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8384 throw new PackageManagerException("Only privileged apps and updated " 8385 + "privileged apps can add child packages. Ignoring package " 8386 + pkg.packageName); 8387 } 8388 final int childCount = pkg.childPackages.size(); 8389 for (int i = 0; i < childCount; i++) { 8390 PackageParser.Package childPkg = pkg.childPackages.get(i); 8391 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8392 childPkg.packageName)) { 8393 throw new PackageManagerException("Cannot override a child package of " 8394 + "another disabled system app. Ignoring package " + pkg.packageName); 8395 } 8396 } 8397 } 8398 8399 // writer 8400 synchronized (mPackages) { 8401 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8402 // Only system apps can add new shared libraries. 8403 if (pkg.libraryNames != null) { 8404 for (int i=0; i<pkg.libraryNames.size(); i++) { 8405 String name = pkg.libraryNames.get(i); 8406 boolean allowed = false; 8407 if (pkg.isUpdatedSystemApp()) { 8408 // New library entries can only be added through the 8409 // system image. This is important to get rid of a lot 8410 // of nasty edge cases: for example if we allowed a non- 8411 // system update of the app to add a library, then uninstalling 8412 // the update would make the library go away, and assumptions 8413 // we made such as through app install filtering would now 8414 // have allowed apps on the device which aren't compatible 8415 // with it. Better to just have the restriction here, be 8416 // conservative, and create many fewer cases that can negatively 8417 // impact the user experience. 8418 final PackageSetting sysPs = mSettings 8419 .getDisabledSystemPkgLPr(pkg.packageName); 8420 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8421 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8422 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8423 allowed = true; 8424 break; 8425 } 8426 } 8427 } 8428 } else { 8429 allowed = true; 8430 } 8431 if (allowed) { 8432 if (!mSharedLibraries.containsKey(name)) { 8433 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8434 } else if (!name.equals(pkg.packageName)) { 8435 Slog.w(TAG, "Package " + pkg.packageName + " library " 8436 + name + " already exists; skipping"); 8437 } 8438 } else { 8439 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8440 + name + " that is not declared on system image; skipping"); 8441 } 8442 } 8443 if ((scanFlags & SCAN_BOOTING) == 0) { 8444 // If we are not booting, we need to update any applications 8445 // that are clients of our shared library. If we are booting, 8446 // this will all be done once the scan is complete. 8447 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8448 } 8449 } 8450 } 8451 } 8452 8453 if ((scanFlags & SCAN_BOOTING) != 0) { 8454 // No apps can run during boot scan, so they don't need to be frozen 8455 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8456 // Caller asked to not kill app, so it's probably not frozen 8457 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8458 // Caller asked us to ignore frozen check for some reason; they 8459 // probably didn't know the package name 8460 } else { 8461 // We're doing major surgery on this package, so it better be frozen 8462 // right now to keep it from launching 8463 checkPackageFrozen(pkgName); 8464 } 8465 8466 // Also need to kill any apps that are dependent on the library. 8467 if (clientLibPkgs != null) { 8468 for (int i=0; i<clientLibPkgs.size(); i++) { 8469 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8470 killApplication(clientPkg.applicationInfo.packageName, 8471 clientPkg.applicationInfo.uid, "update lib"); 8472 } 8473 } 8474 8475 // Make sure we're not adding any bogus keyset info 8476 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8477 ksms.assertScannedPackageValid(pkg); 8478 8479 // writer 8480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8481 8482 boolean createIdmapFailed = false; 8483 synchronized (mPackages) { 8484 // We don't expect installation to fail beyond this point 8485 8486 if (pkgSetting.pkg != null) { 8487 // Note that |user| might be null during the initial boot scan. If a codePath 8488 // for an app has changed during a boot scan, it's due to an app update that's 8489 // part of the system partition and marker changes must be applied to all users. 8490 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8491 (user != null) ? user : UserHandle.ALL); 8492 } 8493 8494 // Add the new setting to mSettings 8495 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8496 // Add the new setting to mPackages 8497 mPackages.put(pkg.applicationInfo.packageName, pkg); 8498 // Make sure we don't accidentally delete its data. 8499 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8500 while (iter.hasNext()) { 8501 PackageCleanItem item = iter.next(); 8502 if (pkgName.equals(item.packageName)) { 8503 iter.remove(); 8504 } 8505 } 8506 8507 // Take care of first install / last update times. 8508 if (currentTime != 0) { 8509 if (pkgSetting.firstInstallTime == 0) { 8510 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8511 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8512 pkgSetting.lastUpdateTime = currentTime; 8513 } 8514 } else if (pkgSetting.firstInstallTime == 0) { 8515 // We need *something*. Take time time stamp of the file. 8516 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8517 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8518 if (scanFileTime != pkgSetting.timeStamp) { 8519 // A package on the system image has changed; consider this 8520 // to be an update. 8521 pkgSetting.lastUpdateTime = scanFileTime; 8522 } 8523 } 8524 8525 // Add the package's KeySets to the global KeySetManagerService 8526 ksms.addScannedPackageLPw(pkg); 8527 8528 int N = pkg.providers.size(); 8529 StringBuilder r = null; 8530 int i; 8531 for (i=0; i<N; i++) { 8532 PackageParser.Provider p = pkg.providers.get(i); 8533 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8534 p.info.processName, pkg.applicationInfo.uid); 8535 mProviders.addProvider(p); 8536 p.syncable = p.info.isSyncable; 8537 if (p.info.authority != null) { 8538 String names[] = p.info.authority.split(";"); 8539 p.info.authority = null; 8540 for (int j = 0; j < names.length; j++) { 8541 if (j == 1 && p.syncable) { 8542 // We only want the first authority for a provider to possibly be 8543 // syncable, so if we already added this provider using a different 8544 // authority clear the syncable flag. We copy the provider before 8545 // changing it because the mProviders object contains a reference 8546 // to a provider that we don't want to change. 8547 // Only do this for the second authority since the resulting provider 8548 // object can be the same for all future authorities for this provider. 8549 p = new PackageParser.Provider(p); 8550 p.syncable = false; 8551 } 8552 if (!mProvidersByAuthority.containsKey(names[j])) { 8553 mProvidersByAuthority.put(names[j], p); 8554 if (p.info.authority == null) { 8555 p.info.authority = names[j]; 8556 } else { 8557 p.info.authority = p.info.authority + ";" + names[j]; 8558 } 8559 if (DEBUG_PACKAGE_SCANNING) { 8560 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8561 Log.d(TAG, "Registered content provider: " + names[j] 8562 + ", className = " + p.info.name + ", isSyncable = " 8563 + p.info.isSyncable); 8564 } 8565 } else { 8566 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8567 Slog.w(TAG, "Skipping provider name " + names[j] + 8568 " (in package " + pkg.applicationInfo.packageName + 8569 "): name already used by " 8570 + ((other != null && other.getComponentName() != null) 8571 ? other.getComponentName().getPackageName() : "?")); 8572 } 8573 } 8574 } 8575 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8576 if (r == null) { 8577 r = new StringBuilder(256); 8578 } else { 8579 r.append(' '); 8580 } 8581 r.append(p.info.name); 8582 } 8583 } 8584 if (r != null) { 8585 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8586 } 8587 8588 N = pkg.services.size(); 8589 r = null; 8590 for (i=0; i<N; i++) { 8591 PackageParser.Service s = pkg.services.get(i); 8592 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8593 s.info.processName, pkg.applicationInfo.uid); 8594 mServices.addService(s); 8595 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8596 if (r == null) { 8597 r = new StringBuilder(256); 8598 } else { 8599 r.append(' '); 8600 } 8601 r.append(s.info.name); 8602 } 8603 } 8604 if (r != null) { 8605 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8606 } 8607 8608 N = pkg.receivers.size(); 8609 r = null; 8610 for (i=0; i<N; i++) { 8611 PackageParser.Activity a = pkg.receivers.get(i); 8612 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8613 a.info.processName, pkg.applicationInfo.uid); 8614 mReceivers.addActivity(a, "receiver"); 8615 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8616 if (r == null) { 8617 r = new StringBuilder(256); 8618 } else { 8619 r.append(' '); 8620 } 8621 r.append(a.info.name); 8622 } 8623 } 8624 if (r != null) { 8625 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8626 } 8627 8628 N = pkg.activities.size(); 8629 r = null; 8630 for (i=0; i<N; i++) { 8631 PackageParser.Activity a = pkg.activities.get(i); 8632 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8633 a.info.processName, pkg.applicationInfo.uid); 8634 mActivities.addActivity(a, "activity"); 8635 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8636 if (r == null) { 8637 r = new StringBuilder(256); 8638 } else { 8639 r.append(' '); 8640 } 8641 r.append(a.info.name); 8642 } 8643 } 8644 if (r != null) { 8645 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8646 } 8647 8648 N = pkg.permissionGroups.size(); 8649 r = null; 8650 for (i=0; i<N; i++) { 8651 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8652 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8653 if (cur == null) { 8654 mPermissionGroups.put(pg.info.name, pg); 8655 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8656 if (r == null) { 8657 r = new StringBuilder(256); 8658 } else { 8659 r.append(' '); 8660 } 8661 r.append(pg.info.name); 8662 } 8663 } else { 8664 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8665 + pg.info.packageName + " ignored: original from " 8666 + cur.info.packageName); 8667 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8668 if (r == null) { 8669 r = new StringBuilder(256); 8670 } else { 8671 r.append(' '); 8672 } 8673 r.append("DUP:"); 8674 r.append(pg.info.name); 8675 } 8676 } 8677 } 8678 if (r != null) { 8679 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8680 } 8681 8682 N = pkg.permissions.size(); 8683 r = null; 8684 for (i=0; i<N; i++) { 8685 PackageParser.Permission p = pkg.permissions.get(i); 8686 8687 // Assume by default that we did not install this permission into the system. 8688 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8689 8690 // Now that permission groups have a special meaning, we ignore permission 8691 // groups for legacy apps to prevent unexpected behavior. In particular, 8692 // permissions for one app being granted to someone just becase they happen 8693 // to be in a group defined by another app (before this had no implications). 8694 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8695 p.group = mPermissionGroups.get(p.info.group); 8696 // Warn for a permission in an unknown group. 8697 if (p.info.group != null && p.group == null) { 8698 Slog.w(TAG, "Permission " + p.info.name + " from package " 8699 + p.info.packageName + " in an unknown group " + p.info.group); 8700 } 8701 } 8702 8703 ArrayMap<String, BasePermission> permissionMap = 8704 p.tree ? mSettings.mPermissionTrees 8705 : mSettings.mPermissions; 8706 BasePermission bp = permissionMap.get(p.info.name); 8707 8708 // Allow system apps to redefine non-system permissions 8709 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8710 final boolean currentOwnerIsSystem = (bp.perm != null 8711 && isSystemApp(bp.perm.owner)); 8712 if (isSystemApp(p.owner)) { 8713 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8714 // It's a built-in permission and no owner, take ownership now 8715 bp.packageSetting = pkgSetting; 8716 bp.perm = p; 8717 bp.uid = pkg.applicationInfo.uid; 8718 bp.sourcePackage = p.info.packageName; 8719 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8720 } else if (!currentOwnerIsSystem) { 8721 String msg = "New decl " + p.owner + " of permission " 8722 + p.info.name + " is system; overriding " + bp.sourcePackage; 8723 reportSettingsProblem(Log.WARN, msg); 8724 bp = null; 8725 } 8726 } 8727 } 8728 8729 if (bp == null) { 8730 bp = new BasePermission(p.info.name, p.info.packageName, 8731 BasePermission.TYPE_NORMAL); 8732 permissionMap.put(p.info.name, bp); 8733 } 8734 8735 if (bp.perm == null) { 8736 if (bp.sourcePackage == null 8737 || bp.sourcePackage.equals(p.info.packageName)) { 8738 BasePermission tree = findPermissionTreeLP(p.info.name); 8739 if (tree == null 8740 || tree.sourcePackage.equals(p.info.packageName)) { 8741 bp.packageSetting = pkgSetting; 8742 bp.perm = p; 8743 bp.uid = pkg.applicationInfo.uid; 8744 bp.sourcePackage = p.info.packageName; 8745 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8746 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8747 if (r == null) { 8748 r = new StringBuilder(256); 8749 } else { 8750 r.append(' '); 8751 } 8752 r.append(p.info.name); 8753 } 8754 } else { 8755 Slog.w(TAG, "Permission " + p.info.name + " from package " 8756 + p.info.packageName + " ignored: base tree " 8757 + tree.name + " is from package " 8758 + tree.sourcePackage); 8759 } 8760 } else { 8761 Slog.w(TAG, "Permission " + p.info.name + " from package " 8762 + p.info.packageName + " ignored: original from " 8763 + bp.sourcePackage); 8764 } 8765 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8766 if (r == null) { 8767 r = new StringBuilder(256); 8768 } else { 8769 r.append(' '); 8770 } 8771 r.append("DUP:"); 8772 r.append(p.info.name); 8773 } 8774 if (bp.perm == p) { 8775 bp.protectionLevel = p.info.protectionLevel; 8776 } 8777 } 8778 8779 if (r != null) { 8780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8781 } 8782 8783 N = pkg.instrumentation.size(); 8784 r = null; 8785 for (i=0; i<N; i++) { 8786 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8787 a.info.packageName = pkg.applicationInfo.packageName; 8788 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8789 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8790 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8791 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8792 a.info.dataDir = pkg.applicationInfo.dataDir; 8793 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8794 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8795 8796 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8797 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8798 mInstrumentation.put(a.getComponentName(), a); 8799 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8800 if (r == null) { 8801 r = new StringBuilder(256); 8802 } else { 8803 r.append(' '); 8804 } 8805 r.append(a.info.name); 8806 } 8807 } 8808 if (r != null) { 8809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8810 } 8811 8812 if (pkg.protectedBroadcasts != null) { 8813 N = pkg.protectedBroadcasts.size(); 8814 for (i=0; i<N; i++) { 8815 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8816 } 8817 } 8818 8819 pkgSetting.setTimeStamp(scanFileTime); 8820 8821 // Create idmap files for pairs of (packages, overlay packages). 8822 // Note: "android", ie framework-res.apk, is handled by native layers. 8823 if (pkg.mOverlayTarget != null) { 8824 // This is an overlay package. 8825 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8826 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8827 mOverlays.put(pkg.mOverlayTarget, 8828 new ArrayMap<String, PackageParser.Package>()); 8829 } 8830 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8831 map.put(pkg.packageName, pkg); 8832 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8833 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8834 createIdmapFailed = true; 8835 } 8836 } 8837 } else if (mOverlays.containsKey(pkg.packageName) && 8838 !pkg.packageName.equals("android")) { 8839 // This is a regular package, with one or more known overlay packages. 8840 createIdmapsForPackageLI(pkg); 8841 } 8842 } 8843 8844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8845 8846 if (createIdmapFailed) { 8847 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8848 "scanPackageLI failed to createIdmap"); 8849 } 8850 return pkg; 8851 } 8852 8853 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8854 PackageParser.Package update, UserHandle user) { 8855 if (existing.applicationInfo == null || update.applicationInfo == null) { 8856 // This isn't due to an app installation. 8857 return; 8858 } 8859 8860 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8861 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8862 8863 // The codePath hasn't changed, so there's nothing for us to do. 8864 if (Objects.equals(oldCodePath, newCodePath)) { 8865 return; 8866 } 8867 8868 File canonicalNewCodePath; 8869 try { 8870 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8871 } catch (IOException e) { 8872 Slog.w(TAG, "Failed to get canonical path.", e); 8873 return; 8874 } 8875 8876 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8877 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8878 // that the last component of the path (i.e, the name) doesn't need canonicalization 8879 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8880 // but may change in the future. Hopefully this function won't exist at that point. 8881 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8882 oldCodePath.getName()); 8883 8884 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8885 // with "@". 8886 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8887 if (!oldMarkerPrefix.endsWith("@")) { 8888 oldMarkerPrefix += "@"; 8889 } 8890 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8891 if (!newMarkerPrefix.endsWith("@")) { 8892 newMarkerPrefix += "@"; 8893 } 8894 8895 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8896 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8897 for (String updatedPath : updatedPaths) { 8898 String updatedPathName = new File(updatedPath).getName(); 8899 markerSuffixes.add(updatedPathName.replace('/', '@')); 8900 } 8901 8902 for (int userId : resolveUserIds(user.getIdentifier())) { 8903 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8904 8905 for (String markerSuffix : markerSuffixes) { 8906 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 8907 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 8908 if (oldForeignUseMark.exists()) { 8909 try { 8910 Os.rename(oldForeignUseMark.getAbsolutePath(), 8911 newForeignUseMark.getAbsolutePath()); 8912 } catch (ErrnoException e) { 8913 Slog.w(TAG, "Failed to rename foreign use marker", e); 8914 oldForeignUseMark.delete(); 8915 } 8916 } 8917 } 8918 } 8919 } 8920 8921 /** 8922 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8923 * is derived purely on the basis of the contents of {@code scanFile} and 8924 * {@code cpuAbiOverride}. 8925 * 8926 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8927 */ 8928 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8929 String cpuAbiOverride, boolean extractLibs) 8930 throws PackageManagerException { 8931 // TODO: We can probably be smarter about this stuff. For installed apps, 8932 // we can calculate this information at install time once and for all. For 8933 // system apps, we can probably assume that this information doesn't change 8934 // after the first boot scan. As things stand, we do lots of unnecessary work. 8935 8936 // Give ourselves some initial paths; we'll come back for another 8937 // pass once we've determined ABI below. 8938 setNativeLibraryPaths(pkg); 8939 8940 // We would never need to extract libs for forward-locked and external packages, 8941 // since the container service will do it for us. We shouldn't attempt to 8942 // extract libs from system app when it was not updated. 8943 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8944 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8945 extractLibs = false; 8946 } 8947 8948 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8949 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8950 8951 NativeLibraryHelper.Handle handle = null; 8952 try { 8953 handle = NativeLibraryHelper.Handle.create(pkg); 8954 // TODO(multiArch): This can be null for apps that didn't go through the 8955 // usual installation process. We can calculate it again, like we 8956 // do during install time. 8957 // 8958 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8959 // unnecessary. 8960 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8961 8962 // Null out the abis so that they can be recalculated. 8963 pkg.applicationInfo.primaryCpuAbi = null; 8964 pkg.applicationInfo.secondaryCpuAbi = null; 8965 if (isMultiArch(pkg.applicationInfo)) { 8966 // Warn if we've set an abiOverride for multi-lib packages.. 8967 // By definition, we need to copy both 32 and 64 bit libraries for 8968 // such packages. 8969 if (pkg.cpuAbiOverride != null 8970 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8971 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8972 } 8973 8974 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8975 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8976 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8977 if (extractLibs) { 8978 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8979 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8980 useIsaSpecificSubdirs); 8981 } else { 8982 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8983 } 8984 } 8985 8986 maybeThrowExceptionForMultiArchCopy( 8987 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8988 8989 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8990 if (extractLibs) { 8991 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8992 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8993 useIsaSpecificSubdirs); 8994 } else { 8995 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8996 } 8997 } 8998 8999 maybeThrowExceptionForMultiArchCopy( 9000 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9001 9002 if (abi64 >= 0) { 9003 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9004 } 9005 9006 if (abi32 >= 0) { 9007 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9008 if (abi64 >= 0) { 9009 if (pkg.use32bitAbi) { 9010 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9011 pkg.applicationInfo.primaryCpuAbi = abi; 9012 } else { 9013 pkg.applicationInfo.secondaryCpuAbi = abi; 9014 } 9015 } else { 9016 pkg.applicationInfo.primaryCpuAbi = abi; 9017 } 9018 } 9019 9020 } else { 9021 String[] abiList = (cpuAbiOverride != null) ? 9022 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9023 9024 // Enable gross and lame hacks for apps that are built with old 9025 // SDK tools. We must scan their APKs for renderscript bitcode and 9026 // not launch them if it's present. Don't bother checking on devices 9027 // that don't have 64 bit support. 9028 boolean needsRenderScriptOverride = false; 9029 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9030 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9031 abiList = Build.SUPPORTED_32_BIT_ABIS; 9032 needsRenderScriptOverride = true; 9033 } 9034 9035 final int copyRet; 9036 if (extractLibs) { 9037 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9038 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9039 } else { 9040 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9041 } 9042 9043 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9044 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9045 "Error unpackaging native libs for app, errorCode=" + copyRet); 9046 } 9047 9048 if (copyRet >= 0) { 9049 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9050 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9051 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9052 } else if (needsRenderScriptOverride) { 9053 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9054 } 9055 } 9056 } catch (IOException ioe) { 9057 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9058 } finally { 9059 IoUtils.closeQuietly(handle); 9060 } 9061 9062 // Now that we've calculated the ABIs and determined if it's an internal app, 9063 // we will go ahead and populate the nativeLibraryPath. 9064 setNativeLibraryPaths(pkg); 9065 } 9066 9067 /** 9068 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9069 * i.e, so that all packages can be run inside a single process if required. 9070 * 9071 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9072 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9073 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9074 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9075 * updating a package that belongs to a shared user. 9076 * 9077 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9078 * adds unnecessary complexity. 9079 */ 9080 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9081 PackageParser.Package scannedPackage, boolean bootComplete) { 9082 String requiredInstructionSet = null; 9083 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9084 requiredInstructionSet = VMRuntime.getInstructionSet( 9085 scannedPackage.applicationInfo.primaryCpuAbi); 9086 } 9087 9088 PackageSetting requirer = null; 9089 for (PackageSetting ps : packagesForUser) { 9090 // If packagesForUser contains scannedPackage, we skip it. This will happen 9091 // when scannedPackage is an update of an existing package. Without this check, 9092 // we will never be able to change the ABI of any package belonging to a shared 9093 // user, even if it's compatible with other packages. 9094 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9095 if (ps.primaryCpuAbiString == null) { 9096 continue; 9097 } 9098 9099 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9100 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9101 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9102 // this but there's not much we can do. 9103 String errorMessage = "Instruction set mismatch, " 9104 + ((requirer == null) ? "[caller]" : requirer) 9105 + " requires " + requiredInstructionSet + " whereas " + ps 9106 + " requires " + instructionSet; 9107 Slog.w(TAG, errorMessage); 9108 } 9109 9110 if (requiredInstructionSet == null) { 9111 requiredInstructionSet = instructionSet; 9112 requirer = ps; 9113 } 9114 } 9115 } 9116 9117 if (requiredInstructionSet != null) { 9118 String adjustedAbi; 9119 if (requirer != null) { 9120 // requirer != null implies that either scannedPackage was null or that scannedPackage 9121 // did not require an ABI, in which case we have to adjust scannedPackage to match 9122 // the ABI of the set (which is the same as requirer's ABI) 9123 adjustedAbi = requirer.primaryCpuAbiString; 9124 if (scannedPackage != null) { 9125 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9126 } 9127 } else { 9128 // requirer == null implies that we're updating all ABIs in the set to 9129 // match scannedPackage. 9130 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9131 } 9132 9133 for (PackageSetting ps : packagesForUser) { 9134 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9135 if (ps.primaryCpuAbiString != null) { 9136 continue; 9137 } 9138 9139 ps.primaryCpuAbiString = adjustedAbi; 9140 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9141 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9142 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9143 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9144 + " (requirer=" 9145 + (requirer == null ? "null" : requirer.pkg.packageName) 9146 + ", scannedPackage=" 9147 + (scannedPackage != null ? scannedPackage.packageName : "null") 9148 + ")"); 9149 try { 9150 mInstaller.rmdex(ps.codePathString, 9151 getDexCodeInstructionSet(getPreferredInstructionSet())); 9152 } catch (InstallerException ignored) { 9153 } 9154 } 9155 } 9156 } 9157 } 9158 } 9159 9160 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9161 synchronized (mPackages) { 9162 mResolverReplaced = true; 9163 // Set up information for custom user intent resolution activity. 9164 mResolveActivity.applicationInfo = pkg.applicationInfo; 9165 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9166 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9167 mResolveActivity.processName = pkg.applicationInfo.packageName; 9168 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9169 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9170 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9171 mResolveActivity.theme = 0; 9172 mResolveActivity.exported = true; 9173 mResolveActivity.enabled = true; 9174 mResolveInfo.activityInfo = mResolveActivity; 9175 mResolveInfo.priority = 0; 9176 mResolveInfo.preferredOrder = 0; 9177 mResolveInfo.match = 0; 9178 mResolveComponentName = mCustomResolverComponentName; 9179 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9180 mResolveComponentName); 9181 } 9182 } 9183 9184 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9185 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9186 9187 // Set up information for ephemeral installer activity 9188 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9189 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9190 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9191 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9192 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9193 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9194 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9195 mEphemeralInstallerActivity.theme = 0; 9196 mEphemeralInstallerActivity.exported = true; 9197 mEphemeralInstallerActivity.enabled = true; 9198 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9199 mEphemeralInstallerInfo.priority = 0; 9200 mEphemeralInstallerInfo.preferredOrder = 0; 9201 mEphemeralInstallerInfo.match = 0; 9202 9203 if (DEBUG_EPHEMERAL) { 9204 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9205 } 9206 } 9207 9208 private static String calculateBundledApkRoot(final String codePathString) { 9209 final File codePath = new File(codePathString); 9210 final File codeRoot; 9211 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9212 codeRoot = Environment.getRootDirectory(); 9213 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9214 codeRoot = Environment.getOemDirectory(); 9215 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9216 codeRoot = Environment.getVendorDirectory(); 9217 } else { 9218 // Unrecognized code path; take its top real segment as the apk root: 9219 // e.g. /something/app/blah.apk => /something 9220 try { 9221 File f = codePath.getCanonicalFile(); 9222 File parent = f.getParentFile(); // non-null because codePath is a file 9223 File tmp; 9224 while ((tmp = parent.getParentFile()) != null) { 9225 f = parent; 9226 parent = tmp; 9227 } 9228 codeRoot = f; 9229 Slog.w(TAG, "Unrecognized code path " 9230 + codePath + " - using " + codeRoot); 9231 } catch (IOException e) { 9232 // Can't canonicalize the code path -- shenanigans? 9233 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9234 return Environment.getRootDirectory().getPath(); 9235 } 9236 } 9237 return codeRoot.getPath(); 9238 } 9239 9240 /** 9241 * Derive and set the location of native libraries for the given package, 9242 * which varies depending on where and how the package was installed. 9243 */ 9244 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9245 final ApplicationInfo info = pkg.applicationInfo; 9246 final String codePath = pkg.codePath; 9247 final File codeFile = new File(codePath); 9248 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9249 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9250 9251 info.nativeLibraryRootDir = null; 9252 info.nativeLibraryRootRequiresIsa = false; 9253 info.nativeLibraryDir = null; 9254 info.secondaryNativeLibraryDir = null; 9255 9256 if (isApkFile(codeFile)) { 9257 // Monolithic install 9258 if (bundledApp) { 9259 // If "/system/lib64/apkname" exists, assume that is the per-package 9260 // native library directory to use; otherwise use "/system/lib/apkname". 9261 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9262 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9263 getPrimaryInstructionSet(info)); 9264 9265 // This is a bundled system app so choose the path based on the ABI. 9266 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9267 // is just the default path. 9268 final String apkName = deriveCodePathName(codePath); 9269 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9270 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9271 apkName).getAbsolutePath(); 9272 9273 if (info.secondaryCpuAbi != null) { 9274 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9275 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9276 secondaryLibDir, apkName).getAbsolutePath(); 9277 } 9278 } else if (asecApp) { 9279 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9280 .getAbsolutePath(); 9281 } else { 9282 final String apkName = deriveCodePathName(codePath); 9283 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9284 .getAbsolutePath(); 9285 } 9286 9287 info.nativeLibraryRootRequiresIsa = false; 9288 info.nativeLibraryDir = info.nativeLibraryRootDir; 9289 } else { 9290 // Cluster install 9291 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9292 info.nativeLibraryRootRequiresIsa = true; 9293 9294 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9295 getPrimaryInstructionSet(info)).getAbsolutePath(); 9296 9297 if (info.secondaryCpuAbi != null) { 9298 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9299 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9300 } 9301 } 9302 } 9303 9304 /** 9305 * Calculate the abis and roots for a bundled app. These can uniquely 9306 * be determined from the contents of the system partition, i.e whether 9307 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9308 * of this information, and instead assume that the system was built 9309 * sensibly. 9310 */ 9311 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9312 PackageSetting pkgSetting) { 9313 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9314 9315 // If "/system/lib64/apkname" exists, assume that is the per-package 9316 // native library directory to use; otherwise use "/system/lib/apkname". 9317 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9318 setBundledAppAbi(pkg, apkRoot, apkName); 9319 // pkgSetting might be null during rescan following uninstall of updates 9320 // to a bundled app, so accommodate that possibility. The settings in 9321 // that case will be established later from the parsed package. 9322 // 9323 // If the settings aren't null, sync them up with what we've just derived. 9324 // note that apkRoot isn't stored in the package settings. 9325 if (pkgSetting != null) { 9326 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9327 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9328 } 9329 } 9330 9331 /** 9332 * Deduces the ABI of a bundled app and sets the relevant fields on the 9333 * parsed pkg object. 9334 * 9335 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9336 * under which system libraries are installed. 9337 * @param apkName the name of the installed package. 9338 */ 9339 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9340 final File codeFile = new File(pkg.codePath); 9341 9342 final boolean has64BitLibs; 9343 final boolean has32BitLibs; 9344 if (isApkFile(codeFile)) { 9345 // Monolithic install 9346 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9347 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9348 } else { 9349 // Cluster install 9350 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9351 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9352 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9353 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9354 has64BitLibs = (new File(rootDir, isa)).exists(); 9355 } else { 9356 has64BitLibs = false; 9357 } 9358 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9359 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9360 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9361 has32BitLibs = (new File(rootDir, isa)).exists(); 9362 } else { 9363 has32BitLibs = false; 9364 } 9365 } 9366 9367 if (has64BitLibs && !has32BitLibs) { 9368 // The package has 64 bit libs, but not 32 bit libs. Its primary 9369 // ABI should be 64 bit. We can safely assume here that the bundled 9370 // native libraries correspond to the most preferred ABI in the list. 9371 9372 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9373 pkg.applicationInfo.secondaryCpuAbi = null; 9374 } else if (has32BitLibs && !has64BitLibs) { 9375 // The package has 32 bit libs but not 64 bit libs. Its primary 9376 // ABI should be 32 bit. 9377 9378 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9379 pkg.applicationInfo.secondaryCpuAbi = null; 9380 } else if (has32BitLibs && has64BitLibs) { 9381 // The application has both 64 and 32 bit bundled libraries. We check 9382 // here that the app declares multiArch support, and warn if it doesn't. 9383 // 9384 // We will be lenient here and record both ABIs. The primary will be the 9385 // ABI that's higher on the list, i.e, a device that's configured to prefer 9386 // 64 bit apps will see a 64 bit primary ABI, 9387 9388 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9389 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9390 } 9391 9392 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9393 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9394 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9395 } else { 9396 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9397 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9398 } 9399 } else { 9400 pkg.applicationInfo.primaryCpuAbi = null; 9401 pkg.applicationInfo.secondaryCpuAbi = null; 9402 } 9403 } 9404 9405 private void killApplication(String pkgName, int appId, String reason) { 9406 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9407 } 9408 9409 private void killApplication(String pkgName, int appId, int userId, String reason) { 9410 // Request the ActivityManager to kill the process(only for existing packages) 9411 // so that we do not end up in a confused state while the user is still using the older 9412 // version of the application while the new one gets installed. 9413 final long token = Binder.clearCallingIdentity(); 9414 try { 9415 IActivityManager am = ActivityManagerNative.getDefault(); 9416 if (am != null) { 9417 try { 9418 am.killApplication(pkgName, appId, userId, reason); 9419 } catch (RemoteException e) { 9420 } 9421 } 9422 } finally { 9423 Binder.restoreCallingIdentity(token); 9424 } 9425 } 9426 9427 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9428 // Remove the parent package setting 9429 PackageSetting ps = (PackageSetting) pkg.mExtras; 9430 if (ps != null) { 9431 removePackageLI(ps, chatty); 9432 } 9433 // Remove the child package setting 9434 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9435 for (int i = 0; i < childCount; i++) { 9436 PackageParser.Package childPkg = pkg.childPackages.get(i); 9437 ps = (PackageSetting) childPkg.mExtras; 9438 if (ps != null) { 9439 removePackageLI(ps, chatty); 9440 } 9441 } 9442 } 9443 9444 void removePackageLI(PackageSetting ps, boolean chatty) { 9445 if (DEBUG_INSTALL) { 9446 if (chatty) 9447 Log.d(TAG, "Removing package " + ps.name); 9448 } 9449 9450 // writer 9451 synchronized (mPackages) { 9452 mPackages.remove(ps.name); 9453 final PackageParser.Package pkg = ps.pkg; 9454 if (pkg != null) { 9455 cleanPackageDataStructuresLILPw(pkg, chatty); 9456 } 9457 } 9458 } 9459 9460 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9461 if (DEBUG_INSTALL) { 9462 if (chatty) 9463 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9464 } 9465 9466 // writer 9467 synchronized (mPackages) { 9468 // Remove the parent package 9469 mPackages.remove(pkg.applicationInfo.packageName); 9470 cleanPackageDataStructuresLILPw(pkg, chatty); 9471 9472 // Remove the child packages 9473 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9474 for (int i = 0; i < childCount; i++) { 9475 PackageParser.Package childPkg = pkg.childPackages.get(i); 9476 mPackages.remove(childPkg.applicationInfo.packageName); 9477 cleanPackageDataStructuresLILPw(childPkg, chatty); 9478 } 9479 } 9480 } 9481 9482 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9483 int N = pkg.providers.size(); 9484 StringBuilder r = null; 9485 int i; 9486 for (i=0; i<N; i++) { 9487 PackageParser.Provider p = pkg.providers.get(i); 9488 mProviders.removeProvider(p); 9489 if (p.info.authority == null) { 9490 9491 /* There was another ContentProvider with this authority when 9492 * this app was installed so this authority is null, 9493 * Ignore it as we don't have to unregister the provider. 9494 */ 9495 continue; 9496 } 9497 String names[] = p.info.authority.split(";"); 9498 for (int j = 0; j < names.length; j++) { 9499 if (mProvidersByAuthority.get(names[j]) == p) { 9500 mProvidersByAuthority.remove(names[j]); 9501 if (DEBUG_REMOVE) { 9502 if (chatty) 9503 Log.d(TAG, "Unregistered content provider: " + names[j] 9504 + ", className = " + p.info.name + ", isSyncable = " 9505 + p.info.isSyncable); 9506 } 9507 } 9508 } 9509 if (DEBUG_REMOVE && chatty) { 9510 if (r == null) { 9511 r = new StringBuilder(256); 9512 } else { 9513 r.append(' '); 9514 } 9515 r.append(p.info.name); 9516 } 9517 } 9518 if (r != null) { 9519 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9520 } 9521 9522 N = pkg.services.size(); 9523 r = null; 9524 for (i=0; i<N; i++) { 9525 PackageParser.Service s = pkg.services.get(i); 9526 mServices.removeService(s); 9527 if (chatty) { 9528 if (r == null) { 9529 r = new StringBuilder(256); 9530 } else { 9531 r.append(' '); 9532 } 9533 r.append(s.info.name); 9534 } 9535 } 9536 if (r != null) { 9537 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9538 } 9539 9540 N = pkg.receivers.size(); 9541 r = null; 9542 for (i=0; i<N; i++) { 9543 PackageParser.Activity a = pkg.receivers.get(i); 9544 mReceivers.removeActivity(a, "receiver"); 9545 if (DEBUG_REMOVE && chatty) { 9546 if (r == null) { 9547 r = new StringBuilder(256); 9548 } else { 9549 r.append(' '); 9550 } 9551 r.append(a.info.name); 9552 } 9553 } 9554 if (r != null) { 9555 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9556 } 9557 9558 N = pkg.activities.size(); 9559 r = null; 9560 for (i=0; i<N; i++) { 9561 PackageParser.Activity a = pkg.activities.get(i); 9562 mActivities.removeActivity(a, "activity"); 9563 if (DEBUG_REMOVE && chatty) { 9564 if (r == null) { 9565 r = new StringBuilder(256); 9566 } else { 9567 r.append(' '); 9568 } 9569 r.append(a.info.name); 9570 } 9571 } 9572 if (r != null) { 9573 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9574 } 9575 9576 N = pkg.permissions.size(); 9577 r = null; 9578 for (i=0; i<N; i++) { 9579 PackageParser.Permission p = pkg.permissions.get(i); 9580 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9581 if (bp == null) { 9582 bp = mSettings.mPermissionTrees.get(p.info.name); 9583 } 9584 if (bp != null && bp.perm == p) { 9585 bp.perm = null; 9586 if (DEBUG_REMOVE && chatty) { 9587 if (r == null) { 9588 r = new StringBuilder(256); 9589 } else { 9590 r.append(' '); 9591 } 9592 r.append(p.info.name); 9593 } 9594 } 9595 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9596 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9597 if (appOpPkgs != null) { 9598 appOpPkgs.remove(pkg.packageName); 9599 } 9600 } 9601 } 9602 if (r != null) { 9603 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9604 } 9605 9606 N = pkg.requestedPermissions.size(); 9607 r = null; 9608 for (i=0; i<N; i++) { 9609 String perm = pkg.requestedPermissions.get(i); 9610 BasePermission bp = mSettings.mPermissions.get(perm); 9611 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9612 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9613 if (appOpPkgs != null) { 9614 appOpPkgs.remove(pkg.packageName); 9615 if (appOpPkgs.isEmpty()) { 9616 mAppOpPermissionPackages.remove(perm); 9617 } 9618 } 9619 } 9620 } 9621 if (r != null) { 9622 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9623 } 9624 9625 N = pkg.instrumentation.size(); 9626 r = null; 9627 for (i=0; i<N; i++) { 9628 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9629 mInstrumentation.remove(a.getComponentName()); 9630 if (DEBUG_REMOVE && chatty) { 9631 if (r == null) { 9632 r = new StringBuilder(256); 9633 } else { 9634 r.append(' '); 9635 } 9636 r.append(a.info.name); 9637 } 9638 } 9639 if (r != null) { 9640 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9641 } 9642 9643 r = null; 9644 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9645 // Only system apps can hold shared libraries. 9646 if (pkg.libraryNames != null) { 9647 for (i=0; i<pkg.libraryNames.size(); i++) { 9648 String name = pkg.libraryNames.get(i); 9649 SharedLibraryEntry cur = mSharedLibraries.get(name); 9650 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9651 mSharedLibraries.remove(name); 9652 if (DEBUG_REMOVE && chatty) { 9653 if (r == null) { 9654 r = new StringBuilder(256); 9655 } else { 9656 r.append(' '); 9657 } 9658 r.append(name); 9659 } 9660 } 9661 } 9662 } 9663 } 9664 if (r != null) { 9665 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9666 } 9667 } 9668 9669 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9670 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9671 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9672 return true; 9673 } 9674 } 9675 return false; 9676 } 9677 9678 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9679 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9680 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9681 9682 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9683 // Update the parent permissions 9684 updatePermissionsLPw(pkg.packageName, pkg, flags); 9685 // Update the child permissions 9686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9687 for (int i = 0; i < childCount; i++) { 9688 PackageParser.Package childPkg = pkg.childPackages.get(i); 9689 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9690 } 9691 } 9692 9693 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9694 int flags) { 9695 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9696 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9697 } 9698 9699 private void updatePermissionsLPw(String changingPkg, 9700 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9701 // Make sure there are no dangling permission trees. 9702 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9703 while (it.hasNext()) { 9704 final BasePermission bp = it.next(); 9705 if (bp.packageSetting == null) { 9706 // We may not yet have parsed the package, so just see if 9707 // we still know about its settings. 9708 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9709 } 9710 if (bp.packageSetting == null) { 9711 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9712 + " from package " + bp.sourcePackage); 9713 it.remove(); 9714 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9715 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9716 Slog.i(TAG, "Removing old permission tree: " + bp.name 9717 + " from package " + bp.sourcePackage); 9718 flags |= UPDATE_PERMISSIONS_ALL; 9719 it.remove(); 9720 } 9721 } 9722 } 9723 9724 // Make sure all dynamic permissions have been assigned to a package, 9725 // and make sure there are no dangling permissions. 9726 it = mSettings.mPermissions.values().iterator(); 9727 while (it.hasNext()) { 9728 final BasePermission bp = it.next(); 9729 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9730 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9731 + bp.name + " pkg=" + bp.sourcePackage 9732 + " info=" + bp.pendingInfo); 9733 if (bp.packageSetting == null && bp.pendingInfo != null) { 9734 final BasePermission tree = findPermissionTreeLP(bp.name); 9735 if (tree != null && tree.perm != null) { 9736 bp.packageSetting = tree.packageSetting; 9737 bp.perm = new PackageParser.Permission(tree.perm.owner, 9738 new PermissionInfo(bp.pendingInfo)); 9739 bp.perm.info.packageName = tree.perm.info.packageName; 9740 bp.perm.info.name = bp.name; 9741 bp.uid = tree.uid; 9742 } 9743 } 9744 } 9745 if (bp.packageSetting == null) { 9746 // We may not yet have parsed the package, so just see if 9747 // we still know about its settings. 9748 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9749 } 9750 if (bp.packageSetting == null) { 9751 Slog.w(TAG, "Removing dangling permission: " + bp.name 9752 + " from package " + bp.sourcePackage); 9753 it.remove(); 9754 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9755 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9756 Slog.i(TAG, "Removing old permission: " + bp.name 9757 + " from package " + bp.sourcePackage); 9758 flags |= UPDATE_PERMISSIONS_ALL; 9759 it.remove(); 9760 } 9761 } 9762 } 9763 9764 // Now update the permissions for all packages, in particular 9765 // replace the granted permissions of the system packages. 9766 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9767 for (PackageParser.Package pkg : mPackages.values()) { 9768 if (pkg != pkgInfo) { 9769 // Only replace for packages on requested volume 9770 final String volumeUuid = getVolumeUuidForPackage(pkg); 9771 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9772 && Objects.equals(replaceVolumeUuid, volumeUuid); 9773 grantPermissionsLPw(pkg, replace, changingPkg); 9774 } 9775 } 9776 } 9777 9778 if (pkgInfo != null) { 9779 // Only replace for packages on requested volume 9780 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9781 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9782 && Objects.equals(replaceVolumeUuid, volumeUuid); 9783 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9784 } 9785 } 9786 9787 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9788 String packageOfInterest) { 9789 // IMPORTANT: There are two types of permissions: install and runtime. 9790 // Install time permissions are granted when the app is installed to 9791 // all device users and users added in the future. Runtime permissions 9792 // are granted at runtime explicitly to specific users. Normal and signature 9793 // protected permissions are install time permissions. Dangerous permissions 9794 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9795 // otherwise they are runtime permissions. This function does not manage 9796 // runtime permissions except for the case an app targeting Lollipop MR1 9797 // being upgraded to target a newer SDK, in which case dangerous permissions 9798 // are transformed from install time to runtime ones. 9799 9800 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9801 if (ps == null) { 9802 return; 9803 } 9804 9805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9806 9807 PermissionsState permissionsState = ps.getPermissionsState(); 9808 PermissionsState origPermissions = permissionsState; 9809 9810 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9811 9812 boolean runtimePermissionsRevoked = false; 9813 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9814 9815 boolean changedInstallPermission = false; 9816 9817 if (replace) { 9818 ps.installPermissionsFixed = false; 9819 if (!ps.isSharedUser()) { 9820 origPermissions = new PermissionsState(permissionsState); 9821 permissionsState.reset(); 9822 } else { 9823 // We need to know only about runtime permission changes since the 9824 // calling code always writes the install permissions state but 9825 // the runtime ones are written only if changed. The only cases of 9826 // changed runtime permissions here are promotion of an install to 9827 // runtime and revocation of a runtime from a shared user. 9828 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9829 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9830 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9831 runtimePermissionsRevoked = true; 9832 } 9833 } 9834 } 9835 9836 permissionsState.setGlobalGids(mGlobalGids); 9837 9838 final int N = pkg.requestedPermissions.size(); 9839 for (int i=0; i<N; i++) { 9840 final String name = pkg.requestedPermissions.get(i); 9841 final BasePermission bp = mSettings.mPermissions.get(name); 9842 9843 if (DEBUG_INSTALL) { 9844 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9845 } 9846 9847 if (bp == null || bp.packageSetting == null) { 9848 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9849 Slog.w(TAG, "Unknown permission " + name 9850 + " in package " + pkg.packageName); 9851 } 9852 continue; 9853 } 9854 9855 final String perm = bp.name; 9856 boolean allowedSig = false; 9857 int grant = GRANT_DENIED; 9858 9859 // Keep track of app op permissions. 9860 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9861 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9862 if (pkgs == null) { 9863 pkgs = new ArraySet<>(); 9864 mAppOpPermissionPackages.put(bp.name, pkgs); 9865 } 9866 pkgs.add(pkg.packageName); 9867 } 9868 9869 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9870 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9871 >= Build.VERSION_CODES.M; 9872 switch (level) { 9873 case PermissionInfo.PROTECTION_NORMAL: { 9874 // For all apps normal permissions are install time ones. 9875 grant = GRANT_INSTALL; 9876 } break; 9877 9878 case PermissionInfo.PROTECTION_DANGEROUS: { 9879 // If a permission review is required for legacy apps we represent 9880 // their permissions as always granted runtime ones since we need 9881 // to keep the review required permission flag per user while an 9882 // install permission's state is shared across all users. 9883 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9884 // For legacy apps dangerous permissions are install time ones. 9885 grant = GRANT_INSTALL; 9886 } else if (origPermissions.hasInstallPermission(bp.name)) { 9887 // For legacy apps that became modern, install becomes runtime. 9888 grant = GRANT_UPGRADE; 9889 } else if (mPromoteSystemApps 9890 && isSystemApp(ps) 9891 && mExistingSystemPackages.contains(ps.name)) { 9892 // For legacy system apps, install becomes runtime. 9893 // We cannot check hasInstallPermission() for system apps since those 9894 // permissions were granted implicitly and not persisted pre-M. 9895 grant = GRANT_UPGRADE; 9896 } else { 9897 // For modern apps keep runtime permissions unchanged. 9898 grant = GRANT_RUNTIME; 9899 } 9900 } break; 9901 9902 case PermissionInfo.PROTECTION_SIGNATURE: { 9903 // For all apps signature permissions are install time ones. 9904 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9905 if (allowedSig) { 9906 grant = GRANT_INSTALL; 9907 } 9908 } break; 9909 } 9910 9911 if (DEBUG_INSTALL) { 9912 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9913 } 9914 9915 if (grant != GRANT_DENIED) { 9916 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9917 // If this is an existing, non-system package, then 9918 // we can't add any new permissions to it. 9919 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9920 // Except... if this is a permission that was added 9921 // to the platform (note: need to only do this when 9922 // updating the platform). 9923 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9924 grant = GRANT_DENIED; 9925 } 9926 } 9927 } 9928 9929 switch (grant) { 9930 case GRANT_INSTALL: { 9931 // Revoke this as runtime permission to handle the case of 9932 // a runtime permission being downgraded to an install one. 9933 // Also in permission review mode we keep dangerous permissions 9934 // for legacy apps 9935 for (int userId : UserManagerService.getInstance().getUserIds()) { 9936 if (origPermissions.getRuntimePermissionState( 9937 bp.name, userId) != null) { 9938 // Revoke the runtime permission and clear the flags. 9939 origPermissions.revokeRuntimePermission(bp, userId); 9940 origPermissions.updatePermissionFlags(bp, userId, 9941 PackageManager.MASK_PERMISSION_FLAGS, 0); 9942 // If we revoked a permission permission, we have to write. 9943 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9944 changedRuntimePermissionUserIds, userId); 9945 } 9946 } 9947 // Grant an install permission. 9948 if (permissionsState.grantInstallPermission(bp) != 9949 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9950 changedInstallPermission = true; 9951 } 9952 } break; 9953 9954 case GRANT_RUNTIME: { 9955 // Grant previously granted runtime permissions. 9956 for (int userId : UserManagerService.getInstance().getUserIds()) { 9957 PermissionState permissionState = origPermissions 9958 .getRuntimePermissionState(bp.name, userId); 9959 int flags = permissionState != null 9960 ? permissionState.getFlags() : 0; 9961 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9962 if (permissionsState.grantRuntimePermission(bp, userId) == 9963 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9964 // If we cannot put the permission as it was, we have to write. 9965 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9966 changedRuntimePermissionUserIds, userId); 9967 } 9968 // If the app supports runtime permissions no need for a review. 9969 if (Build.PERMISSIONS_REVIEW_REQUIRED 9970 && appSupportsRuntimePermissions 9971 && (flags & PackageManager 9972 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9973 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9974 // Since we changed the flags, we have to write. 9975 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9976 changedRuntimePermissionUserIds, userId); 9977 } 9978 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9979 && !appSupportsRuntimePermissions) { 9980 // For legacy apps that need a permission review, every new 9981 // runtime permission is granted but it is pending a review. 9982 // We also need to review only platform defined runtime 9983 // permissions as these are the only ones the platform knows 9984 // how to disable the API to simulate revocation as legacy 9985 // apps don't expect to run with revoked permissions. 9986 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9987 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9988 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9989 // We changed the flags, hence have to write. 9990 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9991 changedRuntimePermissionUserIds, userId); 9992 } 9993 } 9994 if (permissionsState.grantRuntimePermission(bp, userId) 9995 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9996 // We changed the permission, hence have to write. 9997 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9998 changedRuntimePermissionUserIds, userId); 9999 } 10000 } 10001 // Propagate the permission flags. 10002 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10003 } 10004 } break; 10005 10006 case GRANT_UPGRADE: { 10007 // Grant runtime permissions for a previously held install permission. 10008 PermissionState permissionState = origPermissions 10009 .getInstallPermissionState(bp.name); 10010 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10011 10012 if (origPermissions.revokeInstallPermission(bp) 10013 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10014 // We will be transferring the permission flags, so clear them. 10015 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10016 PackageManager.MASK_PERMISSION_FLAGS, 0); 10017 changedInstallPermission = true; 10018 } 10019 10020 // If the permission is not to be promoted to runtime we ignore it and 10021 // also its other flags as they are not applicable to install permissions. 10022 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10023 for (int userId : currentUserIds) { 10024 if (permissionsState.grantRuntimePermission(bp, userId) != 10025 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10026 // Transfer the permission flags. 10027 permissionsState.updatePermissionFlags(bp, userId, 10028 flags, flags); 10029 // If we granted the permission, we have to write. 10030 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10031 changedRuntimePermissionUserIds, userId); 10032 } 10033 } 10034 } 10035 } break; 10036 10037 default: { 10038 if (packageOfInterest == null 10039 || packageOfInterest.equals(pkg.packageName)) { 10040 Slog.w(TAG, "Not granting permission " + perm 10041 + " to package " + pkg.packageName 10042 + " because it was previously installed without"); 10043 } 10044 } break; 10045 } 10046 } else { 10047 if (permissionsState.revokeInstallPermission(bp) != 10048 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10049 // Also drop the permission flags. 10050 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10051 PackageManager.MASK_PERMISSION_FLAGS, 0); 10052 changedInstallPermission = true; 10053 Slog.i(TAG, "Un-granting permission " + perm 10054 + " from package " + pkg.packageName 10055 + " (protectionLevel=" + bp.protectionLevel 10056 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10057 + ")"); 10058 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10059 // Don't print warning for app op permissions, since it is fine for them 10060 // not to be granted, there is a UI for the user to decide. 10061 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10062 Slog.w(TAG, "Not granting permission " + perm 10063 + " to package " + pkg.packageName 10064 + " (protectionLevel=" + bp.protectionLevel 10065 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10066 + ")"); 10067 } 10068 } 10069 } 10070 } 10071 10072 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10073 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10074 // This is the first that we have heard about this package, so the 10075 // permissions we have now selected are fixed until explicitly 10076 // changed. 10077 ps.installPermissionsFixed = true; 10078 } 10079 10080 // Persist the runtime permissions state for users with changes. If permissions 10081 // were revoked because no app in the shared user declares them we have to 10082 // write synchronously to avoid losing runtime permissions state. 10083 for (int userId : changedRuntimePermissionUserIds) { 10084 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10085 } 10086 10087 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10088 } 10089 10090 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10091 boolean allowed = false; 10092 final int NP = PackageParser.NEW_PERMISSIONS.length; 10093 for (int ip=0; ip<NP; ip++) { 10094 final PackageParser.NewPermissionInfo npi 10095 = PackageParser.NEW_PERMISSIONS[ip]; 10096 if (npi.name.equals(perm) 10097 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10098 allowed = true; 10099 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10100 + pkg.packageName); 10101 break; 10102 } 10103 } 10104 return allowed; 10105 } 10106 10107 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10108 BasePermission bp, PermissionsState origPermissions) { 10109 boolean allowed; 10110 allowed = (compareSignatures( 10111 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10112 == PackageManager.SIGNATURE_MATCH) 10113 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10114 == PackageManager.SIGNATURE_MATCH); 10115 if (!allowed && (bp.protectionLevel 10116 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10117 if (isSystemApp(pkg)) { 10118 // For updated system applications, a system permission 10119 // is granted only if it had been defined by the original application. 10120 if (pkg.isUpdatedSystemApp()) { 10121 final PackageSetting sysPs = mSettings 10122 .getDisabledSystemPkgLPr(pkg.packageName); 10123 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10124 // If the original was granted this permission, we take 10125 // that grant decision as read and propagate it to the 10126 // update. 10127 if (sysPs.isPrivileged()) { 10128 allowed = true; 10129 } 10130 } else { 10131 // The system apk may have been updated with an older 10132 // version of the one on the data partition, but which 10133 // granted a new system permission that it didn't have 10134 // before. In this case we do want to allow the app to 10135 // now get the new permission if the ancestral apk is 10136 // privileged to get it. 10137 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10138 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10139 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10140 allowed = true; 10141 break; 10142 } 10143 } 10144 } 10145 // Also if a privileged parent package on the system image or any of 10146 // its children requested a privileged permission, the updated child 10147 // packages can also get the permission. 10148 if (pkg.parentPackage != null) { 10149 final PackageSetting disabledSysParentPs = mSettings 10150 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10151 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10152 && disabledSysParentPs.isPrivileged()) { 10153 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10154 allowed = true; 10155 } else if (disabledSysParentPs.pkg.childPackages != null) { 10156 final int count = disabledSysParentPs.pkg.childPackages.size(); 10157 for (int i = 0; i < count; i++) { 10158 PackageParser.Package disabledSysChildPkg = 10159 disabledSysParentPs.pkg.childPackages.get(i); 10160 if (isPackageRequestingPermission(disabledSysChildPkg, 10161 perm)) { 10162 allowed = true; 10163 break; 10164 } 10165 } 10166 } 10167 } 10168 } 10169 } 10170 } else { 10171 allowed = isPrivilegedApp(pkg); 10172 } 10173 } 10174 } 10175 if (!allowed) { 10176 if (!allowed && (bp.protectionLevel 10177 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10178 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10179 // If this was a previously normal/dangerous permission that got moved 10180 // to a system permission as part of the runtime permission redesign, then 10181 // we still want to blindly grant it to old apps. 10182 allowed = true; 10183 } 10184 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10185 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10186 // If this permission is to be granted to the system installer and 10187 // this app is an installer, then it gets the permission. 10188 allowed = true; 10189 } 10190 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10191 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10192 // If this permission is to be granted to the system verifier and 10193 // this app is a verifier, then it gets the permission. 10194 allowed = true; 10195 } 10196 if (!allowed && (bp.protectionLevel 10197 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10198 && isSystemApp(pkg)) { 10199 // Any pre-installed system app is allowed to get this permission. 10200 allowed = true; 10201 } 10202 if (!allowed && (bp.protectionLevel 10203 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10204 // For development permissions, a development permission 10205 // is granted only if it was already granted. 10206 allowed = origPermissions.hasInstallPermission(perm); 10207 } 10208 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10209 && pkg.packageName.equals(mSetupWizardPackage)) { 10210 // If this permission is to be granted to the system setup wizard and 10211 // this app is a setup wizard, then it gets the permission. 10212 allowed = true; 10213 } 10214 } 10215 return allowed; 10216 } 10217 10218 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10219 final int permCount = pkg.requestedPermissions.size(); 10220 for (int j = 0; j < permCount; j++) { 10221 String requestedPermission = pkg.requestedPermissions.get(j); 10222 if (permission.equals(requestedPermission)) { 10223 return true; 10224 } 10225 } 10226 return false; 10227 } 10228 10229 final class ActivityIntentResolver 10230 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10231 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10232 boolean defaultOnly, int userId) { 10233 if (!sUserManager.exists(userId)) return null; 10234 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10235 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10236 } 10237 10238 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10239 int userId) { 10240 if (!sUserManager.exists(userId)) return null; 10241 mFlags = flags; 10242 return super.queryIntent(intent, resolvedType, 10243 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10244 } 10245 10246 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10247 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10248 if (!sUserManager.exists(userId)) return null; 10249 if (packageActivities == null) { 10250 return null; 10251 } 10252 mFlags = flags; 10253 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10254 final int N = packageActivities.size(); 10255 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10256 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10257 10258 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10259 for (int i = 0; i < N; ++i) { 10260 intentFilters = packageActivities.get(i).intents; 10261 if (intentFilters != null && intentFilters.size() > 0) { 10262 PackageParser.ActivityIntentInfo[] array = 10263 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10264 intentFilters.toArray(array); 10265 listCut.add(array); 10266 } 10267 } 10268 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10269 } 10270 10271 /** 10272 * Finds a privileged activity that matches the specified activity names. 10273 */ 10274 private PackageParser.Activity findMatchingActivity( 10275 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10276 for (PackageParser.Activity sysActivity : activityList) { 10277 if (sysActivity.info.name.equals(activityInfo.name)) { 10278 return sysActivity; 10279 } 10280 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10281 return sysActivity; 10282 } 10283 if (sysActivity.info.targetActivity != null) { 10284 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10285 return sysActivity; 10286 } 10287 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10288 return sysActivity; 10289 } 10290 } 10291 } 10292 return null; 10293 } 10294 10295 public class IterGenerator<E> { 10296 public Iterator<E> generate(ActivityIntentInfo info) { 10297 return null; 10298 } 10299 } 10300 10301 public class ActionIterGenerator extends IterGenerator<String> { 10302 @Override 10303 public Iterator<String> generate(ActivityIntentInfo info) { 10304 return info.actionsIterator(); 10305 } 10306 } 10307 10308 public class CategoriesIterGenerator extends IterGenerator<String> { 10309 @Override 10310 public Iterator<String> generate(ActivityIntentInfo info) { 10311 return info.categoriesIterator(); 10312 } 10313 } 10314 10315 public class SchemesIterGenerator extends IterGenerator<String> { 10316 @Override 10317 public Iterator<String> generate(ActivityIntentInfo info) { 10318 return info.schemesIterator(); 10319 } 10320 } 10321 10322 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10323 @Override 10324 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10325 return info.authoritiesIterator(); 10326 } 10327 } 10328 10329 /** 10330 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10331 * MODIFIED. Do not pass in a list that should not be changed. 10332 */ 10333 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10334 IterGenerator<T> generator, Iterator<T> searchIterator) { 10335 // loop through the set of actions; every one must be found in the intent filter 10336 while (searchIterator.hasNext()) { 10337 // we must have at least one filter in the list to consider a match 10338 if (intentList.size() == 0) { 10339 break; 10340 } 10341 10342 final T searchAction = searchIterator.next(); 10343 10344 // loop through the set of intent filters 10345 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10346 while (intentIter.hasNext()) { 10347 final ActivityIntentInfo intentInfo = intentIter.next(); 10348 boolean selectionFound = false; 10349 10350 // loop through the intent filter's selection criteria; at least one 10351 // of them must match the searched criteria 10352 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10353 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10354 final T intentSelection = intentSelectionIter.next(); 10355 if (intentSelection != null && intentSelection.equals(searchAction)) { 10356 selectionFound = true; 10357 break; 10358 } 10359 } 10360 10361 // the selection criteria wasn't found in this filter's set; this filter 10362 // is not a potential match 10363 if (!selectionFound) { 10364 intentIter.remove(); 10365 } 10366 } 10367 } 10368 } 10369 10370 private boolean isProtectedAction(ActivityIntentInfo filter) { 10371 final Iterator<String> actionsIter = filter.actionsIterator(); 10372 while (actionsIter != null && actionsIter.hasNext()) { 10373 final String filterAction = actionsIter.next(); 10374 if (PROTECTED_ACTIONS.contains(filterAction)) { 10375 return true; 10376 } 10377 } 10378 return false; 10379 } 10380 10381 /** 10382 * Adjusts the priority of the given intent filter according to policy. 10383 * <p> 10384 * <ul> 10385 * <li>The priority for non privileged applications is capped to '0'</li> 10386 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10387 * <li>The priority for unbundled updates to privileged applications is capped to the 10388 * priority defined on the system partition</li> 10389 * </ul> 10390 * <p> 10391 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10392 * allowed to obtain any priority on any action. 10393 */ 10394 private void adjustPriority( 10395 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10396 // nothing to do; priority is fine as-is 10397 if (intent.getPriority() <= 0) { 10398 return; 10399 } 10400 10401 final ActivityInfo activityInfo = intent.activity.info; 10402 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10403 10404 final boolean privilegedApp = 10405 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10406 if (!privilegedApp) { 10407 // non-privileged applications can never define a priority >0 10408 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10409 + " package: " + applicationInfo.packageName 10410 + " activity: " + intent.activity.className 10411 + " origPrio: " + intent.getPriority()); 10412 intent.setPriority(0); 10413 return; 10414 } 10415 10416 if (systemActivities == null) { 10417 // the system package is not disabled; we're parsing the system partition 10418 if (isProtectedAction(intent)) { 10419 if (mDeferProtectedFilters) { 10420 // We can't deal with these just yet. No component should ever obtain a 10421 // >0 priority for a protected actions, with ONE exception -- the setup 10422 // wizard. The setup wizard, however, cannot be known until we're able to 10423 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10424 // until all intent filters have been processed. Chicken, meet egg. 10425 // Let the filter temporarily have a high priority and rectify the 10426 // priorities after all system packages have been scanned. 10427 mProtectedFilters.add(intent); 10428 if (DEBUG_FILTERS) { 10429 Slog.i(TAG, "Protected action; save for later;" 10430 + " package: " + applicationInfo.packageName 10431 + " activity: " + intent.activity.className 10432 + " origPrio: " + intent.getPriority()); 10433 } 10434 return; 10435 } else { 10436 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10437 Slog.i(TAG, "No setup wizard;" 10438 + " All protected intents capped to priority 0"); 10439 } 10440 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10441 if (DEBUG_FILTERS) { 10442 Slog.i(TAG, "Found setup wizard;" 10443 + " allow priority " + intent.getPriority() + ";" 10444 + " package: " + intent.activity.info.packageName 10445 + " activity: " + intent.activity.className 10446 + " priority: " + intent.getPriority()); 10447 } 10448 // setup wizard gets whatever it wants 10449 return; 10450 } 10451 Slog.w(TAG, "Protected action; cap priority to 0;" 10452 + " package: " + intent.activity.info.packageName 10453 + " activity: " + intent.activity.className 10454 + " origPrio: " + intent.getPriority()); 10455 intent.setPriority(0); 10456 return; 10457 } 10458 } 10459 // privileged apps on the system image get whatever priority they request 10460 return; 10461 } 10462 10463 // privileged app unbundled update ... try to find the same activity 10464 final PackageParser.Activity foundActivity = 10465 findMatchingActivity(systemActivities, activityInfo); 10466 if (foundActivity == null) { 10467 // this is a new activity; it cannot obtain >0 priority 10468 if (DEBUG_FILTERS) { 10469 Slog.i(TAG, "New activity; cap priority to 0;" 10470 + " package: " + applicationInfo.packageName 10471 + " activity: " + intent.activity.className 10472 + " origPrio: " + intent.getPriority()); 10473 } 10474 intent.setPriority(0); 10475 return; 10476 } 10477 10478 // found activity, now check for filter equivalence 10479 10480 // a shallow copy is enough; we modify the list, not its contents 10481 final List<ActivityIntentInfo> intentListCopy = 10482 new ArrayList<>(foundActivity.intents); 10483 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10484 10485 // find matching action subsets 10486 final Iterator<String> actionsIterator = intent.actionsIterator(); 10487 if (actionsIterator != null) { 10488 getIntentListSubset( 10489 intentListCopy, new ActionIterGenerator(), actionsIterator); 10490 if (intentListCopy.size() == 0) { 10491 // no more intents to match; we're not equivalent 10492 if (DEBUG_FILTERS) { 10493 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10494 + " package: " + applicationInfo.packageName 10495 + " activity: " + intent.activity.className 10496 + " origPrio: " + intent.getPriority()); 10497 } 10498 intent.setPriority(0); 10499 return; 10500 } 10501 } 10502 10503 // find matching category subsets 10504 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10505 if (categoriesIterator != null) { 10506 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10507 categoriesIterator); 10508 if (intentListCopy.size() == 0) { 10509 // no more intents to match; we're not equivalent 10510 if (DEBUG_FILTERS) { 10511 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10512 + " package: " + applicationInfo.packageName 10513 + " activity: " + intent.activity.className 10514 + " origPrio: " + intent.getPriority()); 10515 } 10516 intent.setPriority(0); 10517 return; 10518 } 10519 } 10520 10521 // find matching schemes subsets 10522 final Iterator<String> schemesIterator = intent.schemesIterator(); 10523 if (schemesIterator != null) { 10524 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10525 schemesIterator); 10526 if (intentListCopy.size() == 0) { 10527 // no more intents to match; we're not equivalent 10528 if (DEBUG_FILTERS) { 10529 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10530 + " package: " + applicationInfo.packageName 10531 + " activity: " + intent.activity.className 10532 + " origPrio: " + intent.getPriority()); 10533 } 10534 intent.setPriority(0); 10535 return; 10536 } 10537 } 10538 10539 // find matching authorities subsets 10540 final Iterator<IntentFilter.AuthorityEntry> 10541 authoritiesIterator = intent.authoritiesIterator(); 10542 if (authoritiesIterator != null) { 10543 getIntentListSubset(intentListCopy, 10544 new AuthoritiesIterGenerator(), 10545 authoritiesIterator); 10546 if (intentListCopy.size() == 0) { 10547 // no more intents to match; we're not equivalent 10548 if (DEBUG_FILTERS) { 10549 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10550 + " package: " + applicationInfo.packageName 10551 + " activity: " + intent.activity.className 10552 + " origPrio: " + intent.getPriority()); 10553 } 10554 intent.setPriority(0); 10555 return; 10556 } 10557 } 10558 10559 // we found matching filter(s); app gets the max priority of all intents 10560 int cappedPriority = 0; 10561 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10562 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10563 } 10564 if (intent.getPriority() > cappedPriority) { 10565 if (DEBUG_FILTERS) { 10566 Slog.i(TAG, "Found matching filter(s);" 10567 + " cap priority to " + cappedPriority + ";" 10568 + " package: " + applicationInfo.packageName 10569 + " activity: " + intent.activity.className 10570 + " origPrio: " + intent.getPriority()); 10571 } 10572 intent.setPriority(cappedPriority); 10573 return; 10574 } 10575 // all this for nothing; the requested priority was <= what was on the system 10576 } 10577 10578 public final void addActivity(PackageParser.Activity a, String type) { 10579 mActivities.put(a.getComponentName(), a); 10580 if (DEBUG_SHOW_INFO) 10581 Log.v( 10582 TAG, " " + type + " " + 10583 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10584 if (DEBUG_SHOW_INFO) 10585 Log.v(TAG, " Class=" + a.info.name); 10586 final int NI = a.intents.size(); 10587 for (int j=0; j<NI; j++) { 10588 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10589 if ("activity".equals(type)) { 10590 final PackageSetting ps = 10591 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10592 final List<PackageParser.Activity> systemActivities = 10593 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10594 adjustPriority(systemActivities, intent); 10595 } 10596 if (DEBUG_SHOW_INFO) { 10597 Log.v(TAG, " IntentFilter:"); 10598 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10599 } 10600 if (!intent.debugCheck()) { 10601 Log.w(TAG, "==> For Activity " + a.info.name); 10602 } 10603 addFilter(intent); 10604 } 10605 } 10606 10607 public final void removeActivity(PackageParser.Activity a, String type) { 10608 mActivities.remove(a.getComponentName()); 10609 if (DEBUG_SHOW_INFO) { 10610 Log.v(TAG, " " + type + " " 10611 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10612 : a.info.name) + ":"); 10613 Log.v(TAG, " Class=" + a.info.name); 10614 } 10615 final int NI = a.intents.size(); 10616 for (int j=0; j<NI; j++) { 10617 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10618 if (DEBUG_SHOW_INFO) { 10619 Log.v(TAG, " IntentFilter:"); 10620 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10621 } 10622 removeFilter(intent); 10623 } 10624 } 10625 10626 @Override 10627 protected boolean allowFilterResult( 10628 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10629 ActivityInfo filterAi = filter.activity.info; 10630 for (int i=dest.size()-1; i>=0; i--) { 10631 ActivityInfo destAi = dest.get(i).activityInfo; 10632 if (destAi.name == filterAi.name 10633 && destAi.packageName == filterAi.packageName) { 10634 return false; 10635 } 10636 } 10637 return true; 10638 } 10639 10640 @Override 10641 protected ActivityIntentInfo[] newArray(int size) { 10642 return new ActivityIntentInfo[size]; 10643 } 10644 10645 @Override 10646 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10647 if (!sUserManager.exists(userId)) return true; 10648 PackageParser.Package p = filter.activity.owner; 10649 if (p != null) { 10650 PackageSetting ps = (PackageSetting)p.mExtras; 10651 if (ps != null) { 10652 // System apps are never considered stopped for purposes of 10653 // filtering, because there may be no way for the user to 10654 // actually re-launch them. 10655 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10656 && ps.getStopped(userId); 10657 } 10658 } 10659 return false; 10660 } 10661 10662 @Override 10663 protected boolean isPackageForFilter(String packageName, 10664 PackageParser.ActivityIntentInfo info) { 10665 return packageName.equals(info.activity.owner.packageName); 10666 } 10667 10668 @Override 10669 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10670 int match, int userId) { 10671 if (!sUserManager.exists(userId)) return null; 10672 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10673 return null; 10674 } 10675 final PackageParser.Activity activity = info.activity; 10676 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10677 if (ps == null) { 10678 return null; 10679 } 10680 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10681 ps.readUserState(userId), userId); 10682 if (ai == null) { 10683 return null; 10684 } 10685 final ResolveInfo res = new ResolveInfo(); 10686 res.activityInfo = ai; 10687 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10688 res.filter = info; 10689 } 10690 if (info != null) { 10691 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10692 } 10693 res.priority = info.getPriority(); 10694 res.preferredOrder = activity.owner.mPreferredOrder; 10695 //System.out.println("Result: " + res.activityInfo.className + 10696 // " = " + res.priority); 10697 res.match = match; 10698 res.isDefault = info.hasDefault; 10699 res.labelRes = info.labelRes; 10700 res.nonLocalizedLabel = info.nonLocalizedLabel; 10701 if (userNeedsBadging(userId)) { 10702 res.noResourceId = true; 10703 } else { 10704 res.icon = info.icon; 10705 } 10706 res.iconResourceId = info.icon; 10707 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10708 return res; 10709 } 10710 10711 @Override 10712 protected void sortResults(List<ResolveInfo> results) { 10713 Collections.sort(results, mResolvePrioritySorter); 10714 } 10715 10716 @Override 10717 protected void dumpFilter(PrintWriter out, String prefix, 10718 PackageParser.ActivityIntentInfo filter) { 10719 out.print(prefix); out.print( 10720 Integer.toHexString(System.identityHashCode(filter.activity))); 10721 out.print(' '); 10722 filter.activity.printComponentShortName(out); 10723 out.print(" filter "); 10724 out.println(Integer.toHexString(System.identityHashCode(filter))); 10725 } 10726 10727 @Override 10728 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10729 return filter.activity; 10730 } 10731 10732 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10733 PackageParser.Activity activity = (PackageParser.Activity)label; 10734 out.print(prefix); out.print( 10735 Integer.toHexString(System.identityHashCode(activity))); 10736 out.print(' '); 10737 activity.printComponentShortName(out); 10738 if (count > 1) { 10739 out.print(" ("); out.print(count); out.print(" filters)"); 10740 } 10741 out.println(); 10742 } 10743 10744 // Keys are String (activity class name), values are Activity. 10745 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10746 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10747 private int mFlags; 10748 } 10749 10750 private final class ServiceIntentResolver 10751 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10752 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10753 boolean defaultOnly, int userId) { 10754 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10755 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10756 } 10757 10758 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10759 int userId) { 10760 if (!sUserManager.exists(userId)) return null; 10761 mFlags = flags; 10762 return super.queryIntent(intent, resolvedType, 10763 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10764 } 10765 10766 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10767 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10768 if (!sUserManager.exists(userId)) return null; 10769 if (packageServices == null) { 10770 return null; 10771 } 10772 mFlags = flags; 10773 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10774 final int N = packageServices.size(); 10775 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10776 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10777 10778 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10779 for (int i = 0; i < N; ++i) { 10780 intentFilters = packageServices.get(i).intents; 10781 if (intentFilters != null && intentFilters.size() > 0) { 10782 PackageParser.ServiceIntentInfo[] array = 10783 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10784 intentFilters.toArray(array); 10785 listCut.add(array); 10786 } 10787 } 10788 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10789 } 10790 10791 public final void addService(PackageParser.Service s) { 10792 mServices.put(s.getComponentName(), s); 10793 if (DEBUG_SHOW_INFO) { 10794 Log.v(TAG, " " 10795 + (s.info.nonLocalizedLabel != null 10796 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10797 Log.v(TAG, " Class=" + s.info.name); 10798 } 10799 final int NI = s.intents.size(); 10800 int j; 10801 for (j=0; j<NI; j++) { 10802 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10803 if (DEBUG_SHOW_INFO) { 10804 Log.v(TAG, " IntentFilter:"); 10805 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10806 } 10807 if (!intent.debugCheck()) { 10808 Log.w(TAG, "==> For Service " + s.info.name); 10809 } 10810 addFilter(intent); 10811 } 10812 } 10813 10814 public final void removeService(PackageParser.Service s) { 10815 mServices.remove(s.getComponentName()); 10816 if (DEBUG_SHOW_INFO) { 10817 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10818 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10819 Log.v(TAG, " Class=" + s.info.name); 10820 } 10821 final int NI = s.intents.size(); 10822 int j; 10823 for (j=0; j<NI; j++) { 10824 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10825 if (DEBUG_SHOW_INFO) { 10826 Log.v(TAG, " IntentFilter:"); 10827 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10828 } 10829 removeFilter(intent); 10830 } 10831 } 10832 10833 @Override 10834 protected boolean allowFilterResult( 10835 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10836 ServiceInfo filterSi = filter.service.info; 10837 for (int i=dest.size()-1; i>=0; i--) { 10838 ServiceInfo destAi = dest.get(i).serviceInfo; 10839 if (destAi.name == filterSi.name 10840 && destAi.packageName == filterSi.packageName) { 10841 return false; 10842 } 10843 } 10844 return true; 10845 } 10846 10847 @Override 10848 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10849 return new PackageParser.ServiceIntentInfo[size]; 10850 } 10851 10852 @Override 10853 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10854 if (!sUserManager.exists(userId)) return true; 10855 PackageParser.Package p = filter.service.owner; 10856 if (p != null) { 10857 PackageSetting ps = (PackageSetting)p.mExtras; 10858 if (ps != null) { 10859 // System apps are never considered stopped for purposes of 10860 // filtering, because there may be no way for the user to 10861 // actually re-launch them. 10862 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10863 && ps.getStopped(userId); 10864 } 10865 } 10866 return false; 10867 } 10868 10869 @Override 10870 protected boolean isPackageForFilter(String packageName, 10871 PackageParser.ServiceIntentInfo info) { 10872 return packageName.equals(info.service.owner.packageName); 10873 } 10874 10875 @Override 10876 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10877 int match, int userId) { 10878 if (!sUserManager.exists(userId)) return null; 10879 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10880 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10881 return null; 10882 } 10883 final PackageParser.Service service = info.service; 10884 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10885 if (ps == null) { 10886 return null; 10887 } 10888 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10889 ps.readUserState(userId), userId); 10890 if (si == null) { 10891 return null; 10892 } 10893 final ResolveInfo res = new ResolveInfo(); 10894 res.serviceInfo = si; 10895 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10896 res.filter = filter; 10897 } 10898 res.priority = info.getPriority(); 10899 res.preferredOrder = service.owner.mPreferredOrder; 10900 res.match = match; 10901 res.isDefault = info.hasDefault; 10902 res.labelRes = info.labelRes; 10903 res.nonLocalizedLabel = info.nonLocalizedLabel; 10904 res.icon = info.icon; 10905 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10906 return res; 10907 } 10908 10909 @Override 10910 protected void sortResults(List<ResolveInfo> results) { 10911 Collections.sort(results, mResolvePrioritySorter); 10912 } 10913 10914 @Override 10915 protected void dumpFilter(PrintWriter out, String prefix, 10916 PackageParser.ServiceIntentInfo filter) { 10917 out.print(prefix); out.print( 10918 Integer.toHexString(System.identityHashCode(filter.service))); 10919 out.print(' '); 10920 filter.service.printComponentShortName(out); 10921 out.print(" filter "); 10922 out.println(Integer.toHexString(System.identityHashCode(filter))); 10923 } 10924 10925 @Override 10926 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10927 return filter.service; 10928 } 10929 10930 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10931 PackageParser.Service service = (PackageParser.Service)label; 10932 out.print(prefix); out.print( 10933 Integer.toHexString(System.identityHashCode(service))); 10934 out.print(' '); 10935 service.printComponentShortName(out); 10936 if (count > 1) { 10937 out.print(" ("); out.print(count); out.print(" filters)"); 10938 } 10939 out.println(); 10940 } 10941 10942// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10943// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10944// final List<ResolveInfo> retList = Lists.newArrayList(); 10945// while (i.hasNext()) { 10946// final ResolveInfo resolveInfo = (ResolveInfo) i; 10947// if (isEnabledLP(resolveInfo.serviceInfo)) { 10948// retList.add(resolveInfo); 10949// } 10950// } 10951// return retList; 10952// } 10953 10954 // Keys are String (activity class name), values are Activity. 10955 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10956 = new ArrayMap<ComponentName, PackageParser.Service>(); 10957 private int mFlags; 10958 }; 10959 10960 private final class ProviderIntentResolver 10961 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10963 boolean defaultOnly, int userId) { 10964 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10965 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10966 } 10967 10968 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10969 int userId) { 10970 if (!sUserManager.exists(userId)) 10971 return null; 10972 mFlags = flags; 10973 return super.queryIntent(intent, resolvedType, 10974 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10975 } 10976 10977 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10978 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10979 if (!sUserManager.exists(userId)) 10980 return null; 10981 if (packageProviders == null) { 10982 return null; 10983 } 10984 mFlags = flags; 10985 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10986 final int N = packageProviders.size(); 10987 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10988 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10989 10990 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10991 for (int i = 0; i < N; ++i) { 10992 intentFilters = packageProviders.get(i).intents; 10993 if (intentFilters != null && intentFilters.size() > 0) { 10994 PackageParser.ProviderIntentInfo[] array = 10995 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10996 intentFilters.toArray(array); 10997 listCut.add(array); 10998 } 10999 } 11000 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11001 } 11002 11003 public final void addProvider(PackageParser.Provider p) { 11004 if (mProviders.containsKey(p.getComponentName())) { 11005 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11006 return; 11007 } 11008 11009 mProviders.put(p.getComponentName(), p); 11010 if (DEBUG_SHOW_INFO) { 11011 Log.v(TAG, " " 11012 + (p.info.nonLocalizedLabel != null 11013 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11014 Log.v(TAG, " Class=" + p.info.name); 11015 } 11016 final int NI = p.intents.size(); 11017 int j; 11018 for (j = 0; j < NI; j++) { 11019 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11020 if (DEBUG_SHOW_INFO) { 11021 Log.v(TAG, " IntentFilter:"); 11022 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11023 } 11024 if (!intent.debugCheck()) { 11025 Log.w(TAG, "==> For Provider " + p.info.name); 11026 } 11027 addFilter(intent); 11028 } 11029 } 11030 11031 public final void removeProvider(PackageParser.Provider p) { 11032 mProviders.remove(p.getComponentName()); 11033 if (DEBUG_SHOW_INFO) { 11034 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11035 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11036 Log.v(TAG, " Class=" + p.info.name); 11037 } 11038 final int NI = p.intents.size(); 11039 int j; 11040 for (j = 0; j < NI; j++) { 11041 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11042 if (DEBUG_SHOW_INFO) { 11043 Log.v(TAG, " IntentFilter:"); 11044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11045 } 11046 removeFilter(intent); 11047 } 11048 } 11049 11050 @Override 11051 protected boolean allowFilterResult( 11052 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11053 ProviderInfo filterPi = filter.provider.info; 11054 for (int i = dest.size() - 1; i >= 0; i--) { 11055 ProviderInfo destPi = dest.get(i).providerInfo; 11056 if (destPi.name == filterPi.name 11057 && destPi.packageName == filterPi.packageName) { 11058 return false; 11059 } 11060 } 11061 return true; 11062 } 11063 11064 @Override 11065 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11066 return new PackageParser.ProviderIntentInfo[size]; 11067 } 11068 11069 @Override 11070 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11071 if (!sUserManager.exists(userId)) 11072 return true; 11073 PackageParser.Package p = filter.provider.owner; 11074 if (p != null) { 11075 PackageSetting ps = (PackageSetting) p.mExtras; 11076 if (ps != null) { 11077 // System apps are never considered stopped for purposes of 11078 // filtering, because there may be no way for the user to 11079 // actually re-launch them. 11080 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11081 && ps.getStopped(userId); 11082 } 11083 } 11084 return false; 11085 } 11086 11087 @Override 11088 protected boolean isPackageForFilter(String packageName, 11089 PackageParser.ProviderIntentInfo info) { 11090 return packageName.equals(info.provider.owner.packageName); 11091 } 11092 11093 @Override 11094 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11095 int match, int userId) { 11096 if (!sUserManager.exists(userId)) 11097 return null; 11098 final PackageParser.ProviderIntentInfo info = filter; 11099 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11100 return null; 11101 } 11102 final PackageParser.Provider provider = info.provider; 11103 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11104 if (ps == null) { 11105 return null; 11106 } 11107 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11108 ps.readUserState(userId), userId); 11109 if (pi == null) { 11110 return null; 11111 } 11112 final ResolveInfo res = new ResolveInfo(); 11113 res.providerInfo = pi; 11114 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11115 res.filter = filter; 11116 } 11117 res.priority = info.getPriority(); 11118 res.preferredOrder = provider.owner.mPreferredOrder; 11119 res.match = match; 11120 res.isDefault = info.hasDefault; 11121 res.labelRes = info.labelRes; 11122 res.nonLocalizedLabel = info.nonLocalizedLabel; 11123 res.icon = info.icon; 11124 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11125 return res; 11126 } 11127 11128 @Override 11129 protected void sortResults(List<ResolveInfo> results) { 11130 Collections.sort(results, mResolvePrioritySorter); 11131 } 11132 11133 @Override 11134 protected void dumpFilter(PrintWriter out, String prefix, 11135 PackageParser.ProviderIntentInfo filter) { 11136 out.print(prefix); 11137 out.print( 11138 Integer.toHexString(System.identityHashCode(filter.provider))); 11139 out.print(' '); 11140 filter.provider.printComponentShortName(out); 11141 out.print(" filter "); 11142 out.println(Integer.toHexString(System.identityHashCode(filter))); 11143 } 11144 11145 @Override 11146 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11147 return filter.provider; 11148 } 11149 11150 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11151 PackageParser.Provider provider = (PackageParser.Provider)label; 11152 out.print(prefix); out.print( 11153 Integer.toHexString(System.identityHashCode(provider))); 11154 out.print(' '); 11155 provider.printComponentShortName(out); 11156 if (count > 1) { 11157 out.print(" ("); out.print(count); out.print(" filters)"); 11158 } 11159 out.println(); 11160 } 11161 11162 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11163 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11164 private int mFlags; 11165 } 11166 11167 private static final class EphemeralIntentResolver 11168 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11169 @Override 11170 protected EphemeralResolveIntentInfo[] newArray(int size) { 11171 return new EphemeralResolveIntentInfo[size]; 11172 } 11173 11174 @Override 11175 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11176 return true; 11177 } 11178 11179 @Override 11180 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11181 int userId) { 11182 if (!sUserManager.exists(userId)) { 11183 return null; 11184 } 11185 return info.getEphemeralResolveInfo(); 11186 } 11187 } 11188 11189 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11190 new Comparator<ResolveInfo>() { 11191 public int compare(ResolveInfo r1, ResolveInfo r2) { 11192 int v1 = r1.priority; 11193 int v2 = r2.priority; 11194 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11195 if (v1 != v2) { 11196 return (v1 > v2) ? -1 : 1; 11197 } 11198 v1 = r1.preferredOrder; 11199 v2 = r2.preferredOrder; 11200 if (v1 != v2) { 11201 return (v1 > v2) ? -1 : 1; 11202 } 11203 if (r1.isDefault != r2.isDefault) { 11204 return r1.isDefault ? -1 : 1; 11205 } 11206 v1 = r1.match; 11207 v2 = r2.match; 11208 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11209 if (v1 != v2) { 11210 return (v1 > v2) ? -1 : 1; 11211 } 11212 if (r1.system != r2.system) { 11213 return r1.system ? -1 : 1; 11214 } 11215 if (r1.activityInfo != null) { 11216 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11217 } 11218 if (r1.serviceInfo != null) { 11219 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11220 } 11221 if (r1.providerInfo != null) { 11222 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11223 } 11224 return 0; 11225 } 11226 }; 11227 11228 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11229 new Comparator<ProviderInfo>() { 11230 public int compare(ProviderInfo p1, ProviderInfo p2) { 11231 final int v1 = p1.initOrder; 11232 final int v2 = p2.initOrder; 11233 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11234 } 11235 }; 11236 11237 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11238 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11239 final int[] userIds) { 11240 mHandler.post(new Runnable() { 11241 @Override 11242 public void run() { 11243 try { 11244 final IActivityManager am = ActivityManagerNative.getDefault(); 11245 if (am == null) return; 11246 final int[] resolvedUserIds; 11247 if (userIds == null) { 11248 resolvedUserIds = am.getRunningUserIds(); 11249 } else { 11250 resolvedUserIds = userIds; 11251 } 11252 for (int id : resolvedUserIds) { 11253 final Intent intent = new Intent(action, 11254 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11255 if (extras != null) { 11256 intent.putExtras(extras); 11257 } 11258 if (targetPkg != null) { 11259 intent.setPackage(targetPkg); 11260 } 11261 // Modify the UID when posting to other users 11262 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11263 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11264 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11265 intent.putExtra(Intent.EXTRA_UID, uid); 11266 } 11267 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11268 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11269 if (DEBUG_BROADCASTS) { 11270 RuntimeException here = new RuntimeException("here"); 11271 here.fillInStackTrace(); 11272 Slog.d(TAG, "Sending to user " + id + ": " 11273 + intent.toShortString(false, true, false, false) 11274 + " " + intent.getExtras(), here); 11275 } 11276 am.broadcastIntent(null, intent, null, finishedReceiver, 11277 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11278 null, finishedReceiver != null, false, id); 11279 } 11280 } catch (RemoteException ex) { 11281 } 11282 } 11283 }); 11284 } 11285 11286 /** 11287 * Check if the external storage media is available. This is true if there 11288 * is a mounted external storage medium or if the external storage is 11289 * emulated. 11290 */ 11291 private boolean isExternalMediaAvailable() { 11292 return mMediaMounted || Environment.isExternalStorageEmulated(); 11293 } 11294 11295 @Override 11296 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11297 // writer 11298 synchronized (mPackages) { 11299 if (!isExternalMediaAvailable()) { 11300 // If the external storage is no longer mounted at this point, 11301 // the caller may not have been able to delete all of this 11302 // packages files and can not delete any more. Bail. 11303 return null; 11304 } 11305 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11306 if (lastPackage != null) { 11307 pkgs.remove(lastPackage); 11308 } 11309 if (pkgs.size() > 0) { 11310 return pkgs.get(0); 11311 } 11312 } 11313 return null; 11314 } 11315 11316 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11317 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11318 userId, andCode ? 1 : 0, packageName); 11319 if (mSystemReady) { 11320 msg.sendToTarget(); 11321 } else { 11322 if (mPostSystemReadyMessages == null) { 11323 mPostSystemReadyMessages = new ArrayList<>(); 11324 } 11325 mPostSystemReadyMessages.add(msg); 11326 } 11327 } 11328 11329 void startCleaningPackages() { 11330 // reader 11331 if (!isExternalMediaAvailable()) { 11332 return; 11333 } 11334 synchronized (mPackages) { 11335 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11336 return; 11337 } 11338 } 11339 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11340 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11341 IActivityManager am = ActivityManagerNative.getDefault(); 11342 if (am != null) { 11343 try { 11344 am.startService(null, intent, null, mContext.getOpPackageName(), 11345 UserHandle.USER_SYSTEM); 11346 } catch (RemoteException e) { 11347 } 11348 } 11349 } 11350 11351 @Override 11352 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11353 int installFlags, String installerPackageName, int userId) { 11354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11355 11356 final int callingUid = Binder.getCallingUid(); 11357 enforceCrossUserPermission(callingUid, userId, 11358 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11359 11360 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11361 try { 11362 if (observer != null) { 11363 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11364 } 11365 } catch (RemoteException re) { 11366 } 11367 return; 11368 } 11369 11370 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11371 installFlags |= PackageManager.INSTALL_FROM_ADB; 11372 11373 } else { 11374 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11375 // about installerPackageName. 11376 11377 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11378 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11379 } 11380 11381 UserHandle user; 11382 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11383 user = UserHandle.ALL; 11384 } else { 11385 user = new UserHandle(userId); 11386 } 11387 11388 // Only system components can circumvent runtime permissions when installing. 11389 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11390 && mContext.checkCallingOrSelfPermission(Manifest.permission 11391 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11392 throw new SecurityException("You need the " 11393 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11394 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11395 } 11396 11397 final File originFile = new File(originPath); 11398 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11399 11400 final Message msg = mHandler.obtainMessage(INIT_COPY); 11401 final VerificationInfo verificationInfo = new VerificationInfo( 11402 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11403 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11404 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11405 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11406 null /*certificates*/); 11407 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11408 msg.obj = params; 11409 11410 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11411 System.identityHashCode(msg.obj)); 11412 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11413 System.identityHashCode(msg.obj)); 11414 11415 mHandler.sendMessage(msg); 11416 } 11417 11418 void installStage(String packageName, File stagedDir, String stagedCid, 11419 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11420 String installerPackageName, int installerUid, UserHandle user, 11421 Certificate[][] certificates) { 11422 if (DEBUG_EPHEMERAL) { 11423 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11424 Slog.d(TAG, "Ephemeral install of " + packageName); 11425 } 11426 } 11427 final VerificationInfo verificationInfo = new VerificationInfo( 11428 sessionParams.originatingUri, sessionParams.referrerUri, 11429 sessionParams.originatingUid, installerUid); 11430 11431 final OriginInfo origin; 11432 if (stagedDir != null) { 11433 origin = OriginInfo.fromStagedFile(stagedDir); 11434 } else { 11435 origin = OriginInfo.fromStagedContainer(stagedCid); 11436 } 11437 11438 final Message msg = mHandler.obtainMessage(INIT_COPY); 11439 final InstallParams params = new InstallParams(origin, null, observer, 11440 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11441 verificationInfo, user, sessionParams.abiOverride, 11442 sessionParams.grantedRuntimePermissions, certificates); 11443 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11444 msg.obj = params; 11445 11446 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11447 System.identityHashCode(msg.obj)); 11448 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11449 System.identityHashCode(msg.obj)); 11450 11451 mHandler.sendMessage(msg); 11452 } 11453 11454 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11455 int userId) { 11456 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11457 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11458 } 11459 11460 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11461 int appId, int userId) { 11462 Bundle extras = new Bundle(1); 11463 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11464 11465 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11466 packageName, extras, 0, null, null, new int[] {userId}); 11467 try { 11468 IActivityManager am = ActivityManagerNative.getDefault(); 11469 if (isSystem && am.isUserRunning(userId, 0)) { 11470 // The just-installed/enabled app is bundled on the system, so presumed 11471 // to be able to run automatically without needing an explicit launch. 11472 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11473 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11474 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11475 .setPackage(packageName); 11476 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11477 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11478 } 11479 } catch (RemoteException e) { 11480 // shouldn't happen 11481 Slog.w(TAG, "Unable to bootstrap installed package", e); 11482 } 11483 } 11484 11485 @Override 11486 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11487 int userId) { 11488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11489 PackageSetting pkgSetting; 11490 final int uid = Binder.getCallingUid(); 11491 enforceCrossUserPermission(uid, userId, 11492 true /* requireFullPermission */, true /* checkShell */, 11493 "setApplicationHiddenSetting for user " + userId); 11494 11495 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11496 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11497 return false; 11498 } 11499 11500 long callingId = Binder.clearCallingIdentity(); 11501 try { 11502 boolean sendAdded = false; 11503 boolean sendRemoved = false; 11504 // writer 11505 synchronized (mPackages) { 11506 pkgSetting = mSettings.mPackages.get(packageName); 11507 if (pkgSetting == null) { 11508 return false; 11509 } 11510 // Do not allow "android" is being disabled 11511 if ("android".equals(packageName)) { 11512 Slog.w(TAG, "Cannot hide package: android"); 11513 return false; 11514 } 11515 // Only allow protected packages to hide themselves. 11516 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11517 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11518 Slog.w(TAG, "Not hiding protected package: " + packageName); 11519 return false; 11520 } 11521 11522 if (pkgSetting.getHidden(userId) != hidden) { 11523 pkgSetting.setHidden(hidden, userId); 11524 mSettings.writePackageRestrictionsLPr(userId); 11525 if (hidden) { 11526 sendRemoved = true; 11527 } else { 11528 sendAdded = true; 11529 } 11530 } 11531 } 11532 if (sendAdded) { 11533 sendPackageAddedForUser(packageName, pkgSetting, userId); 11534 return true; 11535 } 11536 if (sendRemoved) { 11537 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11538 "hiding pkg"); 11539 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11540 return true; 11541 } 11542 } finally { 11543 Binder.restoreCallingIdentity(callingId); 11544 } 11545 return false; 11546 } 11547 11548 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11549 int userId) { 11550 final PackageRemovedInfo info = new PackageRemovedInfo(); 11551 info.removedPackage = packageName; 11552 info.removedUsers = new int[] {userId}; 11553 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11554 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11555 } 11556 11557 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11558 if (pkgList.length > 0) { 11559 Bundle extras = new Bundle(1); 11560 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11561 11562 sendPackageBroadcast( 11563 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11564 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11565 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11566 new int[] {userId}); 11567 } 11568 } 11569 11570 /** 11571 * Returns true if application is not found or there was an error. Otherwise it returns 11572 * the hidden state of the package for the given user. 11573 */ 11574 @Override 11575 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11576 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11577 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11578 true /* requireFullPermission */, false /* checkShell */, 11579 "getApplicationHidden for user " + userId); 11580 PackageSetting pkgSetting; 11581 long callingId = Binder.clearCallingIdentity(); 11582 try { 11583 // writer 11584 synchronized (mPackages) { 11585 pkgSetting = mSettings.mPackages.get(packageName); 11586 if (pkgSetting == null) { 11587 return true; 11588 } 11589 return pkgSetting.getHidden(userId); 11590 } 11591 } finally { 11592 Binder.restoreCallingIdentity(callingId); 11593 } 11594 } 11595 11596 /** 11597 * @hide 11598 */ 11599 @Override 11600 public int installExistingPackageAsUser(String packageName, int userId) { 11601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11602 null); 11603 PackageSetting pkgSetting; 11604 final int uid = Binder.getCallingUid(); 11605 enforceCrossUserPermission(uid, userId, 11606 true /* requireFullPermission */, true /* checkShell */, 11607 "installExistingPackage for user " + userId); 11608 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11609 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11610 } 11611 11612 long callingId = Binder.clearCallingIdentity(); 11613 try { 11614 boolean installed = false; 11615 11616 // writer 11617 synchronized (mPackages) { 11618 pkgSetting = mSettings.mPackages.get(packageName); 11619 if (pkgSetting == null) { 11620 return PackageManager.INSTALL_FAILED_INVALID_URI; 11621 } 11622 if (!pkgSetting.getInstalled(userId)) { 11623 pkgSetting.setInstalled(true, userId); 11624 pkgSetting.setHidden(false, userId); 11625 mSettings.writePackageRestrictionsLPr(userId); 11626 installed = true; 11627 } 11628 } 11629 11630 if (installed) { 11631 if (pkgSetting.pkg != null) { 11632 synchronized (mInstallLock) { 11633 // We don't need to freeze for a brand new install 11634 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11635 } 11636 } 11637 sendPackageAddedForUser(packageName, pkgSetting, userId); 11638 } 11639 } finally { 11640 Binder.restoreCallingIdentity(callingId); 11641 } 11642 11643 return PackageManager.INSTALL_SUCCEEDED; 11644 } 11645 11646 boolean isUserRestricted(int userId, String restrictionKey) { 11647 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11648 if (restrictions.getBoolean(restrictionKey, false)) { 11649 Log.w(TAG, "User is restricted: " + restrictionKey); 11650 return true; 11651 } 11652 return false; 11653 } 11654 11655 @Override 11656 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11657 int userId) { 11658 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11659 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11660 true /* requireFullPermission */, true /* checkShell */, 11661 "setPackagesSuspended for user " + userId); 11662 11663 if (ArrayUtils.isEmpty(packageNames)) { 11664 return packageNames; 11665 } 11666 11667 // List of package names for whom the suspended state has changed. 11668 List<String> changedPackages = new ArrayList<>(packageNames.length); 11669 // List of package names for whom the suspended state is not set as requested in this 11670 // method. 11671 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11672 long callingId = Binder.clearCallingIdentity(); 11673 try { 11674 for (int i = 0; i < packageNames.length; i++) { 11675 String packageName = packageNames[i]; 11676 boolean changed = false; 11677 final int appId; 11678 synchronized (mPackages) { 11679 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11680 if (pkgSetting == null) { 11681 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11682 + "\". Skipping suspending/un-suspending."); 11683 unactionedPackages.add(packageName); 11684 continue; 11685 } 11686 appId = pkgSetting.appId; 11687 if (pkgSetting.getSuspended(userId) != suspended) { 11688 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11689 unactionedPackages.add(packageName); 11690 continue; 11691 } 11692 pkgSetting.setSuspended(suspended, userId); 11693 mSettings.writePackageRestrictionsLPr(userId); 11694 changed = true; 11695 changedPackages.add(packageName); 11696 } 11697 } 11698 11699 if (changed && suspended) { 11700 killApplication(packageName, UserHandle.getUid(userId, appId), 11701 "suspending package"); 11702 } 11703 } 11704 } finally { 11705 Binder.restoreCallingIdentity(callingId); 11706 } 11707 11708 if (!changedPackages.isEmpty()) { 11709 sendPackagesSuspendedForUser(changedPackages.toArray( 11710 new String[changedPackages.size()]), userId, suspended); 11711 } 11712 11713 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11714 } 11715 11716 @Override 11717 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11718 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11719 true /* requireFullPermission */, false /* checkShell */, 11720 "isPackageSuspendedForUser for user " + userId); 11721 synchronized (mPackages) { 11722 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11723 if (pkgSetting == null) { 11724 throw new IllegalArgumentException("Unknown target package: " + packageName); 11725 } 11726 return pkgSetting.getSuspended(userId); 11727 } 11728 } 11729 11730 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11731 if (isPackageDeviceAdmin(packageName, userId)) { 11732 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11733 + "\": has an active device admin"); 11734 return false; 11735 } 11736 11737 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11738 if (packageName.equals(activeLauncherPackageName)) { 11739 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11740 + "\": contains the active launcher"); 11741 return false; 11742 } 11743 11744 if (packageName.equals(mRequiredInstallerPackage)) { 11745 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11746 + "\": required for package installation"); 11747 return false; 11748 } 11749 11750 if (packageName.equals(mRequiredVerifierPackage)) { 11751 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11752 + "\": required for package verification"); 11753 return false; 11754 } 11755 11756 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11757 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11758 + "\": is the default dialer"); 11759 return false; 11760 } 11761 11762 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11763 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11764 + "\": protected package"); 11765 return false; 11766 } 11767 11768 return true; 11769 } 11770 11771 private String getActiveLauncherPackageName(int userId) { 11772 Intent intent = new Intent(Intent.ACTION_MAIN); 11773 intent.addCategory(Intent.CATEGORY_HOME); 11774 ResolveInfo resolveInfo = resolveIntent( 11775 intent, 11776 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11777 PackageManager.MATCH_DEFAULT_ONLY, 11778 userId); 11779 11780 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11781 } 11782 11783 private String getDefaultDialerPackageName(int userId) { 11784 synchronized (mPackages) { 11785 return mSettings.getDefaultDialerPackageNameLPw(userId); 11786 } 11787 } 11788 11789 @Override 11790 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11791 mContext.enforceCallingOrSelfPermission( 11792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11793 "Only package verification agents can verify applications"); 11794 11795 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11796 final PackageVerificationResponse response = new PackageVerificationResponse( 11797 verificationCode, Binder.getCallingUid()); 11798 msg.arg1 = id; 11799 msg.obj = response; 11800 mHandler.sendMessage(msg); 11801 } 11802 11803 @Override 11804 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11805 long millisecondsToDelay) { 11806 mContext.enforceCallingOrSelfPermission( 11807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11808 "Only package verification agents can extend verification timeouts"); 11809 11810 final PackageVerificationState state = mPendingVerification.get(id); 11811 final PackageVerificationResponse response = new PackageVerificationResponse( 11812 verificationCodeAtTimeout, Binder.getCallingUid()); 11813 11814 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11815 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11816 } 11817 if (millisecondsToDelay < 0) { 11818 millisecondsToDelay = 0; 11819 } 11820 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11821 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11822 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11823 } 11824 11825 if ((state != null) && !state.timeoutExtended()) { 11826 state.extendTimeout(); 11827 11828 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11829 msg.arg1 = id; 11830 msg.obj = response; 11831 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11832 } 11833 } 11834 11835 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11836 int verificationCode, UserHandle user) { 11837 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11838 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11839 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11840 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11841 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11842 11843 mContext.sendBroadcastAsUser(intent, user, 11844 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11845 } 11846 11847 private ComponentName matchComponentForVerifier(String packageName, 11848 List<ResolveInfo> receivers) { 11849 ActivityInfo targetReceiver = null; 11850 11851 final int NR = receivers.size(); 11852 for (int i = 0; i < NR; i++) { 11853 final ResolveInfo info = receivers.get(i); 11854 if (info.activityInfo == null) { 11855 continue; 11856 } 11857 11858 if (packageName.equals(info.activityInfo.packageName)) { 11859 targetReceiver = info.activityInfo; 11860 break; 11861 } 11862 } 11863 11864 if (targetReceiver == null) { 11865 return null; 11866 } 11867 11868 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11869 } 11870 11871 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11872 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11873 if (pkgInfo.verifiers.length == 0) { 11874 return null; 11875 } 11876 11877 final int N = pkgInfo.verifiers.length; 11878 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11879 for (int i = 0; i < N; i++) { 11880 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11881 11882 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11883 receivers); 11884 if (comp == null) { 11885 continue; 11886 } 11887 11888 final int verifierUid = getUidForVerifier(verifierInfo); 11889 if (verifierUid == -1) { 11890 continue; 11891 } 11892 11893 if (DEBUG_VERIFY) { 11894 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11895 + " with the correct signature"); 11896 } 11897 sufficientVerifiers.add(comp); 11898 verificationState.addSufficientVerifier(verifierUid); 11899 } 11900 11901 return sufficientVerifiers; 11902 } 11903 11904 private int getUidForVerifier(VerifierInfo verifierInfo) { 11905 synchronized (mPackages) { 11906 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11907 if (pkg == null) { 11908 return -1; 11909 } else if (pkg.mSignatures.length != 1) { 11910 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11911 + " has more than one signature; ignoring"); 11912 return -1; 11913 } 11914 11915 /* 11916 * If the public key of the package's signature does not match 11917 * our expected public key, then this is a different package and 11918 * we should skip. 11919 */ 11920 11921 final byte[] expectedPublicKey; 11922 try { 11923 final Signature verifierSig = pkg.mSignatures[0]; 11924 final PublicKey publicKey = verifierSig.getPublicKey(); 11925 expectedPublicKey = publicKey.getEncoded(); 11926 } catch (CertificateException e) { 11927 return -1; 11928 } 11929 11930 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11931 11932 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11933 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11934 + " does not have the expected public key; ignoring"); 11935 return -1; 11936 } 11937 11938 return pkg.applicationInfo.uid; 11939 } 11940 } 11941 11942 @Override 11943 public void finishPackageInstall(int token, boolean didLaunch) { 11944 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11945 11946 if (DEBUG_INSTALL) { 11947 Slog.v(TAG, "BM finishing package install for " + token); 11948 } 11949 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11950 11951 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11952 mHandler.sendMessage(msg); 11953 } 11954 11955 /** 11956 * Get the verification agent timeout. 11957 * 11958 * @return verification timeout in milliseconds 11959 */ 11960 private long getVerificationTimeout() { 11961 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11962 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11963 DEFAULT_VERIFICATION_TIMEOUT); 11964 } 11965 11966 /** 11967 * Get the default verification agent response code. 11968 * 11969 * @return default verification response code 11970 */ 11971 private int getDefaultVerificationResponse() { 11972 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11973 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11974 DEFAULT_VERIFICATION_RESPONSE); 11975 } 11976 11977 /** 11978 * Check whether or not package verification has been enabled. 11979 * 11980 * @return true if verification should be performed 11981 */ 11982 private boolean isVerificationEnabled(int userId, int installFlags) { 11983 if (!DEFAULT_VERIFY_ENABLE) { 11984 return false; 11985 } 11986 // Ephemeral apps don't get the full verification treatment 11987 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11988 if (DEBUG_EPHEMERAL) { 11989 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11990 } 11991 return false; 11992 } 11993 11994 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11995 11996 // Check if installing from ADB 11997 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11998 // Do not run verification in a test harness environment 11999 if (ActivityManager.isRunningInTestHarness()) { 12000 return false; 12001 } 12002 if (ensureVerifyAppsEnabled) { 12003 return true; 12004 } 12005 // Check if the developer does not want package verification for ADB installs 12006 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12007 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12008 return false; 12009 } 12010 } 12011 12012 if (ensureVerifyAppsEnabled) { 12013 return true; 12014 } 12015 12016 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12017 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12018 } 12019 12020 @Override 12021 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12022 throws RemoteException { 12023 mContext.enforceCallingOrSelfPermission( 12024 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12025 "Only intentfilter verification agents can verify applications"); 12026 12027 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12028 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12029 Binder.getCallingUid(), verificationCode, failedDomains); 12030 msg.arg1 = id; 12031 msg.obj = response; 12032 mHandler.sendMessage(msg); 12033 } 12034 12035 @Override 12036 public int getIntentVerificationStatus(String packageName, int userId) { 12037 synchronized (mPackages) { 12038 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12039 } 12040 } 12041 12042 @Override 12043 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12044 mContext.enforceCallingOrSelfPermission( 12045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12046 12047 boolean result = false; 12048 synchronized (mPackages) { 12049 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12050 } 12051 if (result) { 12052 scheduleWritePackageRestrictionsLocked(userId); 12053 } 12054 return result; 12055 } 12056 12057 @Override 12058 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12059 String packageName) { 12060 synchronized (mPackages) { 12061 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12062 } 12063 } 12064 12065 @Override 12066 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12067 if (TextUtils.isEmpty(packageName)) { 12068 return ParceledListSlice.emptyList(); 12069 } 12070 synchronized (mPackages) { 12071 PackageParser.Package pkg = mPackages.get(packageName); 12072 if (pkg == null || pkg.activities == null) { 12073 return ParceledListSlice.emptyList(); 12074 } 12075 final int count = pkg.activities.size(); 12076 ArrayList<IntentFilter> result = new ArrayList<>(); 12077 for (int n=0; n<count; n++) { 12078 PackageParser.Activity activity = pkg.activities.get(n); 12079 if (activity.intents != null && activity.intents.size() > 0) { 12080 result.addAll(activity.intents); 12081 } 12082 } 12083 return new ParceledListSlice<>(result); 12084 } 12085 } 12086 12087 @Override 12088 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12089 mContext.enforceCallingOrSelfPermission( 12090 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12091 12092 synchronized (mPackages) { 12093 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12094 if (packageName != null) { 12095 result |= updateIntentVerificationStatus(packageName, 12096 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12097 userId); 12098 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12099 packageName, userId); 12100 } 12101 return result; 12102 } 12103 } 12104 12105 @Override 12106 public String getDefaultBrowserPackageName(int userId) { 12107 synchronized (mPackages) { 12108 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12109 } 12110 } 12111 12112 /** 12113 * Get the "allow unknown sources" setting. 12114 * 12115 * @return the current "allow unknown sources" setting 12116 */ 12117 private int getUnknownSourcesSettings() { 12118 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12119 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12120 -1); 12121 } 12122 12123 @Override 12124 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12125 final int uid = Binder.getCallingUid(); 12126 // writer 12127 synchronized (mPackages) { 12128 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12129 if (targetPackageSetting == null) { 12130 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12131 } 12132 12133 PackageSetting installerPackageSetting; 12134 if (installerPackageName != null) { 12135 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12136 if (installerPackageSetting == null) { 12137 throw new IllegalArgumentException("Unknown installer package: " 12138 + installerPackageName); 12139 } 12140 } else { 12141 installerPackageSetting = null; 12142 } 12143 12144 Signature[] callerSignature; 12145 Object obj = mSettings.getUserIdLPr(uid); 12146 if (obj != null) { 12147 if (obj instanceof SharedUserSetting) { 12148 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12149 } else if (obj instanceof PackageSetting) { 12150 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12151 } else { 12152 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12153 } 12154 } else { 12155 throw new SecurityException("Unknown calling UID: " + uid); 12156 } 12157 12158 // Verify: can't set installerPackageName to a package that is 12159 // not signed with the same cert as the caller. 12160 if (installerPackageSetting != null) { 12161 if (compareSignatures(callerSignature, 12162 installerPackageSetting.signatures.mSignatures) 12163 != PackageManager.SIGNATURE_MATCH) { 12164 throw new SecurityException( 12165 "Caller does not have same cert as new installer package " 12166 + installerPackageName); 12167 } 12168 } 12169 12170 // Verify: if target already has an installer package, it must 12171 // be signed with the same cert as the caller. 12172 if (targetPackageSetting.installerPackageName != null) { 12173 PackageSetting setting = mSettings.mPackages.get( 12174 targetPackageSetting.installerPackageName); 12175 // If the currently set package isn't valid, then it's always 12176 // okay to change it. 12177 if (setting != null) { 12178 if (compareSignatures(callerSignature, 12179 setting.signatures.mSignatures) 12180 != PackageManager.SIGNATURE_MATCH) { 12181 throw new SecurityException( 12182 "Caller does not have same cert as old installer package " 12183 + targetPackageSetting.installerPackageName); 12184 } 12185 } 12186 } 12187 12188 // Okay! 12189 targetPackageSetting.installerPackageName = installerPackageName; 12190 if (installerPackageName != null) { 12191 mSettings.mInstallerPackages.add(installerPackageName); 12192 } 12193 scheduleWriteSettingsLocked(); 12194 } 12195 } 12196 12197 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12198 // Queue up an async operation since the package installation may take a little while. 12199 mHandler.post(new Runnable() { 12200 public void run() { 12201 mHandler.removeCallbacks(this); 12202 // Result object to be returned 12203 PackageInstalledInfo res = new PackageInstalledInfo(); 12204 res.setReturnCode(currentStatus); 12205 res.uid = -1; 12206 res.pkg = null; 12207 res.removedInfo = null; 12208 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12209 args.doPreInstall(res.returnCode); 12210 synchronized (mInstallLock) { 12211 installPackageTracedLI(args, res); 12212 } 12213 args.doPostInstall(res.returnCode, res.uid); 12214 } 12215 12216 // A restore should be performed at this point if (a) the install 12217 // succeeded, (b) the operation is not an update, and (c) the new 12218 // package has not opted out of backup participation. 12219 final boolean update = res.removedInfo != null 12220 && res.removedInfo.removedPackage != null; 12221 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12222 boolean doRestore = !update 12223 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12224 12225 // Set up the post-install work request bookkeeping. This will be used 12226 // and cleaned up by the post-install event handling regardless of whether 12227 // there's a restore pass performed. Token values are >= 1. 12228 int token; 12229 if (mNextInstallToken < 0) mNextInstallToken = 1; 12230 token = mNextInstallToken++; 12231 12232 PostInstallData data = new PostInstallData(args, res); 12233 mRunningInstalls.put(token, data); 12234 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12235 12236 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12237 // Pass responsibility to the Backup Manager. It will perform a 12238 // restore if appropriate, then pass responsibility back to the 12239 // Package Manager to run the post-install observer callbacks 12240 // and broadcasts. 12241 IBackupManager bm = IBackupManager.Stub.asInterface( 12242 ServiceManager.getService(Context.BACKUP_SERVICE)); 12243 if (bm != null) { 12244 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12245 + " to BM for possible restore"); 12246 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12247 try { 12248 // TODO: http://b/22388012 12249 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12250 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12251 } else { 12252 doRestore = false; 12253 } 12254 } catch (RemoteException e) { 12255 // can't happen; the backup manager is local 12256 } catch (Exception e) { 12257 Slog.e(TAG, "Exception trying to enqueue restore", e); 12258 doRestore = false; 12259 } 12260 } else { 12261 Slog.e(TAG, "Backup Manager not found!"); 12262 doRestore = false; 12263 } 12264 } 12265 12266 if (!doRestore) { 12267 // No restore possible, or the Backup Manager was mysteriously not 12268 // available -- just fire the post-install work request directly. 12269 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12270 12271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12272 12273 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12274 mHandler.sendMessage(msg); 12275 } 12276 } 12277 }); 12278 } 12279 12280 /** 12281 * Callback from PackageSettings whenever an app is first transitioned out of the 12282 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12283 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12284 * here whether the app is the target of an ongoing install, and only send the 12285 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12286 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12287 * handling. 12288 */ 12289 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12290 // Serialize this with the rest of the install-process message chain. In the 12291 // restore-at-install case, this Runnable will necessarily run before the 12292 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12293 // are coherent. In the non-restore case, the app has already completed install 12294 // and been launched through some other means, so it is not in a problematic 12295 // state for observers to see the FIRST_LAUNCH signal. 12296 mHandler.post(new Runnable() { 12297 @Override 12298 public void run() { 12299 for (int i = 0; i < mRunningInstalls.size(); i++) { 12300 final PostInstallData data = mRunningInstalls.valueAt(i); 12301 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12302 continue; 12303 } 12304 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12305 // right package; but is it for the right user? 12306 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12307 if (userId == data.res.newUsers[uIndex]) { 12308 if (DEBUG_BACKUP) { 12309 Slog.i(TAG, "Package " + pkgName 12310 + " being restored so deferring FIRST_LAUNCH"); 12311 } 12312 return; 12313 } 12314 } 12315 } 12316 } 12317 // didn't find it, so not being restored 12318 if (DEBUG_BACKUP) { 12319 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12320 } 12321 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12322 } 12323 }); 12324 } 12325 12326 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12327 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12328 installerPkg, null, userIds); 12329 } 12330 12331 private abstract class HandlerParams { 12332 private static final int MAX_RETRIES = 4; 12333 12334 /** 12335 * Number of times startCopy() has been attempted and had a non-fatal 12336 * error. 12337 */ 12338 private int mRetries = 0; 12339 12340 /** User handle for the user requesting the information or installation. */ 12341 private final UserHandle mUser; 12342 String traceMethod; 12343 int traceCookie; 12344 12345 HandlerParams(UserHandle user) { 12346 mUser = user; 12347 } 12348 12349 UserHandle getUser() { 12350 return mUser; 12351 } 12352 12353 HandlerParams setTraceMethod(String traceMethod) { 12354 this.traceMethod = traceMethod; 12355 return this; 12356 } 12357 12358 HandlerParams setTraceCookie(int traceCookie) { 12359 this.traceCookie = traceCookie; 12360 return this; 12361 } 12362 12363 final boolean startCopy() { 12364 boolean res; 12365 try { 12366 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12367 12368 if (++mRetries > MAX_RETRIES) { 12369 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12370 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12371 handleServiceError(); 12372 return false; 12373 } else { 12374 handleStartCopy(); 12375 res = true; 12376 } 12377 } catch (RemoteException e) { 12378 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12379 mHandler.sendEmptyMessage(MCS_RECONNECT); 12380 res = false; 12381 } 12382 handleReturnCode(); 12383 return res; 12384 } 12385 12386 final void serviceError() { 12387 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12388 handleServiceError(); 12389 handleReturnCode(); 12390 } 12391 12392 abstract void handleStartCopy() throws RemoteException; 12393 abstract void handleServiceError(); 12394 abstract void handleReturnCode(); 12395 } 12396 12397 class MeasureParams extends HandlerParams { 12398 private final PackageStats mStats; 12399 private boolean mSuccess; 12400 12401 private final IPackageStatsObserver mObserver; 12402 12403 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12404 super(new UserHandle(stats.userHandle)); 12405 mObserver = observer; 12406 mStats = stats; 12407 } 12408 12409 @Override 12410 public String toString() { 12411 return "MeasureParams{" 12412 + Integer.toHexString(System.identityHashCode(this)) 12413 + " " + mStats.packageName + "}"; 12414 } 12415 12416 @Override 12417 void handleStartCopy() throws RemoteException { 12418 synchronized (mInstallLock) { 12419 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12420 } 12421 12422 if (mSuccess) { 12423 boolean mounted = false; 12424 try { 12425 final String status = Environment.getExternalStorageState(); 12426 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12427 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12428 } catch (Exception e) { 12429 } 12430 12431 if (mounted) { 12432 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12433 12434 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12435 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12436 12437 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12438 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12439 12440 // Always subtract cache size, since it's a subdirectory 12441 mStats.externalDataSize -= mStats.externalCacheSize; 12442 12443 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12444 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12445 12446 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12447 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12448 } 12449 } 12450 } 12451 12452 @Override 12453 void handleReturnCode() { 12454 if (mObserver != null) { 12455 try { 12456 mObserver.onGetStatsCompleted(mStats, mSuccess); 12457 } catch (RemoteException e) { 12458 Slog.i(TAG, "Observer no longer exists."); 12459 } 12460 } 12461 } 12462 12463 @Override 12464 void handleServiceError() { 12465 Slog.e(TAG, "Could not measure application " + mStats.packageName 12466 + " external storage"); 12467 } 12468 } 12469 12470 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12471 throws RemoteException { 12472 long result = 0; 12473 for (File path : paths) { 12474 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12475 } 12476 return result; 12477 } 12478 12479 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12480 for (File path : paths) { 12481 try { 12482 mcs.clearDirectory(path.getAbsolutePath()); 12483 } catch (RemoteException e) { 12484 } 12485 } 12486 } 12487 12488 static class OriginInfo { 12489 /** 12490 * Location where install is coming from, before it has been 12491 * copied/renamed into place. This could be a single monolithic APK 12492 * file, or a cluster directory. This location may be untrusted. 12493 */ 12494 final File file; 12495 final String cid; 12496 12497 /** 12498 * Flag indicating that {@link #file} or {@link #cid} has already been 12499 * staged, meaning downstream users don't need to defensively copy the 12500 * contents. 12501 */ 12502 final boolean staged; 12503 12504 /** 12505 * Flag indicating that {@link #file} or {@link #cid} is an already 12506 * installed app that is being moved. 12507 */ 12508 final boolean existing; 12509 12510 final String resolvedPath; 12511 final File resolvedFile; 12512 12513 static OriginInfo fromNothing() { 12514 return new OriginInfo(null, null, false, false); 12515 } 12516 12517 static OriginInfo fromUntrustedFile(File file) { 12518 return new OriginInfo(file, null, false, false); 12519 } 12520 12521 static OriginInfo fromExistingFile(File file) { 12522 return new OriginInfo(file, null, false, true); 12523 } 12524 12525 static OriginInfo fromStagedFile(File file) { 12526 return new OriginInfo(file, null, true, false); 12527 } 12528 12529 static OriginInfo fromStagedContainer(String cid) { 12530 return new OriginInfo(null, cid, true, false); 12531 } 12532 12533 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12534 this.file = file; 12535 this.cid = cid; 12536 this.staged = staged; 12537 this.existing = existing; 12538 12539 if (cid != null) { 12540 resolvedPath = PackageHelper.getSdDir(cid); 12541 resolvedFile = new File(resolvedPath); 12542 } else if (file != null) { 12543 resolvedPath = file.getAbsolutePath(); 12544 resolvedFile = file; 12545 } else { 12546 resolvedPath = null; 12547 resolvedFile = null; 12548 } 12549 } 12550 } 12551 12552 static class MoveInfo { 12553 final int moveId; 12554 final String fromUuid; 12555 final String toUuid; 12556 final String packageName; 12557 final String dataAppName; 12558 final int appId; 12559 final String seinfo; 12560 final int targetSdkVersion; 12561 12562 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12563 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12564 this.moveId = moveId; 12565 this.fromUuid = fromUuid; 12566 this.toUuid = toUuid; 12567 this.packageName = packageName; 12568 this.dataAppName = dataAppName; 12569 this.appId = appId; 12570 this.seinfo = seinfo; 12571 this.targetSdkVersion = targetSdkVersion; 12572 } 12573 } 12574 12575 static class VerificationInfo { 12576 /** A constant used to indicate that a uid value is not present. */ 12577 public static final int NO_UID = -1; 12578 12579 /** URI referencing where the package was downloaded from. */ 12580 final Uri originatingUri; 12581 12582 /** HTTP referrer URI associated with the originatingURI. */ 12583 final Uri referrer; 12584 12585 /** UID of the application that the install request originated from. */ 12586 final int originatingUid; 12587 12588 /** UID of application requesting the install */ 12589 final int installerUid; 12590 12591 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12592 this.originatingUri = originatingUri; 12593 this.referrer = referrer; 12594 this.originatingUid = originatingUid; 12595 this.installerUid = installerUid; 12596 } 12597 } 12598 12599 class InstallParams extends HandlerParams { 12600 final OriginInfo origin; 12601 final MoveInfo move; 12602 final IPackageInstallObserver2 observer; 12603 int installFlags; 12604 final String installerPackageName; 12605 final String volumeUuid; 12606 private InstallArgs mArgs; 12607 private int mRet; 12608 final String packageAbiOverride; 12609 final String[] grantedRuntimePermissions; 12610 final VerificationInfo verificationInfo; 12611 final Certificate[][] certificates; 12612 12613 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12614 int installFlags, String installerPackageName, String volumeUuid, 12615 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12616 String[] grantedPermissions, Certificate[][] certificates) { 12617 super(user); 12618 this.origin = origin; 12619 this.move = move; 12620 this.observer = observer; 12621 this.installFlags = installFlags; 12622 this.installerPackageName = installerPackageName; 12623 this.volumeUuid = volumeUuid; 12624 this.verificationInfo = verificationInfo; 12625 this.packageAbiOverride = packageAbiOverride; 12626 this.grantedRuntimePermissions = grantedPermissions; 12627 this.certificates = certificates; 12628 } 12629 12630 @Override 12631 public String toString() { 12632 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12633 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12634 } 12635 12636 private int installLocationPolicy(PackageInfoLite pkgLite) { 12637 String packageName = pkgLite.packageName; 12638 int installLocation = pkgLite.installLocation; 12639 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12640 // reader 12641 synchronized (mPackages) { 12642 // Currently installed package which the new package is attempting to replace or 12643 // null if no such package is installed. 12644 PackageParser.Package installedPkg = mPackages.get(packageName); 12645 // Package which currently owns the data which the new package will own if installed. 12646 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12647 // will be null whereas dataOwnerPkg will contain information about the package 12648 // which was uninstalled while keeping its data. 12649 PackageParser.Package dataOwnerPkg = installedPkg; 12650 if (dataOwnerPkg == null) { 12651 PackageSetting ps = mSettings.mPackages.get(packageName); 12652 if (ps != null) { 12653 dataOwnerPkg = ps.pkg; 12654 } 12655 } 12656 12657 if (dataOwnerPkg != null) { 12658 // If installed, the package will get access to data left on the device by its 12659 // predecessor. As a security measure, this is permited only if this is not a 12660 // version downgrade or if the predecessor package is marked as debuggable and 12661 // a downgrade is explicitly requested. 12662 // 12663 // On debuggable platform builds, downgrades are permitted even for 12664 // non-debuggable packages to make testing easier. Debuggable platform builds do 12665 // not offer security guarantees and thus it's OK to disable some security 12666 // mechanisms to make debugging/testing easier on those builds. However, even on 12667 // debuggable builds downgrades of packages are permitted only if requested via 12668 // installFlags. This is because we aim to keep the behavior of debuggable 12669 // platform builds as close as possible to the behavior of non-debuggable 12670 // platform builds. 12671 final boolean downgradeRequested = 12672 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12673 final boolean packageDebuggable = 12674 (dataOwnerPkg.applicationInfo.flags 12675 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12676 final boolean downgradePermitted = 12677 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12678 if (!downgradePermitted) { 12679 try { 12680 checkDowngrade(dataOwnerPkg, pkgLite); 12681 } catch (PackageManagerException e) { 12682 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12683 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12684 } 12685 } 12686 } 12687 12688 if (installedPkg != null) { 12689 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12690 // Check for updated system application. 12691 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12692 if (onSd) { 12693 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12694 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12695 } 12696 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12697 } else { 12698 if (onSd) { 12699 // Install flag overrides everything. 12700 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12701 } 12702 // If current upgrade specifies particular preference 12703 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12704 // Application explicitly specified internal. 12705 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12706 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12707 // App explictly prefers external. Let policy decide 12708 } else { 12709 // Prefer previous location 12710 if (isExternal(installedPkg)) { 12711 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12712 } 12713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12714 } 12715 } 12716 } else { 12717 // Invalid install. Return error code 12718 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12719 } 12720 } 12721 } 12722 // All the special cases have been taken care of. 12723 // Return result based on recommended install location. 12724 if (onSd) { 12725 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12726 } 12727 return pkgLite.recommendedInstallLocation; 12728 } 12729 12730 /* 12731 * Invoke remote method to get package information and install 12732 * location values. Override install location based on default 12733 * policy if needed and then create install arguments based 12734 * on the install location. 12735 */ 12736 public void handleStartCopy() throws RemoteException { 12737 int ret = PackageManager.INSTALL_SUCCEEDED; 12738 12739 // If we're already staged, we've firmly committed to an install location 12740 if (origin.staged) { 12741 if (origin.file != null) { 12742 installFlags |= PackageManager.INSTALL_INTERNAL; 12743 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12744 } else if (origin.cid != null) { 12745 installFlags |= PackageManager.INSTALL_EXTERNAL; 12746 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12747 } else { 12748 throw new IllegalStateException("Invalid stage location"); 12749 } 12750 } 12751 12752 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12753 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12754 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12755 PackageInfoLite pkgLite = null; 12756 12757 if (onInt && onSd) { 12758 // Check if both bits are set. 12759 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12760 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12761 } else if (onSd && ephemeral) { 12762 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12763 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12764 } else { 12765 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12766 packageAbiOverride); 12767 12768 if (DEBUG_EPHEMERAL && ephemeral) { 12769 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12770 } 12771 12772 /* 12773 * If we have too little free space, try to free cache 12774 * before giving up. 12775 */ 12776 if (!origin.staged && pkgLite.recommendedInstallLocation 12777 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12778 // TODO: focus freeing disk space on the target device 12779 final StorageManager storage = StorageManager.from(mContext); 12780 final long lowThreshold = storage.getStorageLowBytes( 12781 Environment.getDataDirectory()); 12782 12783 final long sizeBytes = mContainerService.calculateInstalledSize( 12784 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12785 12786 try { 12787 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12788 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12789 installFlags, packageAbiOverride); 12790 } catch (InstallerException e) { 12791 Slog.w(TAG, "Failed to free cache", e); 12792 } 12793 12794 /* 12795 * The cache free must have deleted the file we 12796 * downloaded to install. 12797 * 12798 * TODO: fix the "freeCache" call to not delete 12799 * the file we care about. 12800 */ 12801 if (pkgLite.recommendedInstallLocation 12802 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12803 pkgLite.recommendedInstallLocation 12804 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12805 } 12806 } 12807 } 12808 12809 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12810 int loc = pkgLite.recommendedInstallLocation; 12811 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12812 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12813 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12814 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12815 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12816 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12817 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12818 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12819 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12820 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12821 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12822 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12823 } else { 12824 // Override with defaults if needed. 12825 loc = installLocationPolicy(pkgLite); 12826 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12827 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12828 } else if (!onSd && !onInt) { 12829 // Override install location with flags 12830 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12831 // Set the flag to install on external media. 12832 installFlags |= PackageManager.INSTALL_EXTERNAL; 12833 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12834 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12835 if (DEBUG_EPHEMERAL) { 12836 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12837 } 12838 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12839 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12840 |PackageManager.INSTALL_INTERNAL); 12841 } else { 12842 // Make sure the flag for installing on external 12843 // media is unset 12844 installFlags |= PackageManager.INSTALL_INTERNAL; 12845 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12846 } 12847 } 12848 } 12849 } 12850 12851 final InstallArgs args = createInstallArgs(this); 12852 mArgs = args; 12853 12854 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12855 // TODO: http://b/22976637 12856 // Apps installed for "all" users use the device owner to verify the app 12857 UserHandle verifierUser = getUser(); 12858 if (verifierUser == UserHandle.ALL) { 12859 verifierUser = UserHandle.SYSTEM; 12860 } 12861 12862 /* 12863 * Determine if we have any installed package verifiers. If we 12864 * do, then we'll defer to them to verify the packages. 12865 */ 12866 final int requiredUid = mRequiredVerifierPackage == null ? -1 12867 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12868 verifierUser.getIdentifier()); 12869 if (!origin.existing && requiredUid != -1 12870 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12871 final Intent verification = new Intent( 12872 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12873 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12874 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12875 PACKAGE_MIME_TYPE); 12876 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12877 12878 // Query all live verifiers based on current user state 12879 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12880 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12881 12882 if (DEBUG_VERIFY) { 12883 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12884 + verification.toString() + " with " + pkgLite.verifiers.length 12885 + " optional verifiers"); 12886 } 12887 12888 final int verificationId = mPendingVerificationToken++; 12889 12890 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12891 12892 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12893 installerPackageName); 12894 12895 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12896 installFlags); 12897 12898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12899 pkgLite.packageName); 12900 12901 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12902 pkgLite.versionCode); 12903 12904 if (verificationInfo != null) { 12905 if (verificationInfo.originatingUri != null) { 12906 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12907 verificationInfo.originatingUri); 12908 } 12909 if (verificationInfo.referrer != null) { 12910 verification.putExtra(Intent.EXTRA_REFERRER, 12911 verificationInfo.referrer); 12912 } 12913 if (verificationInfo.originatingUid >= 0) { 12914 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12915 verificationInfo.originatingUid); 12916 } 12917 if (verificationInfo.installerUid >= 0) { 12918 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12919 verificationInfo.installerUid); 12920 } 12921 } 12922 12923 final PackageVerificationState verificationState = new PackageVerificationState( 12924 requiredUid, args); 12925 12926 mPendingVerification.append(verificationId, verificationState); 12927 12928 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12929 receivers, verificationState); 12930 12931 /* 12932 * If any sufficient verifiers were listed in the package 12933 * manifest, attempt to ask them. 12934 */ 12935 if (sufficientVerifiers != null) { 12936 final int N = sufficientVerifiers.size(); 12937 if (N == 0) { 12938 Slog.i(TAG, "Additional verifiers required, but none installed."); 12939 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12940 } else { 12941 for (int i = 0; i < N; i++) { 12942 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12943 12944 final Intent sufficientIntent = new Intent(verification); 12945 sufficientIntent.setComponent(verifierComponent); 12946 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12947 } 12948 } 12949 } 12950 12951 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12952 mRequiredVerifierPackage, receivers); 12953 if (ret == PackageManager.INSTALL_SUCCEEDED 12954 && mRequiredVerifierPackage != null) { 12955 Trace.asyncTraceBegin( 12956 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12957 /* 12958 * Send the intent to the required verification agent, 12959 * but only start the verification timeout after the 12960 * target BroadcastReceivers have run. 12961 */ 12962 verification.setComponent(requiredVerifierComponent); 12963 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12964 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12965 new BroadcastReceiver() { 12966 @Override 12967 public void onReceive(Context context, Intent intent) { 12968 final Message msg = mHandler 12969 .obtainMessage(CHECK_PENDING_VERIFICATION); 12970 msg.arg1 = verificationId; 12971 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12972 } 12973 }, null, 0, null, null); 12974 12975 /* 12976 * We don't want the copy to proceed until verification 12977 * succeeds, so null out this field. 12978 */ 12979 mArgs = null; 12980 } 12981 } else { 12982 /* 12983 * No package verification is enabled, so immediately start 12984 * the remote call to initiate copy using temporary file. 12985 */ 12986 ret = args.copyApk(mContainerService, true); 12987 } 12988 } 12989 12990 mRet = ret; 12991 } 12992 12993 @Override 12994 void handleReturnCode() { 12995 // If mArgs is null, then MCS couldn't be reached. When it 12996 // reconnects, it will try again to install. At that point, this 12997 // will succeed. 12998 if (mArgs != null) { 12999 processPendingInstall(mArgs, mRet); 13000 } 13001 } 13002 13003 @Override 13004 void handleServiceError() { 13005 mArgs = createInstallArgs(this); 13006 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13007 } 13008 13009 public boolean isForwardLocked() { 13010 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13011 } 13012 } 13013 13014 /** 13015 * Used during creation of InstallArgs 13016 * 13017 * @param installFlags package installation flags 13018 * @return true if should be installed on external storage 13019 */ 13020 private static boolean installOnExternalAsec(int installFlags) { 13021 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13022 return false; 13023 } 13024 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13025 return true; 13026 } 13027 return false; 13028 } 13029 13030 /** 13031 * Used during creation of InstallArgs 13032 * 13033 * @param installFlags package installation flags 13034 * @return true if should be installed as forward locked 13035 */ 13036 private static boolean installForwardLocked(int installFlags) { 13037 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13038 } 13039 13040 private InstallArgs createInstallArgs(InstallParams params) { 13041 if (params.move != null) { 13042 return new MoveInstallArgs(params); 13043 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13044 return new AsecInstallArgs(params); 13045 } else { 13046 return new FileInstallArgs(params); 13047 } 13048 } 13049 13050 /** 13051 * Create args that describe an existing installed package. Typically used 13052 * when cleaning up old installs, or used as a move source. 13053 */ 13054 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13055 String resourcePath, String[] instructionSets) { 13056 final boolean isInAsec; 13057 if (installOnExternalAsec(installFlags)) { 13058 /* Apps on SD card are always in ASEC containers. */ 13059 isInAsec = true; 13060 } else if (installForwardLocked(installFlags) 13061 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13062 /* 13063 * Forward-locked apps are only in ASEC containers if they're the 13064 * new style 13065 */ 13066 isInAsec = true; 13067 } else { 13068 isInAsec = false; 13069 } 13070 13071 if (isInAsec) { 13072 return new AsecInstallArgs(codePath, instructionSets, 13073 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13074 } else { 13075 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13076 } 13077 } 13078 13079 static abstract class InstallArgs { 13080 /** @see InstallParams#origin */ 13081 final OriginInfo origin; 13082 /** @see InstallParams#move */ 13083 final MoveInfo move; 13084 13085 final IPackageInstallObserver2 observer; 13086 // Always refers to PackageManager flags only 13087 final int installFlags; 13088 final String installerPackageName; 13089 final String volumeUuid; 13090 final UserHandle user; 13091 final String abiOverride; 13092 final String[] installGrantPermissions; 13093 /** If non-null, drop an async trace when the install completes */ 13094 final String traceMethod; 13095 final int traceCookie; 13096 final Certificate[][] certificates; 13097 13098 // The list of instruction sets supported by this app. This is currently 13099 // only used during the rmdex() phase to clean up resources. We can get rid of this 13100 // if we move dex files under the common app path. 13101 /* nullable */ String[] instructionSets; 13102 13103 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13104 int installFlags, String installerPackageName, String volumeUuid, 13105 UserHandle user, String[] instructionSets, 13106 String abiOverride, String[] installGrantPermissions, 13107 String traceMethod, int traceCookie, Certificate[][] certificates) { 13108 this.origin = origin; 13109 this.move = move; 13110 this.installFlags = installFlags; 13111 this.observer = observer; 13112 this.installerPackageName = installerPackageName; 13113 this.volumeUuid = volumeUuid; 13114 this.user = user; 13115 this.instructionSets = instructionSets; 13116 this.abiOverride = abiOverride; 13117 this.installGrantPermissions = installGrantPermissions; 13118 this.traceMethod = traceMethod; 13119 this.traceCookie = traceCookie; 13120 this.certificates = certificates; 13121 } 13122 13123 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13124 abstract int doPreInstall(int status); 13125 13126 /** 13127 * Rename package into final resting place. All paths on the given 13128 * scanned package should be updated to reflect the rename. 13129 */ 13130 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13131 abstract int doPostInstall(int status, int uid); 13132 13133 /** @see PackageSettingBase#codePathString */ 13134 abstract String getCodePath(); 13135 /** @see PackageSettingBase#resourcePathString */ 13136 abstract String getResourcePath(); 13137 13138 // Need installer lock especially for dex file removal. 13139 abstract void cleanUpResourcesLI(); 13140 abstract boolean doPostDeleteLI(boolean delete); 13141 13142 /** 13143 * Called before the source arguments are copied. This is used mostly 13144 * for MoveParams when it needs to read the source file to put it in the 13145 * destination. 13146 */ 13147 int doPreCopy() { 13148 return PackageManager.INSTALL_SUCCEEDED; 13149 } 13150 13151 /** 13152 * Called after the source arguments are copied. This is used mostly for 13153 * MoveParams when it needs to read the source file to put it in the 13154 * destination. 13155 */ 13156 int doPostCopy(int uid) { 13157 return PackageManager.INSTALL_SUCCEEDED; 13158 } 13159 13160 protected boolean isFwdLocked() { 13161 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13162 } 13163 13164 protected boolean isExternalAsec() { 13165 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13166 } 13167 13168 protected boolean isEphemeral() { 13169 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13170 } 13171 13172 UserHandle getUser() { 13173 return user; 13174 } 13175 } 13176 13177 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13178 if (!allCodePaths.isEmpty()) { 13179 if (instructionSets == null) { 13180 throw new IllegalStateException("instructionSet == null"); 13181 } 13182 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13183 for (String codePath : allCodePaths) { 13184 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13185 try { 13186 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13187 } catch (InstallerException ignored) { 13188 } 13189 } 13190 } 13191 } 13192 } 13193 13194 /** 13195 * Logic to handle installation of non-ASEC applications, including copying 13196 * and renaming logic. 13197 */ 13198 class FileInstallArgs extends InstallArgs { 13199 private File codeFile; 13200 private File resourceFile; 13201 13202 // Example topology: 13203 // /data/app/com.example/base.apk 13204 // /data/app/com.example/split_foo.apk 13205 // /data/app/com.example/lib/arm/libfoo.so 13206 // /data/app/com.example/lib/arm64/libfoo.so 13207 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13208 13209 /** New install */ 13210 FileInstallArgs(InstallParams params) { 13211 super(params.origin, params.move, params.observer, params.installFlags, 13212 params.installerPackageName, params.volumeUuid, 13213 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13214 params.grantedRuntimePermissions, 13215 params.traceMethod, params.traceCookie, params.certificates); 13216 if (isFwdLocked()) { 13217 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13218 } 13219 } 13220 13221 /** Existing install */ 13222 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13223 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13224 null, null, null, 0, null /*certificates*/); 13225 this.codeFile = (codePath != null) ? new File(codePath) : null; 13226 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13227 } 13228 13229 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13231 try { 13232 return doCopyApk(imcs, temp); 13233 } finally { 13234 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13235 } 13236 } 13237 13238 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13239 if (origin.staged) { 13240 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13241 codeFile = origin.file; 13242 resourceFile = origin.file; 13243 return PackageManager.INSTALL_SUCCEEDED; 13244 } 13245 13246 try { 13247 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13248 final File tempDir = 13249 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13250 codeFile = tempDir; 13251 resourceFile = tempDir; 13252 } catch (IOException e) { 13253 Slog.w(TAG, "Failed to create copy file: " + e); 13254 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13255 } 13256 13257 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13258 @Override 13259 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13260 if (!FileUtils.isValidExtFilename(name)) { 13261 throw new IllegalArgumentException("Invalid filename: " + name); 13262 } 13263 try { 13264 final File file = new File(codeFile, name); 13265 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13266 O_RDWR | O_CREAT, 0644); 13267 Os.chmod(file.getAbsolutePath(), 0644); 13268 return new ParcelFileDescriptor(fd); 13269 } catch (ErrnoException e) { 13270 throw new RemoteException("Failed to open: " + e.getMessage()); 13271 } 13272 } 13273 }; 13274 13275 int ret = PackageManager.INSTALL_SUCCEEDED; 13276 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13277 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13278 Slog.e(TAG, "Failed to copy package"); 13279 return ret; 13280 } 13281 13282 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13283 NativeLibraryHelper.Handle handle = null; 13284 try { 13285 handle = NativeLibraryHelper.Handle.create(codeFile); 13286 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13287 abiOverride); 13288 } catch (IOException e) { 13289 Slog.e(TAG, "Copying native libraries failed", e); 13290 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13291 } finally { 13292 IoUtils.closeQuietly(handle); 13293 } 13294 13295 return ret; 13296 } 13297 13298 int doPreInstall(int status) { 13299 if (status != PackageManager.INSTALL_SUCCEEDED) { 13300 cleanUp(); 13301 } 13302 return status; 13303 } 13304 13305 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13306 if (status != PackageManager.INSTALL_SUCCEEDED) { 13307 cleanUp(); 13308 return false; 13309 } 13310 13311 final File targetDir = codeFile.getParentFile(); 13312 final File beforeCodeFile = codeFile; 13313 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13314 13315 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13316 try { 13317 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13318 } catch (ErrnoException e) { 13319 Slog.w(TAG, "Failed to rename", e); 13320 return false; 13321 } 13322 13323 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13324 Slog.w(TAG, "Failed to restorecon"); 13325 return false; 13326 } 13327 13328 // Reflect the rename internally 13329 codeFile = afterCodeFile; 13330 resourceFile = afterCodeFile; 13331 13332 // Reflect the rename in scanned details 13333 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13334 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13335 afterCodeFile, pkg.baseCodePath)); 13336 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13337 afterCodeFile, pkg.splitCodePaths)); 13338 13339 // Reflect the rename in app info 13340 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13341 pkg.setApplicationInfoCodePath(pkg.codePath); 13342 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13343 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13344 pkg.setApplicationInfoResourcePath(pkg.codePath); 13345 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13346 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13347 13348 return true; 13349 } 13350 13351 int doPostInstall(int status, int uid) { 13352 if (status != PackageManager.INSTALL_SUCCEEDED) { 13353 cleanUp(); 13354 } 13355 return status; 13356 } 13357 13358 @Override 13359 String getCodePath() { 13360 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13361 } 13362 13363 @Override 13364 String getResourcePath() { 13365 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13366 } 13367 13368 private boolean cleanUp() { 13369 if (codeFile == null || !codeFile.exists()) { 13370 return false; 13371 } 13372 13373 removeCodePathLI(codeFile); 13374 13375 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13376 resourceFile.delete(); 13377 } 13378 13379 return true; 13380 } 13381 13382 void cleanUpResourcesLI() { 13383 // Try enumerating all code paths before deleting 13384 List<String> allCodePaths = Collections.EMPTY_LIST; 13385 if (codeFile != null && codeFile.exists()) { 13386 try { 13387 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13388 allCodePaths = pkg.getAllCodePaths(); 13389 } catch (PackageParserException e) { 13390 // Ignored; we tried our best 13391 } 13392 } 13393 13394 cleanUp(); 13395 removeDexFiles(allCodePaths, instructionSets); 13396 } 13397 13398 boolean doPostDeleteLI(boolean delete) { 13399 // XXX err, shouldn't we respect the delete flag? 13400 cleanUpResourcesLI(); 13401 return true; 13402 } 13403 } 13404 13405 private boolean isAsecExternal(String cid) { 13406 final String asecPath = PackageHelper.getSdFilesystem(cid); 13407 return !asecPath.startsWith(mAsecInternalPath); 13408 } 13409 13410 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13411 PackageManagerException { 13412 if (copyRet < 0) { 13413 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13414 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13415 throw new PackageManagerException(copyRet, message); 13416 } 13417 } 13418 } 13419 13420 /** 13421 * Extract the MountService "container ID" from the full code path of an 13422 * .apk. 13423 */ 13424 static String cidFromCodePath(String fullCodePath) { 13425 int eidx = fullCodePath.lastIndexOf("/"); 13426 String subStr1 = fullCodePath.substring(0, eidx); 13427 int sidx = subStr1.lastIndexOf("/"); 13428 return subStr1.substring(sidx+1, eidx); 13429 } 13430 13431 /** 13432 * Logic to handle installation of ASEC applications, including copying and 13433 * renaming logic. 13434 */ 13435 class AsecInstallArgs extends InstallArgs { 13436 static final String RES_FILE_NAME = "pkg.apk"; 13437 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13438 13439 String cid; 13440 String packagePath; 13441 String resourcePath; 13442 13443 /** New install */ 13444 AsecInstallArgs(InstallParams params) { 13445 super(params.origin, params.move, params.observer, params.installFlags, 13446 params.installerPackageName, params.volumeUuid, 13447 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13448 params.grantedRuntimePermissions, 13449 params.traceMethod, params.traceCookie, params.certificates); 13450 } 13451 13452 /** Existing install */ 13453 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13454 boolean isExternal, boolean isForwardLocked) { 13455 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13456 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13457 instructionSets, null, null, null, 0, null /*certificates*/); 13458 // Hackily pretend we're still looking at a full code path 13459 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13460 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13461 } 13462 13463 // Extract cid from fullCodePath 13464 int eidx = fullCodePath.lastIndexOf("/"); 13465 String subStr1 = fullCodePath.substring(0, eidx); 13466 int sidx = subStr1.lastIndexOf("/"); 13467 cid = subStr1.substring(sidx+1, eidx); 13468 setMountPath(subStr1); 13469 } 13470 13471 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13472 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13473 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13474 instructionSets, null, null, null, 0, null /*certificates*/); 13475 this.cid = cid; 13476 setMountPath(PackageHelper.getSdDir(cid)); 13477 } 13478 13479 void createCopyFile() { 13480 cid = mInstallerService.allocateExternalStageCidLegacy(); 13481 } 13482 13483 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13484 if (origin.staged && origin.cid != null) { 13485 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13486 cid = origin.cid; 13487 setMountPath(PackageHelper.getSdDir(cid)); 13488 return PackageManager.INSTALL_SUCCEEDED; 13489 } 13490 13491 if (temp) { 13492 createCopyFile(); 13493 } else { 13494 /* 13495 * Pre-emptively destroy the container since it's destroyed if 13496 * copying fails due to it existing anyway. 13497 */ 13498 PackageHelper.destroySdDir(cid); 13499 } 13500 13501 final String newMountPath = imcs.copyPackageToContainer( 13502 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13503 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13504 13505 if (newMountPath != null) { 13506 setMountPath(newMountPath); 13507 return PackageManager.INSTALL_SUCCEEDED; 13508 } else { 13509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13510 } 13511 } 13512 13513 @Override 13514 String getCodePath() { 13515 return packagePath; 13516 } 13517 13518 @Override 13519 String getResourcePath() { 13520 return resourcePath; 13521 } 13522 13523 int doPreInstall(int status) { 13524 if (status != PackageManager.INSTALL_SUCCEEDED) { 13525 // Destroy container 13526 PackageHelper.destroySdDir(cid); 13527 } else { 13528 boolean mounted = PackageHelper.isContainerMounted(cid); 13529 if (!mounted) { 13530 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13531 Process.SYSTEM_UID); 13532 if (newMountPath != null) { 13533 setMountPath(newMountPath); 13534 } else { 13535 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13536 } 13537 } 13538 } 13539 return status; 13540 } 13541 13542 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13543 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13544 String newMountPath = null; 13545 if (PackageHelper.isContainerMounted(cid)) { 13546 // Unmount the container 13547 if (!PackageHelper.unMountSdDir(cid)) { 13548 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13549 return false; 13550 } 13551 } 13552 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13553 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13554 " which might be stale. Will try to clean up."); 13555 // Clean up the stale container and proceed to recreate. 13556 if (!PackageHelper.destroySdDir(newCacheId)) { 13557 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13558 return false; 13559 } 13560 // Successfully cleaned up stale container. Try to rename again. 13561 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13562 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13563 + " inspite of cleaning it up."); 13564 return false; 13565 } 13566 } 13567 if (!PackageHelper.isContainerMounted(newCacheId)) { 13568 Slog.w(TAG, "Mounting container " + newCacheId); 13569 newMountPath = PackageHelper.mountSdDir(newCacheId, 13570 getEncryptKey(), Process.SYSTEM_UID); 13571 } else { 13572 newMountPath = PackageHelper.getSdDir(newCacheId); 13573 } 13574 if (newMountPath == null) { 13575 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13576 return false; 13577 } 13578 Log.i(TAG, "Succesfully renamed " + cid + 13579 " to " + newCacheId + 13580 " at new path: " + newMountPath); 13581 cid = newCacheId; 13582 13583 final File beforeCodeFile = new File(packagePath); 13584 setMountPath(newMountPath); 13585 final File afterCodeFile = new File(packagePath); 13586 13587 // Reflect the rename in scanned details 13588 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13589 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13590 afterCodeFile, pkg.baseCodePath)); 13591 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13592 afterCodeFile, pkg.splitCodePaths)); 13593 13594 // Reflect the rename in app info 13595 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13596 pkg.setApplicationInfoCodePath(pkg.codePath); 13597 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13598 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13599 pkg.setApplicationInfoResourcePath(pkg.codePath); 13600 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13601 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13602 13603 return true; 13604 } 13605 13606 private void setMountPath(String mountPath) { 13607 final File mountFile = new File(mountPath); 13608 13609 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13610 if (monolithicFile.exists()) { 13611 packagePath = monolithicFile.getAbsolutePath(); 13612 if (isFwdLocked()) { 13613 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13614 } else { 13615 resourcePath = packagePath; 13616 } 13617 } else { 13618 packagePath = mountFile.getAbsolutePath(); 13619 resourcePath = packagePath; 13620 } 13621 } 13622 13623 int doPostInstall(int status, int uid) { 13624 if (status != PackageManager.INSTALL_SUCCEEDED) { 13625 cleanUp(); 13626 } else { 13627 final int groupOwner; 13628 final String protectedFile; 13629 if (isFwdLocked()) { 13630 groupOwner = UserHandle.getSharedAppGid(uid); 13631 protectedFile = RES_FILE_NAME; 13632 } else { 13633 groupOwner = -1; 13634 protectedFile = null; 13635 } 13636 13637 if (uid < Process.FIRST_APPLICATION_UID 13638 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13639 Slog.e(TAG, "Failed to finalize " + cid); 13640 PackageHelper.destroySdDir(cid); 13641 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13642 } 13643 13644 boolean mounted = PackageHelper.isContainerMounted(cid); 13645 if (!mounted) { 13646 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13647 } 13648 } 13649 return status; 13650 } 13651 13652 private void cleanUp() { 13653 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13654 13655 // Destroy secure container 13656 PackageHelper.destroySdDir(cid); 13657 } 13658 13659 private List<String> getAllCodePaths() { 13660 final File codeFile = new File(getCodePath()); 13661 if (codeFile != null && codeFile.exists()) { 13662 try { 13663 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13664 return pkg.getAllCodePaths(); 13665 } catch (PackageParserException e) { 13666 // Ignored; we tried our best 13667 } 13668 } 13669 return Collections.EMPTY_LIST; 13670 } 13671 13672 void cleanUpResourcesLI() { 13673 // Enumerate all code paths before deleting 13674 cleanUpResourcesLI(getAllCodePaths()); 13675 } 13676 13677 private void cleanUpResourcesLI(List<String> allCodePaths) { 13678 cleanUp(); 13679 removeDexFiles(allCodePaths, instructionSets); 13680 } 13681 13682 String getPackageName() { 13683 return getAsecPackageName(cid); 13684 } 13685 13686 boolean doPostDeleteLI(boolean delete) { 13687 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13688 final List<String> allCodePaths = getAllCodePaths(); 13689 boolean mounted = PackageHelper.isContainerMounted(cid); 13690 if (mounted) { 13691 // Unmount first 13692 if (PackageHelper.unMountSdDir(cid)) { 13693 mounted = false; 13694 } 13695 } 13696 if (!mounted && delete) { 13697 cleanUpResourcesLI(allCodePaths); 13698 } 13699 return !mounted; 13700 } 13701 13702 @Override 13703 int doPreCopy() { 13704 if (isFwdLocked()) { 13705 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13706 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13707 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13708 } 13709 } 13710 13711 return PackageManager.INSTALL_SUCCEEDED; 13712 } 13713 13714 @Override 13715 int doPostCopy(int uid) { 13716 if (isFwdLocked()) { 13717 if (uid < Process.FIRST_APPLICATION_UID 13718 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13719 RES_FILE_NAME)) { 13720 Slog.e(TAG, "Failed to finalize " + cid); 13721 PackageHelper.destroySdDir(cid); 13722 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13723 } 13724 } 13725 13726 return PackageManager.INSTALL_SUCCEEDED; 13727 } 13728 } 13729 13730 /** 13731 * Logic to handle movement of existing installed applications. 13732 */ 13733 class MoveInstallArgs extends InstallArgs { 13734 private File codeFile; 13735 private File resourceFile; 13736 13737 /** New install */ 13738 MoveInstallArgs(InstallParams params) { 13739 super(params.origin, params.move, params.observer, params.installFlags, 13740 params.installerPackageName, params.volumeUuid, 13741 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13742 params.grantedRuntimePermissions, 13743 params.traceMethod, params.traceCookie, params.certificates); 13744 } 13745 13746 int copyApk(IMediaContainerService imcs, boolean temp) { 13747 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13748 + move.fromUuid + " to " + move.toUuid); 13749 synchronized (mInstaller) { 13750 try { 13751 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13752 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13753 } catch (InstallerException e) { 13754 Slog.w(TAG, "Failed to move app", e); 13755 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13756 } 13757 } 13758 13759 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13760 resourceFile = codeFile; 13761 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13762 13763 return PackageManager.INSTALL_SUCCEEDED; 13764 } 13765 13766 int doPreInstall(int status) { 13767 if (status != PackageManager.INSTALL_SUCCEEDED) { 13768 cleanUp(move.toUuid); 13769 } 13770 return status; 13771 } 13772 13773 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13774 if (status != PackageManager.INSTALL_SUCCEEDED) { 13775 cleanUp(move.toUuid); 13776 return false; 13777 } 13778 13779 // Reflect the move in app info 13780 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13781 pkg.setApplicationInfoCodePath(pkg.codePath); 13782 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13783 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13784 pkg.setApplicationInfoResourcePath(pkg.codePath); 13785 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13786 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13787 13788 return true; 13789 } 13790 13791 int doPostInstall(int status, int uid) { 13792 if (status == PackageManager.INSTALL_SUCCEEDED) { 13793 cleanUp(move.fromUuid); 13794 } else { 13795 cleanUp(move.toUuid); 13796 } 13797 return status; 13798 } 13799 13800 @Override 13801 String getCodePath() { 13802 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13803 } 13804 13805 @Override 13806 String getResourcePath() { 13807 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13808 } 13809 13810 private boolean cleanUp(String volumeUuid) { 13811 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13812 move.dataAppName); 13813 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13814 final int[] userIds = sUserManager.getUserIds(); 13815 synchronized (mInstallLock) { 13816 // Clean up both app data and code 13817 // All package moves are frozen until finished 13818 for (int userId : userIds) { 13819 try { 13820 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13821 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13822 } catch (InstallerException e) { 13823 Slog.w(TAG, String.valueOf(e)); 13824 } 13825 } 13826 removeCodePathLI(codeFile); 13827 } 13828 return true; 13829 } 13830 13831 void cleanUpResourcesLI() { 13832 throw new UnsupportedOperationException(); 13833 } 13834 13835 boolean doPostDeleteLI(boolean delete) { 13836 throw new UnsupportedOperationException(); 13837 } 13838 } 13839 13840 static String getAsecPackageName(String packageCid) { 13841 int idx = packageCid.lastIndexOf("-"); 13842 if (idx == -1) { 13843 return packageCid; 13844 } 13845 return packageCid.substring(0, idx); 13846 } 13847 13848 // Utility method used to create code paths based on package name and available index. 13849 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13850 String idxStr = ""; 13851 int idx = 1; 13852 // Fall back to default value of idx=1 if prefix is not 13853 // part of oldCodePath 13854 if (oldCodePath != null) { 13855 String subStr = oldCodePath; 13856 // Drop the suffix right away 13857 if (suffix != null && subStr.endsWith(suffix)) { 13858 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13859 } 13860 // If oldCodePath already contains prefix find out the 13861 // ending index to either increment or decrement. 13862 int sidx = subStr.lastIndexOf(prefix); 13863 if (sidx != -1) { 13864 subStr = subStr.substring(sidx + prefix.length()); 13865 if (subStr != null) { 13866 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13867 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13868 } 13869 try { 13870 idx = Integer.parseInt(subStr); 13871 if (idx <= 1) { 13872 idx++; 13873 } else { 13874 idx--; 13875 } 13876 } catch(NumberFormatException e) { 13877 } 13878 } 13879 } 13880 } 13881 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13882 return prefix + idxStr; 13883 } 13884 13885 private File getNextCodePath(File targetDir, String packageName) { 13886 int suffix = 1; 13887 File result; 13888 do { 13889 result = new File(targetDir, packageName + "-" + suffix); 13890 suffix++; 13891 } while (result.exists()); 13892 return result; 13893 } 13894 13895 // Utility method that returns the relative package path with respect 13896 // to the installation directory. Like say for /data/data/com.test-1.apk 13897 // string com.test-1 is returned. 13898 static String deriveCodePathName(String codePath) { 13899 if (codePath == null) { 13900 return null; 13901 } 13902 final File codeFile = new File(codePath); 13903 final String name = codeFile.getName(); 13904 if (codeFile.isDirectory()) { 13905 return name; 13906 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13907 final int lastDot = name.lastIndexOf('.'); 13908 return name.substring(0, lastDot); 13909 } else { 13910 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13911 return null; 13912 } 13913 } 13914 13915 static class PackageInstalledInfo { 13916 String name; 13917 int uid; 13918 // The set of users that originally had this package installed. 13919 int[] origUsers; 13920 // The set of users that now have this package installed. 13921 int[] newUsers; 13922 PackageParser.Package pkg; 13923 int returnCode; 13924 String returnMsg; 13925 PackageRemovedInfo removedInfo; 13926 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13927 13928 public void setError(int code, String msg) { 13929 setReturnCode(code); 13930 setReturnMessage(msg); 13931 Slog.w(TAG, msg); 13932 } 13933 13934 public void setError(String msg, PackageParserException e) { 13935 setReturnCode(e.error); 13936 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13937 Slog.w(TAG, msg, e); 13938 } 13939 13940 public void setError(String msg, PackageManagerException e) { 13941 returnCode = e.error; 13942 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13943 Slog.w(TAG, msg, e); 13944 } 13945 13946 public void setReturnCode(int returnCode) { 13947 this.returnCode = returnCode; 13948 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13949 for (int i = 0; i < childCount; i++) { 13950 addedChildPackages.valueAt(i).returnCode = returnCode; 13951 } 13952 } 13953 13954 private void setReturnMessage(String returnMsg) { 13955 this.returnMsg = returnMsg; 13956 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13957 for (int i = 0; i < childCount; i++) { 13958 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13959 } 13960 } 13961 13962 // In some error cases we want to convey more info back to the observer 13963 String origPackage; 13964 String origPermission; 13965 } 13966 13967 /* 13968 * Install a non-existing package. 13969 */ 13970 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13971 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13972 PackageInstalledInfo res) { 13973 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13974 13975 // Remember this for later, in case we need to rollback this install 13976 String pkgName = pkg.packageName; 13977 13978 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13979 13980 synchronized(mPackages) { 13981 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13982 // A package with the same name is already installed, though 13983 // it has been renamed to an older name. The package we 13984 // are trying to install should be installed as an update to 13985 // the existing one, but that has not been requested, so bail. 13986 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13987 + " without first uninstalling package running as " 13988 + mSettings.mRenamedPackages.get(pkgName)); 13989 return; 13990 } 13991 if (mPackages.containsKey(pkgName)) { 13992 // Don't allow installation over an existing package with the same name. 13993 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13994 + " without first uninstalling."); 13995 return; 13996 } 13997 } 13998 13999 try { 14000 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14001 System.currentTimeMillis(), user); 14002 14003 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14004 14005 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14006 prepareAppDataAfterInstallLIF(newPackage); 14007 14008 } else { 14009 // Remove package from internal structures, but keep around any 14010 // data that might have already existed 14011 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14012 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14013 } 14014 } catch (PackageManagerException e) { 14015 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14016 } 14017 14018 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14019 } 14020 14021 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14022 // Can't rotate keys during boot or if sharedUser. 14023 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14024 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14025 return false; 14026 } 14027 // app is using upgradeKeySets; make sure all are valid 14028 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14029 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14030 for (int i = 0; i < upgradeKeySets.length; i++) { 14031 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14032 Slog.wtf(TAG, "Package " 14033 + (oldPs.name != null ? oldPs.name : "<null>") 14034 + " contains upgrade-key-set reference to unknown key-set: " 14035 + upgradeKeySets[i] 14036 + " reverting to signatures check."); 14037 return false; 14038 } 14039 } 14040 return true; 14041 } 14042 14043 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14044 // Upgrade keysets are being used. Determine if new package has a superset of the 14045 // required keys. 14046 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14047 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14048 for (int i = 0; i < upgradeKeySets.length; i++) { 14049 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14050 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14051 return true; 14052 } 14053 } 14054 return false; 14055 } 14056 14057 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14058 try (DigestInputStream digestStream = 14059 new DigestInputStream(new FileInputStream(file), digest)) { 14060 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14061 } 14062 } 14063 14064 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14065 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14066 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14067 14068 final PackageParser.Package oldPackage; 14069 final String pkgName = pkg.packageName; 14070 final int[] allUsers; 14071 final int[] installedUsers; 14072 14073 synchronized(mPackages) { 14074 oldPackage = mPackages.get(pkgName); 14075 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14076 14077 // don't allow upgrade to target a release SDK from a pre-release SDK 14078 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14079 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14080 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14081 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14082 if (oldTargetsPreRelease 14083 && !newTargetsPreRelease 14084 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14085 Slog.w(TAG, "Can't install package targeting released sdk"); 14086 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14087 return; 14088 } 14089 14090 // don't allow an upgrade from full to ephemeral 14091 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14092 if (isEphemeral && !oldIsEphemeral) { 14093 // can't downgrade from full to ephemeral 14094 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14095 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14096 return; 14097 } 14098 14099 // verify signatures are valid 14100 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14101 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14102 if (!checkUpgradeKeySetLP(ps, pkg)) { 14103 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14104 "New package not signed by keys specified by upgrade-keysets: " 14105 + pkgName); 14106 return; 14107 } 14108 } else { 14109 // default to original signature matching 14110 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14111 != PackageManager.SIGNATURE_MATCH) { 14112 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14113 "New package has a different signature: " + pkgName); 14114 return; 14115 } 14116 } 14117 14118 // don't allow a system upgrade unless the upgrade hash matches 14119 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14120 byte[] digestBytes = null; 14121 try { 14122 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14123 updateDigest(digest, new File(pkg.baseCodePath)); 14124 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14125 for (String path : pkg.splitCodePaths) { 14126 updateDigest(digest, new File(path)); 14127 } 14128 } 14129 digestBytes = digest.digest(); 14130 } catch (NoSuchAlgorithmException | IOException e) { 14131 res.setError(INSTALL_FAILED_INVALID_APK, 14132 "Could not compute hash: " + pkgName); 14133 return; 14134 } 14135 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14136 res.setError(INSTALL_FAILED_INVALID_APK, 14137 "New package fails restrict-update check: " + pkgName); 14138 return; 14139 } 14140 // retain upgrade restriction 14141 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14142 } 14143 14144 // Check for shared user id changes 14145 String invalidPackageName = 14146 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14147 if (invalidPackageName != null) { 14148 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14149 "Package " + invalidPackageName + " tried to change user " 14150 + oldPackage.mSharedUserId); 14151 return; 14152 } 14153 14154 // In case of rollback, remember per-user/profile install state 14155 allUsers = sUserManager.getUserIds(); 14156 installedUsers = ps.queryInstalledUsers(allUsers, true); 14157 } 14158 14159 // Update what is removed 14160 res.removedInfo = new PackageRemovedInfo(); 14161 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14162 res.removedInfo.removedPackage = oldPackage.packageName; 14163 res.removedInfo.isUpdate = true; 14164 res.removedInfo.origUsers = installedUsers; 14165 final int childCount = (oldPackage.childPackages != null) 14166 ? oldPackage.childPackages.size() : 0; 14167 for (int i = 0; i < childCount; i++) { 14168 boolean childPackageUpdated = false; 14169 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14170 if (res.addedChildPackages != null) { 14171 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14172 if (childRes != null) { 14173 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14174 childRes.removedInfo.removedPackage = childPkg.packageName; 14175 childRes.removedInfo.isUpdate = true; 14176 childPackageUpdated = true; 14177 } 14178 } 14179 if (!childPackageUpdated) { 14180 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14181 childRemovedRes.removedPackage = childPkg.packageName; 14182 childRemovedRes.isUpdate = false; 14183 childRemovedRes.dataRemoved = true; 14184 synchronized (mPackages) { 14185 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14186 if (childPs != null) { 14187 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14188 } 14189 } 14190 if (res.removedInfo.removedChildPackages == null) { 14191 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14192 } 14193 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14194 } 14195 } 14196 14197 boolean sysPkg = (isSystemApp(oldPackage)); 14198 if (sysPkg) { 14199 // Set the system/privileged flags as needed 14200 final boolean privileged = 14201 (oldPackage.applicationInfo.privateFlags 14202 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14203 final int systemPolicyFlags = policyFlags 14204 | PackageParser.PARSE_IS_SYSTEM 14205 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14206 14207 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14208 user, allUsers, installerPackageName, res); 14209 } else { 14210 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14211 user, allUsers, installerPackageName, res); 14212 } 14213 } 14214 14215 public List<String> getPreviousCodePaths(String packageName) { 14216 final PackageSetting ps = mSettings.mPackages.get(packageName); 14217 final List<String> result = new ArrayList<String>(); 14218 if (ps != null && ps.oldCodePaths != null) { 14219 result.addAll(ps.oldCodePaths); 14220 } 14221 return result; 14222 } 14223 14224 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14225 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14226 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14227 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14228 + deletedPackage); 14229 14230 String pkgName = deletedPackage.packageName; 14231 boolean deletedPkg = true; 14232 boolean addedPkg = false; 14233 boolean updatedSettings = false; 14234 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14235 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14236 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14237 14238 final long origUpdateTime = (pkg.mExtras != null) 14239 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14240 14241 // First delete the existing package while retaining the data directory 14242 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14243 res.removedInfo, true, pkg)) { 14244 // If the existing package wasn't successfully deleted 14245 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14246 deletedPkg = false; 14247 } else { 14248 // Successfully deleted the old package; proceed with replace. 14249 14250 // If deleted package lived in a container, give users a chance to 14251 // relinquish resources before killing. 14252 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14253 if (DEBUG_INSTALL) { 14254 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14255 } 14256 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14257 final ArrayList<String> pkgList = new ArrayList<String>(1); 14258 pkgList.add(deletedPackage.applicationInfo.packageName); 14259 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14260 } 14261 14262 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14263 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14264 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14265 14266 try { 14267 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14268 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14269 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14270 14271 // Update the in-memory copy of the previous code paths. 14272 PackageSetting ps = mSettings.mPackages.get(pkgName); 14273 if (!killApp) { 14274 if (ps.oldCodePaths == null) { 14275 ps.oldCodePaths = new ArraySet<>(); 14276 } 14277 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14278 if (deletedPackage.splitCodePaths != null) { 14279 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14280 } 14281 } else { 14282 ps.oldCodePaths = null; 14283 } 14284 if (ps.childPackageNames != null) { 14285 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14286 final String childPkgName = ps.childPackageNames.get(i); 14287 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14288 childPs.oldCodePaths = ps.oldCodePaths; 14289 } 14290 } 14291 prepareAppDataAfterInstallLIF(newPackage); 14292 addedPkg = true; 14293 } catch (PackageManagerException e) { 14294 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14295 } 14296 } 14297 14298 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14299 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14300 14301 // Revert all internal state mutations and added folders for the failed install 14302 if (addedPkg) { 14303 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14304 res.removedInfo, true, null); 14305 } 14306 14307 // Restore the old package 14308 if (deletedPkg) { 14309 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14310 File restoreFile = new File(deletedPackage.codePath); 14311 // Parse old package 14312 boolean oldExternal = isExternal(deletedPackage); 14313 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14314 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14315 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14316 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14317 try { 14318 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14319 null); 14320 } catch (PackageManagerException e) { 14321 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14322 + e.getMessage()); 14323 return; 14324 } 14325 14326 synchronized (mPackages) { 14327 // Ensure the installer package name up to date 14328 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14329 14330 // Update permissions for restored package 14331 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14332 14333 mSettings.writeLPr(); 14334 } 14335 14336 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14337 } 14338 } else { 14339 synchronized (mPackages) { 14340 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14341 if (ps != null) { 14342 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14343 if (res.removedInfo.removedChildPackages != null) { 14344 final int childCount = res.removedInfo.removedChildPackages.size(); 14345 // Iterate in reverse as we may modify the collection 14346 for (int i = childCount - 1; i >= 0; i--) { 14347 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14348 if (res.addedChildPackages.containsKey(childPackageName)) { 14349 res.removedInfo.removedChildPackages.removeAt(i); 14350 } else { 14351 PackageRemovedInfo childInfo = res.removedInfo 14352 .removedChildPackages.valueAt(i); 14353 childInfo.removedForAllUsers = mPackages.get( 14354 childInfo.removedPackage) == null; 14355 } 14356 } 14357 } 14358 } 14359 } 14360 } 14361 } 14362 14363 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14364 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14365 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14366 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14367 + ", old=" + deletedPackage); 14368 14369 final boolean disabledSystem; 14370 14371 // Remove existing system package 14372 removePackageLI(deletedPackage, true); 14373 14374 synchronized (mPackages) { 14375 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14376 } 14377 if (!disabledSystem) { 14378 // We didn't need to disable the .apk as a current system package, 14379 // which means we are replacing another update that is already 14380 // installed. We need to make sure to delete the older one's .apk. 14381 res.removedInfo.args = createInstallArgsForExisting(0, 14382 deletedPackage.applicationInfo.getCodePath(), 14383 deletedPackage.applicationInfo.getResourcePath(), 14384 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14385 } else { 14386 res.removedInfo.args = null; 14387 } 14388 14389 // Successfully disabled the old package. Now proceed with re-installation 14390 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14391 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14392 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14393 14394 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14395 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14396 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14397 14398 PackageParser.Package newPackage = null; 14399 try { 14400 // Add the package to the internal data structures 14401 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14402 14403 // Set the update and install times 14404 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14405 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14406 System.currentTimeMillis()); 14407 14408 // Update the package dynamic state if succeeded 14409 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14410 // Now that the install succeeded make sure we remove data 14411 // directories for any child package the update removed. 14412 final int deletedChildCount = (deletedPackage.childPackages != null) 14413 ? deletedPackage.childPackages.size() : 0; 14414 final int newChildCount = (newPackage.childPackages != null) 14415 ? newPackage.childPackages.size() : 0; 14416 for (int i = 0; i < deletedChildCount; i++) { 14417 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14418 boolean childPackageDeleted = true; 14419 for (int j = 0; j < newChildCount; j++) { 14420 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14421 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14422 childPackageDeleted = false; 14423 break; 14424 } 14425 } 14426 if (childPackageDeleted) { 14427 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14428 deletedChildPkg.packageName); 14429 if (ps != null && res.removedInfo.removedChildPackages != null) { 14430 PackageRemovedInfo removedChildRes = res.removedInfo 14431 .removedChildPackages.get(deletedChildPkg.packageName); 14432 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14433 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14434 } 14435 } 14436 } 14437 14438 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14439 prepareAppDataAfterInstallLIF(newPackage); 14440 } 14441 } catch (PackageManagerException e) { 14442 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14443 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14444 } 14445 14446 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14447 // Re installation failed. Restore old information 14448 // Remove new pkg information 14449 if (newPackage != null) { 14450 removeInstalledPackageLI(newPackage, true); 14451 } 14452 // Add back the old system package 14453 try { 14454 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14455 } catch (PackageManagerException e) { 14456 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14457 } 14458 14459 synchronized (mPackages) { 14460 if (disabledSystem) { 14461 enableSystemPackageLPw(deletedPackage); 14462 } 14463 14464 // Ensure the installer package name up to date 14465 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14466 14467 // Update permissions for restored package 14468 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14469 14470 mSettings.writeLPr(); 14471 } 14472 14473 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14474 + " after failed upgrade"); 14475 } 14476 } 14477 14478 /** 14479 * Checks whether the parent or any of the child packages have a change shared 14480 * user. For a package to be a valid update the shred users of the parent and 14481 * the children should match. We may later support changing child shared users. 14482 * @param oldPkg The updated package. 14483 * @param newPkg The update package. 14484 * @return The shared user that change between the versions. 14485 */ 14486 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14487 PackageParser.Package newPkg) { 14488 // Check parent shared user 14489 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14490 return newPkg.packageName; 14491 } 14492 // Check child shared users 14493 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14494 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14495 for (int i = 0; i < newChildCount; i++) { 14496 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14497 // If this child was present, did it have the same shared user? 14498 for (int j = 0; j < oldChildCount; j++) { 14499 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14500 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14501 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14502 return newChildPkg.packageName; 14503 } 14504 } 14505 } 14506 return null; 14507 } 14508 14509 private void removeNativeBinariesLI(PackageSetting ps) { 14510 // Remove the lib path for the parent package 14511 if (ps != null) { 14512 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14513 // Remove the lib path for the child packages 14514 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14515 for (int i = 0; i < childCount; i++) { 14516 PackageSetting childPs = null; 14517 synchronized (mPackages) { 14518 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14519 } 14520 if (childPs != null) { 14521 NativeLibraryHelper.removeNativeBinariesLI(childPs 14522 .legacyNativeLibraryPathString); 14523 } 14524 } 14525 } 14526 } 14527 14528 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14529 // Enable the parent package 14530 mSettings.enableSystemPackageLPw(pkg.packageName); 14531 // Enable the child packages 14532 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14533 for (int i = 0; i < childCount; i++) { 14534 PackageParser.Package childPkg = pkg.childPackages.get(i); 14535 mSettings.enableSystemPackageLPw(childPkg.packageName); 14536 } 14537 } 14538 14539 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14540 PackageParser.Package newPkg) { 14541 // Disable the parent package (parent always replaced) 14542 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14543 // Disable the child packages 14544 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14545 for (int i = 0; i < childCount; i++) { 14546 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14547 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14548 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14549 } 14550 return disabled; 14551 } 14552 14553 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14554 String installerPackageName) { 14555 // Enable the parent package 14556 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14557 // Enable the child packages 14558 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14559 for (int i = 0; i < childCount; i++) { 14560 PackageParser.Package childPkg = pkg.childPackages.get(i); 14561 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14562 } 14563 } 14564 14565 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14566 // Collect all used permissions in the UID 14567 ArraySet<String> usedPermissions = new ArraySet<>(); 14568 final int packageCount = su.packages.size(); 14569 for (int i = 0; i < packageCount; i++) { 14570 PackageSetting ps = su.packages.valueAt(i); 14571 if (ps.pkg == null) { 14572 continue; 14573 } 14574 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14575 for (int j = 0; j < requestedPermCount; j++) { 14576 String permission = ps.pkg.requestedPermissions.get(j); 14577 BasePermission bp = mSettings.mPermissions.get(permission); 14578 if (bp != null) { 14579 usedPermissions.add(permission); 14580 } 14581 } 14582 } 14583 14584 PermissionsState permissionsState = su.getPermissionsState(); 14585 // Prune install permissions 14586 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14587 final int installPermCount = installPermStates.size(); 14588 for (int i = installPermCount - 1; i >= 0; i--) { 14589 PermissionState permissionState = installPermStates.get(i); 14590 if (!usedPermissions.contains(permissionState.getName())) { 14591 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14592 if (bp != null) { 14593 permissionsState.revokeInstallPermission(bp); 14594 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14595 PackageManager.MASK_PERMISSION_FLAGS, 0); 14596 } 14597 } 14598 } 14599 14600 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14601 14602 // Prune runtime permissions 14603 for (int userId : allUserIds) { 14604 List<PermissionState> runtimePermStates = permissionsState 14605 .getRuntimePermissionStates(userId); 14606 final int runtimePermCount = runtimePermStates.size(); 14607 for (int i = runtimePermCount - 1; i >= 0; i--) { 14608 PermissionState permissionState = runtimePermStates.get(i); 14609 if (!usedPermissions.contains(permissionState.getName())) { 14610 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14611 if (bp != null) { 14612 permissionsState.revokeRuntimePermission(bp, userId); 14613 permissionsState.updatePermissionFlags(bp, userId, 14614 PackageManager.MASK_PERMISSION_FLAGS, 0); 14615 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14616 runtimePermissionChangedUserIds, userId); 14617 } 14618 } 14619 } 14620 } 14621 14622 return runtimePermissionChangedUserIds; 14623 } 14624 14625 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14626 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14627 // Update the parent package setting 14628 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14629 res, user); 14630 // Update the child packages setting 14631 final int childCount = (newPackage.childPackages != null) 14632 ? newPackage.childPackages.size() : 0; 14633 for (int i = 0; i < childCount; i++) { 14634 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14635 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14636 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14637 childRes.origUsers, childRes, user); 14638 } 14639 } 14640 14641 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14642 String installerPackageName, int[] allUsers, int[] installedForUsers, 14643 PackageInstalledInfo res, UserHandle user) { 14644 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14645 14646 String pkgName = newPackage.packageName; 14647 synchronized (mPackages) { 14648 //write settings. the installStatus will be incomplete at this stage. 14649 //note that the new package setting would have already been 14650 //added to mPackages. It hasn't been persisted yet. 14651 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14653 mSettings.writeLPr(); 14654 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14655 } 14656 14657 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14658 synchronized (mPackages) { 14659 updatePermissionsLPw(newPackage.packageName, newPackage, 14660 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14661 ? UPDATE_PERMISSIONS_ALL : 0)); 14662 // For system-bundled packages, we assume that installing an upgraded version 14663 // of the package implies that the user actually wants to run that new code, 14664 // so we enable the package. 14665 PackageSetting ps = mSettings.mPackages.get(pkgName); 14666 final int userId = user.getIdentifier(); 14667 if (ps != null) { 14668 if (isSystemApp(newPackage)) { 14669 if (DEBUG_INSTALL) { 14670 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14671 } 14672 // Enable system package for requested users 14673 if (res.origUsers != null) { 14674 for (int origUserId : res.origUsers) { 14675 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14676 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14677 origUserId, installerPackageName); 14678 } 14679 } 14680 } 14681 // Also convey the prior install/uninstall state 14682 if (allUsers != null && installedForUsers != null) { 14683 for (int currentUserId : allUsers) { 14684 final boolean installed = ArrayUtils.contains( 14685 installedForUsers, currentUserId); 14686 if (DEBUG_INSTALL) { 14687 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14688 } 14689 ps.setInstalled(installed, currentUserId); 14690 } 14691 // these install state changes will be persisted in the 14692 // upcoming call to mSettings.writeLPr(). 14693 } 14694 } 14695 // It's implied that when a user requests installation, they want the app to be 14696 // installed and enabled. 14697 if (userId != UserHandle.USER_ALL) { 14698 ps.setInstalled(true, userId); 14699 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14700 } 14701 } 14702 res.name = pkgName; 14703 res.uid = newPackage.applicationInfo.uid; 14704 res.pkg = newPackage; 14705 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14706 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14707 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14708 //to update install status 14709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14710 mSettings.writeLPr(); 14711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14712 } 14713 14714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14715 } 14716 14717 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14718 try { 14719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14720 installPackageLI(args, res); 14721 } finally { 14722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14723 } 14724 } 14725 14726 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14727 final int installFlags = args.installFlags; 14728 final String installerPackageName = args.installerPackageName; 14729 final String volumeUuid = args.volumeUuid; 14730 final File tmpPackageFile = new File(args.getCodePath()); 14731 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14732 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14733 || (args.volumeUuid != null)); 14734 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14735 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14736 boolean replace = false; 14737 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14738 if (args.move != null) { 14739 // moving a complete application; perform an initial scan on the new install location 14740 scanFlags |= SCAN_INITIAL; 14741 } 14742 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14743 scanFlags |= SCAN_DONT_KILL_APP; 14744 } 14745 14746 // Result object to be returned 14747 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14748 14749 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14750 14751 // Sanity check 14752 if (ephemeral && (forwardLocked || onExternal)) { 14753 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14754 + " external=" + onExternal); 14755 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14756 return; 14757 } 14758 14759 // Retrieve PackageSettings and parse package 14760 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14761 | PackageParser.PARSE_ENFORCE_CODE 14762 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14763 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14764 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14765 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14766 PackageParser pp = new PackageParser(); 14767 pp.setSeparateProcesses(mSeparateProcesses); 14768 pp.setDisplayMetrics(mMetrics); 14769 14770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14771 final PackageParser.Package pkg; 14772 try { 14773 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14774 } catch (PackageParserException e) { 14775 res.setError("Failed parse during installPackageLI", e); 14776 return; 14777 } finally { 14778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14779 } 14780 14781 // If we are installing a clustered package add results for the children 14782 if (pkg.childPackages != null) { 14783 synchronized (mPackages) { 14784 final int childCount = pkg.childPackages.size(); 14785 for (int i = 0; i < childCount; i++) { 14786 PackageParser.Package childPkg = pkg.childPackages.get(i); 14787 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14788 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14789 childRes.pkg = childPkg; 14790 childRes.name = childPkg.packageName; 14791 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14792 if (childPs != null) { 14793 childRes.origUsers = childPs.queryInstalledUsers( 14794 sUserManager.getUserIds(), true); 14795 } 14796 if ((mPackages.containsKey(childPkg.packageName))) { 14797 childRes.removedInfo = new PackageRemovedInfo(); 14798 childRes.removedInfo.removedPackage = childPkg.packageName; 14799 } 14800 if (res.addedChildPackages == null) { 14801 res.addedChildPackages = new ArrayMap<>(); 14802 } 14803 res.addedChildPackages.put(childPkg.packageName, childRes); 14804 } 14805 } 14806 } 14807 14808 // If package doesn't declare API override, mark that we have an install 14809 // time CPU ABI override. 14810 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14811 pkg.cpuAbiOverride = args.abiOverride; 14812 } 14813 14814 String pkgName = res.name = pkg.packageName; 14815 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14816 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14817 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14818 return; 14819 } 14820 } 14821 14822 try { 14823 // either use what we've been given or parse directly from the APK 14824 if (args.certificates != null) { 14825 try { 14826 PackageParser.populateCertificates(pkg, args.certificates); 14827 } catch (PackageParserException e) { 14828 // there was something wrong with the certificates we were given; 14829 // try to pull them from the APK 14830 PackageParser.collectCertificates(pkg, parseFlags); 14831 } 14832 } else { 14833 PackageParser.collectCertificates(pkg, parseFlags); 14834 } 14835 } catch (PackageParserException e) { 14836 res.setError("Failed collect during installPackageLI", e); 14837 return; 14838 } 14839 14840 // Get rid of all references to package scan path via parser. 14841 pp = null; 14842 String oldCodePath = null; 14843 boolean systemApp = false; 14844 synchronized (mPackages) { 14845 // Check if installing already existing package 14846 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14847 String oldName = mSettings.mRenamedPackages.get(pkgName); 14848 if (pkg.mOriginalPackages != null 14849 && pkg.mOriginalPackages.contains(oldName) 14850 && mPackages.containsKey(oldName)) { 14851 // This package is derived from an original package, 14852 // and this device has been updating from that original 14853 // name. We must continue using the original name, so 14854 // rename the new package here. 14855 pkg.setPackageName(oldName); 14856 pkgName = pkg.packageName; 14857 replace = true; 14858 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14859 + oldName + " pkgName=" + pkgName); 14860 } else if (mPackages.containsKey(pkgName)) { 14861 // This package, under its official name, already exists 14862 // on the device; we should replace it. 14863 replace = true; 14864 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14865 } 14866 14867 // Child packages are installed through the parent package 14868 if (pkg.parentPackage != null) { 14869 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14870 "Package " + pkg.packageName + " is child of package " 14871 + pkg.parentPackage.parentPackage + ". Child packages " 14872 + "can be updated only through the parent package."); 14873 return; 14874 } 14875 14876 if (replace) { 14877 // Prevent apps opting out from runtime permissions 14878 PackageParser.Package oldPackage = mPackages.get(pkgName); 14879 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14880 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14881 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14882 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14883 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14884 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14885 + " doesn't support runtime permissions but the old" 14886 + " target SDK " + oldTargetSdk + " does."); 14887 return; 14888 } 14889 14890 // Prevent installing of child packages 14891 if (oldPackage.parentPackage != null) { 14892 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14893 "Package " + pkg.packageName + " is child of package " 14894 + oldPackage.parentPackage + ". Child packages " 14895 + "can be updated only through the parent package."); 14896 return; 14897 } 14898 } 14899 } 14900 14901 PackageSetting ps = mSettings.mPackages.get(pkgName); 14902 if (ps != null) { 14903 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14904 14905 // Quick sanity check that we're signed correctly if updating; 14906 // we'll check this again later when scanning, but we want to 14907 // bail early here before tripping over redefined permissions. 14908 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14909 if (!checkUpgradeKeySetLP(ps, pkg)) { 14910 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14911 + pkg.packageName + " upgrade keys do not match the " 14912 + "previously installed version"); 14913 return; 14914 } 14915 } else { 14916 try { 14917 verifySignaturesLP(ps, pkg); 14918 } catch (PackageManagerException e) { 14919 res.setError(e.error, e.getMessage()); 14920 return; 14921 } 14922 } 14923 14924 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14925 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14926 systemApp = (ps.pkg.applicationInfo.flags & 14927 ApplicationInfo.FLAG_SYSTEM) != 0; 14928 } 14929 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14930 } 14931 14932 // Check whether the newly-scanned package wants to define an already-defined perm 14933 int N = pkg.permissions.size(); 14934 for (int i = N-1; i >= 0; i--) { 14935 PackageParser.Permission perm = pkg.permissions.get(i); 14936 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14937 if (bp != null) { 14938 // If the defining package is signed with our cert, it's okay. This 14939 // also includes the "updating the same package" case, of course. 14940 // "updating same package" could also involve key-rotation. 14941 final boolean sigsOk; 14942 if (bp.sourcePackage.equals(pkg.packageName) 14943 && (bp.packageSetting instanceof PackageSetting) 14944 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14945 scanFlags))) { 14946 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14947 } else { 14948 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14949 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14950 } 14951 if (!sigsOk) { 14952 // If the owning package is the system itself, we log but allow 14953 // install to proceed; we fail the install on all other permission 14954 // redefinitions. 14955 if (!bp.sourcePackage.equals("android")) { 14956 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14957 + pkg.packageName + " attempting to redeclare permission " 14958 + perm.info.name + " already owned by " + bp.sourcePackage); 14959 res.origPermission = perm.info.name; 14960 res.origPackage = bp.sourcePackage; 14961 return; 14962 } else { 14963 Slog.w(TAG, "Package " + pkg.packageName 14964 + " attempting to redeclare system permission " 14965 + perm.info.name + "; ignoring new declaration"); 14966 pkg.permissions.remove(i); 14967 } 14968 } 14969 } 14970 } 14971 } 14972 14973 if (systemApp) { 14974 if (onExternal) { 14975 // Abort update; system app can't be replaced with app on sdcard 14976 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14977 "Cannot install updates to system apps on sdcard"); 14978 return; 14979 } else if (ephemeral) { 14980 // Abort update; system app can't be replaced with an ephemeral app 14981 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14982 "Cannot update a system app with an ephemeral app"); 14983 return; 14984 } 14985 } 14986 14987 if (args.move != null) { 14988 // We did an in-place move, so dex is ready to roll 14989 scanFlags |= SCAN_NO_DEX; 14990 scanFlags |= SCAN_MOVE; 14991 14992 synchronized (mPackages) { 14993 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14994 if (ps == null) { 14995 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14996 "Missing settings for moved package " + pkgName); 14997 } 14998 14999 // We moved the entire application as-is, so bring over the 15000 // previously derived ABI information. 15001 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15002 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15003 } 15004 15005 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15006 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15007 scanFlags |= SCAN_NO_DEX; 15008 15009 try { 15010 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15011 args.abiOverride : pkg.cpuAbiOverride); 15012 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15013 true /* extract libs */); 15014 } catch (PackageManagerException pme) { 15015 Slog.e(TAG, "Error deriving application ABI", pme); 15016 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15017 return; 15018 } 15019 15020 // Shared libraries for the package need to be updated. 15021 synchronized (mPackages) { 15022 try { 15023 updateSharedLibrariesLPw(pkg, null); 15024 } catch (PackageManagerException e) { 15025 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15026 } 15027 } 15028 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15029 // Do not run PackageDexOptimizer through the local performDexOpt 15030 // method because `pkg` may not be in `mPackages` yet. 15031 // 15032 // Also, don't fail application installs if the dexopt step fails. 15033 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15034 null /* instructionSets */, false /* checkProfiles */, 15035 getCompilerFilterForReason(REASON_INSTALL), 15036 getOrCreateCompilerPackageStats(pkg)); 15037 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15038 15039 // Notify BackgroundDexOptService that the package has been changed. 15040 // If this is an update of a package which used to fail to compile, 15041 // BDOS will remove it from its blacklist. 15042 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15043 } 15044 15045 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15046 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15047 return; 15048 } 15049 15050 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15051 15052 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15053 "installPackageLI")) { 15054 if (replace) { 15055 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15056 installerPackageName, res); 15057 } else { 15058 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15059 args.user, installerPackageName, volumeUuid, res); 15060 } 15061 } 15062 synchronized (mPackages) { 15063 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15064 if (ps != null) { 15065 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15066 } 15067 15068 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15069 for (int i = 0; i < childCount; i++) { 15070 PackageParser.Package childPkg = pkg.childPackages.get(i); 15071 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15072 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15073 if (childPs != null) { 15074 childRes.newUsers = childPs.queryInstalledUsers( 15075 sUserManager.getUserIds(), true); 15076 } 15077 } 15078 } 15079 } 15080 15081 private void startIntentFilterVerifications(int userId, boolean replacing, 15082 PackageParser.Package pkg) { 15083 if (mIntentFilterVerifierComponent == null) { 15084 Slog.w(TAG, "No IntentFilter verification will not be done as " 15085 + "there is no IntentFilterVerifier available!"); 15086 return; 15087 } 15088 15089 final int verifierUid = getPackageUid( 15090 mIntentFilterVerifierComponent.getPackageName(), 15091 MATCH_DEBUG_TRIAGED_MISSING, 15092 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15093 15094 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15095 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15096 mHandler.sendMessage(msg); 15097 15098 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15099 for (int i = 0; i < childCount; i++) { 15100 PackageParser.Package childPkg = pkg.childPackages.get(i); 15101 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15102 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15103 mHandler.sendMessage(msg); 15104 } 15105 } 15106 15107 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15108 PackageParser.Package pkg) { 15109 int size = pkg.activities.size(); 15110 if (size == 0) { 15111 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15112 "No activity, so no need to verify any IntentFilter!"); 15113 return; 15114 } 15115 15116 final boolean hasDomainURLs = hasDomainURLs(pkg); 15117 if (!hasDomainURLs) { 15118 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15119 "No domain URLs, so no need to verify any IntentFilter!"); 15120 return; 15121 } 15122 15123 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15124 + " if any IntentFilter from the " + size 15125 + " Activities needs verification ..."); 15126 15127 int count = 0; 15128 final String packageName = pkg.packageName; 15129 15130 synchronized (mPackages) { 15131 // If this is a new install and we see that we've already run verification for this 15132 // package, we have nothing to do: it means the state was restored from backup. 15133 if (!replacing) { 15134 IntentFilterVerificationInfo ivi = 15135 mSettings.getIntentFilterVerificationLPr(packageName); 15136 if (ivi != null) { 15137 if (DEBUG_DOMAIN_VERIFICATION) { 15138 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15139 + ivi.getStatusString()); 15140 } 15141 return; 15142 } 15143 } 15144 15145 // If any filters need to be verified, then all need to be. 15146 boolean needToVerify = false; 15147 for (PackageParser.Activity a : pkg.activities) { 15148 for (ActivityIntentInfo filter : a.intents) { 15149 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15150 if (DEBUG_DOMAIN_VERIFICATION) { 15151 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15152 } 15153 needToVerify = true; 15154 break; 15155 } 15156 } 15157 } 15158 15159 if (needToVerify) { 15160 final int verificationId = mIntentFilterVerificationToken++; 15161 for (PackageParser.Activity a : pkg.activities) { 15162 for (ActivityIntentInfo filter : a.intents) { 15163 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15164 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15165 "Verification needed for IntentFilter:" + filter.toString()); 15166 mIntentFilterVerifier.addOneIntentFilterVerification( 15167 verifierUid, userId, verificationId, filter, packageName); 15168 count++; 15169 } 15170 } 15171 } 15172 } 15173 } 15174 15175 if (count > 0) { 15176 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15177 + " IntentFilter verification" + (count > 1 ? "s" : "") 15178 + " for userId:" + userId); 15179 mIntentFilterVerifier.startVerifications(userId); 15180 } else { 15181 if (DEBUG_DOMAIN_VERIFICATION) { 15182 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15183 } 15184 } 15185 } 15186 15187 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15188 final ComponentName cn = filter.activity.getComponentName(); 15189 final String packageName = cn.getPackageName(); 15190 15191 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15192 packageName); 15193 if (ivi == null) { 15194 return true; 15195 } 15196 int status = ivi.getStatus(); 15197 switch (status) { 15198 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15199 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15200 return true; 15201 15202 default: 15203 // Nothing to do 15204 return false; 15205 } 15206 } 15207 15208 private static boolean isMultiArch(ApplicationInfo info) { 15209 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15210 } 15211 15212 private static boolean isExternal(PackageParser.Package pkg) { 15213 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15214 } 15215 15216 private static boolean isExternal(PackageSetting ps) { 15217 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15218 } 15219 15220 private static boolean isEphemeral(PackageParser.Package pkg) { 15221 return pkg.applicationInfo.isEphemeralApp(); 15222 } 15223 15224 private static boolean isEphemeral(PackageSetting ps) { 15225 return ps.pkg != null && isEphemeral(ps.pkg); 15226 } 15227 15228 private static boolean isSystemApp(PackageParser.Package pkg) { 15229 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15230 } 15231 15232 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15233 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15234 } 15235 15236 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15237 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15238 } 15239 15240 private static boolean isSystemApp(PackageSetting ps) { 15241 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15242 } 15243 15244 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15245 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15246 } 15247 15248 private int packageFlagsToInstallFlags(PackageSetting ps) { 15249 int installFlags = 0; 15250 if (isEphemeral(ps)) { 15251 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15252 } 15253 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15254 // This existing package was an external ASEC install when we have 15255 // the external flag without a UUID 15256 installFlags |= PackageManager.INSTALL_EXTERNAL; 15257 } 15258 if (ps.isForwardLocked()) { 15259 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15260 } 15261 return installFlags; 15262 } 15263 15264 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15265 if (isExternal(pkg)) { 15266 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15267 return StorageManager.UUID_PRIMARY_PHYSICAL; 15268 } else { 15269 return pkg.volumeUuid; 15270 } 15271 } else { 15272 return StorageManager.UUID_PRIVATE_INTERNAL; 15273 } 15274 } 15275 15276 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15277 if (isExternal(pkg)) { 15278 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15279 return mSettings.getExternalVersion(); 15280 } else { 15281 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15282 } 15283 } else { 15284 return mSettings.getInternalVersion(); 15285 } 15286 } 15287 15288 private void deleteTempPackageFiles() { 15289 final FilenameFilter filter = new FilenameFilter() { 15290 public boolean accept(File dir, String name) { 15291 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15292 } 15293 }; 15294 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15295 file.delete(); 15296 } 15297 } 15298 15299 @Override 15300 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15301 int flags) { 15302 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15303 flags); 15304 } 15305 15306 @Override 15307 public void deletePackage(final String packageName, 15308 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15309 mContext.enforceCallingOrSelfPermission( 15310 android.Manifest.permission.DELETE_PACKAGES, null); 15311 Preconditions.checkNotNull(packageName); 15312 Preconditions.checkNotNull(observer); 15313 final int uid = Binder.getCallingUid(); 15314 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15315 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15316 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15317 mContext.enforceCallingOrSelfPermission( 15318 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15319 "deletePackage for user " + userId); 15320 } 15321 15322 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15323 try { 15324 observer.onPackageDeleted(packageName, 15325 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15326 } catch (RemoteException re) { 15327 } 15328 return; 15329 } 15330 15331 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15332 try { 15333 observer.onPackageDeleted(packageName, 15334 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15335 } catch (RemoteException re) { 15336 } 15337 return; 15338 } 15339 15340 if (DEBUG_REMOVE) { 15341 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15342 + " deleteAllUsers: " + deleteAllUsers ); 15343 } 15344 // Queue up an async operation since the package deletion may take a little while. 15345 mHandler.post(new Runnable() { 15346 public void run() { 15347 mHandler.removeCallbacks(this); 15348 int returnCode; 15349 if (!deleteAllUsers) { 15350 returnCode = deletePackageX(packageName, userId, deleteFlags); 15351 } else { 15352 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15353 // If nobody is blocking uninstall, proceed with delete for all users 15354 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15355 returnCode = deletePackageX(packageName, userId, deleteFlags); 15356 } else { 15357 // Otherwise uninstall individually for users with blockUninstalls=false 15358 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15359 for (int userId : users) { 15360 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15361 returnCode = deletePackageX(packageName, userId, userFlags); 15362 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15363 Slog.w(TAG, "Package delete failed for user " + userId 15364 + ", returnCode " + returnCode); 15365 } 15366 } 15367 } 15368 // The app has only been marked uninstalled for certain users. 15369 // We still need to report that delete was blocked 15370 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15371 } 15372 } 15373 try { 15374 observer.onPackageDeleted(packageName, returnCode, null); 15375 } catch (RemoteException e) { 15376 Log.i(TAG, "Observer no longer exists."); 15377 } //end catch 15378 } //end run 15379 }); 15380 } 15381 15382 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15383 int[] result = EMPTY_INT_ARRAY; 15384 for (int userId : userIds) { 15385 if (getBlockUninstallForUser(packageName, userId)) { 15386 result = ArrayUtils.appendInt(result, userId); 15387 } 15388 } 15389 return result; 15390 } 15391 15392 @Override 15393 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15394 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15395 } 15396 15397 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15398 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15399 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15400 try { 15401 if (dpm != null) { 15402 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15403 /* callingUserOnly =*/ false); 15404 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15405 : deviceOwnerComponentName.getPackageName(); 15406 // Does the package contains the device owner? 15407 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15408 // this check is probably not needed, since DO should be registered as a device 15409 // admin on some user too. (Original bug for this: b/17657954) 15410 if (packageName.equals(deviceOwnerPackageName)) { 15411 return true; 15412 } 15413 // Does it contain a device admin for any user? 15414 int[] users; 15415 if (userId == UserHandle.USER_ALL) { 15416 users = sUserManager.getUserIds(); 15417 } else { 15418 users = new int[]{userId}; 15419 } 15420 for (int i = 0; i < users.length; ++i) { 15421 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15422 return true; 15423 } 15424 } 15425 } 15426 } catch (RemoteException e) { 15427 } 15428 return false; 15429 } 15430 15431 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15432 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15433 } 15434 15435 /** 15436 * This method is an internal method that could be get invoked either 15437 * to delete an installed package or to clean up a failed installation. 15438 * After deleting an installed package, a broadcast is sent to notify any 15439 * listeners that the package has been removed. For cleaning up a failed 15440 * installation, the broadcast is not necessary since the package's 15441 * installation wouldn't have sent the initial broadcast either 15442 * The key steps in deleting a package are 15443 * deleting the package information in internal structures like mPackages, 15444 * deleting the packages base directories through installd 15445 * updating mSettings to reflect current status 15446 * persisting settings for later use 15447 * sending a broadcast if necessary 15448 */ 15449 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15450 final PackageRemovedInfo info = new PackageRemovedInfo(); 15451 final boolean res; 15452 15453 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15454 ? UserHandle.USER_ALL : userId; 15455 15456 if (isPackageDeviceAdmin(packageName, removeUser)) { 15457 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15458 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15459 } 15460 15461 PackageSetting uninstalledPs = null; 15462 15463 // for the uninstall-updates case and restricted profiles, remember the per- 15464 // user handle installed state 15465 int[] allUsers; 15466 synchronized (mPackages) { 15467 uninstalledPs = mSettings.mPackages.get(packageName); 15468 if (uninstalledPs == null) { 15469 Slog.w(TAG, "Not removing non-existent package " + packageName); 15470 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15471 } 15472 allUsers = sUserManager.getUserIds(); 15473 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15474 } 15475 15476 final int freezeUser; 15477 if (isUpdatedSystemApp(uninstalledPs) 15478 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15479 // We're downgrading a system app, which will apply to all users, so 15480 // freeze them all during the downgrade 15481 freezeUser = UserHandle.USER_ALL; 15482 } else { 15483 freezeUser = removeUser; 15484 } 15485 15486 synchronized (mInstallLock) { 15487 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15488 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15489 deleteFlags, "deletePackageX")) { 15490 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15491 deleteFlags | REMOVE_CHATTY, info, true, null); 15492 } 15493 synchronized (mPackages) { 15494 if (res) { 15495 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15496 } 15497 } 15498 } 15499 15500 if (res) { 15501 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15502 info.sendPackageRemovedBroadcasts(killApp); 15503 info.sendSystemPackageUpdatedBroadcasts(); 15504 info.sendSystemPackageAppearedBroadcasts(); 15505 } 15506 // Force a gc here. 15507 Runtime.getRuntime().gc(); 15508 // Delete the resources here after sending the broadcast to let 15509 // other processes clean up before deleting resources. 15510 if (info.args != null) { 15511 synchronized (mInstallLock) { 15512 info.args.doPostDeleteLI(true); 15513 } 15514 } 15515 15516 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15517 } 15518 15519 class PackageRemovedInfo { 15520 String removedPackage; 15521 int uid = -1; 15522 int removedAppId = -1; 15523 int[] origUsers; 15524 int[] removedUsers = null; 15525 boolean isRemovedPackageSystemUpdate = false; 15526 boolean isUpdate; 15527 boolean dataRemoved; 15528 boolean removedForAllUsers; 15529 // Clean up resources deleted packages. 15530 InstallArgs args = null; 15531 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15532 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15533 15534 void sendPackageRemovedBroadcasts(boolean killApp) { 15535 sendPackageRemovedBroadcastInternal(killApp); 15536 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15537 for (int i = 0; i < childCount; i++) { 15538 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15539 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15540 } 15541 } 15542 15543 void sendSystemPackageUpdatedBroadcasts() { 15544 if (isRemovedPackageSystemUpdate) { 15545 sendSystemPackageUpdatedBroadcastsInternal(); 15546 final int childCount = (removedChildPackages != null) 15547 ? removedChildPackages.size() : 0; 15548 for (int i = 0; i < childCount; i++) { 15549 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15550 if (childInfo.isRemovedPackageSystemUpdate) { 15551 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15552 } 15553 } 15554 } 15555 } 15556 15557 void sendSystemPackageAppearedBroadcasts() { 15558 final int packageCount = (appearedChildPackages != null) 15559 ? appearedChildPackages.size() : 0; 15560 for (int i = 0; i < packageCount; i++) { 15561 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15562 for (int userId : installedInfo.newUsers) { 15563 sendPackageAddedForUser(installedInfo.name, true, 15564 UserHandle.getAppId(installedInfo.uid), userId); 15565 } 15566 } 15567 } 15568 15569 private void sendSystemPackageUpdatedBroadcastsInternal() { 15570 Bundle extras = new Bundle(2); 15571 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15572 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15573 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15574 extras, 0, null, null, null); 15575 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15576 extras, 0, null, null, null); 15577 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15578 null, 0, removedPackage, null, null); 15579 } 15580 15581 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15582 Bundle extras = new Bundle(2); 15583 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15584 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15585 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15586 if (isUpdate || isRemovedPackageSystemUpdate) { 15587 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15588 } 15589 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15590 if (removedPackage != null) { 15591 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15592 extras, 0, null, null, removedUsers); 15593 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15594 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15595 removedPackage, extras, 0, null, null, removedUsers); 15596 } 15597 } 15598 if (removedAppId >= 0) { 15599 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15600 removedUsers); 15601 } 15602 } 15603 } 15604 15605 /* 15606 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15607 * flag is not set, the data directory is removed as well. 15608 * make sure this flag is set for partially installed apps. If not its meaningless to 15609 * delete a partially installed application. 15610 */ 15611 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15612 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15613 String packageName = ps.name; 15614 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15615 // Retrieve object to delete permissions for shared user later on 15616 final PackageParser.Package deletedPkg; 15617 final PackageSetting deletedPs; 15618 // reader 15619 synchronized (mPackages) { 15620 deletedPkg = mPackages.get(packageName); 15621 deletedPs = mSettings.mPackages.get(packageName); 15622 if (outInfo != null) { 15623 outInfo.removedPackage = packageName; 15624 outInfo.removedUsers = deletedPs != null 15625 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15626 : null; 15627 } 15628 } 15629 15630 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15631 15632 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15633 final PackageParser.Package resolvedPkg; 15634 if (deletedPkg != null) { 15635 resolvedPkg = deletedPkg; 15636 } else { 15637 // We don't have a parsed package when it lives on an ejected 15638 // adopted storage device, so fake something together 15639 resolvedPkg = new PackageParser.Package(ps.name); 15640 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15641 } 15642 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15643 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15644 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15645 if (outInfo != null) { 15646 outInfo.dataRemoved = true; 15647 } 15648 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15649 } 15650 15651 // writer 15652 synchronized (mPackages) { 15653 if (deletedPs != null) { 15654 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15655 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15656 clearDefaultBrowserIfNeeded(packageName); 15657 if (outInfo != null) { 15658 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15659 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15660 } 15661 updatePermissionsLPw(deletedPs.name, null, 0); 15662 if (deletedPs.sharedUser != null) { 15663 // Remove permissions associated with package. Since runtime 15664 // permissions are per user we have to kill the removed package 15665 // or packages running under the shared user of the removed 15666 // package if revoking the permissions requested only by the removed 15667 // package is successful and this causes a change in gids. 15668 for (int userId : UserManagerService.getInstance().getUserIds()) { 15669 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15670 userId); 15671 if (userIdToKill == UserHandle.USER_ALL 15672 || userIdToKill >= UserHandle.USER_SYSTEM) { 15673 // If gids changed for this user, kill all affected packages. 15674 mHandler.post(new Runnable() { 15675 @Override 15676 public void run() { 15677 // This has to happen with no lock held. 15678 killApplication(deletedPs.name, deletedPs.appId, 15679 KILL_APP_REASON_GIDS_CHANGED); 15680 } 15681 }); 15682 break; 15683 } 15684 } 15685 } 15686 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15687 } 15688 // make sure to preserve per-user disabled state if this removal was just 15689 // a downgrade of a system app to the factory package 15690 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15691 if (DEBUG_REMOVE) { 15692 Slog.d(TAG, "Propagating install state across downgrade"); 15693 } 15694 for (int userId : allUserHandles) { 15695 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15696 if (DEBUG_REMOVE) { 15697 Slog.d(TAG, " user " + userId + " => " + installed); 15698 } 15699 ps.setInstalled(installed, userId); 15700 } 15701 } 15702 } 15703 // can downgrade to reader 15704 if (writeSettings) { 15705 // Save settings now 15706 mSettings.writeLPr(); 15707 } 15708 } 15709 if (outInfo != null) { 15710 // A user ID was deleted here. Go through all users and remove it 15711 // from KeyStore. 15712 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15713 } 15714 } 15715 15716 static boolean locationIsPrivileged(File path) { 15717 try { 15718 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15719 .getCanonicalPath(); 15720 return path.getCanonicalPath().startsWith(privilegedAppDir); 15721 } catch (IOException e) { 15722 Slog.e(TAG, "Unable to access code path " + path); 15723 } 15724 return false; 15725 } 15726 15727 /* 15728 * Tries to delete system package. 15729 */ 15730 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15731 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15732 boolean writeSettings) { 15733 if (deletedPs.parentPackageName != null) { 15734 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15735 return false; 15736 } 15737 15738 final boolean applyUserRestrictions 15739 = (allUserHandles != null) && (outInfo.origUsers != null); 15740 final PackageSetting disabledPs; 15741 // Confirm if the system package has been updated 15742 // An updated system app can be deleted. This will also have to restore 15743 // the system pkg from system partition 15744 // reader 15745 synchronized (mPackages) { 15746 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15747 } 15748 15749 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15750 + " disabledPs=" + disabledPs); 15751 15752 if (disabledPs == null) { 15753 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15754 return false; 15755 } else if (DEBUG_REMOVE) { 15756 Slog.d(TAG, "Deleting system pkg from data partition"); 15757 } 15758 15759 if (DEBUG_REMOVE) { 15760 if (applyUserRestrictions) { 15761 Slog.d(TAG, "Remembering install states:"); 15762 for (int userId : allUserHandles) { 15763 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15764 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15765 } 15766 } 15767 } 15768 15769 // Delete the updated package 15770 outInfo.isRemovedPackageSystemUpdate = true; 15771 if (outInfo.removedChildPackages != null) { 15772 final int childCount = (deletedPs.childPackageNames != null) 15773 ? deletedPs.childPackageNames.size() : 0; 15774 for (int i = 0; i < childCount; i++) { 15775 String childPackageName = deletedPs.childPackageNames.get(i); 15776 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15777 .contains(childPackageName)) { 15778 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15779 childPackageName); 15780 if (childInfo != null) { 15781 childInfo.isRemovedPackageSystemUpdate = true; 15782 } 15783 } 15784 } 15785 } 15786 15787 if (disabledPs.versionCode < deletedPs.versionCode) { 15788 // Delete data for downgrades 15789 flags &= ~PackageManager.DELETE_KEEP_DATA; 15790 } else { 15791 // Preserve data by setting flag 15792 flags |= PackageManager.DELETE_KEEP_DATA; 15793 } 15794 15795 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15796 outInfo, writeSettings, disabledPs.pkg); 15797 if (!ret) { 15798 return false; 15799 } 15800 15801 // writer 15802 synchronized (mPackages) { 15803 // Reinstate the old system package 15804 enableSystemPackageLPw(disabledPs.pkg); 15805 // Remove any native libraries from the upgraded package. 15806 removeNativeBinariesLI(deletedPs); 15807 } 15808 15809 // Install the system package 15810 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15811 int parseFlags = mDefParseFlags 15812 | PackageParser.PARSE_MUST_BE_APK 15813 | PackageParser.PARSE_IS_SYSTEM 15814 | PackageParser.PARSE_IS_SYSTEM_DIR; 15815 if (locationIsPrivileged(disabledPs.codePath)) { 15816 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15817 } 15818 15819 final PackageParser.Package newPkg; 15820 try { 15821 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15822 } catch (PackageManagerException e) { 15823 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15824 + e.getMessage()); 15825 return false; 15826 } 15827 15828 prepareAppDataAfterInstallLIF(newPkg); 15829 15830 // writer 15831 synchronized (mPackages) { 15832 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15833 15834 // Propagate the permissions state as we do not want to drop on the floor 15835 // runtime permissions. The update permissions method below will take 15836 // care of removing obsolete permissions and grant install permissions. 15837 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15838 updatePermissionsLPw(newPkg.packageName, newPkg, 15839 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15840 15841 if (applyUserRestrictions) { 15842 if (DEBUG_REMOVE) { 15843 Slog.d(TAG, "Propagating install state across reinstall"); 15844 } 15845 for (int userId : allUserHandles) { 15846 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15847 if (DEBUG_REMOVE) { 15848 Slog.d(TAG, " user " + userId + " => " + installed); 15849 } 15850 ps.setInstalled(installed, userId); 15851 15852 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15853 } 15854 // Regardless of writeSettings we need to ensure that this restriction 15855 // state propagation is persisted 15856 mSettings.writeAllUsersPackageRestrictionsLPr(); 15857 } 15858 // can downgrade to reader here 15859 if (writeSettings) { 15860 mSettings.writeLPr(); 15861 } 15862 } 15863 return true; 15864 } 15865 15866 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15867 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15868 PackageRemovedInfo outInfo, boolean writeSettings, 15869 PackageParser.Package replacingPackage) { 15870 synchronized (mPackages) { 15871 if (outInfo != null) { 15872 outInfo.uid = ps.appId; 15873 } 15874 15875 if (outInfo != null && outInfo.removedChildPackages != null) { 15876 final int childCount = (ps.childPackageNames != null) 15877 ? ps.childPackageNames.size() : 0; 15878 for (int i = 0; i < childCount; i++) { 15879 String childPackageName = ps.childPackageNames.get(i); 15880 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15881 if (childPs == null) { 15882 return false; 15883 } 15884 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15885 childPackageName); 15886 if (childInfo != null) { 15887 childInfo.uid = childPs.appId; 15888 } 15889 } 15890 } 15891 } 15892 15893 // Delete package data from internal structures and also remove data if flag is set 15894 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15895 15896 // Delete the child packages data 15897 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15898 for (int i = 0; i < childCount; i++) { 15899 PackageSetting childPs; 15900 synchronized (mPackages) { 15901 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15902 } 15903 if (childPs != null) { 15904 PackageRemovedInfo childOutInfo = (outInfo != null 15905 && outInfo.removedChildPackages != null) 15906 ? outInfo.removedChildPackages.get(childPs.name) : null; 15907 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15908 && (replacingPackage != null 15909 && !replacingPackage.hasChildPackage(childPs.name)) 15910 ? flags & ~DELETE_KEEP_DATA : flags; 15911 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15912 deleteFlags, writeSettings); 15913 } 15914 } 15915 15916 // Delete application code and resources only for parent packages 15917 if (ps.parentPackageName == null) { 15918 if (deleteCodeAndResources && (outInfo != null)) { 15919 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15920 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15921 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15922 } 15923 } 15924 15925 return true; 15926 } 15927 15928 @Override 15929 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15930 int userId) { 15931 mContext.enforceCallingOrSelfPermission( 15932 android.Manifest.permission.DELETE_PACKAGES, null); 15933 synchronized (mPackages) { 15934 PackageSetting ps = mSettings.mPackages.get(packageName); 15935 if (ps == null) { 15936 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15937 return false; 15938 } 15939 if (!ps.getInstalled(userId)) { 15940 // Can't block uninstall for an app that is not installed or enabled. 15941 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15942 return false; 15943 } 15944 ps.setBlockUninstall(blockUninstall, userId); 15945 mSettings.writePackageRestrictionsLPr(userId); 15946 } 15947 return true; 15948 } 15949 15950 @Override 15951 public boolean getBlockUninstallForUser(String packageName, int userId) { 15952 synchronized (mPackages) { 15953 PackageSetting ps = mSettings.mPackages.get(packageName); 15954 if (ps == null) { 15955 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15956 return false; 15957 } 15958 return ps.getBlockUninstall(userId); 15959 } 15960 } 15961 15962 @Override 15963 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15964 int callingUid = Binder.getCallingUid(); 15965 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15966 throw new SecurityException( 15967 "setRequiredForSystemUser can only be run by the system or root"); 15968 } 15969 synchronized (mPackages) { 15970 PackageSetting ps = mSettings.mPackages.get(packageName); 15971 if (ps == null) { 15972 Log.w(TAG, "Package doesn't exist: " + packageName); 15973 return false; 15974 } 15975 if (systemUserApp) { 15976 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15977 } else { 15978 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15979 } 15980 mSettings.writeLPr(); 15981 } 15982 return true; 15983 } 15984 15985 /* 15986 * This method handles package deletion in general 15987 */ 15988 private boolean deletePackageLIF(String packageName, UserHandle user, 15989 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15990 PackageRemovedInfo outInfo, boolean writeSettings, 15991 PackageParser.Package replacingPackage) { 15992 if (packageName == null) { 15993 Slog.w(TAG, "Attempt to delete null packageName."); 15994 return false; 15995 } 15996 15997 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15998 15999 PackageSetting ps; 16000 16001 synchronized (mPackages) { 16002 ps = mSettings.mPackages.get(packageName); 16003 if (ps == null) { 16004 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16005 return false; 16006 } 16007 16008 if (ps.parentPackageName != null && (!isSystemApp(ps) 16009 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16010 if (DEBUG_REMOVE) { 16011 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16012 + ((user == null) ? UserHandle.USER_ALL : user)); 16013 } 16014 final int removedUserId = (user != null) ? user.getIdentifier() 16015 : UserHandle.USER_ALL; 16016 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16017 return false; 16018 } 16019 markPackageUninstalledForUserLPw(ps, user); 16020 scheduleWritePackageRestrictionsLocked(user); 16021 return true; 16022 } 16023 } 16024 16025 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16026 && user.getIdentifier() != UserHandle.USER_ALL)) { 16027 // The caller is asking that the package only be deleted for a single 16028 // user. To do this, we just mark its uninstalled state and delete 16029 // its data. If this is a system app, we only allow this to happen if 16030 // they have set the special DELETE_SYSTEM_APP which requests different 16031 // semantics than normal for uninstalling system apps. 16032 markPackageUninstalledForUserLPw(ps, user); 16033 16034 if (!isSystemApp(ps)) { 16035 // Do not uninstall the APK if an app should be cached 16036 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16037 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16038 // Other user still have this package installed, so all 16039 // we need to do is clear this user's data and save that 16040 // it is uninstalled. 16041 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16042 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16043 return false; 16044 } 16045 scheduleWritePackageRestrictionsLocked(user); 16046 return true; 16047 } else { 16048 // We need to set it back to 'installed' so the uninstall 16049 // broadcasts will be sent correctly. 16050 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16051 ps.setInstalled(true, user.getIdentifier()); 16052 } 16053 } else { 16054 // This is a system app, so we assume that the 16055 // other users still have this package installed, so all 16056 // we need to do is clear this user's data and save that 16057 // it is uninstalled. 16058 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16059 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16060 return false; 16061 } 16062 scheduleWritePackageRestrictionsLocked(user); 16063 return true; 16064 } 16065 } 16066 16067 // If we are deleting a composite package for all users, keep track 16068 // of result for each child. 16069 if (ps.childPackageNames != null && outInfo != null) { 16070 synchronized (mPackages) { 16071 final int childCount = ps.childPackageNames.size(); 16072 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16073 for (int i = 0; i < childCount; i++) { 16074 String childPackageName = ps.childPackageNames.get(i); 16075 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16076 childInfo.removedPackage = childPackageName; 16077 outInfo.removedChildPackages.put(childPackageName, childInfo); 16078 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16079 if (childPs != null) { 16080 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16081 } 16082 } 16083 } 16084 } 16085 16086 boolean ret = false; 16087 if (isSystemApp(ps)) { 16088 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16089 // When an updated system application is deleted we delete the existing resources 16090 // as well and fall back to existing code in system partition 16091 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16092 } else { 16093 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16094 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16095 outInfo, writeSettings, replacingPackage); 16096 } 16097 16098 // Take a note whether we deleted the package for all users 16099 if (outInfo != null) { 16100 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16101 if (outInfo.removedChildPackages != null) { 16102 synchronized (mPackages) { 16103 final int childCount = outInfo.removedChildPackages.size(); 16104 for (int i = 0; i < childCount; i++) { 16105 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16106 if (childInfo != null) { 16107 childInfo.removedForAllUsers = mPackages.get( 16108 childInfo.removedPackage) == null; 16109 } 16110 } 16111 } 16112 } 16113 // If we uninstalled an update to a system app there may be some 16114 // child packages that appeared as they are declared in the system 16115 // app but were not declared in the update. 16116 if (isSystemApp(ps)) { 16117 synchronized (mPackages) { 16118 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16119 final int childCount = (updatedPs.childPackageNames != null) 16120 ? updatedPs.childPackageNames.size() : 0; 16121 for (int i = 0; i < childCount; i++) { 16122 String childPackageName = updatedPs.childPackageNames.get(i); 16123 if (outInfo.removedChildPackages == null 16124 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16125 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16126 if (childPs == null) { 16127 continue; 16128 } 16129 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16130 installRes.name = childPackageName; 16131 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16132 installRes.pkg = mPackages.get(childPackageName); 16133 installRes.uid = childPs.pkg.applicationInfo.uid; 16134 if (outInfo.appearedChildPackages == null) { 16135 outInfo.appearedChildPackages = new ArrayMap<>(); 16136 } 16137 outInfo.appearedChildPackages.put(childPackageName, installRes); 16138 } 16139 } 16140 } 16141 } 16142 } 16143 16144 return ret; 16145 } 16146 16147 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16148 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16149 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16150 for (int nextUserId : userIds) { 16151 if (DEBUG_REMOVE) { 16152 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16153 } 16154 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16155 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16156 false /*hidden*/, false /*suspended*/, null, null, null, 16157 false /*blockUninstall*/, 16158 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16159 } 16160 } 16161 16162 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16163 PackageRemovedInfo outInfo) { 16164 final PackageParser.Package pkg; 16165 synchronized (mPackages) { 16166 pkg = mPackages.get(ps.name); 16167 } 16168 16169 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16170 : new int[] {userId}; 16171 for (int nextUserId : userIds) { 16172 if (DEBUG_REMOVE) { 16173 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16174 + nextUserId); 16175 } 16176 16177 destroyAppDataLIF(pkg, userId, 16178 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16179 destroyAppProfilesLIF(pkg, userId); 16180 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16181 schedulePackageCleaning(ps.name, nextUserId, false); 16182 synchronized (mPackages) { 16183 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16184 scheduleWritePackageRestrictionsLocked(nextUserId); 16185 } 16186 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16187 } 16188 } 16189 16190 if (outInfo != null) { 16191 outInfo.removedPackage = ps.name; 16192 outInfo.removedAppId = ps.appId; 16193 outInfo.removedUsers = userIds; 16194 } 16195 16196 return true; 16197 } 16198 16199 private final class ClearStorageConnection implements ServiceConnection { 16200 IMediaContainerService mContainerService; 16201 16202 @Override 16203 public void onServiceConnected(ComponentName name, IBinder service) { 16204 synchronized (this) { 16205 mContainerService = IMediaContainerService.Stub.asInterface(service); 16206 notifyAll(); 16207 } 16208 } 16209 16210 @Override 16211 public void onServiceDisconnected(ComponentName name) { 16212 } 16213 } 16214 16215 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16216 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16217 16218 final boolean mounted; 16219 if (Environment.isExternalStorageEmulated()) { 16220 mounted = true; 16221 } else { 16222 final String status = Environment.getExternalStorageState(); 16223 16224 mounted = status.equals(Environment.MEDIA_MOUNTED) 16225 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16226 } 16227 16228 if (!mounted) { 16229 return; 16230 } 16231 16232 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16233 int[] users; 16234 if (userId == UserHandle.USER_ALL) { 16235 users = sUserManager.getUserIds(); 16236 } else { 16237 users = new int[] { userId }; 16238 } 16239 final ClearStorageConnection conn = new ClearStorageConnection(); 16240 if (mContext.bindServiceAsUser( 16241 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16242 try { 16243 for (int curUser : users) { 16244 long timeout = SystemClock.uptimeMillis() + 5000; 16245 synchronized (conn) { 16246 long now; 16247 while (conn.mContainerService == null && 16248 (now = SystemClock.uptimeMillis()) < timeout) { 16249 try { 16250 conn.wait(timeout - now); 16251 } catch (InterruptedException e) { 16252 } 16253 } 16254 } 16255 if (conn.mContainerService == null) { 16256 return; 16257 } 16258 16259 final UserEnvironment userEnv = new UserEnvironment(curUser); 16260 clearDirectory(conn.mContainerService, 16261 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16262 if (allData) { 16263 clearDirectory(conn.mContainerService, 16264 userEnv.buildExternalStorageAppDataDirs(packageName)); 16265 clearDirectory(conn.mContainerService, 16266 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16267 } 16268 } 16269 } finally { 16270 mContext.unbindService(conn); 16271 } 16272 } 16273 } 16274 16275 @Override 16276 public void clearApplicationProfileData(String packageName) { 16277 enforceSystemOrRoot("Only the system can clear all profile data"); 16278 16279 final PackageParser.Package pkg; 16280 synchronized (mPackages) { 16281 pkg = mPackages.get(packageName); 16282 } 16283 16284 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16285 synchronized (mInstallLock) { 16286 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16287 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16288 true /* removeBaseMarker */); 16289 } 16290 } 16291 } 16292 16293 @Override 16294 public void clearApplicationUserData(final String packageName, 16295 final IPackageDataObserver observer, final int userId) { 16296 mContext.enforceCallingOrSelfPermission( 16297 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16298 16299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16300 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16301 16302 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16303 throw new SecurityException("Cannot clear data for a protected package: " 16304 + packageName); 16305 } 16306 // Queue up an async operation since the package deletion may take a little while. 16307 mHandler.post(new Runnable() { 16308 public void run() { 16309 mHandler.removeCallbacks(this); 16310 final boolean succeeded; 16311 try (PackageFreezer freezer = freezePackage(packageName, 16312 "clearApplicationUserData")) { 16313 synchronized (mInstallLock) { 16314 succeeded = clearApplicationUserDataLIF(packageName, userId); 16315 } 16316 clearExternalStorageDataSync(packageName, userId, true); 16317 } 16318 if (succeeded) { 16319 // invoke DeviceStorageMonitor's update method to clear any notifications 16320 DeviceStorageMonitorInternal dsm = LocalServices 16321 .getService(DeviceStorageMonitorInternal.class); 16322 if (dsm != null) { 16323 dsm.checkMemory(); 16324 } 16325 } 16326 if(observer != null) { 16327 try { 16328 observer.onRemoveCompleted(packageName, succeeded); 16329 } catch (RemoteException e) { 16330 Log.i(TAG, "Observer no longer exists."); 16331 } 16332 } //end if observer 16333 } //end run 16334 }); 16335 } 16336 16337 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16338 if (packageName == null) { 16339 Slog.w(TAG, "Attempt to delete null packageName."); 16340 return false; 16341 } 16342 16343 // Try finding details about the requested package 16344 PackageParser.Package pkg; 16345 synchronized (mPackages) { 16346 pkg = mPackages.get(packageName); 16347 if (pkg == null) { 16348 final PackageSetting ps = mSettings.mPackages.get(packageName); 16349 if (ps != null) { 16350 pkg = ps.pkg; 16351 } 16352 } 16353 16354 if (pkg == null) { 16355 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16356 return false; 16357 } 16358 16359 PackageSetting ps = (PackageSetting) pkg.mExtras; 16360 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16361 } 16362 16363 clearAppDataLIF(pkg, userId, 16364 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16365 16366 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16367 removeKeystoreDataIfNeeded(userId, appId); 16368 16369 UserManagerInternal umInternal = getUserManagerInternal(); 16370 final int flags; 16371 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16372 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16373 } else if (umInternal.isUserRunning(userId)) { 16374 flags = StorageManager.FLAG_STORAGE_DE; 16375 } else { 16376 flags = 0; 16377 } 16378 prepareAppDataContentsLIF(pkg, userId, flags); 16379 16380 return true; 16381 } 16382 16383 /** 16384 * Reverts user permission state changes (permissions and flags) in 16385 * all packages for a given user. 16386 * 16387 * @param userId The device user for which to do a reset. 16388 */ 16389 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16390 final int packageCount = mPackages.size(); 16391 for (int i = 0; i < packageCount; i++) { 16392 PackageParser.Package pkg = mPackages.valueAt(i); 16393 PackageSetting ps = (PackageSetting) pkg.mExtras; 16394 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16395 } 16396 } 16397 16398 private void resetNetworkPolicies(int userId) { 16399 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16400 } 16401 16402 /** 16403 * Reverts user permission state changes (permissions and flags). 16404 * 16405 * @param ps The package for which to reset. 16406 * @param userId The device user for which to do a reset. 16407 */ 16408 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16409 final PackageSetting ps, final int userId) { 16410 if (ps.pkg == null) { 16411 return; 16412 } 16413 16414 // These are flags that can change base on user actions. 16415 final int userSettableMask = FLAG_PERMISSION_USER_SET 16416 | FLAG_PERMISSION_USER_FIXED 16417 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16418 | FLAG_PERMISSION_REVIEW_REQUIRED; 16419 16420 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16421 | FLAG_PERMISSION_POLICY_FIXED; 16422 16423 boolean writeInstallPermissions = false; 16424 boolean writeRuntimePermissions = false; 16425 16426 final int permissionCount = ps.pkg.requestedPermissions.size(); 16427 for (int i = 0; i < permissionCount; i++) { 16428 String permission = ps.pkg.requestedPermissions.get(i); 16429 16430 BasePermission bp = mSettings.mPermissions.get(permission); 16431 if (bp == null) { 16432 continue; 16433 } 16434 16435 // If shared user we just reset the state to which only this app contributed. 16436 if (ps.sharedUser != null) { 16437 boolean used = false; 16438 final int packageCount = ps.sharedUser.packages.size(); 16439 for (int j = 0; j < packageCount; j++) { 16440 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16441 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16442 && pkg.pkg.requestedPermissions.contains(permission)) { 16443 used = true; 16444 break; 16445 } 16446 } 16447 if (used) { 16448 continue; 16449 } 16450 } 16451 16452 PermissionsState permissionsState = ps.getPermissionsState(); 16453 16454 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16455 16456 // Always clear the user settable flags. 16457 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16458 bp.name) != null; 16459 // If permission review is enabled and this is a legacy app, mark the 16460 // permission as requiring a review as this is the initial state. 16461 int flags = 0; 16462 if (Build.PERMISSIONS_REVIEW_REQUIRED 16463 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16464 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16465 } 16466 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16467 if (hasInstallState) { 16468 writeInstallPermissions = true; 16469 } else { 16470 writeRuntimePermissions = true; 16471 } 16472 } 16473 16474 // Below is only runtime permission handling. 16475 if (!bp.isRuntime()) { 16476 continue; 16477 } 16478 16479 // Never clobber system or policy. 16480 if ((oldFlags & policyOrSystemFlags) != 0) { 16481 continue; 16482 } 16483 16484 // If this permission was granted by default, make sure it is. 16485 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16486 if (permissionsState.grantRuntimePermission(bp, userId) 16487 != PERMISSION_OPERATION_FAILURE) { 16488 writeRuntimePermissions = true; 16489 } 16490 // If permission review is enabled the permissions for a legacy apps 16491 // are represented as constantly granted runtime ones, so don't revoke. 16492 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16493 // Otherwise, reset the permission. 16494 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16495 switch (revokeResult) { 16496 case PERMISSION_OPERATION_SUCCESS: 16497 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16498 writeRuntimePermissions = true; 16499 final int appId = ps.appId; 16500 mHandler.post(new Runnable() { 16501 @Override 16502 public void run() { 16503 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16504 } 16505 }); 16506 } break; 16507 } 16508 } 16509 } 16510 16511 // Synchronously write as we are taking permissions away. 16512 if (writeRuntimePermissions) { 16513 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16514 } 16515 16516 // Synchronously write as we are taking permissions away. 16517 if (writeInstallPermissions) { 16518 mSettings.writeLPr(); 16519 } 16520 } 16521 16522 /** 16523 * Remove entries from the keystore daemon. Will only remove it if the 16524 * {@code appId} is valid. 16525 */ 16526 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16527 if (appId < 0) { 16528 return; 16529 } 16530 16531 final KeyStore keyStore = KeyStore.getInstance(); 16532 if (keyStore != null) { 16533 if (userId == UserHandle.USER_ALL) { 16534 for (final int individual : sUserManager.getUserIds()) { 16535 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16536 } 16537 } else { 16538 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16539 } 16540 } else { 16541 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16542 } 16543 } 16544 16545 @Override 16546 public void deleteApplicationCacheFiles(final String packageName, 16547 final IPackageDataObserver observer) { 16548 final int userId = UserHandle.getCallingUserId(); 16549 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16550 } 16551 16552 @Override 16553 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16554 final IPackageDataObserver observer) { 16555 mContext.enforceCallingOrSelfPermission( 16556 android.Manifest.permission.DELETE_CACHE_FILES, null); 16557 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16558 /* requireFullPermission= */ true, /* checkShell= */ false, 16559 "delete application cache files"); 16560 16561 final PackageParser.Package pkg; 16562 synchronized (mPackages) { 16563 pkg = mPackages.get(packageName); 16564 } 16565 16566 // Queue up an async operation since the package deletion may take a little while. 16567 mHandler.post(new Runnable() { 16568 public void run() { 16569 synchronized (mInstallLock) { 16570 final int flags = StorageManager.FLAG_STORAGE_DE 16571 | StorageManager.FLAG_STORAGE_CE; 16572 // We're only clearing cache files, so we don't care if the 16573 // app is unfrozen and still able to run 16574 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16575 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16576 } 16577 clearExternalStorageDataSync(packageName, userId, false); 16578 if (observer != null) { 16579 try { 16580 observer.onRemoveCompleted(packageName, true); 16581 } catch (RemoteException e) { 16582 Log.i(TAG, "Observer no longer exists."); 16583 } 16584 } 16585 } 16586 }); 16587 } 16588 16589 @Override 16590 public void getPackageSizeInfo(final String packageName, int userHandle, 16591 final IPackageStatsObserver observer) { 16592 mContext.enforceCallingOrSelfPermission( 16593 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16594 if (packageName == null) { 16595 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16596 } 16597 16598 PackageStats stats = new PackageStats(packageName, userHandle); 16599 16600 /* 16601 * Queue up an async operation since the package measurement may take a 16602 * little while. 16603 */ 16604 Message msg = mHandler.obtainMessage(INIT_COPY); 16605 msg.obj = new MeasureParams(stats, observer); 16606 mHandler.sendMessage(msg); 16607 } 16608 16609 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16610 final PackageSetting ps; 16611 synchronized (mPackages) { 16612 ps = mSettings.mPackages.get(packageName); 16613 if (ps == null) { 16614 Slog.w(TAG, "Failed to find settings for " + packageName); 16615 return false; 16616 } 16617 } 16618 try { 16619 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16620 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16621 ps.getCeDataInode(userId), ps.codePathString, stats); 16622 } catch (InstallerException e) { 16623 Slog.w(TAG, String.valueOf(e)); 16624 return false; 16625 } 16626 16627 // For now, ignore code size of packages on system partition 16628 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16629 stats.codeSize = 0; 16630 } 16631 16632 return true; 16633 } 16634 16635 private int getUidTargetSdkVersionLockedLPr(int uid) { 16636 Object obj = mSettings.getUserIdLPr(uid); 16637 if (obj instanceof SharedUserSetting) { 16638 final SharedUserSetting sus = (SharedUserSetting) obj; 16639 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16640 final Iterator<PackageSetting> it = sus.packages.iterator(); 16641 while (it.hasNext()) { 16642 final PackageSetting ps = it.next(); 16643 if (ps.pkg != null) { 16644 int v = ps.pkg.applicationInfo.targetSdkVersion; 16645 if (v < vers) vers = v; 16646 } 16647 } 16648 return vers; 16649 } else if (obj instanceof PackageSetting) { 16650 final PackageSetting ps = (PackageSetting) obj; 16651 if (ps.pkg != null) { 16652 return ps.pkg.applicationInfo.targetSdkVersion; 16653 } 16654 } 16655 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16656 } 16657 16658 @Override 16659 public void addPreferredActivity(IntentFilter filter, int match, 16660 ComponentName[] set, ComponentName activity, int userId) { 16661 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16662 "Adding preferred"); 16663 } 16664 16665 private void addPreferredActivityInternal(IntentFilter filter, int match, 16666 ComponentName[] set, ComponentName activity, boolean always, int userId, 16667 String opname) { 16668 // writer 16669 int callingUid = Binder.getCallingUid(); 16670 enforceCrossUserPermission(callingUid, userId, 16671 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16672 if (filter.countActions() == 0) { 16673 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16674 return; 16675 } 16676 synchronized (mPackages) { 16677 if (mContext.checkCallingOrSelfPermission( 16678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16679 != PackageManager.PERMISSION_GRANTED) { 16680 if (getUidTargetSdkVersionLockedLPr(callingUid) 16681 < Build.VERSION_CODES.FROYO) { 16682 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16683 + callingUid); 16684 return; 16685 } 16686 mContext.enforceCallingOrSelfPermission( 16687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16688 } 16689 16690 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16691 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16692 + userId + ":"); 16693 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16694 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16695 scheduleWritePackageRestrictionsLocked(userId); 16696 postPreferredActivityChangedBroadcast(userId); 16697 } 16698 } 16699 16700 private void postPreferredActivityChangedBroadcast(int userId) { 16701 mHandler.post(() -> { 16702 final IActivityManager am = ActivityManagerNative.getDefault(); 16703 if (am == null) { 16704 return; 16705 } 16706 16707 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16708 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16709 try { 16710 am.broadcastIntent(null, intent, null, null, 16711 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16712 null, false, false, userId); 16713 } catch (RemoteException e) { 16714 } 16715 }); 16716 } 16717 16718 @Override 16719 public void replacePreferredActivity(IntentFilter filter, int match, 16720 ComponentName[] set, ComponentName activity, int userId) { 16721 if (filter.countActions() != 1) { 16722 throw new IllegalArgumentException( 16723 "replacePreferredActivity expects filter to have only 1 action."); 16724 } 16725 if (filter.countDataAuthorities() != 0 16726 || filter.countDataPaths() != 0 16727 || filter.countDataSchemes() > 1 16728 || filter.countDataTypes() != 0) { 16729 throw new IllegalArgumentException( 16730 "replacePreferredActivity expects filter to have no data authorities, " + 16731 "paths, or types; and at most one scheme."); 16732 } 16733 16734 final int callingUid = Binder.getCallingUid(); 16735 enforceCrossUserPermission(callingUid, userId, 16736 true /* requireFullPermission */, false /* checkShell */, 16737 "replace preferred activity"); 16738 synchronized (mPackages) { 16739 if (mContext.checkCallingOrSelfPermission( 16740 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16741 != PackageManager.PERMISSION_GRANTED) { 16742 if (getUidTargetSdkVersionLockedLPr(callingUid) 16743 < Build.VERSION_CODES.FROYO) { 16744 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16745 + Binder.getCallingUid()); 16746 return; 16747 } 16748 mContext.enforceCallingOrSelfPermission( 16749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16750 } 16751 16752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16753 if (pir != null) { 16754 // Get all of the existing entries that exactly match this filter. 16755 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16756 if (existing != null && existing.size() == 1) { 16757 PreferredActivity cur = existing.get(0); 16758 if (DEBUG_PREFERRED) { 16759 Slog.i(TAG, "Checking replace of preferred:"); 16760 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16761 if (!cur.mPref.mAlways) { 16762 Slog.i(TAG, " -- CUR; not mAlways!"); 16763 } else { 16764 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16765 Slog.i(TAG, " -- CUR: mSet=" 16766 + Arrays.toString(cur.mPref.mSetComponents)); 16767 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16768 Slog.i(TAG, " -- NEW: mMatch=" 16769 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16770 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16771 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16772 } 16773 } 16774 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16775 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16776 && cur.mPref.sameSet(set)) { 16777 // Setting the preferred activity to what it happens to be already 16778 if (DEBUG_PREFERRED) { 16779 Slog.i(TAG, "Replacing with same preferred activity " 16780 + cur.mPref.mShortComponent + " for user " 16781 + userId + ":"); 16782 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16783 } 16784 return; 16785 } 16786 } 16787 16788 if (existing != null) { 16789 if (DEBUG_PREFERRED) { 16790 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16791 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16792 } 16793 for (int i = 0; i < existing.size(); i++) { 16794 PreferredActivity pa = existing.get(i); 16795 if (DEBUG_PREFERRED) { 16796 Slog.i(TAG, "Removing existing preferred activity " 16797 + pa.mPref.mComponent + ":"); 16798 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16799 } 16800 pir.removeFilter(pa); 16801 } 16802 } 16803 } 16804 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16805 "Replacing preferred"); 16806 } 16807 } 16808 16809 @Override 16810 public void clearPackagePreferredActivities(String packageName) { 16811 final int uid = Binder.getCallingUid(); 16812 // writer 16813 synchronized (mPackages) { 16814 PackageParser.Package pkg = mPackages.get(packageName); 16815 if (pkg == null || pkg.applicationInfo.uid != uid) { 16816 if (mContext.checkCallingOrSelfPermission( 16817 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16818 != PackageManager.PERMISSION_GRANTED) { 16819 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16820 < Build.VERSION_CODES.FROYO) { 16821 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16822 + Binder.getCallingUid()); 16823 return; 16824 } 16825 mContext.enforceCallingOrSelfPermission( 16826 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16827 } 16828 } 16829 16830 int user = UserHandle.getCallingUserId(); 16831 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16832 scheduleWritePackageRestrictionsLocked(user); 16833 } 16834 } 16835 } 16836 16837 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16838 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16839 ArrayList<PreferredActivity> removed = null; 16840 boolean changed = false; 16841 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16842 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16843 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16844 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16845 continue; 16846 } 16847 Iterator<PreferredActivity> it = pir.filterIterator(); 16848 while (it.hasNext()) { 16849 PreferredActivity pa = it.next(); 16850 // Mark entry for removal only if it matches the package name 16851 // and the entry is of type "always". 16852 if (packageName == null || 16853 (pa.mPref.mComponent.getPackageName().equals(packageName) 16854 && pa.mPref.mAlways)) { 16855 if (removed == null) { 16856 removed = new ArrayList<PreferredActivity>(); 16857 } 16858 removed.add(pa); 16859 } 16860 } 16861 if (removed != null) { 16862 for (int j=0; j<removed.size(); j++) { 16863 PreferredActivity pa = removed.get(j); 16864 pir.removeFilter(pa); 16865 } 16866 changed = true; 16867 } 16868 } 16869 if (changed) { 16870 postPreferredActivityChangedBroadcast(userId); 16871 } 16872 return changed; 16873 } 16874 16875 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16876 private void clearIntentFilterVerificationsLPw(int userId) { 16877 final int packageCount = mPackages.size(); 16878 for (int i = 0; i < packageCount; i++) { 16879 PackageParser.Package pkg = mPackages.valueAt(i); 16880 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16881 } 16882 } 16883 16884 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16885 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16886 if (userId == UserHandle.USER_ALL) { 16887 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16888 sUserManager.getUserIds())) { 16889 for (int oneUserId : sUserManager.getUserIds()) { 16890 scheduleWritePackageRestrictionsLocked(oneUserId); 16891 } 16892 } 16893 } else { 16894 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16895 scheduleWritePackageRestrictionsLocked(userId); 16896 } 16897 } 16898 } 16899 16900 void clearDefaultBrowserIfNeeded(String packageName) { 16901 for (int oneUserId : sUserManager.getUserIds()) { 16902 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16903 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16904 if (packageName.equals(defaultBrowserPackageName)) { 16905 setDefaultBrowserPackageName(null, oneUserId); 16906 } 16907 } 16908 } 16909 16910 @Override 16911 public void resetApplicationPreferences(int userId) { 16912 mContext.enforceCallingOrSelfPermission( 16913 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16914 final long identity = Binder.clearCallingIdentity(); 16915 // writer 16916 try { 16917 synchronized (mPackages) { 16918 clearPackagePreferredActivitiesLPw(null, userId); 16919 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16920 // TODO: We have to reset the default SMS and Phone. This requires 16921 // significant refactoring to keep all default apps in the package 16922 // manager (cleaner but more work) or have the services provide 16923 // callbacks to the package manager to request a default app reset. 16924 applyFactoryDefaultBrowserLPw(userId); 16925 clearIntentFilterVerificationsLPw(userId); 16926 primeDomainVerificationsLPw(userId); 16927 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16928 scheduleWritePackageRestrictionsLocked(userId); 16929 } 16930 resetNetworkPolicies(userId); 16931 } finally { 16932 Binder.restoreCallingIdentity(identity); 16933 } 16934 } 16935 16936 @Override 16937 public int getPreferredActivities(List<IntentFilter> outFilters, 16938 List<ComponentName> outActivities, String packageName) { 16939 16940 int num = 0; 16941 final int userId = UserHandle.getCallingUserId(); 16942 // reader 16943 synchronized (mPackages) { 16944 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16945 if (pir != null) { 16946 final Iterator<PreferredActivity> it = pir.filterIterator(); 16947 while (it.hasNext()) { 16948 final PreferredActivity pa = it.next(); 16949 if (packageName == null 16950 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16951 && pa.mPref.mAlways)) { 16952 if (outFilters != null) { 16953 outFilters.add(new IntentFilter(pa)); 16954 } 16955 if (outActivities != null) { 16956 outActivities.add(pa.mPref.mComponent); 16957 } 16958 } 16959 } 16960 } 16961 } 16962 16963 return num; 16964 } 16965 16966 @Override 16967 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16968 int userId) { 16969 int callingUid = Binder.getCallingUid(); 16970 if (callingUid != Process.SYSTEM_UID) { 16971 throw new SecurityException( 16972 "addPersistentPreferredActivity can only be run by the system"); 16973 } 16974 if (filter.countActions() == 0) { 16975 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16976 return; 16977 } 16978 synchronized (mPackages) { 16979 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16980 ":"); 16981 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16982 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16983 new PersistentPreferredActivity(filter, activity)); 16984 scheduleWritePackageRestrictionsLocked(userId); 16985 postPreferredActivityChangedBroadcast(userId); 16986 } 16987 } 16988 16989 @Override 16990 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16991 int callingUid = Binder.getCallingUid(); 16992 if (callingUid != Process.SYSTEM_UID) { 16993 throw new SecurityException( 16994 "clearPackagePersistentPreferredActivities can only be run by the system"); 16995 } 16996 ArrayList<PersistentPreferredActivity> removed = null; 16997 boolean changed = false; 16998 synchronized (mPackages) { 16999 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17000 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17001 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17002 .valueAt(i); 17003 if (userId != thisUserId) { 17004 continue; 17005 } 17006 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17007 while (it.hasNext()) { 17008 PersistentPreferredActivity ppa = it.next(); 17009 // Mark entry for removal only if it matches the package name. 17010 if (ppa.mComponent.getPackageName().equals(packageName)) { 17011 if (removed == null) { 17012 removed = new ArrayList<PersistentPreferredActivity>(); 17013 } 17014 removed.add(ppa); 17015 } 17016 } 17017 if (removed != null) { 17018 for (int j=0; j<removed.size(); j++) { 17019 PersistentPreferredActivity ppa = removed.get(j); 17020 ppir.removeFilter(ppa); 17021 } 17022 changed = true; 17023 } 17024 } 17025 17026 if (changed) { 17027 scheduleWritePackageRestrictionsLocked(userId); 17028 postPreferredActivityChangedBroadcast(userId); 17029 } 17030 } 17031 } 17032 17033 /** 17034 * Common machinery for picking apart a restored XML blob and passing 17035 * it to a caller-supplied functor to be applied to the running system. 17036 */ 17037 private void restoreFromXml(XmlPullParser parser, int userId, 17038 String expectedStartTag, BlobXmlRestorer functor) 17039 throws IOException, XmlPullParserException { 17040 int type; 17041 while ((type = parser.next()) != XmlPullParser.START_TAG 17042 && type != XmlPullParser.END_DOCUMENT) { 17043 } 17044 if (type != XmlPullParser.START_TAG) { 17045 // oops didn't find a start tag?! 17046 if (DEBUG_BACKUP) { 17047 Slog.e(TAG, "Didn't find start tag during restore"); 17048 } 17049 return; 17050 } 17051Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17052 // this is supposed to be TAG_PREFERRED_BACKUP 17053 if (!expectedStartTag.equals(parser.getName())) { 17054 if (DEBUG_BACKUP) { 17055 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17056 } 17057 return; 17058 } 17059 17060 // skip interfering stuff, then we're aligned with the backing implementation 17061 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17062Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17063 functor.apply(parser, userId); 17064 } 17065 17066 private interface BlobXmlRestorer { 17067 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17068 } 17069 17070 /** 17071 * Non-Binder method, support for the backup/restore mechanism: write the 17072 * full set of preferred activities in its canonical XML format. Returns the 17073 * XML output as a byte array, or null if there is none. 17074 */ 17075 @Override 17076 public byte[] getPreferredActivityBackup(int userId) { 17077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17078 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17079 } 17080 17081 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17082 try { 17083 final XmlSerializer serializer = new FastXmlSerializer(); 17084 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17085 serializer.startDocument(null, true); 17086 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17087 17088 synchronized (mPackages) { 17089 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17090 } 17091 17092 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17093 serializer.endDocument(); 17094 serializer.flush(); 17095 } catch (Exception e) { 17096 if (DEBUG_BACKUP) { 17097 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17098 } 17099 return null; 17100 } 17101 17102 return dataStream.toByteArray(); 17103 } 17104 17105 @Override 17106 public void restorePreferredActivities(byte[] backup, int userId) { 17107 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17108 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17109 } 17110 17111 try { 17112 final XmlPullParser parser = Xml.newPullParser(); 17113 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17114 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17115 new BlobXmlRestorer() { 17116 @Override 17117 public void apply(XmlPullParser parser, int userId) 17118 throws XmlPullParserException, IOException { 17119 synchronized (mPackages) { 17120 mSettings.readPreferredActivitiesLPw(parser, userId); 17121 } 17122 } 17123 } ); 17124 } catch (Exception e) { 17125 if (DEBUG_BACKUP) { 17126 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17127 } 17128 } 17129 } 17130 17131 /** 17132 * Non-Binder method, support for the backup/restore mechanism: write the 17133 * default browser (etc) settings in its canonical XML format. Returns the default 17134 * browser XML representation as a byte array, or null if there is none. 17135 */ 17136 @Override 17137 public byte[] getDefaultAppsBackup(int userId) { 17138 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17139 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17140 } 17141 17142 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17143 try { 17144 final XmlSerializer serializer = new FastXmlSerializer(); 17145 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17146 serializer.startDocument(null, true); 17147 serializer.startTag(null, TAG_DEFAULT_APPS); 17148 17149 synchronized (mPackages) { 17150 mSettings.writeDefaultAppsLPr(serializer, userId); 17151 } 17152 17153 serializer.endTag(null, TAG_DEFAULT_APPS); 17154 serializer.endDocument(); 17155 serializer.flush(); 17156 } catch (Exception e) { 17157 if (DEBUG_BACKUP) { 17158 Slog.e(TAG, "Unable to write default apps for backup", e); 17159 } 17160 return null; 17161 } 17162 17163 return dataStream.toByteArray(); 17164 } 17165 17166 @Override 17167 public void restoreDefaultApps(byte[] backup, int userId) { 17168 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17169 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17170 } 17171 17172 try { 17173 final XmlPullParser parser = Xml.newPullParser(); 17174 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17175 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17176 new BlobXmlRestorer() { 17177 @Override 17178 public void apply(XmlPullParser parser, int userId) 17179 throws XmlPullParserException, IOException { 17180 synchronized (mPackages) { 17181 mSettings.readDefaultAppsLPw(parser, userId); 17182 } 17183 } 17184 } ); 17185 } catch (Exception e) { 17186 if (DEBUG_BACKUP) { 17187 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17188 } 17189 } 17190 } 17191 17192 @Override 17193 public byte[] getIntentFilterVerificationBackup(int userId) { 17194 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17195 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17196 } 17197 17198 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17199 try { 17200 final XmlSerializer serializer = new FastXmlSerializer(); 17201 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17202 serializer.startDocument(null, true); 17203 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17204 17205 synchronized (mPackages) { 17206 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17207 } 17208 17209 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17210 serializer.endDocument(); 17211 serializer.flush(); 17212 } catch (Exception e) { 17213 if (DEBUG_BACKUP) { 17214 Slog.e(TAG, "Unable to write default apps for backup", e); 17215 } 17216 return null; 17217 } 17218 17219 return dataStream.toByteArray(); 17220 } 17221 17222 @Override 17223 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17224 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17225 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17226 } 17227 17228 try { 17229 final XmlPullParser parser = Xml.newPullParser(); 17230 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17231 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17232 new BlobXmlRestorer() { 17233 @Override 17234 public void apply(XmlPullParser parser, int userId) 17235 throws XmlPullParserException, IOException { 17236 synchronized (mPackages) { 17237 mSettings.readAllDomainVerificationsLPr(parser, userId); 17238 mSettings.writeLPr(); 17239 } 17240 } 17241 } ); 17242 } catch (Exception e) { 17243 if (DEBUG_BACKUP) { 17244 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17245 } 17246 } 17247 } 17248 17249 @Override 17250 public byte[] getPermissionGrantBackup(int userId) { 17251 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17252 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17253 } 17254 17255 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17256 try { 17257 final XmlSerializer serializer = new FastXmlSerializer(); 17258 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17259 serializer.startDocument(null, true); 17260 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17261 17262 synchronized (mPackages) { 17263 serializeRuntimePermissionGrantsLPr(serializer, userId); 17264 } 17265 17266 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17267 serializer.endDocument(); 17268 serializer.flush(); 17269 } catch (Exception e) { 17270 if (DEBUG_BACKUP) { 17271 Slog.e(TAG, "Unable to write default apps for backup", e); 17272 } 17273 return null; 17274 } 17275 17276 return dataStream.toByteArray(); 17277 } 17278 17279 @Override 17280 public void restorePermissionGrants(byte[] backup, int userId) { 17281 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17282 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17283 } 17284 17285 try { 17286 final XmlPullParser parser = Xml.newPullParser(); 17287 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17288 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17289 new BlobXmlRestorer() { 17290 @Override 17291 public void apply(XmlPullParser parser, int userId) 17292 throws XmlPullParserException, IOException { 17293 synchronized (mPackages) { 17294 processRestoredPermissionGrantsLPr(parser, userId); 17295 } 17296 } 17297 } ); 17298 } catch (Exception e) { 17299 if (DEBUG_BACKUP) { 17300 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17301 } 17302 } 17303 } 17304 17305 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17306 throws IOException { 17307 serializer.startTag(null, TAG_ALL_GRANTS); 17308 17309 final int N = mSettings.mPackages.size(); 17310 for (int i = 0; i < N; i++) { 17311 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17312 boolean pkgGrantsKnown = false; 17313 17314 PermissionsState packagePerms = ps.getPermissionsState(); 17315 17316 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17317 final int grantFlags = state.getFlags(); 17318 // only look at grants that are not system/policy fixed 17319 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17320 final boolean isGranted = state.isGranted(); 17321 // And only back up the user-twiddled state bits 17322 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17323 final String packageName = mSettings.mPackages.keyAt(i); 17324 if (!pkgGrantsKnown) { 17325 serializer.startTag(null, TAG_GRANT); 17326 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17327 pkgGrantsKnown = true; 17328 } 17329 17330 final boolean userSet = 17331 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17332 final boolean userFixed = 17333 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17334 final boolean revoke = 17335 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17336 17337 serializer.startTag(null, TAG_PERMISSION); 17338 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17339 if (isGranted) { 17340 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17341 } 17342 if (userSet) { 17343 serializer.attribute(null, ATTR_USER_SET, "true"); 17344 } 17345 if (userFixed) { 17346 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17347 } 17348 if (revoke) { 17349 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17350 } 17351 serializer.endTag(null, TAG_PERMISSION); 17352 } 17353 } 17354 } 17355 17356 if (pkgGrantsKnown) { 17357 serializer.endTag(null, TAG_GRANT); 17358 } 17359 } 17360 17361 serializer.endTag(null, TAG_ALL_GRANTS); 17362 } 17363 17364 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17365 throws XmlPullParserException, IOException { 17366 String pkgName = null; 17367 int outerDepth = parser.getDepth(); 17368 int type; 17369 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17370 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17371 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17372 continue; 17373 } 17374 17375 final String tagName = parser.getName(); 17376 if (tagName.equals(TAG_GRANT)) { 17377 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17378 if (DEBUG_BACKUP) { 17379 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17380 } 17381 } else if (tagName.equals(TAG_PERMISSION)) { 17382 17383 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17384 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17385 17386 int newFlagSet = 0; 17387 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17388 newFlagSet |= FLAG_PERMISSION_USER_SET; 17389 } 17390 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17391 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17392 } 17393 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17394 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17395 } 17396 if (DEBUG_BACKUP) { 17397 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17398 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17399 } 17400 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17401 if (ps != null) { 17402 // Already installed so we apply the grant immediately 17403 if (DEBUG_BACKUP) { 17404 Slog.v(TAG, " + already installed; applying"); 17405 } 17406 PermissionsState perms = ps.getPermissionsState(); 17407 BasePermission bp = mSettings.mPermissions.get(permName); 17408 if (bp != null) { 17409 if (isGranted) { 17410 perms.grantRuntimePermission(bp, userId); 17411 } 17412 if (newFlagSet != 0) { 17413 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17414 } 17415 } 17416 } else { 17417 // Need to wait for post-restore install to apply the grant 17418 if (DEBUG_BACKUP) { 17419 Slog.v(TAG, " - not yet installed; saving for later"); 17420 } 17421 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17422 isGranted, newFlagSet, userId); 17423 } 17424 } else { 17425 PackageManagerService.reportSettingsProblem(Log.WARN, 17426 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17427 XmlUtils.skipCurrentTag(parser); 17428 } 17429 } 17430 17431 scheduleWriteSettingsLocked(); 17432 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17433 } 17434 17435 @Override 17436 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17437 int sourceUserId, int targetUserId, int flags) { 17438 mContext.enforceCallingOrSelfPermission( 17439 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17440 int callingUid = Binder.getCallingUid(); 17441 enforceOwnerRights(ownerPackage, callingUid); 17442 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17443 if (intentFilter.countActions() == 0) { 17444 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17445 return; 17446 } 17447 synchronized (mPackages) { 17448 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17449 ownerPackage, targetUserId, flags); 17450 CrossProfileIntentResolver resolver = 17451 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17452 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17453 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17454 if (existing != null) { 17455 int size = existing.size(); 17456 for (int i = 0; i < size; i++) { 17457 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17458 return; 17459 } 17460 } 17461 } 17462 resolver.addFilter(newFilter); 17463 scheduleWritePackageRestrictionsLocked(sourceUserId); 17464 } 17465 } 17466 17467 @Override 17468 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17469 mContext.enforceCallingOrSelfPermission( 17470 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17471 int callingUid = Binder.getCallingUid(); 17472 enforceOwnerRights(ownerPackage, callingUid); 17473 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17474 synchronized (mPackages) { 17475 CrossProfileIntentResolver resolver = 17476 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17477 ArraySet<CrossProfileIntentFilter> set = 17478 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17479 for (CrossProfileIntentFilter filter : set) { 17480 if (filter.getOwnerPackage().equals(ownerPackage)) { 17481 resolver.removeFilter(filter); 17482 } 17483 } 17484 scheduleWritePackageRestrictionsLocked(sourceUserId); 17485 } 17486 } 17487 17488 // Enforcing that callingUid is owning pkg on userId 17489 private void enforceOwnerRights(String pkg, int callingUid) { 17490 // The system owns everything. 17491 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17492 return; 17493 } 17494 int callingUserId = UserHandle.getUserId(callingUid); 17495 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17496 if (pi == null) { 17497 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17498 + callingUserId); 17499 } 17500 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17501 throw new SecurityException("Calling uid " + callingUid 17502 + " does not own package " + pkg); 17503 } 17504 } 17505 17506 @Override 17507 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17508 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17509 } 17510 17511 private Intent getHomeIntent() { 17512 Intent intent = new Intent(Intent.ACTION_MAIN); 17513 intent.addCategory(Intent.CATEGORY_HOME); 17514 intent.addCategory(Intent.CATEGORY_DEFAULT); 17515 return intent; 17516 } 17517 17518 private IntentFilter getHomeFilter() { 17519 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17520 filter.addCategory(Intent.CATEGORY_HOME); 17521 filter.addCategory(Intent.CATEGORY_DEFAULT); 17522 return filter; 17523 } 17524 17525 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17526 int userId) { 17527 Intent intent = getHomeIntent(); 17528 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17529 PackageManager.GET_META_DATA, userId); 17530 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17531 true, false, false, userId); 17532 17533 allHomeCandidates.clear(); 17534 if (list != null) { 17535 for (ResolveInfo ri : list) { 17536 allHomeCandidates.add(ri); 17537 } 17538 } 17539 return (preferred == null || preferred.activityInfo == null) 17540 ? null 17541 : new ComponentName(preferred.activityInfo.packageName, 17542 preferred.activityInfo.name); 17543 } 17544 17545 @Override 17546 public void setHomeActivity(ComponentName comp, int userId) { 17547 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17548 getHomeActivitiesAsUser(homeActivities, userId); 17549 17550 boolean found = false; 17551 17552 final int size = homeActivities.size(); 17553 final ComponentName[] set = new ComponentName[size]; 17554 for (int i = 0; i < size; i++) { 17555 final ResolveInfo candidate = homeActivities.get(i); 17556 final ActivityInfo info = candidate.activityInfo; 17557 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17558 set[i] = activityName; 17559 if (!found && activityName.equals(comp)) { 17560 found = true; 17561 } 17562 } 17563 if (!found) { 17564 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17565 + userId); 17566 } 17567 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17568 set, comp, userId); 17569 } 17570 17571 private @Nullable String getSetupWizardPackageName() { 17572 final Intent intent = new Intent(Intent.ACTION_MAIN); 17573 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17574 17575 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17576 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17577 | MATCH_DISABLED_COMPONENTS, 17578 UserHandle.myUserId()); 17579 if (matches.size() == 1) { 17580 return matches.get(0).getComponentInfo().packageName; 17581 } else { 17582 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17583 + ": matches=" + matches); 17584 return null; 17585 } 17586 } 17587 17588 @Override 17589 public void setApplicationEnabledSetting(String appPackageName, 17590 int newState, int flags, int userId, String callingPackage) { 17591 if (!sUserManager.exists(userId)) return; 17592 if (callingPackage == null) { 17593 callingPackage = Integer.toString(Binder.getCallingUid()); 17594 } 17595 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17596 } 17597 17598 @Override 17599 public void setComponentEnabledSetting(ComponentName componentName, 17600 int newState, int flags, int userId) { 17601 if (!sUserManager.exists(userId)) return; 17602 setEnabledSetting(componentName.getPackageName(), 17603 componentName.getClassName(), newState, flags, userId, null); 17604 } 17605 17606 private void setEnabledSetting(final String packageName, String className, int newState, 17607 final int flags, int userId, String callingPackage) { 17608 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17609 || newState == COMPONENT_ENABLED_STATE_ENABLED 17610 || newState == COMPONENT_ENABLED_STATE_DISABLED 17611 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17612 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17613 throw new IllegalArgumentException("Invalid new component state: " 17614 + newState); 17615 } 17616 PackageSetting pkgSetting; 17617 final int uid = Binder.getCallingUid(); 17618 final int permission; 17619 if (uid == Process.SYSTEM_UID) { 17620 permission = PackageManager.PERMISSION_GRANTED; 17621 } else { 17622 permission = mContext.checkCallingOrSelfPermission( 17623 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17624 } 17625 enforceCrossUserPermission(uid, userId, 17626 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17627 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17628 boolean sendNow = false; 17629 boolean isApp = (className == null); 17630 String componentName = isApp ? packageName : className; 17631 int packageUid = -1; 17632 ArrayList<String> components; 17633 17634 // writer 17635 synchronized (mPackages) { 17636 pkgSetting = mSettings.mPackages.get(packageName); 17637 if (pkgSetting == null) { 17638 if (className == null) { 17639 throw new IllegalArgumentException("Unknown package: " + packageName); 17640 } 17641 throw new IllegalArgumentException( 17642 "Unknown component: " + packageName + "/" + className); 17643 } 17644 } 17645 17646 // Limit who can change which apps 17647 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17648 // Don't allow apps that don't have permission to modify other apps 17649 if (!allowedByPermission) { 17650 throw new SecurityException( 17651 "Permission Denial: attempt to change component state from pid=" 17652 + Binder.getCallingPid() 17653 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17654 } 17655 // Don't allow changing protected packages. 17656 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17657 throw new SecurityException("Cannot disable a protected package: " + packageName); 17658 } 17659 } 17660 17661 synchronized (mPackages) { 17662 if (uid == Process.SHELL_UID) { 17663 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17664 int oldState = pkgSetting.getEnabled(userId); 17665 if (className == null 17666 && 17667 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17668 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17669 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17670 && 17671 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17672 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17673 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17674 // ok 17675 } else { 17676 throw new SecurityException( 17677 "Shell cannot change component state for " + packageName + "/" 17678 + className + " to " + newState); 17679 } 17680 } 17681 if (className == null) { 17682 // We're dealing with an application/package level state change 17683 if (pkgSetting.getEnabled(userId) == newState) { 17684 // Nothing to do 17685 return; 17686 } 17687 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17688 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17689 // Don't care about who enables an app. 17690 callingPackage = null; 17691 } 17692 pkgSetting.setEnabled(newState, userId, callingPackage); 17693 // pkgSetting.pkg.mSetEnabled = newState; 17694 } else { 17695 // We're dealing with a component level state change 17696 // First, verify that this is a valid class name. 17697 PackageParser.Package pkg = pkgSetting.pkg; 17698 if (pkg == null || !pkg.hasComponentClassName(className)) { 17699 if (pkg != null && 17700 pkg.applicationInfo.targetSdkVersion >= 17701 Build.VERSION_CODES.JELLY_BEAN) { 17702 throw new IllegalArgumentException("Component class " + className 17703 + " does not exist in " + packageName); 17704 } else { 17705 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17706 + className + " does not exist in " + packageName); 17707 } 17708 } 17709 switch (newState) { 17710 case COMPONENT_ENABLED_STATE_ENABLED: 17711 if (!pkgSetting.enableComponentLPw(className, userId)) { 17712 return; 17713 } 17714 break; 17715 case COMPONENT_ENABLED_STATE_DISABLED: 17716 if (!pkgSetting.disableComponentLPw(className, userId)) { 17717 return; 17718 } 17719 break; 17720 case COMPONENT_ENABLED_STATE_DEFAULT: 17721 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17722 return; 17723 } 17724 break; 17725 default: 17726 Slog.e(TAG, "Invalid new component state: " + newState); 17727 return; 17728 } 17729 } 17730 scheduleWritePackageRestrictionsLocked(userId); 17731 components = mPendingBroadcasts.get(userId, packageName); 17732 final boolean newPackage = components == null; 17733 if (newPackage) { 17734 components = new ArrayList<String>(); 17735 } 17736 if (!components.contains(componentName)) { 17737 components.add(componentName); 17738 } 17739 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17740 sendNow = true; 17741 // Purge entry from pending broadcast list if another one exists already 17742 // since we are sending one right away. 17743 mPendingBroadcasts.remove(userId, packageName); 17744 } else { 17745 if (newPackage) { 17746 mPendingBroadcasts.put(userId, packageName, components); 17747 } 17748 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17749 // Schedule a message 17750 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17751 } 17752 } 17753 } 17754 17755 long callingId = Binder.clearCallingIdentity(); 17756 try { 17757 if (sendNow) { 17758 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17759 sendPackageChangedBroadcast(packageName, 17760 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17761 } 17762 } finally { 17763 Binder.restoreCallingIdentity(callingId); 17764 } 17765 } 17766 17767 @Override 17768 public void flushPackageRestrictionsAsUser(int userId) { 17769 if (!sUserManager.exists(userId)) { 17770 return; 17771 } 17772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17773 false /* checkShell */, "flushPackageRestrictions"); 17774 synchronized (mPackages) { 17775 mSettings.writePackageRestrictionsLPr(userId); 17776 mDirtyUsers.remove(userId); 17777 if (mDirtyUsers.isEmpty()) { 17778 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17779 } 17780 } 17781 } 17782 17783 private void sendPackageChangedBroadcast(String packageName, 17784 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17785 if (DEBUG_INSTALL) 17786 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17787 + componentNames); 17788 Bundle extras = new Bundle(4); 17789 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17790 String nameList[] = new String[componentNames.size()]; 17791 componentNames.toArray(nameList); 17792 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17793 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17794 extras.putInt(Intent.EXTRA_UID, packageUid); 17795 // If this is not reporting a change of the overall package, then only send it 17796 // to registered receivers. We don't want to launch a swath of apps for every 17797 // little component state change. 17798 final int flags = !componentNames.contains(packageName) 17799 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17800 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17801 new int[] {UserHandle.getUserId(packageUid)}); 17802 } 17803 17804 @Override 17805 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17806 if (!sUserManager.exists(userId)) return; 17807 final int uid = Binder.getCallingUid(); 17808 final int permission = mContext.checkCallingOrSelfPermission( 17809 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17810 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17811 enforceCrossUserPermission(uid, userId, 17812 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17813 // writer 17814 synchronized (mPackages) { 17815 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17816 allowedByPermission, uid, userId)) { 17817 scheduleWritePackageRestrictionsLocked(userId); 17818 } 17819 } 17820 } 17821 17822 @Override 17823 public String getInstallerPackageName(String packageName) { 17824 // reader 17825 synchronized (mPackages) { 17826 return mSettings.getInstallerPackageNameLPr(packageName); 17827 } 17828 } 17829 17830 public boolean isOrphaned(String packageName) { 17831 // reader 17832 synchronized (mPackages) { 17833 return mSettings.isOrphaned(packageName); 17834 } 17835 } 17836 17837 @Override 17838 public int getApplicationEnabledSetting(String packageName, int userId) { 17839 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17840 int uid = Binder.getCallingUid(); 17841 enforceCrossUserPermission(uid, userId, 17842 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17843 // reader 17844 synchronized (mPackages) { 17845 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17846 } 17847 } 17848 17849 @Override 17850 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17851 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17852 int uid = Binder.getCallingUid(); 17853 enforceCrossUserPermission(uid, userId, 17854 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17855 // reader 17856 synchronized (mPackages) { 17857 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17858 } 17859 } 17860 17861 @Override 17862 public void enterSafeMode() { 17863 enforceSystemOrRoot("Only the system can request entering safe mode"); 17864 17865 if (!mSystemReady) { 17866 mSafeMode = true; 17867 } 17868 } 17869 17870 @Override 17871 public void systemReady() { 17872 mSystemReady = true; 17873 17874 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 17875 // disabled after already being started. 17876 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 17877 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 17878 17879 // Read the compatibilty setting when the system is ready. 17880 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17881 mContext.getContentResolver(), 17882 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17883 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17884 if (DEBUG_SETTINGS) { 17885 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17886 } 17887 17888 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17889 17890 synchronized (mPackages) { 17891 // Verify that all of the preferred activity components actually 17892 // exist. It is possible for applications to be updated and at 17893 // that point remove a previously declared activity component that 17894 // had been set as a preferred activity. We try to clean this up 17895 // the next time we encounter that preferred activity, but it is 17896 // possible for the user flow to never be able to return to that 17897 // situation so here we do a sanity check to make sure we haven't 17898 // left any junk around. 17899 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17900 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17901 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17902 removed.clear(); 17903 for (PreferredActivity pa : pir.filterSet()) { 17904 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17905 removed.add(pa); 17906 } 17907 } 17908 if (removed.size() > 0) { 17909 for (int r=0; r<removed.size(); r++) { 17910 PreferredActivity pa = removed.get(r); 17911 Slog.w(TAG, "Removing dangling preferred activity: " 17912 + pa.mPref.mComponent); 17913 pir.removeFilter(pa); 17914 } 17915 mSettings.writePackageRestrictionsLPr( 17916 mSettings.mPreferredActivities.keyAt(i)); 17917 } 17918 } 17919 17920 for (int userId : UserManagerService.getInstance().getUserIds()) { 17921 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17922 grantPermissionsUserIds = ArrayUtils.appendInt( 17923 grantPermissionsUserIds, userId); 17924 } 17925 } 17926 } 17927 sUserManager.systemReady(); 17928 17929 // If we upgraded grant all default permissions before kicking off. 17930 for (int userId : grantPermissionsUserIds) { 17931 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17932 } 17933 17934 // Kick off any messages waiting for system ready 17935 if (mPostSystemReadyMessages != null) { 17936 for (Message msg : mPostSystemReadyMessages) { 17937 msg.sendToTarget(); 17938 } 17939 mPostSystemReadyMessages = null; 17940 } 17941 17942 // Watch for external volumes that come and go over time 17943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17944 storage.registerListener(mStorageListener); 17945 17946 mInstallerService.systemReady(); 17947 mPackageDexOptimizer.systemReady(); 17948 17949 MountServiceInternal mountServiceInternal = LocalServices.getService( 17950 MountServiceInternal.class); 17951 mountServiceInternal.addExternalStoragePolicy( 17952 new MountServiceInternal.ExternalStorageMountPolicy() { 17953 @Override 17954 public int getMountMode(int uid, String packageName) { 17955 if (Process.isIsolated(uid)) { 17956 return Zygote.MOUNT_EXTERNAL_NONE; 17957 } 17958 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17959 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17960 } 17961 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17962 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17963 } 17964 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17965 return Zygote.MOUNT_EXTERNAL_READ; 17966 } 17967 return Zygote.MOUNT_EXTERNAL_WRITE; 17968 } 17969 17970 @Override 17971 public boolean hasExternalStorage(int uid, String packageName) { 17972 return true; 17973 } 17974 }); 17975 17976 // Now that we're mostly running, clean up stale users and apps 17977 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17978 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17979 } 17980 17981 @Override 17982 public boolean isSafeMode() { 17983 return mSafeMode; 17984 } 17985 17986 @Override 17987 public boolean hasSystemUidErrors() { 17988 return mHasSystemUidErrors; 17989 } 17990 17991 static String arrayToString(int[] array) { 17992 StringBuffer buf = new StringBuffer(128); 17993 buf.append('['); 17994 if (array != null) { 17995 for (int i=0; i<array.length; i++) { 17996 if (i > 0) buf.append(", "); 17997 buf.append(array[i]); 17998 } 17999 } 18000 buf.append(']'); 18001 return buf.toString(); 18002 } 18003 18004 static class DumpState { 18005 public static final int DUMP_LIBS = 1 << 0; 18006 public static final int DUMP_FEATURES = 1 << 1; 18007 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18008 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18009 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18010 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18011 public static final int DUMP_PERMISSIONS = 1 << 6; 18012 public static final int DUMP_PACKAGES = 1 << 7; 18013 public static final int DUMP_SHARED_USERS = 1 << 8; 18014 public static final int DUMP_MESSAGES = 1 << 9; 18015 public static final int DUMP_PROVIDERS = 1 << 10; 18016 public static final int DUMP_VERIFIERS = 1 << 11; 18017 public static final int DUMP_PREFERRED = 1 << 12; 18018 public static final int DUMP_PREFERRED_XML = 1 << 13; 18019 public static final int DUMP_KEYSETS = 1 << 14; 18020 public static final int DUMP_VERSION = 1 << 15; 18021 public static final int DUMP_INSTALLS = 1 << 16; 18022 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18023 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18024 public static final int DUMP_FROZEN = 1 << 19; 18025 public static final int DUMP_DEXOPT = 1 << 20; 18026 public static final int DUMP_COMPILER_STATS = 1 << 21; 18027 18028 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18029 18030 private int mTypes; 18031 18032 private int mOptions; 18033 18034 private boolean mTitlePrinted; 18035 18036 private SharedUserSetting mSharedUser; 18037 18038 public boolean isDumping(int type) { 18039 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18040 return true; 18041 } 18042 18043 return (mTypes & type) != 0; 18044 } 18045 18046 public void setDump(int type) { 18047 mTypes |= type; 18048 } 18049 18050 public boolean isOptionEnabled(int option) { 18051 return (mOptions & option) != 0; 18052 } 18053 18054 public void setOptionEnabled(int option) { 18055 mOptions |= option; 18056 } 18057 18058 public boolean onTitlePrinted() { 18059 final boolean printed = mTitlePrinted; 18060 mTitlePrinted = true; 18061 return printed; 18062 } 18063 18064 public boolean getTitlePrinted() { 18065 return mTitlePrinted; 18066 } 18067 18068 public void setTitlePrinted(boolean enabled) { 18069 mTitlePrinted = enabled; 18070 } 18071 18072 public SharedUserSetting getSharedUser() { 18073 return mSharedUser; 18074 } 18075 18076 public void setSharedUser(SharedUserSetting user) { 18077 mSharedUser = user; 18078 } 18079 } 18080 18081 @Override 18082 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18083 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18084 (new PackageManagerShellCommand(this)).exec( 18085 this, in, out, err, args, resultReceiver); 18086 } 18087 18088 @Override 18089 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18090 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18091 != PackageManager.PERMISSION_GRANTED) { 18092 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18093 + Binder.getCallingPid() 18094 + ", uid=" + Binder.getCallingUid() 18095 + " without permission " 18096 + android.Manifest.permission.DUMP); 18097 return; 18098 } 18099 18100 DumpState dumpState = new DumpState(); 18101 boolean fullPreferred = false; 18102 boolean checkin = false; 18103 18104 String packageName = null; 18105 ArraySet<String> permissionNames = null; 18106 18107 int opti = 0; 18108 while (opti < args.length) { 18109 String opt = args[opti]; 18110 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18111 break; 18112 } 18113 opti++; 18114 18115 if ("-a".equals(opt)) { 18116 // Right now we only know how to print all. 18117 } else if ("-h".equals(opt)) { 18118 pw.println("Package manager dump options:"); 18119 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18120 pw.println(" --checkin: dump for a checkin"); 18121 pw.println(" -f: print details of intent filters"); 18122 pw.println(" -h: print this help"); 18123 pw.println(" cmd may be one of:"); 18124 pw.println(" l[ibraries]: list known shared libraries"); 18125 pw.println(" f[eatures]: list device features"); 18126 pw.println(" k[eysets]: print known keysets"); 18127 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18128 pw.println(" perm[issions]: dump permissions"); 18129 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18130 pw.println(" pref[erred]: print preferred package settings"); 18131 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18132 pw.println(" prov[iders]: dump content providers"); 18133 pw.println(" p[ackages]: dump installed packages"); 18134 pw.println(" s[hared-users]: dump shared user IDs"); 18135 pw.println(" m[essages]: print collected runtime messages"); 18136 pw.println(" v[erifiers]: print package verifier info"); 18137 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18138 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18139 pw.println(" version: print database version info"); 18140 pw.println(" write: write current settings now"); 18141 pw.println(" installs: details about install sessions"); 18142 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18143 pw.println(" dexopt: dump dexopt state"); 18144 pw.println(" compiler-stats: dump compiler statistics"); 18145 pw.println(" <package.name>: info about given package"); 18146 return; 18147 } else if ("--checkin".equals(opt)) { 18148 checkin = true; 18149 } else if ("-f".equals(opt)) { 18150 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18151 } else { 18152 pw.println("Unknown argument: " + opt + "; use -h for help"); 18153 } 18154 } 18155 18156 // Is the caller requesting to dump a particular piece of data? 18157 if (opti < args.length) { 18158 String cmd = args[opti]; 18159 opti++; 18160 // Is this a package name? 18161 if ("android".equals(cmd) || cmd.contains(".")) { 18162 packageName = cmd; 18163 // When dumping a single package, we always dump all of its 18164 // filter information since the amount of data will be reasonable. 18165 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18166 } else if ("check-permission".equals(cmd)) { 18167 if (opti >= args.length) { 18168 pw.println("Error: check-permission missing permission argument"); 18169 return; 18170 } 18171 String perm = args[opti]; 18172 opti++; 18173 if (opti >= args.length) { 18174 pw.println("Error: check-permission missing package argument"); 18175 return; 18176 } 18177 String pkg = args[opti]; 18178 opti++; 18179 int user = UserHandle.getUserId(Binder.getCallingUid()); 18180 if (opti < args.length) { 18181 try { 18182 user = Integer.parseInt(args[opti]); 18183 } catch (NumberFormatException e) { 18184 pw.println("Error: check-permission user argument is not a number: " 18185 + args[opti]); 18186 return; 18187 } 18188 } 18189 pw.println(checkPermission(perm, pkg, user)); 18190 return; 18191 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18192 dumpState.setDump(DumpState.DUMP_LIBS); 18193 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18194 dumpState.setDump(DumpState.DUMP_FEATURES); 18195 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18196 if (opti >= args.length) { 18197 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18198 | DumpState.DUMP_SERVICE_RESOLVERS 18199 | DumpState.DUMP_RECEIVER_RESOLVERS 18200 | DumpState.DUMP_CONTENT_RESOLVERS); 18201 } else { 18202 while (opti < args.length) { 18203 String name = args[opti]; 18204 if ("a".equals(name) || "activity".equals(name)) { 18205 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18206 } else if ("s".equals(name) || "service".equals(name)) { 18207 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18208 } else if ("r".equals(name) || "receiver".equals(name)) { 18209 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18210 } else if ("c".equals(name) || "content".equals(name)) { 18211 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18212 } else { 18213 pw.println("Error: unknown resolver table type: " + name); 18214 return; 18215 } 18216 opti++; 18217 } 18218 } 18219 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18220 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18221 } else if ("permission".equals(cmd)) { 18222 if (opti >= args.length) { 18223 pw.println("Error: permission requires permission name"); 18224 return; 18225 } 18226 permissionNames = new ArraySet<>(); 18227 while (opti < args.length) { 18228 permissionNames.add(args[opti]); 18229 opti++; 18230 } 18231 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18232 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18233 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18234 dumpState.setDump(DumpState.DUMP_PREFERRED); 18235 } else if ("preferred-xml".equals(cmd)) { 18236 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18237 if (opti < args.length && "--full".equals(args[opti])) { 18238 fullPreferred = true; 18239 opti++; 18240 } 18241 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18242 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18243 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18244 dumpState.setDump(DumpState.DUMP_PACKAGES); 18245 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18246 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18247 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18248 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18249 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18250 dumpState.setDump(DumpState.DUMP_MESSAGES); 18251 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18252 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18253 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18254 || "intent-filter-verifiers".equals(cmd)) { 18255 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18256 } else if ("version".equals(cmd)) { 18257 dumpState.setDump(DumpState.DUMP_VERSION); 18258 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18259 dumpState.setDump(DumpState.DUMP_KEYSETS); 18260 } else if ("installs".equals(cmd)) { 18261 dumpState.setDump(DumpState.DUMP_INSTALLS); 18262 } else if ("frozen".equals(cmd)) { 18263 dumpState.setDump(DumpState.DUMP_FROZEN); 18264 } else if ("dexopt".equals(cmd)) { 18265 dumpState.setDump(DumpState.DUMP_DEXOPT); 18266 } else if ("compiler-stats".equals(cmd)) { 18267 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18268 } else if ("write".equals(cmd)) { 18269 synchronized (mPackages) { 18270 mSettings.writeLPr(); 18271 pw.println("Settings written."); 18272 return; 18273 } 18274 } 18275 } 18276 18277 if (checkin) { 18278 pw.println("vers,1"); 18279 } 18280 18281 // reader 18282 synchronized (mPackages) { 18283 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18284 if (!checkin) { 18285 if (dumpState.onTitlePrinted()) 18286 pw.println(); 18287 pw.println("Database versions:"); 18288 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18289 } 18290 } 18291 18292 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18293 if (!checkin) { 18294 if (dumpState.onTitlePrinted()) 18295 pw.println(); 18296 pw.println("Verifiers:"); 18297 pw.print(" Required: "); 18298 pw.print(mRequiredVerifierPackage); 18299 pw.print(" (uid="); 18300 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18301 UserHandle.USER_SYSTEM)); 18302 pw.println(")"); 18303 } else if (mRequiredVerifierPackage != null) { 18304 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18305 pw.print(","); 18306 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18307 UserHandle.USER_SYSTEM)); 18308 } 18309 } 18310 18311 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18312 packageName == null) { 18313 if (mIntentFilterVerifierComponent != null) { 18314 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18315 if (!checkin) { 18316 if (dumpState.onTitlePrinted()) 18317 pw.println(); 18318 pw.println("Intent Filter Verifier:"); 18319 pw.print(" Using: "); 18320 pw.print(verifierPackageName); 18321 pw.print(" (uid="); 18322 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18323 UserHandle.USER_SYSTEM)); 18324 pw.println(")"); 18325 } else if (verifierPackageName != null) { 18326 pw.print("ifv,"); pw.print(verifierPackageName); 18327 pw.print(","); 18328 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18329 UserHandle.USER_SYSTEM)); 18330 } 18331 } else { 18332 pw.println(); 18333 pw.println("No Intent Filter Verifier available!"); 18334 } 18335 } 18336 18337 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18338 boolean printedHeader = false; 18339 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18340 while (it.hasNext()) { 18341 String name = it.next(); 18342 SharedLibraryEntry ent = mSharedLibraries.get(name); 18343 if (!checkin) { 18344 if (!printedHeader) { 18345 if (dumpState.onTitlePrinted()) 18346 pw.println(); 18347 pw.println("Libraries:"); 18348 printedHeader = true; 18349 } 18350 pw.print(" "); 18351 } else { 18352 pw.print("lib,"); 18353 } 18354 pw.print(name); 18355 if (!checkin) { 18356 pw.print(" -> "); 18357 } 18358 if (ent.path != null) { 18359 if (!checkin) { 18360 pw.print("(jar) "); 18361 pw.print(ent.path); 18362 } else { 18363 pw.print(",jar,"); 18364 pw.print(ent.path); 18365 } 18366 } else { 18367 if (!checkin) { 18368 pw.print("(apk) "); 18369 pw.print(ent.apk); 18370 } else { 18371 pw.print(",apk,"); 18372 pw.print(ent.apk); 18373 } 18374 } 18375 pw.println(); 18376 } 18377 } 18378 18379 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18380 if (dumpState.onTitlePrinted()) 18381 pw.println(); 18382 if (!checkin) { 18383 pw.println("Features:"); 18384 } 18385 18386 for (FeatureInfo feat : mAvailableFeatures.values()) { 18387 if (checkin) { 18388 pw.print("feat,"); 18389 pw.print(feat.name); 18390 pw.print(","); 18391 pw.println(feat.version); 18392 } else { 18393 pw.print(" "); 18394 pw.print(feat.name); 18395 if (feat.version > 0) { 18396 pw.print(" version="); 18397 pw.print(feat.version); 18398 } 18399 pw.println(); 18400 } 18401 } 18402 } 18403 18404 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18405 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18406 : "Activity Resolver Table:", " ", packageName, 18407 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18408 dumpState.setTitlePrinted(true); 18409 } 18410 } 18411 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18412 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18413 : "Receiver Resolver Table:", " ", packageName, 18414 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18415 dumpState.setTitlePrinted(true); 18416 } 18417 } 18418 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18419 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18420 : "Service Resolver Table:", " ", packageName, 18421 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18422 dumpState.setTitlePrinted(true); 18423 } 18424 } 18425 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18426 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18427 : "Provider Resolver Table:", " ", packageName, 18428 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18429 dumpState.setTitlePrinted(true); 18430 } 18431 } 18432 18433 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18434 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18435 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18436 int user = mSettings.mPreferredActivities.keyAt(i); 18437 if (pir.dump(pw, 18438 dumpState.getTitlePrinted() 18439 ? "\nPreferred Activities User " + user + ":" 18440 : "Preferred Activities User " + user + ":", " ", 18441 packageName, true, false)) { 18442 dumpState.setTitlePrinted(true); 18443 } 18444 } 18445 } 18446 18447 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18448 pw.flush(); 18449 FileOutputStream fout = new FileOutputStream(fd); 18450 BufferedOutputStream str = new BufferedOutputStream(fout); 18451 XmlSerializer serializer = new FastXmlSerializer(); 18452 try { 18453 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18454 serializer.startDocument(null, true); 18455 serializer.setFeature( 18456 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18457 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18458 serializer.endDocument(); 18459 serializer.flush(); 18460 } catch (IllegalArgumentException e) { 18461 pw.println("Failed writing: " + e); 18462 } catch (IllegalStateException e) { 18463 pw.println("Failed writing: " + e); 18464 } catch (IOException e) { 18465 pw.println("Failed writing: " + e); 18466 } 18467 } 18468 18469 if (!checkin 18470 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18471 && packageName == null) { 18472 pw.println(); 18473 int count = mSettings.mPackages.size(); 18474 if (count == 0) { 18475 pw.println("No applications!"); 18476 pw.println(); 18477 } else { 18478 final String prefix = " "; 18479 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18480 if (allPackageSettings.size() == 0) { 18481 pw.println("No domain preferred apps!"); 18482 pw.println(); 18483 } else { 18484 pw.println("App verification status:"); 18485 pw.println(); 18486 count = 0; 18487 for (PackageSetting ps : allPackageSettings) { 18488 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18489 if (ivi == null || ivi.getPackageName() == null) continue; 18490 pw.println(prefix + "Package: " + ivi.getPackageName()); 18491 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18492 pw.println(prefix + "Status: " + ivi.getStatusString()); 18493 pw.println(); 18494 count++; 18495 } 18496 if (count == 0) { 18497 pw.println(prefix + "No app verification established."); 18498 pw.println(); 18499 } 18500 for (int userId : sUserManager.getUserIds()) { 18501 pw.println("App linkages for user " + userId + ":"); 18502 pw.println(); 18503 count = 0; 18504 for (PackageSetting ps : allPackageSettings) { 18505 final long status = ps.getDomainVerificationStatusForUser(userId); 18506 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18507 continue; 18508 } 18509 pw.println(prefix + "Package: " + ps.name); 18510 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18511 String statusStr = IntentFilterVerificationInfo. 18512 getStatusStringFromValue(status); 18513 pw.println(prefix + "Status: " + statusStr); 18514 pw.println(); 18515 count++; 18516 } 18517 if (count == 0) { 18518 pw.println(prefix + "No configured app linkages."); 18519 pw.println(); 18520 } 18521 } 18522 } 18523 } 18524 } 18525 18526 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18527 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18528 if (packageName == null && permissionNames == null) { 18529 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18530 if (iperm == 0) { 18531 if (dumpState.onTitlePrinted()) 18532 pw.println(); 18533 pw.println("AppOp Permissions:"); 18534 } 18535 pw.print(" AppOp Permission "); 18536 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18537 pw.println(":"); 18538 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18539 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18540 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18541 } 18542 } 18543 } 18544 } 18545 18546 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18547 boolean printedSomething = false; 18548 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18549 if (packageName != null && !packageName.equals(p.info.packageName)) { 18550 continue; 18551 } 18552 if (!printedSomething) { 18553 if (dumpState.onTitlePrinted()) 18554 pw.println(); 18555 pw.println("Registered ContentProviders:"); 18556 printedSomething = true; 18557 } 18558 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18559 pw.print(" "); pw.println(p.toString()); 18560 } 18561 printedSomething = false; 18562 for (Map.Entry<String, PackageParser.Provider> entry : 18563 mProvidersByAuthority.entrySet()) { 18564 PackageParser.Provider p = entry.getValue(); 18565 if (packageName != null && !packageName.equals(p.info.packageName)) { 18566 continue; 18567 } 18568 if (!printedSomething) { 18569 if (dumpState.onTitlePrinted()) 18570 pw.println(); 18571 pw.println("ContentProvider Authorities:"); 18572 printedSomething = true; 18573 } 18574 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18575 pw.print(" "); pw.println(p.toString()); 18576 if (p.info != null && p.info.applicationInfo != null) { 18577 final String appInfo = p.info.applicationInfo.toString(); 18578 pw.print(" applicationInfo="); pw.println(appInfo); 18579 } 18580 } 18581 } 18582 18583 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18584 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18585 } 18586 18587 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18588 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18589 } 18590 18591 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18592 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18593 } 18594 18595 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18596 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18597 } 18598 18599 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18600 // XXX should handle packageName != null by dumping only install data that 18601 // the given package is involved with. 18602 if (dumpState.onTitlePrinted()) pw.println(); 18603 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18604 } 18605 18606 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18607 // XXX should handle packageName != null by dumping only install data that 18608 // the given package is involved with. 18609 if (dumpState.onTitlePrinted()) pw.println(); 18610 18611 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18612 ipw.println(); 18613 ipw.println("Frozen packages:"); 18614 ipw.increaseIndent(); 18615 if (mFrozenPackages.size() == 0) { 18616 ipw.println("(none)"); 18617 } else { 18618 for (int i = 0; i < mFrozenPackages.size(); i++) { 18619 ipw.println(mFrozenPackages.valueAt(i)); 18620 } 18621 } 18622 ipw.decreaseIndent(); 18623 } 18624 18625 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18626 if (dumpState.onTitlePrinted()) pw.println(); 18627 dumpDexoptStateLPr(pw, packageName); 18628 } 18629 18630 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18631 if (dumpState.onTitlePrinted()) pw.println(); 18632 dumpCompilerStatsLPr(pw, packageName); 18633 } 18634 18635 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18636 if (dumpState.onTitlePrinted()) pw.println(); 18637 mSettings.dumpReadMessagesLPr(pw, dumpState); 18638 18639 pw.println(); 18640 pw.println("Package warning messages:"); 18641 BufferedReader in = null; 18642 String line = null; 18643 try { 18644 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18645 while ((line = in.readLine()) != null) { 18646 if (line.contains("ignored: updated version")) continue; 18647 pw.println(line); 18648 } 18649 } catch (IOException ignored) { 18650 } finally { 18651 IoUtils.closeQuietly(in); 18652 } 18653 } 18654 18655 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18656 BufferedReader in = null; 18657 String line = null; 18658 try { 18659 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18660 while ((line = in.readLine()) != null) { 18661 if (line.contains("ignored: updated version")) continue; 18662 pw.print("msg,"); 18663 pw.println(line); 18664 } 18665 } catch (IOException ignored) { 18666 } finally { 18667 IoUtils.closeQuietly(in); 18668 } 18669 } 18670 } 18671 } 18672 18673 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18674 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18675 ipw.println(); 18676 ipw.println("Dexopt state:"); 18677 ipw.increaseIndent(); 18678 Collection<PackageParser.Package> packages = null; 18679 if (packageName != null) { 18680 PackageParser.Package targetPackage = mPackages.get(packageName); 18681 if (targetPackage != null) { 18682 packages = Collections.singletonList(targetPackage); 18683 } else { 18684 ipw.println("Unable to find package: " + packageName); 18685 return; 18686 } 18687 } else { 18688 packages = mPackages.values(); 18689 } 18690 18691 for (PackageParser.Package pkg : packages) { 18692 ipw.println("[" + pkg.packageName + "]"); 18693 ipw.increaseIndent(); 18694 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18695 ipw.decreaseIndent(); 18696 } 18697 } 18698 18699 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18700 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18701 ipw.println(); 18702 ipw.println("Compiler stats:"); 18703 ipw.increaseIndent(); 18704 Collection<PackageParser.Package> packages = null; 18705 if (packageName != null) { 18706 PackageParser.Package targetPackage = mPackages.get(packageName); 18707 if (targetPackage != null) { 18708 packages = Collections.singletonList(targetPackage); 18709 } else { 18710 ipw.println("Unable to find package: " + packageName); 18711 return; 18712 } 18713 } else { 18714 packages = mPackages.values(); 18715 } 18716 18717 for (PackageParser.Package pkg : packages) { 18718 ipw.println("[" + pkg.packageName + "]"); 18719 ipw.increaseIndent(); 18720 18721 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18722 if (stats == null) { 18723 ipw.println("(No recorded stats)"); 18724 } else { 18725 stats.dump(ipw); 18726 } 18727 ipw.decreaseIndent(); 18728 } 18729 } 18730 18731 private String dumpDomainString(String packageName) { 18732 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18733 .getList(); 18734 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18735 18736 ArraySet<String> result = new ArraySet<>(); 18737 if (iviList.size() > 0) { 18738 for (IntentFilterVerificationInfo ivi : iviList) { 18739 for (String host : ivi.getDomains()) { 18740 result.add(host); 18741 } 18742 } 18743 } 18744 if (filters != null && filters.size() > 0) { 18745 for (IntentFilter filter : filters) { 18746 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18747 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18748 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18749 result.addAll(filter.getHostsList()); 18750 } 18751 } 18752 } 18753 18754 StringBuilder sb = new StringBuilder(result.size() * 16); 18755 for (String domain : result) { 18756 if (sb.length() > 0) sb.append(" "); 18757 sb.append(domain); 18758 } 18759 return sb.toString(); 18760 } 18761 18762 // ------- apps on sdcard specific code ------- 18763 static final boolean DEBUG_SD_INSTALL = false; 18764 18765 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18766 18767 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18768 18769 private boolean mMediaMounted = false; 18770 18771 static String getEncryptKey() { 18772 try { 18773 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18774 SD_ENCRYPTION_KEYSTORE_NAME); 18775 if (sdEncKey == null) { 18776 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18777 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18778 if (sdEncKey == null) { 18779 Slog.e(TAG, "Failed to create encryption keys"); 18780 return null; 18781 } 18782 } 18783 return sdEncKey; 18784 } catch (NoSuchAlgorithmException nsae) { 18785 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18786 return null; 18787 } catch (IOException ioe) { 18788 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18789 return null; 18790 } 18791 } 18792 18793 /* 18794 * Update media status on PackageManager. 18795 */ 18796 @Override 18797 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18798 int callingUid = Binder.getCallingUid(); 18799 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18800 throw new SecurityException("Media status can only be updated by the system"); 18801 } 18802 // reader; this apparently protects mMediaMounted, but should probably 18803 // be a different lock in that case. 18804 synchronized (mPackages) { 18805 Log.i(TAG, "Updating external media status from " 18806 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18807 + (mediaStatus ? "mounted" : "unmounted")); 18808 if (DEBUG_SD_INSTALL) 18809 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18810 + ", mMediaMounted=" + mMediaMounted); 18811 if (mediaStatus == mMediaMounted) { 18812 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18813 : 0, -1); 18814 mHandler.sendMessage(msg); 18815 return; 18816 } 18817 mMediaMounted = mediaStatus; 18818 } 18819 // Queue up an async operation since the package installation may take a 18820 // little while. 18821 mHandler.post(new Runnable() { 18822 public void run() { 18823 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18824 } 18825 }); 18826 } 18827 18828 /** 18829 * Called by MountService when the initial ASECs to scan are available. 18830 * Should block until all the ASEC containers are finished being scanned. 18831 */ 18832 public void scanAvailableAsecs() { 18833 updateExternalMediaStatusInner(true, false, false); 18834 } 18835 18836 /* 18837 * Collect information of applications on external media, map them against 18838 * existing containers and update information based on current mount status. 18839 * Please note that we always have to report status if reportStatus has been 18840 * set to true especially when unloading packages. 18841 */ 18842 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18843 boolean externalStorage) { 18844 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18845 int[] uidArr = EmptyArray.INT; 18846 18847 final String[] list = PackageHelper.getSecureContainerList(); 18848 if (ArrayUtils.isEmpty(list)) { 18849 Log.i(TAG, "No secure containers found"); 18850 } else { 18851 // Process list of secure containers and categorize them 18852 // as active or stale based on their package internal state. 18853 18854 // reader 18855 synchronized (mPackages) { 18856 for (String cid : list) { 18857 // Leave stages untouched for now; installer service owns them 18858 if (PackageInstallerService.isStageName(cid)) continue; 18859 18860 if (DEBUG_SD_INSTALL) 18861 Log.i(TAG, "Processing container " + cid); 18862 String pkgName = getAsecPackageName(cid); 18863 if (pkgName == null) { 18864 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18865 continue; 18866 } 18867 if (DEBUG_SD_INSTALL) 18868 Log.i(TAG, "Looking for pkg : " + pkgName); 18869 18870 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18871 if (ps == null) { 18872 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18873 continue; 18874 } 18875 18876 /* 18877 * Skip packages that are not external if we're unmounting 18878 * external storage. 18879 */ 18880 if (externalStorage && !isMounted && !isExternal(ps)) { 18881 continue; 18882 } 18883 18884 final AsecInstallArgs args = new AsecInstallArgs(cid, 18885 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18886 // The package status is changed only if the code path 18887 // matches between settings and the container id. 18888 if (ps.codePathString != null 18889 && ps.codePathString.startsWith(args.getCodePath())) { 18890 if (DEBUG_SD_INSTALL) { 18891 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18892 + " at code path: " + ps.codePathString); 18893 } 18894 18895 // We do have a valid package installed on sdcard 18896 processCids.put(args, ps.codePathString); 18897 final int uid = ps.appId; 18898 if (uid != -1) { 18899 uidArr = ArrayUtils.appendInt(uidArr, uid); 18900 } 18901 } else { 18902 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18903 + ps.codePathString); 18904 } 18905 } 18906 } 18907 18908 Arrays.sort(uidArr); 18909 } 18910 18911 // Process packages with valid entries. 18912 if (isMounted) { 18913 if (DEBUG_SD_INSTALL) 18914 Log.i(TAG, "Loading packages"); 18915 loadMediaPackages(processCids, uidArr, externalStorage); 18916 startCleaningPackages(); 18917 mInstallerService.onSecureContainersAvailable(); 18918 } else { 18919 if (DEBUG_SD_INSTALL) 18920 Log.i(TAG, "Unloading packages"); 18921 unloadMediaPackages(processCids, uidArr, reportStatus); 18922 } 18923 } 18924 18925 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18926 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18927 final int size = infos.size(); 18928 final String[] packageNames = new String[size]; 18929 final int[] packageUids = new int[size]; 18930 for (int i = 0; i < size; i++) { 18931 final ApplicationInfo info = infos.get(i); 18932 packageNames[i] = info.packageName; 18933 packageUids[i] = info.uid; 18934 } 18935 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18936 finishedReceiver); 18937 } 18938 18939 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18940 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18941 sendResourcesChangedBroadcast(mediaStatus, replacing, 18942 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18943 } 18944 18945 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18946 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18947 int size = pkgList.length; 18948 if (size > 0) { 18949 // Send broadcasts here 18950 Bundle extras = new Bundle(); 18951 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18952 if (uidArr != null) { 18953 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18954 } 18955 if (replacing) { 18956 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18957 } 18958 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18959 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18960 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18961 } 18962 } 18963 18964 /* 18965 * Look at potentially valid container ids from processCids If package 18966 * information doesn't match the one on record or package scanning fails, 18967 * the cid is added to list of removeCids. We currently don't delete stale 18968 * containers. 18969 */ 18970 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18971 boolean externalStorage) { 18972 ArrayList<String> pkgList = new ArrayList<String>(); 18973 Set<AsecInstallArgs> keys = processCids.keySet(); 18974 18975 for (AsecInstallArgs args : keys) { 18976 String codePath = processCids.get(args); 18977 if (DEBUG_SD_INSTALL) 18978 Log.i(TAG, "Loading container : " + args.cid); 18979 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18980 try { 18981 // Make sure there are no container errors first. 18982 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18983 Slog.e(TAG, "Failed to mount cid : " + args.cid 18984 + " when installing from sdcard"); 18985 continue; 18986 } 18987 // Check code path here. 18988 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18989 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18990 + " does not match one in settings " + codePath); 18991 continue; 18992 } 18993 // Parse package 18994 int parseFlags = mDefParseFlags; 18995 if (args.isExternalAsec()) { 18996 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18997 } 18998 if (args.isFwdLocked()) { 18999 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19000 } 19001 19002 synchronized (mInstallLock) { 19003 PackageParser.Package pkg = null; 19004 try { 19005 // Sadly we don't know the package name yet to freeze it 19006 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19007 SCAN_IGNORE_FROZEN, 0, null); 19008 } catch (PackageManagerException e) { 19009 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19010 } 19011 // Scan the package 19012 if (pkg != null) { 19013 /* 19014 * TODO why is the lock being held? doPostInstall is 19015 * called in other places without the lock. This needs 19016 * to be straightened out. 19017 */ 19018 // writer 19019 synchronized (mPackages) { 19020 retCode = PackageManager.INSTALL_SUCCEEDED; 19021 pkgList.add(pkg.packageName); 19022 // Post process args 19023 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19024 pkg.applicationInfo.uid); 19025 } 19026 } else { 19027 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19028 } 19029 } 19030 19031 } finally { 19032 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19033 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19034 } 19035 } 19036 } 19037 // writer 19038 synchronized (mPackages) { 19039 // If the platform SDK has changed since the last time we booted, 19040 // we need to re-grant app permission to catch any new ones that 19041 // appear. This is really a hack, and means that apps can in some 19042 // cases get permissions that the user didn't initially explicitly 19043 // allow... it would be nice to have some better way to handle 19044 // this situation. 19045 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19046 : mSettings.getInternalVersion(); 19047 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19048 : StorageManager.UUID_PRIVATE_INTERNAL; 19049 19050 int updateFlags = UPDATE_PERMISSIONS_ALL; 19051 if (ver.sdkVersion != mSdkVersion) { 19052 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19053 + mSdkVersion + "; regranting permissions for external"); 19054 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19055 } 19056 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19057 19058 // Yay, everything is now upgraded 19059 ver.forceCurrent(); 19060 19061 // can downgrade to reader 19062 // Persist settings 19063 mSettings.writeLPr(); 19064 } 19065 // Send a broadcast to let everyone know we are done processing 19066 if (pkgList.size() > 0) { 19067 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19068 } 19069 } 19070 19071 /* 19072 * Utility method to unload a list of specified containers 19073 */ 19074 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19075 // Just unmount all valid containers. 19076 for (AsecInstallArgs arg : cidArgs) { 19077 synchronized (mInstallLock) { 19078 arg.doPostDeleteLI(false); 19079 } 19080 } 19081 } 19082 19083 /* 19084 * Unload packages mounted on external media. This involves deleting package 19085 * data from internal structures, sending broadcasts about disabled packages, 19086 * gc'ing to free up references, unmounting all secure containers 19087 * corresponding to packages on external media, and posting a 19088 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19089 * that we always have to post this message if status has been requested no 19090 * matter what. 19091 */ 19092 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19093 final boolean reportStatus) { 19094 if (DEBUG_SD_INSTALL) 19095 Log.i(TAG, "unloading media packages"); 19096 ArrayList<String> pkgList = new ArrayList<String>(); 19097 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19098 final Set<AsecInstallArgs> keys = processCids.keySet(); 19099 for (AsecInstallArgs args : keys) { 19100 String pkgName = args.getPackageName(); 19101 if (DEBUG_SD_INSTALL) 19102 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19103 // Delete package internally 19104 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19105 synchronized (mInstallLock) { 19106 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19107 final boolean res; 19108 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19109 "unloadMediaPackages")) { 19110 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19111 null); 19112 } 19113 if (res) { 19114 pkgList.add(pkgName); 19115 } else { 19116 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19117 failedList.add(args); 19118 } 19119 } 19120 } 19121 19122 // reader 19123 synchronized (mPackages) { 19124 // We didn't update the settings after removing each package; 19125 // write them now for all packages. 19126 mSettings.writeLPr(); 19127 } 19128 19129 // We have to absolutely send UPDATED_MEDIA_STATUS only 19130 // after confirming that all the receivers processed the ordered 19131 // broadcast when packages get disabled, force a gc to clean things up. 19132 // and unload all the containers. 19133 if (pkgList.size() > 0) { 19134 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19135 new IIntentReceiver.Stub() { 19136 public void performReceive(Intent intent, int resultCode, String data, 19137 Bundle extras, boolean ordered, boolean sticky, 19138 int sendingUser) throws RemoteException { 19139 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19140 reportStatus ? 1 : 0, 1, keys); 19141 mHandler.sendMessage(msg); 19142 } 19143 }); 19144 } else { 19145 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19146 keys); 19147 mHandler.sendMessage(msg); 19148 } 19149 } 19150 19151 private void loadPrivatePackages(final VolumeInfo vol) { 19152 mHandler.post(new Runnable() { 19153 @Override 19154 public void run() { 19155 loadPrivatePackagesInner(vol); 19156 } 19157 }); 19158 } 19159 19160 private void loadPrivatePackagesInner(VolumeInfo vol) { 19161 final String volumeUuid = vol.fsUuid; 19162 if (TextUtils.isEmpty(volumeUuid)) { 19163 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19164 return; 19165 } 19166 19167 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19168 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19169 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19170 19171 final VersionInfo ver; 19172 final List<PackageSetting> packages; 19173 synchronized (mPackages) { 19174 ver = mSettings.findOrCreateVersion(volumeUuid); 19175 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19176 } 19177 19178 for (PackageSetting ps : packages) { 19179 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19180 synchronized (mInstallLock) { 19181 final PackageParser.Package pkg; 19182 try { 19183 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19184 loaded.add(pkg.applicationInfo); 19185 19186 } catch (PackageManagerException e) { 19187 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19188 } 19189 19190 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19191 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19192 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19193 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19194 } 19195 } 19196 } 19197 19198 // Reconcile app data for all started/unlocked users 19199 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19200 final UserManager um = mContext.getSystemService(UserManager.class); 19201 UserManagerInternal umInternal = getUserManagerInternal(); 19202 for (UserInfo user : um.getUsers()) { 19203 final int flags; 19204 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19205 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19206 } else if (umInternal.isUserRunning(user.id)) { 19207 flags = StorageManager.FLAG_STORAGE_DE; 19208 } else { 19209 continue; 19210 } 19211 19212 try { 19213 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19214 synchronized (mInstallLock) { 19215 reconcileAppsDataLI(volumeUuid, user.id, flags); 19216 } 19217 } catch (IllegalStateException e) { 19218 // Device was probably ejected, and we'll process that event momentarily 19219 Slog.w(TAG, "Failed to prepare storage: " + e); 19220 } 19221 } 19222 19223 synchronized (mPackages) { 19224 int updateFlags = UPDATE_PERMISSIONS_ALL; 19225 if (ver.sdkVersion != mSdkVersion) { 19226 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19227 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19228 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19229 } 19230 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19231 19232 // Yay, everything is now upgraded 19233 ver.forceCurrent(); 19234 19235 mSettings.writeLPr(); 19236 } 19237 19238 for (PackageFreezer freezer : freezers) { 19239 freezer.close(); 19240 } 19241 19242 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19243 sendResourcesChangedBroadcast(true, false, loaded, null); 19244 } 19245 19246 private void unloadPrivatePackages(final VolumeInfo vol) { 19247 mHandler.post(new Runnable() { 19248 @Override 19249 public void run() { 19250 unloadPrivatePackagesInner(vol); 19251 } 19252 }); 19253 } 19254 19255 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19256 final String volumeUuid = vol.fsUuid; 19257 if (TextUtils.isEmpty(volumeUuid)) { 19258 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19259 return; 19260 } 19261 19262 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19263 synchronized (mInstallLock) { 19264 synchronized (mPackages) { 19265 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19266 for (PackageSetting ps : packages) { 19267 if (ps.pkg == null) continue; 19268 19269 final ApplicationInfo info = ps.pkg.applicationInfo; 19270 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19271 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19272 19273 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19274 "unloadPrivatePackagesInner")) { 19275 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19276 false, null)) { 19277 unloaded.add(info); 19278 } else { 19279 Slog.w(TAG, "Failed to unload " + ps.codePath); 19280 } 19281 } 19282 19283 // Try very hard to release any references to this package 19284 // so we don't risk the system server being killed due to 19285 // open FDs 19286 AttributeCache.instance().removePackage(ps.name); 19287 } 19288 19289 mSettings.writeLPr(); 19290 } 19291 } 19292 19293 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19294 sendResourcesChangedBroadcast(false, false, unloaded, null); 19295 19296 // Try very hard to release any references to this path so we don't risk 19297 // the system server being killed due to open FDs 19298 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19299 19300 for (int i = 0; i < 3; i++) { 19301 System.gc(); 19302 System.runFinalization(); 19303 } 19304 } 19305 19306 /** 19307 * Prepare storage areas for given user on all mounted devices. 19308 */ 19309 void prepareUserData(int userId, int userSerial, int flags) { 19310 synchronized (mInstallLock) { 19311 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19312 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19313 final String volumeUuid = vol.getFsUuid(); 19314 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19315 } 19316 } 19317 } 19318 19319 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19320 boolean allowRecover) { 19321 // Prepare storage and verify that serial numbers are consistent; if 19322 // there's a mismatch we need to destroy to avoid leaking data 19323 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19324 try { 19325 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19326 19327 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19328 UserManagerService.enforceSerialNumber( 19329 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19330 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19331 UserManagerService.enforceSerialNumber( 19332 Environment.getDataSystemDeDirectory(userId), userSerial); 19333 } 19334 } 19335 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19336 UserManagerService.enforceSerialNumber( 19337 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19338 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19339 UserManagerService.enforceSerialNumber( 19340 Environment.getDataSystemCeDirectory(userId), userSerial); 19341 } 19342 } 19343 19344 synchronized (mInstallLock) { 19345 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19346 } 19347 } catch (Exception e) { 19348 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19349 + " because we failed to prepare: " + e); 19350 destroyUserDataLI(volumeUuid, userId, 19351 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19352 19353 if (allowRecover) { 19354 // Try one last time; if we fail again we're really in trouble 19355 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19356 } 19357 } 19358 } 19359 19360 /** 19361 * Destroy storage areas for given user on all mounted devices. 19362 */ 19363 void destroyUserData(int userId, int flags) { 19364 synchronized (mInstallLock) { 19365 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19366 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19367 final String volumeUuid = vol.getFsUuid(); 19368 destroyUserDataLI(volumeUuid, userId, flags); 19369 } 19370 } 19371 } 19372 19373 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19374 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19375 try { 19376 // Clean up app data, profile data, and media data 19377 mInstaller.destroyUserData(volumeUuid, userId, flags); 19378 19379 // Clean up system data 19380 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19381 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19382 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19383 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19384 } 19385 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19386 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19387 } 19388 } 19389 19390 // Data with special labels is now gone, so finish the job 19391 storage.destroyUserStorage(volumeUuid, userId, flags); 19392 19393 } catch (Exception e) { 19394 logCriticalInfo(Log.WARN, 19395 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19396 } 19397 } 19398 19399 /** 19400 * Examine all users present on given mounted volume, and destroy data 19401 * belonging to users that are no longer valid, or whose user ID has been 19402 * recycled. 19403 */ 19404 private void reconcileUsers(String volumeUuid) { 19405 final List<File> files = new ArrayList<>(); 19406 Collections.addAll(files, FileUtils 19407 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19408 Collections.addAll(files, FileUtils 19409 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19410 Collections.addAll(files, FileUtils 19411 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19412 Collections.addAll(files, FileUtils 19413 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19414 for (File file : files) { 19415 if (!file.isDirectory()) continue; 19416 19417 final int userId; 19418 final UserInfo info; 19419 try { 19420 userId = Integer.parseInt(file.getName()); 19421 info = sUserManager.getUserInfo(userId); 19422 } catch (NumberFormatException e) { 19423 Slog.w(TAG, "Invalid user directory " + file); 19424 continue; 19425 } 19426 19427 boolean destroyUser = false; 19428 if (info == null) { 19429 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19430 + " because no matching user was found"); 19431 destroyUser = true; 19432 } else if (!mOnlyCore) { 19433 try { 19434 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19435 } catch (IOException e) { 19436 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19437 + " because we failed to enforce serial number: " + e); 19438 destroyUser = true; 19439 } 19440 } 19441 19442 if (destroyUser) { 19443 synchronized (mInstallLock) { 19444 destroyUserDataLI(volumeUuid, userId, 19445 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19446 } 19447 } 19448 } 19449 } 19450 19451 private void assertPackageKnown(String volumeUuid, String packageName) 19452 throws PackageManagerException { 19453 synchronized (mPackages) { 19454 final PackageSetting ps = mSettings.mPackages.get(packageName); 19455 if (ps == null) { 19456 throw new PackageManagerException("Package " + packageName + " is unknown"); 19457 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19458 throw new PackageManagerException( 19459 "Package " + packageName + " found on unknown volume " + volumeUuid 19460 + "; expected volume " + ps.volumeUuid); 19461 } 19462 } 19463 } 19464 19465 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19466 throws PackageManagerException { 19467 synchronized (mPackages) { 19468 final PackageSetting ps = mSettings.mPackages.get(packageName); 19469 if (ps == null) { 19470 throw new PackageManagerException("Package " + packageName + " is unknown"); 19471 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19472 throw new PackageManagerException( 19473 "Package " + packageName + " found on unknown volume " + volumeUuid 19474 + "; expected volume " + ps.volumeUuid); 19475 } else if (!ps.getInstalled(userId)) { 19476 throw new PackageManagerException( 19477 "Package " + packageName + " not installed for user " + userId); 19478 } 19479 } 19480 } 19481 19482 /** 19483 * Examine all apps present on given mounted volume, and destroy apps that 19484 * aren't expected, either due to uninstallation or reinstallation on 19485 * another volume. 19486 */ 19487 private void reconcileApps(String volumeUuid) { 19488 final File[] files = FileUtils 19489 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19490 for (File file : files) { 19491 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19492 && !PackageInstallerService.isStageName(file.getName()); 19493 if (!isPackage) { 19494 // Ignore entries which are not packages 19495 continue; 19496 } 19497 19498 try { 19499 final PackageLite pkg = PackageParser.parsePackageLite(file, 19500 PackageParser.PARSE_MUST_BE_APK); 19501 assertPackageKnown(volumeUuid, pkg.packageName); 19502 19503 } catch (PackageParserException | PackageManagerException e) { 19504 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19505 synchronized (mInstallLock) { 19506 removeCodePathLI(file); 19507 } 19508 } 19509 } 19510 } 19511 19512 /** 19513 * Reconcile all app data for the given user. 19514 * <p> 19515 * Verifies that directories exist and that ownership and labeling is 19516 * correct for all installed apps on all mounted volumes. 19517 */ 19518 void reconcileAppsData(int userId, int flags) { 19519 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19520 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19521 final String volumeUuid = vol.getFsUuid(); 19522 synchronized (mInstallLock) { 19523 reconcileAppsDataLI(volumeUuid, userId, flags); 19524 } 19525 } 19526 } 19527 19528 /** 19529 * Reconcile all app data on given mounted volume. 19530 * <p> 19531 * Destroys app data that isn't expected, either due to uninstallation or 19532 * reinstallation on another volume. 19533 * <p> 19534 * Verifies that directories exist and that ownership and labeling is 19535 * correct for all installed apps. 19536 */ 19537 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19538 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19539 + Integer.toHexString(flags)); 19540 19541 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19542 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19543 19544 boolean restoreconNeeded = false; 19545 19546 // First look for stale data that doesn't belong, and check if things 19547 // have changed since we did our last restorecon 19548 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19549 if (StorageManager.isFileEncryptedNativeOrEmulated() 19550 && !StorageManager.isUserKeyUnlocked(userId)) { 19551 throw new RuntimeException( 19552 "Yikes, someone asked us to reconcile CE storage while " + userId 19553 + " was still locked; this would have caused massive data loss!"); 19554 } 19555 19556 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19557 19558 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19559 for (File file : files) { 19560 final String packageName = file.getName(); 19561 try { 19562 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19563 } catch (PackageManagerException e) { 19564 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19565 try { 19566 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19567 StorageManager.FLAG_STORAGE_CE, 0); 19568 } catch (InstallerException e2) { 19569 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19570 } 19571 } 19572 } 19573 } 19574 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19575 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19576 19577 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19578 for (File file : files) { 19579 final String packageName = file.getName(); 19580 try { 19581 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19582 } catch (PackageManagerException e) { 19583 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19584 try { 19585 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19586 StorageManager.FLAG_STORAGE_DE, 0); 19587 } catch (InstallerException e2) { 19588 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19589 } 19590 } 19591 } 19592 } 19593 19594 // Ensure that data directories are ready to roll for all packages 19595 // installed for this volume and user 19596 final List<PackageSetting> packages; 19597 synchronized (mPackages) { 19598 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19599 } 19600 int preparedCount = 0; 19601 for (PackageSetting ps : packages) { 19602 final String packageName = ps.name; 19603 if (ps.pkg == null) { 19604 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19605 // TODO: might be due to legacy ASEC apps; we should circle back 19606 // and reconcile again once they're scanned 19607 continue; 19608 } 19609 19610 if (ps.getInstalled(userId)) { 19611 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19612 19613 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19614 // We may have just shuffled around app data directories, so 19615 // prepare them one more time 19616 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19617 } 19618 19619 preparedCount++; 19620 } 19621 } 19622 19623 if (restoreconNeeded) { 19624 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19625 SELinuxMMAC.setRestoreconDone(ceDir); 19626 } 19627 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19628 SELinuxMMAC.setRestoreconDone(deDir); 19629 } 19630 } 19631 19632 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19633 + " packages; restoreconNeeded was " + restoreconNeeded); 19634 } 19635 19636 /** 19637 * Prepare app data for the given app just after it was installed or 19638 * upgraded. This method carefully only touches users that it's installed 19639 * for, and it forces a restorecon to handle any seinfo changes. 19640 * <p> 19641 * Verifies that directories exist and that ownership and labeling is 19642 * correct for all installed apps. If there is an ownership mismatch, it 19643 * will try recovering system apps by wiping data; third-party app data is 19644 * left intact. 19645 * <p> 19646 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19647 */ 19648 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19649 final PackageSetting ps; 19650 synchronized (mPackages) { 19651 ps = mSettings.mPackages.get(pkg.packageName); 19652 mSettings.writeKernelMappingLPr(ps); 19653 } 19654 19655 final UserManager um = mContext.getSystemService(UserManager.class); 19656 UserManagerInternal umInternal = getUserManagerInternal(); 19657 for (UserInfo user : um.getUsers()) { 19658 final int flags; 19659 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19660 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19661 } else if (umInternal.isUserRunning(user.id)) { 19662 flags = StorageManager.FLAG_STORAGE_DE; 19663 } else { 19664 continue; 19665 } 19666 19667 if (ps.getInstalled(user.id)) { 19668 // Whenever an app changes, force a restorecon of its data 19669 // TODO: when user data is locked, mark that we're still dirty 19670 prepareAppDataLIF(pkg, user.id, flags, true); 19671 } 19672 } 19673 } 19674 19675 /** 19676 * Prepare app data for the given app. 19677 * <p> 19678 * Verifies that directories exist and that ownership and labeling is 19679 * correct for all installed apps. If there is an ownership mismatch, this 19680 * will try recovering system apps by wiping data; third-party app data is 19681 * left intact. 19682 */ 19683 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19684 boolean restoreconNeeded) { 19685 if (pkg == null) { 19686 Slog.wtf(TAG, "Package was null!", new Throwable()); 19687 return; 19688 } 19689 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19690 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19691 for (int i = 0; i < childCount; i++) { 19692 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19693 } 19694 } 19695 19696 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19697 boolean restoreconNeeded) { 19698 if (DEBUG_APP_DATA) { 19699 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19700 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19701 } 19702 19703 final String volumeUuid = pkg.volumeUuid; 19704 final String packageName = pkg.packageName; 19705 final ApplicationInfo app = pkg.applicationInfo; 19706 final int appId = UserHandle.getAppId(app.uid); 19707 19708 Preconditions.checkNotNull(app.seinfo); 19709 19710 try { 19711 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19712 appId, app.seinfo, app.targetSdkVersion); 19713 } catch (InstallerException e) { 19714 if (app.isSystemApp()) { 19715 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19716 + ", but trying to recover: " + e); 19717 destroyAppDataLeafLIF(pkg, userId, flags); 19718 try { 19719 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19720 appId, app.seinfo, app.targetSdkVersion); 19721 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19722 } catch (InstallerException e2) { 19723 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19724 } 19725 } else { 19726 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19727 } 19728 } 19729 19730 if (restoreconNeeded) { 19731 try { 19732 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19733 app.seinfo); 19734 } catch (InstallerException e) { 19735 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19736 } 19737 } 19738 19739 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19740 try { 19741 // CE storage is unlocked right now, so read out the inode and 19742 // remember for use later when it's locked 19743 // TODO: mark this structure as dirty so we persist it! 19744 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19745 StorageManager.FLAG_STORAGE_CE); 19746 synchronized (mPackages) { 19747 final PackageSetting ps = mSettings.mPackages.get(packageName); 19748 if (ps != null) { 19749 ps.setCeDataInode(ceDataInode, userId); 19750 } 19751 } 19752 } catch (InstallerException e) { 19753 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19754 } 19755 } 19756 19757 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19758 } 19759 19760 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19761 if (pkg == null) { 19762 Slog.wtf(TAG, "Package was null!", new Throwable()); 19763 return; 19764 } 19765 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19766 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19767 for (int i = 0; i < childCount; i++) { 19768 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19769 } 19770 } 19771 19772 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19773 final String volumeUuid = pkg.volumeUuid; 19774 final String packageName = pkg.packageName; 19775 final ApplicationInfo app = pkg.applicationInfo; 19776 19777 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19778 // Create a native library symlink only if we have native libraries 19779 // and if the native libraries are 32 bit libraries. We do not provide 19780 // this symlink for 64 bit libraries. 19781 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19782 final String nativeLibPath = app.nativeLibraryDir; 19783 try { 19784 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19785 nativeLibPath, userId); 19786 } catch (InstallerException e) { 19787 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19788 } 19789 } 19790 } 19791 } 19792 19793 /** 19794 * For system apps on non-FBE devices, this method migrates any existing 19795 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19796 * requested by the app. 19797 */ 19798 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19799 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19800 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19801 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19802 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19803 try { 19804 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19805 storageTarget); 19806 } catch (InstallerException e) { 19807 logCriticalInfo(Log.WARN, 19808 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19809 } 19810 return true; 19811 } else { 19812 return false; 19813 } 19814 } 19815 19816 public PackageFreezer freezePackage(String packageName, String killReason) { 19817 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19818 } 19819 19820 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19821 return new PackageFreezer(packageName, userId, killReason); 19822 } 19823 19824 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19825 String killReason) { 19826 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19827 } 19828 19829 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19830 String killReason) { 19831 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19832 return new PackageFreezer(); 19833 } else { 19834 return freezePackage(packageName, userId, killReason); 19835 } 19836 } 19837 19838 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19839 String killReason) { 19840 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19841 } 19842 19843 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19844 String killReason) { 19845 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19846 return new PackageFreezer(); 19847 } else { 19848 return freezePackage(packageName, userId, killReason); 19849 } 19850 } 19851 19852 /** 19853 * Class that freezes and kills the given package upon creation, and 19854 * unfreezes it upon closing. This is typically used when doing surgery on 19855 * app code/data to prevent the app from running while you're working. 19856 */ 19857 private class PackageFreezer implements AutoCloseable { 19858 private final String mPackageName; 19859 private final PackageFreezer[] mChildren; 19860 19861 private final boolean mWeFroze; 19862 19863 private final AtomicBoolean mClosed = new AtomicBoolean(); 19864 private final CloseGuard mCloseGuard = CloseGuard.get(); 19865 19866 /** 19867 * Create and return a stub freezer that doesn't actually do anything, 19868 * typically used when someone requested 19869 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19870 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19871 */ 19872 public PackageFreezer() { 19873 mPackageName = null; 19874 mChildren = null; 19875 mWeFroze = false; 19876 mCloseGuard.open("close"); 19877 } 19878 19879 public PackageFreezer(String packageName, int userId, String killReason) { 19880 synchronized (mPackages) { 19881 mPackageName = packageName; 19882 mWeFroze = mFrozenPackages.add(mPackageName); 19883 19884 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19885 if (ps != null) { 19886 killApplication(ps.name, ps.appId, userId, killReason); 19887 } 19888 19889 final PackageParser.Package p = mPackages.get(packageName); 19890 if (p != null && p.childPackages != null) { 19891 final int N = p.childPackages.size(); 19892 mChildren = new PackageFreezer[N]; 19893 for (int i = 0; i < N; i++) { 19894 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19895 userId, killReason); 19896 } 19897 } else { 19898 mChildren = null; 19899 } 19900 } 19901 mCloseGuard.open("close"); 19902 } 19903 19904 @Override 19905 protected void finalize() throws Throwable { 19906 try { 19907 mCloseGuard.warnIfOpen(); 19908 close(); 19909 } finally { 19910 super.finalize(); 19911 } 19912 } 19913 19914 @Override 19915 public void close() { 19916 mCloseGuard.close(); 19917 if (mClosed.compareAndSet(false, true)) { 19918 synchronized (mPackages) { 19919 if (mWeFroze) { 19920 mFrozenPackages.remove(mPackageName); 19921 } 19922 19923 if (mChildren != null) { 19924 for (PackageFreezer freezer : mChildren) { 19925 freezer.close(); 19926 } 19927 } 19928 } 19929 } 19930 } 19931 } 19932 19933 /** 19934 * Verify that given package is currently frozen. 19935 */ 19936 private void checkPackageFrozen(String packageName) { 19937 synchronized (mPackages) { 19938 if (!mFrozenPackages.contains(packageName)) { 19939 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19940 } 19941 } 19942 } 19943 19944 @Override 19945 public int movePackage(final String packageName, final String volumeUuid) { 19946 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19947 19948 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19949 final int moveId = mNextMoveId.getAndIncrement(); 19950 mHandler.post(new Runnable() { 19951 @Override 19952 public void run() { 19953 try { 19954 movePackageInternal(packageName, volumeUuid, moveId, user); 19955 } catch (PackageManagerException e) { 19956 Slog.w(TAG, "Failed to move " + packageName, e); 19957 mMoveCallbacks.notifyStatusChanged(moveId, 19958 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19959 } 19960 } 19961 }); 19962 return moveId; 19963 } 19964 19965 private void movePackageInternal(final String packageName, final String volumeUuid, 19966 final int moveId, UserHandle user) throws PackageManagerException { 19967 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19968 final PackageManager pm = mContext.getPackageManager(); 19969 19970 final boolean currentAsec; 19971 final String currentVolumeUuid; 19972 final File codeFile; 19973 final String installerPackageName; 19974 final String packageAbiOverride; 19975 final int appId; 19976 final String seinfo; 19977 final String label; 19978 final int targetSdkVersion; 19979 final PackageFreezer freezer; 19980 final int[] installedUserIds; 19981 19982 // reader 19983 synchronized (mPackages) { 19984 final PackageParser.Package pkg = mPackages.get(packageName); 19985 final PackageSetting ps = mSettings.mPackages.get(packageName); 19986 if (pkg == null || ps == null) { 19987 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19988 } 19989 19990 if (pkg.applicationInfo.isSystemApp()) { 19991 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19992 "Cannot move system application"); 19993 } 19994 19995 if (pkg.applicationInfo.isExternalAsec()) { 19996 currentAsec = true; 19997 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19998 } else if (pkg.applicationInfo.isForwardLocked()) { 19999 currentAsec = true; 20000 currentVolumeUuid = "forward_locked"; 20001 } else { 20002 currentAsec = false; 20003 currentVolumeUuid = ps.volumeUuid; 20004 20005 final File probe = new File(pkg.codePath); 20006 final File probeOat = new File(probe, "oat"); 20007 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20008 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20009 "Move only supported for modern cluster style installs"); 20010 } 20011 } 20012 20013 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20014 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20015 "Package already moved to " + volumeUuid); 20016 } 20017 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20018 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20019 "Device admin cannot be moved"); 20020 } 20021 20022 if (mFrozenPackages.contains(packageName)) { 20023 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20024 "Failed to move already frozen package"); 20025 } 20026 20027 codeFile = new File(pkg.codePath); 20028 installerPackageName = ps.installerPackageName; 20029 packageAbiOverride = ps.cpuAbiOverrideString; 20030 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20031 seinfo = pkg.applicationInfo.seinfo; 20032 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20033 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20034 freezer = freezePackage(packageName, "movePackageInternal"); 20035 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20036 } 20037 20038 final Bundle extras = new Bundle(); 20039 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20040 extras.putString(Intent.EXTRA_TITLE, label); 20041 mMoveCallbacks.notifyCreated(moveId, extras); 20042 20043 int installFlags; 20044 final boolean moveCompleteApp; 20045 final File measurePath; 20046 20047 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20048 installFlags = INSTALL_INTERNAL; 20049 moveCompleteApp = !currentAsec; 20050 measurePath = Environment.getDataAppDirectory(volumeUuid); 20051 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20052 installFlags = INSTALL_EXTERNAL; 20053 moveCompleteApp = false; 20054 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20055 } else { 20056 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20057 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20058 || !volume.isMountedWritable()) { 20059 freezer.close(); 20060 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20061 "Move location not mounted private volume"); 20062 } 20063 20064 Preconditions.checkState(!currentAsec); 20065 20066 installFlags = INSTALL_INTERNAL; 20067 moveCompleteApp = true; 20068 measurePath = Environment.getDataAppDirectory(volumeUuid); 20069 } 20070 20071 final PackageStats stats = new PackageStats(null, -1); 20072 synchronized (mInstaller) { 20073 for (int userId : installedUserIds) { 20074 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20075 freezer.close(); 20076 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20077 "Failed to measure package size"); 20078 } 20079 } 20080 } 20081 20082 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20083 + stats.dataSize); 20084 20085 final long startFreeBytes = measurePath.getFreeSpace(); 20086 final long sizeBytes; 20087 if (moveCompleteApp) { 20088 sizeBytes = stats.codeSize + stats.dataSize; 20089 } else { 20090 sizeBytes = stats.codeSize; 20091 } 20092 20093 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20094 freezer.close(); 20095 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20096 "Not enough free space to move"); 20097 } 20098 20099 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20100 20101 final CountDownLatch installedLatch = new CountDownLatch(1); 20102 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20103 @Override 20104 public void onUserActionRequired(Intent intent) throws RemoteException { 20105 throw new IllegalStateException(); 20106 } 20107 20108 @Override 20109 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20110 Bundle extras) throws RemoteException { 20111 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20112 + PackageManager.installStatusToString(returnCode, msg)); 20113 20114 installedLatch.countDown(); 20115 freezer.close(); 20116 20117 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20118 switch (status) { 20119 case PackageInstaller.STATUS_SUCCESS: 20120 mMoveCallbacks.notifyStatusChanged(moveId, 20121 PackageManager.MOVE_SUCCEEDED); 20122 break; 20123 case PackageInstaller.STATUS_FAILURE_STORAGE: 20124 mMoveCallbacks.notifyStatusChanged(moveId, 20125 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20126 break; 20127 default: 20128 mMoveCallbacks.notifyStatusChanged(moveId, 20129 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20130 break; 20131 } 20132 } 20133 }; 20134 20135 final MoveInfo move; 20136 if (moveCompleteApp) { 20137 // Kick off a thread to report progress estimates 20138 new Thread() { 20139 @Override 20140 public void run() { 20141 while (true) { 20142 try { 20143 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20144 break; 20145 } 20146 } catch (InterruptedException ignored) { 20147 } 20148 20149 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20150 final int progress = 10 + (int) MathUtils.constrain( 20151 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20152 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20153 } 20154 } 20155 }.start(); 20156 20157 final String dataAppName = codeFile.getName(); 20158 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20159 dataAppName, appId, seinfo, targetSdkVersion); 20160 } else { 20161 move = null; 20162 } 20163 20164 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20165 20166 final Message msg = mHandler.obtainMessage(INIT_COPY); 20167 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20168 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20169 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20170 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20171 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20172 msg.obj = params; 20173 20174 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20175 System.identityHashCode(msg.obj)); 20176 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20177 System.identityHashCode(msg.obj)); 20178 20179 mHandler.sendMessage(msg); 20180 } 20181 20182 @Override 20183 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20184 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20185 20186 final int realMoveId = mNextMoveId.getAndIncrement(); 20187 final Bundle extras = new Bundle(); 20188 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20189 mMoveCallbacks.notifyCreated(realMoveId, extras); 20190 20191 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20192 @Override 20193 public void onCreated(int moveId, Bundle extras) { 20194 // Ignored 20195 } 20196 20197 @Override 20198 public void onStatusChanged(int moveId, int status, long estMillis) { 20199 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20200 } 20201 }; 20202 20203 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20204 storage.setPrimaryStorageUuid(volumeUuid, callback); 20205 return realMoveId; 20206 } 20207 20208 @Override 20209 public int getMoveStatus(int moveId) { 20210 mContext.enforceCallingOrSelfPermission( 20211 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20212 return mMoveCallbacks.mLastStatus.get(moveId); 20213 } 20214 20215 @Override 20216 public void registerMoveCallback(IPackageMoveObserver callback) { 20217 mContext.enforceCallingOrSelfPermission( 20218 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20219 mMoveCallbacks.register(callback); 20220 } 20221 20222 @Override 20223 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20224 mContext.enforceCallingOrSelfPermission( 20225 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20226 mMoveCallbacks.unregister(callback); 20227 } 20228 20229 @Override 20230 public boolean setInstallLocation(int loc) { 20231 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20232 null); 20233 if (getInstallLocation() == loc) { 20234 return true; 20235 } 20236 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20237 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20238 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20239 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20240 return true; 20241 } 20242 return false; 20243 } 20244 20245 @Override 20246 public int getInstallLocation() { 20247 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20248 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20249 PackageHelper.APP_INSTALL_AUTO); 20250 } 20251 20252 /** Called by UserManagerService */ 20253 void cleanUpUser(UserManagerService userManager, int userHandle) { 20254 synchronized (mPackages) { 20255 mDirtyUsers.remove(userHandle); 20256 mUserNeedsBadging.delete(userHandle); 20257 mSettings.removeUserLPw(userHandle); 20258 mPendingBroadcasts.remove(userHandle); 20259 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20260 removeUnusedPackagesLPw(userManager, userHandle); 20261 } 20262 } 20263 20264 /** 20265 * We're removing userHandle and would like to remove any downloaded packages 20266 * that are no longer in use by any other user. 20267 * @param userHandle the user being removed 20268 */ 20269 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20270 final boolean DEBUG_CLEAN_APKS = false; 20271 int [] users = userManager.getUserIds(); 20272 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20273 while (psit.hasNext()) { 20274 PackageSetting ps = psit.next(); 20275 if (ps.pkg == null) { 20276 continue; 20277 } 20278 final String packageName = ps.pkg.packageName; 20279 // Skip over if system app 20280 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20281 continue; 20282 } 20283 if (DEBUG_CLEAN_APKS) { 20284 Slog.i(TAG, "Checking package " + packageName); 20285 } 20286 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20287 if (keep) { 20288 if (DEBUG_CLEAN_APKS) { 20289 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20290 } 20291 } else { 20292 for (int i = 0; i < users.length; i++) { 20293 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20294 keep = true; 20295 if (DEBUG_CLEAN_APKS) { 20296 Slog.i(TAG, " Keeping package " + packageName + " for user " 20297 + users[i]); 20298 } 20299 break; 20300 } 20301 } 20302 } 20303 if (!keep) { 20304 if (DEBUG_CLEAN_APKS) { 20305 Slog.i(TAG, " Removing package " + packageName); 20306 } 20307 mHandler.post(new Runnable() { 20308 public void run() { 20309 deletePackageX(packageName, userHandle, 0); 20310 } //end run 20311 }); 20312 } 20313 } 20314 } 20315 20316 /** Called by UserManagerService */ 20317 void createNewUser(int userId) { 20318 synchronized (mInstallLock) { 20319 mSettings.createNewUserLI(this, mInstaller, userId); 20320 } 20321 synchronized (mPackages) { 20322 scheduleWritePackageRestrictionsLocked(userId); 20323 scheduleWritePackageListLocked(userId); 20324 applyFactoryDefaultBrowserLPw(userId); 20325 primeDomainVerificationsLPw(userId); 20326 } 20327 } 20328 20329 void onNewUserCreated(final int userId) { 20330 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20331 // If permission review for legacy apps is required, we represent 20332 // dagerous permissions for such apps as always granted runtime 20333 // permissions to keep per user flag state whether review is needed. 20334 // Hence, if a new user is added we have to propagate dangerous 20335 // permission grants for these legacy apps. 20336 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20337 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20338 | UPDATE_PERMISSIONS_REPLACE_ALL); 20339 } 20340 } 20341 20342 @Override 20343 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20344 mContext.enforceCallingOrSelfPermission( 20345 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20346 "Only package verification agents can read the verifier device identity"); 20347 20348 synchronized (mPackages) { 20349 return mSettings.getVerifierDeviceIdentityLPw(); 20350 } 20351 } 20352 20353 @Override 20354 public void setPermissionEnforced(String permission, boolean enforced) { 20355 // TODO: Now that we no longer change GID for storage, this should to away. 20356 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20357 "setPermissionEnforced"); 20358 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20359 synchronized (mPackages) { 20360 if (mSettings.mReadExternalStorageEnforced == null 20361 || mSettings.mReadExternalStorageEnforced != enforced) { 20362 mSettings.mReadExternalStorageEnforced = enforced; 20363 mSettings.writeLPr(); 20364 } 20365 } 20366 // kill any non-foreground processes so we restart them and 20367 // grant/revoke the GID. 20368 final IActivityManager am = ActivityManagerNative.getDefault(); 20369 if (am != null) { 20370 final long token = Binder.clearCallingIdentity(); 20371 try { 20372 am.killProcessesBelowForeground("setPermissionEnforcement"); 20373 } catch (RemoteException e) { 20374 } finally { 20375 Binder.restoreCallingIdentity(token); 20376 } 20377 } 20378 } else { 20379 throw new IllegalArgumentException("No selective enforcement for " + permission); 20380 } 20381 } 20382 20383 @Override 20384 @Deprecated 20385 public boolean isPermissionEnforced(String permission) { 20386 return true; 20387 } 20388 20389 @Override 20390 public boolean isStorageLow() { 20391 final long token = Binder.clearCallingIdentity(); 20392 try { 20393 final DeviceStorageMonitorInternal 20394 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20395 if (dsm != null) { 20396 return dsm.isMemoryLow(); 20397 } else { 20398 return false; 20399 } 20400 } finally { 20401 Binder.restoreCallingIdentity(token); 20402 } 20403 } 20404 20405 @Override 20406 public IPackageInstaller getPackageInstaller() { 20407 return mInstallerService; 20408 } 20409 20410 private boolean userNeedsBadging(int userId) { 20411 int index = mUserNeedsBadging.indexOfKey(userId); 20412 if (index < 0) { 20413 final UserInfo userInfo; 20414 final long token = Binder.clearCallingIdentity(); 20415 try { 20416 userInfo = sUserManager.getUserInfo(userId); 20417 } finally { 20418 Binder.restoreCallingIdentity(token); 20419 } 20420 final boolean b; 20421 if (userInfo != null && userInfo.isManagedProfile()) { 20422 b = true; 20423 } else { 20424 b = false; 20425 } 20426 mUserNeedsBadging.put(userId, b); 20427 return b; 20428 } 20429 return mUserNeedsBadging.valueAt(index); 20430 } 20431 20432 @Override 20433 public KeySet getKeySetByAlias(String packageName, String alias) { 20434 if (packageName == null || alias == null) { 20435 return null; 20436 } 20437 synchronized(mPackages) { 20438 final PackageParser.Package pkg = mPackages.get(packageName); 20439 if (pkg == null) { 20440 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20441 throw new IllegalArgumentException("Unknown package: " + packageName); 20442 } 20443 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20444 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20445 } 20446 } 20447 20448 @Override 20449 public KeySet getSigningKeySet(String packageName) { 20450 if (packageName == null) { 20451 return null; 20452 } 20453 synchronized(mPackages) { 20454 final PackageParser.Package pkg = mPackages.get(packageName); 20455 if (pkg == null) { 20456 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20457 throw new IllegalArgumentException("Unknown package: " + packageName); 20458 } 20459 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20460 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20461 throw new SecurityException("May not access signing KeySet of other apps."); 20462 } 20463 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20464 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20465 } 20466 } 20467 20468 @Override 20469 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20470 if (packageName == null || ks == null) { 20471 return false; 20472 } 20473 synchronized(mPackages) { 20474 final PackageParser.Package pkg = mPackages.get(packageName); 20475 if (pkg == null) { 20476 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20477 throw new IllegalArgumentException("Unknown package: " + packageName); 20478 } 20479 IBinder ksh = ks.getToken(); 20480 if (ksh instanceof KeySetHandle) { 20481 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20482 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20483 } 20484 return false; 20485 } 20486 } 20487 20488 @Override 20489 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20490 if (packageName == null || ks == null) { 20491 return false; 20492 } 20493 synchronized(mPackages) { 20494 final PackageParser.Package pkg = mPackages.get(packageName); 20495 if (pkg == null) { 20496 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20497 throw new IllegalArgumentException("Unknown package: " + packageName); 20498 } 20499 IBinder ksh = ks.getToken(); 20500 if (ksh instanceof KeySetHandle) { 20501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20502 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20503 } 20504 return false; 20505 } 20506 } 20507 20508 private void deletePackageIfUnusedLPr(final String packageName) { 20509 PackageSetting ps = mSettings.mPackages.get(packageName); 20510 if (ps == null) { 20511 return; 20512 } 20513 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20514 // TODO Implement atomic delete if package is unused 20515 // It is currently possible that the package will be deleted even if it is installed 20516 // after this method returns. 20517 mHandler.post(new Runnable() { 20518 public void run() { 20519 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20520 } 20521 }); 20522 } 20523 } 20524 20525 /** 20526 * Check and throw if the given before/after packages would be considered a 20527 * downgrade. 20528 */ 20529 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20530 throws PackageManagerException { 20531 if (after.versionCode < before.mVersionCode) { 20532 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20533 "Update version code " + after.versionCode + " is older than current " 20534 + before.mVersionCode); 20535 } else if (after.versionCode == before.mVersionCode) { 20536 if (after.baseRevisionCode < before.baseRevisionCode) { 20537 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20538 "Update base revision code " + after.baseRevisionCode 20539 + " is older than current " + before.baseRevisionCode); 20540 } 20541 20542 if (!ArrayUtils.isEmpty(after.splitNames)) { 20543 for (int i = 0; i < after.splitNames.length; i++) { 20544 final String splitName = after.splitNames[i]; 20545 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20546 if (j != -1) { 20547 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20548 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20549 "Update split " + splitName + " revision code " 20550 + after.splitRevisionCodes[i] + " is older than current " 20551 + before.splitRevisionCodes[j]); 20552 } 20553 } 20554 } 20555 } 20556 } 20557 } 20558 20559 private static class MoveCallbacks extends Handler { 20560 private static final int MSG_CREATED = 1; 20561 private static final int MSG_STATUS_CHANGED = 2; 20562 20563 private final RemoteCallbackList<IPackageMoveObserver> 20564 mCallbacks = new RemoteCallbackList<>(); 20565 20566 private final SparseIntArray mLastStatus = new SparseIntArray(); 20567 20568 public MoveCallbacks(Looper looper) { 20569 super(looper); 20570 } 20571 20572 public void register(IPackageMoveObserver callback) { 20573 mCallbacks.register(callback); 20574 } 20575 20576 public void unregister(IPackageMoveObserver callback) { 20577 mCallbacks.unregister(callback); 20578 } 20579 20580 @Override 20581 public void handleMessage(Message msg) { 20582 final SomeArgs args = (SomeArgs) msg.obj; 20583 final int n = mCallbacks.beginBroadcast(); 20584 for (int i = 0; i < n; i++) { 20585 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20586 try { 20587 invokeCallback(callback, msg.what, args); 20588 } catch (RemoteException ignored) { 20589 } 20590 } 20591 mCallbacks.finishBroadcast(); 20592 args.recycle(); 20593 } 20594 20595 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20596 throws RemoteException { 20597 switch (what) { 20598 case MSG_CREATED: { 20599 callback.onCreated(args.argi1, (Bundle) args.arg2); 20600 break; 20601 } 20602 case MSG_STATUS_CHANGED: { 20603 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20604 break; 20605 } 20606 } 20607 } 20608 20609 private void notifyCreated(int moveId, Bundle extras) { 20610 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20611 20612 final SomeArgs args = SomeArgs.obtain(); 20613 args.argi1 = moveId; 20614 args.arg2 = extras; 20615 obtainMessage(MSG_CREATED, args).sendToTarget(); 20616 } 20617 20618 private void notifyStatusChanged(int moveId, int status) { 20619 notifyStatusChanged(moveId, status, -1); 20620 } 20621 20622 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20623 Slog.v(TAG, "Move " + moveId + " status " + status); 20624 20625 final SomeArgs args = SomeArgs.obtain(); 20626 args.argi1 = moveId; 20627 args.argi2 = status; 20628 args.arg3 = estMillis; 20629 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20630 20631 synchronized (mLastStatus) { 20632 mLastStatus.put(moveId, status); 20633 } 20634 } 20635 } 20636 20637 private final static class OnPermissionChangeListeners extends Handler { 20638 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20639 20640 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20641 new RemoteCallbackList<>(); 20642 20643 public OnPermissionChangeListeners(Looper looper) { 20644 super(looper); 20645 } 20646 20647 @Override 20648 public void handleMessage(Message msg) { 20649 switch (msg.what) { 20650 case MSG_ON_PERMISSIONS_CHANGED: { 20651 final int uid = msg.arg1; 20652 handleOnPermissionsChanged(uid); 20653 } break; 20654 } 20655 } 20656 20657 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20658 mPermissionListeners.register(listener); 20659 20660 } 20661 20662 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20663 mPermissionListeners.unregister(listener); 20664 } 20665 20666 public void onPermissionsChanged(int uid) { 20667 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20668 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20669 } 20670 } 20671 20672 private void handleOnPermissionsChanged(int uid) { 20673 final int count = mPermissionListeners.beginBroadcast(); 20674 try { 20675 for (int i = 0; i < count; i++) { 20676 IOnPermissionsChangeListener callback = mPermissionListeners 20677 .getBroadcastItem(i); 20678 try { 20679 callback.onPermissionsChanged(uid); 20680 } catch (RemoteException e) { 20681 Log.e(TAG, "Permission listener is dead", e); 20682 } 20683 } 20684 } finally { 20685 mPermissionListeners.finishBroadcast(); 20686 } 20687 } 20688 } 20689 20690 private class PackageManagerInternalImpl extends PackageManagerInternal { 20691 @Override 20692 public void setLocationPackagesProvider(PackagesProvider provider) { 20693 synchronized (mPackages) { 20694 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20695 } 20696 } 20697 20698 @Override 20699 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20700 synchronized (mPackages) { 20701 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20702 } 20703 } 20704 20705 @Override 20706 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20707 synchronized (mPackages) { 20708 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20709 } 20710 } 20711 20712 @Override 20713 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20714 synchronized (mPackages) { 20715 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20716 } 20717 } 20718 20719 @Override 20720 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20721 synchronized (mPackages) { 20722 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20723 } 20724 } 20725 20726 @Override 20727 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20728 synchronized (mPackages) { 20729 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20730 } 20731 } 20732 20733 @Override 20734 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20735 synchronized (mPackages) { 20736 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20737 packageName, userId); 20738 } 20739 } 20740 20741 @Override 20742 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20743 synchronized (mPackages) { 20744 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20745 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20746 packageName, userId); 20747 } 20748 } 20749 20750 @Override 20751 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20752 synchronized (mPackages) { 20753 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20754 packageName, userId); 20755 } 20756 } 20757 20758 @Override 20759 public void setKeepUninstalledPackages(final List<String> packageList) { 20760 Preconditions.checkNotNull(packageList); 20761 List<String> removedFromList = null; 20762 synchronized (mPackages) { 20763 if (mKeepUninstalledPackages != null) { 20764 final int packagesCount = mKeepUninstalledPackages.size(); 20765 for (int i = 0; i < packagesCount; i++) { 20766 String oldPackage = mKeepUninstalledPackages.get(i); 20767 if (packageList != null && packageList.contains(oldPackage)) { 20768 continue; 20769 } 20770 if (removedFromList == null) { 20771 removedFromList = new ArrayList<>(); 20772 } 20773 removedFromList.add(oldPackage); 20774 } 20775 } 20776 mKeepUninstalledPackages = new ArrayList<>(packageList); 20777 if (removedFromList != null) { 20778 final int removedCount = removedFromList.size(); 20779 for (int i = 0; i < removedCount; i++) { 20780 deletePackageIfUnusedLPr(removedFromList.get(i)); 20781 } 20782 } 20783 } 20784 } 20785 20786 @Override 20787 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20788 synchronized (mPackages) { 20789 // If we do not support permission review, done. 20790 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20791 return false; 20792 } 20793 20794 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20795 if (packageSetting == null) { 20796 return false; 20797 } 20798 20799 // Permission review applies only to apps not supporting the new permission model. 20800 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20801 return false; 20802 } 20803 20804 // Legacy apps have the permission and get user consent on launch. 20805 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20806 return permissionsState.isPermissionReviewRequired(userId); 20807 } 20808 } 20809 20810 @Override 20811 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20812 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20813 } 20814 20815 @Override 20816 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20817 int userId) { 20818 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20819 } 20820 20821 @Override 20822 public void setDeviceAndProfileOwnerPackages( 20823 int deviceOwnerUserId, String deviceOwnerPackage, 20824 SparseArray<String> profileOwnerPackages) { 20825 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20826 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20827 } 20828 20829 @Override 20830 public boolean isPackageDataProtected(int userId, String packageName) { 20831 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20832 } 20833 } 20834 20835 @Override 20836 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20837 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20838 synchronized (mPackages) { 20839 final long identity = Binder.clearCallingIdentity(); 20840 try { 20841 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20842 packageNames, userId); 20843 } finally { 20844 Binder.restoreCallingIdentity(identity); 20845 } 20846 } 20847 } 20848 20849 private static void enforceSystemOrPhoneCaller(String tag) { 20850 int callingUid = Binder.getCallingUid(); 20851 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20852 throw new SecurityException( 20853 "Cannot call " + tag + " from UID " + callingUid); 20854 } 20855 } 20856 20857 boolean isHistoricalPackageUsageAvailable() { 20858 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20859 } 20860 20861 /** 20862 * Return a <b>copy</b> of the collection of packages known to the package manager. 20863 * @return A copy of the values of mPackages. 20864 */ 20865 Collection<PackageParser.Package> getPackages() { 20866 synchronized (mPackages) { 20867 return new ArrayList<>(mPackages.values()); 20868 } 20869 } 20870 20871 /** 20872 * Logs process start information (including base APK hash) to the security log. 20873 * @hide 20874 */ 20875 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20876 String apkFile, int pid) { 20877 if (!SecurityLog.isLoggingEnabled()) { 20878 return; 20879 } 20880 Bundle data = new Bundle(); 20881 data.putLong("startTimestamp", System.currentTimeMillis()); 20882 data.putString("processName", processName); 20883 data.putInt("uid", uid); 20884 data.putString("seinfo", seinfo); 20885 data.putString("apkFile", apkFile); 20886 data.putInt("pid", pid); 20887 Message msg = mProcessLoggingHandler.obtainMessage( 20888 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20889 msg.setData(data); 20890 mProcessLoggingHandler.sendMessage(msg); 20891 } 20892 20893 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20894 return mCompilerStats.getPackageStats(pkgName); 20895 } 20896 20897 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20898 return getOrCreateCompilerPackageStats(pkg.packageName); 20899 } 20900 20901 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20902 return mCompilerStats.getOrCreatePackageStats(pkgName); 20903 } 20904 20905 public void deleteCompilerPackageStats(String pkgName) { 20906 mCompilerStats.deletePackageStats(pkgName); 20907 } 20908} 20909