PackageManagerService.java revision 5320ee42c6e9c7916ca5127c99f872b1b8008fd8
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralResolveInfo; 125import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.Process; 181import android.os.RemoteCallbackList; 182import android.os.RemoteException; 183import android.os.ResultReceiver; 184import android.os.SELinux; 185import android.os.ServiceManager; 186import android.os.SystemClock; 187import android.os.SystemProperties; 188import android.os.Trace; 189import android.os.UserHandle; 190import android.os.UserManager; 191import android.os.UserManagerInternal; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.provider.Settings.Global; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.logging.MetricsLogger; 229import com.android.internal.os.IParcelFileDescriptorFactory; 230import com.android.internal.os.InstallerConnection.InstallerException; 231import com.android.internal.os.SomeArgs; 232import com.android.internal.os.Zygote; 233import com.android.internal.telephony.CarrierAppUtils; 234import com.android.internal.util.ArrayUtils; 235import com.android.internal.util.FastPrintWriter; 236import com.android.internal.util.FastXmlSerializer; 237import com.android.internal.util.IndentingPrintWriter; 238import com.android.internal.util.Preconditions; 239import com.android.internal.util.XmlUtils; 240import com.android.server.AttributeCache; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedOutputStream; 266import java.io.BufferedReader; 267import java.io.ByteArrayInputStream; 268import java.io.ByteArrayOutputStream; 269import java.io.File; 270import java.io.FileDescriptor; 271import java.io.FileInputStream; 272import java.io.FileNotFoundException; 273import java.io.FileOutputStream; 274import java.io.FileReader; 275import java.io.FilenameFilter; 276import java.io.IOException; 277import java.io.PrintWriter; 278import java.nio.charset.StandardCharsets; 279import java.security.DigestInputStream; 280import java.security.MessageDigest; 281import java.security.NoSuchAlgorithmException; 282import java.security.PublicKey; 283import java.security.cert.Certificate; 284import java.security.cert.CertificateEncodingException; 285import java.security.cert.CertificateException; 286import java.text.SimpleDateFormat; 287import java.util.ArrayList; 288import java.util.Arrays; 289import java.util.Collection; 290import java.util.Collections; 291import java.util.Comparator; 292import java.util.Date; 293import java.util.HashSet; 294import java.util.Iterator; 295import java.util.List; 296import java.util.Map; 297import java.util.Objects; 298import java.util.Set; 299import java.util.concurrent.CountDownLatch; 300import java.util.concurrent.TimeUnit; 301import java.util.concurrent.atomic.AtomicBoolean; 302import java.util.concurrent.atomic.AtomicInteger; 303 304/** 305 * Keep track of all those APKs everywhere. 306 * <p> 307 * Internally there are two important locks: 308 * <ul> 309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 310 * and other related state. It is a fine-grained lock that should only be held 311 * momentarily, as it's one of the most contended locks in the system. 312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 313 * operations typically involve heavy lifting of application data on disk. Since 314 * {@code installd} is single-threaded, and it's operations can often be slow, 315 * this lock should never be acquired while already holding {@link #mPackages}. 316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 317 * holding {@link #mInstallLock}. 318 * </ul> 319 * Many internal methods rely on the caller to hold the appropriate locks, and 320 * this contract is expressed through method name suffixes: 321 * <ul> 322 * <li>fooLI(): the caller must hold {@link #mInstallLock} 323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 324 * being modified must be frozen 325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 327 * </ul> 328 * <p> 329 * Because this class is very central to the platform's security; please run all 330 * CTS and unit tests whenever making modifications: 331 * 332 * <pre> 333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 335 * </pre> 336 */ 337public class PackageManagerService extends IPackageManager.Stub { 338 static final String TAG = "PackageManager"; 339 static final boolean DEBUG_SETTINGS = false; 340 static final boolean DEBUG_PREFERRED = false; 341 static final boolean DEBUG_UPGRADE = false; 342 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 343 private static final boolean DEBUG_BACKUP = false; 344 private static final boolean DEBUG_INSTALL = false; 345 private static final boolean DEBUG_REMOVE = false; 346 private static final boolean DEBUG_BROADCASTS = false; 347 private static final boolean DEBUG_SHOW_INFO = false; 348 private static final boolean DEBUG_PACKAGE_INFO = false; 349 private static final boolean DEBUG_INTENT_MATCHING = false; 350 private static final boolean DEBUG_PACKAGE_SCANNING = false; 351 private static final boolean DEBUG_VERIFY = false; 352 private static final boolean DEBUG_FILTERS = false; 353 354 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 355 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 356 // user, but by default initialize to this. 357 static final boolean DEBUG_DEXOPT = false; 358 359 private static final boolean DEBUG_ABI_SELECTION = false; 360 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 361 private static final boolean DEBUG_TRIAGED_MISSING = false; 362 private static final boolean DEBUG_APP_DATA = false; 363 364 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 365 366 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 367 368 private static final int RADIO_UID = Process.PHONE_UID; 369 private static final int LOG_UID = Process.LOG_UID; 370 private static final int NFC_UID = Process.NFC_UID; 371 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 372 private static final int SHELL_UID = Process.SHELL_UID; 373 374 // Cap the size of permission trees that 3rd party apps can define 375 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 376 377 // Suffix used during package installation when copying/moving 378 // package apks to install directory. 379 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 380 381 static final int SCAN_NO_DEX = 1<<1; 382 static final int SCAN_FORCE_DEX = 1<<2; 383 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 384 static final int SCAN_NEW_INSTALL = 1<<4; 385 static final int SCAN_NO_PATHS = 1<<5; 386 static final int SCAN_UPDATE_TIME = 1<<6; 387 static final int SCAN_DEFER_DEX = 1<<7; 388 static final int SCAN_BOOTING = 1<<8; 389 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 390 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 391 static final int SCAN_REPLACING = 1<<11; 392 static final int SCAN_REQUIRE_KNOWN = 1<<12; 393 static final int SCAN_MOVE = 1<<13; 394 static final int SCAN_INITIAL = 1<<14; 395 static final int SCAN_CHECK_ONLY = 1<<15; 396 static final int SCAN_DONT_KILL_APP = 1<<17; 397 static final int SCAN_IGNORE_FROZEN = 1<<18; 398 399 static final int REMOVE_CHATTY = 1<<16; 400 401 private static final int[] EMPTY_INT_ARRAY = new int[0]; 402 403 /** 404 * Timeout (in milliseconds) after which the watchdog should declare that 405 * our handler thread is wedged. The usual default for such things is one 406 * minute but we sometimes do very lengthy I/O operations on this thread, 407 * such as installing multi-gigabyte applications, so ours needs to be longer. 408 */ 409 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 410 411 /** 412 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 413 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 414 * settings entry if available, otherwise we use the hardcoded default. If it's been 415 * more than this long since the last fstrim, we force one during the boot sequence. 416 * 417 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 418 * one gets run at the next available charging+idle time. This final mandatory 419 * no-fstrim check kicks in only of the other scheduling criteria is never met. 420 */ 421 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 422 423 /** 424 * Whether verification is enabled by default. 425 */ 426 private static final boolean DEFAULT_VERIFY_ENABLE = true; 427 428 /** 429 * The default maximum time to wait for the verification agent to return in 430 * milliseconds. 431 */ 432 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 433 434 /** 435 * The default response for package verification timeout. 436 * 437 * This can be either PackageManager.VERIFICATION_ALLOW or 438 * PackageManager.VERIFICATION_REJECT. 439 */ 440 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 441 442 static final String PLATFORM_PACKAGE_NAME = "android"; 443 444 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 445 446 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 447 DEFAULT_CONTAINER_PACKAGE, 448 "com.android.defcontainer.DefaultContainerService"); 449 450 private static final String KILL_APP_REASON_GIDS_CHANGED = 451 "permission grant or revoke changed gids"; 452 453 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 454 "permissions revoked"; 455 456 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 457 458 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 459 460 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 461 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 public static final int REASON_CORE_APP = 8; 506 507 public static final int REASON_LAST = REASON_CORE_APP; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 final boolean mIsPreNMR1Upgrade; 535 536 /** The location for ASEC container files on internal storage. */ 537 final String mAsecInternalPath; 538 539 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 540 // LOCK HELD. Can be called with mInstallLock held. 541 @GuardedBy("mInstallLock") 542 final Installer mInstaller; 543 544 /** Directory where installed third-party apps stored */ 545 final File mAppInstallDir; 546 final File mEphemeralInstallDir; 547 548 /** 549 * Directory to which applications installed internally have their 550 * 32 bit native libraries copied. 551 */ 552 private File mAppLib32InstallDir; 553 554 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 555 // apps. 556 final File mDrmAppPrivateInstallDir; 557 558 // ---------------------------------------------------------------- 559 560 // Lock for state used when installing and doing other long running 561 // operations. Methods that must be called with this lock held have 562 // the suffix "LI". 563 final Object mInstallLock = new Object(); 564 565 // ---------------------------------------------------------------- 566 567 // Keys are String (package name), values are Package. This also serves 568 // as the lock for the global state. Methods that must be called with 569 // this lock held have the prefix "LP". 570 @GuardedBy("mPackages") 571 final ArrayMap<String, PackageParser.Package> mPackages = 572 new ArrayMap<String, PackageParser.Package>(); 573 574 final ArrayMap<String, Set<String>> mKnownCodebase = 575 new ArrayMap<String, Set<String>>(); 576 577 // Tracks available target package names -> overlay package paths. 578 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 579 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 580 581 /** 582 * Tracks new system packages [received in an OTA] that we expect to 583 * find updated user-installed versions. Keys are package name, values 584 * are package location. 585 */ 586 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 587 /** 588 * Tracks high priority intent filters for protected actions. During boot, certain 589 * filter actions are protected and should never be allowed to have a high priority 590 * intent filter for them. However, there is one, and only one exception -- the 591 * setup wizard. It must be able to define a high priority intent filter for these 592 * actions to ensure there are no escapes from the wizard. We need to delay processing 593 * of these during boot as we need to look at all of the system packages in order 594 * to know which component is the setup wizard. 595 */ 596 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 597 /** 598 * Whether or not processing protected filters should be deferred. 599 */ 600 private boolean mDeferProtectedFilters = true; 601 602 /** 603 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 604 */ 605 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 606 /** 607 * Whether or not system app permissions should be promoted from install to runtime. 608 */ 609 boolean mPromoteSystemApps; 610 611 @GuardedBy("mPackages") 612 final Settings mSettings; 613 614 /** 615 * Set of package names that are currently "frozen", which means active 616 * surgery is being done on the code/data for that package. The platform 617 * will refuse to launch frozen packages to avoid race conditions. 618 * 619 * @see PackageFreezer 620 */ 621 @GuardedBy("mPackages") 622 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 623 624 final ProtectedPackages mProtectedPackages; 625 626 boolean mFirstBoot; 627 628 // System configuration read by SystemConfig. 629 final int[] mGlobalGids; 630 final SparseArray<ArraySet<String>> mSystemPermissions; 631 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 632 633 // If mac_permissions.xml was found for seinfo labeling. 634 boolean mFoundPolicyFile; 635 636 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 637 638 public static final class SharedLibraryEntry { 639 public final String path; 640 public final String apk; 641 642 SharedLibraryEntry(String _path, String _apk) { 643 path = _path; 644 apk = _apk; 645 } 646 } 647 648 // Currently known shared libraries. 649 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 650 new ArrayMap<String, SharedLibraryEntry>(); 651 652 // All available activities, for your resolving pleasure. 653 final ActivityIntentResolver mActivities = 654 new ActivityIntentResolver(); 655 656 // All available receivers, for your resolving pleasure. 657 final ActivityIntentResolver mReceivers = 658 new ActivityIntentResolver(); 659 660 // All available services, for your resolving pleasure. 661 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 662 663 // All available providers, for your resolving pleasure. 664 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 665 666 // Mapping from provider base names (first directory in content URI codePath) 667 // to the provider information. 668 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 669 new ArrayMap<String, PackageParser.Provider>(); 670 671 // Mapping from instrumentation class names to info about them. 672 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 673 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 674 675 // Mapping from permission names to info about them. 676 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 677 new ArrayMap<String, PackageParser.PermissionGroup>(); 678 679 // Packages whose data we have transfered into another package, thus 680 // should no longer exist. 681 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 682 683 // Broadcast actions that are only available to the system. 684 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 685 686 /** List of packages waiting for verification. */ 687 final SparseArray<PackageVerificationState> mPendingVerification 688 = new SparseArray<PackageVerificationState>(); 689 690 /** Set of packages associated with each app op permission. */ 691 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 692 693 final PackageInstallerService mInstallerService; 694 695 private final PackageDexOptimizer mPackageDexOptimizer; 696 697 private AtomicInteger mNextMoveId = new AtomicInteger(); 698 private final MoveCallbacks mMoveCallbacks; 699 700 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 701 702 // Cache of users who need badging. 703 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 704 705 /** Token for keys in mPendingVerification. */ 706 private int mPendingVerificationToken = 0; 707 708 volatile boolean mSystemReady; 709 volatile boolean mSafeMode; 710 volatile boolean mHasSystemUidErrors; 711 712 ApplicationInfo mAndroidApplication; 713 final ActivityInfo mResolveActivity = new ActivityInfo(); 714 final ResolveInfo mResolveInfo = new ResolveInfo(); 715 ComponentName mResolveComponentName; 716 PackageParser.Package mPlatformPackage; 717 ComponentName mCustomResolverComponentName; 718 719 boolean mResolverReplaced = false; 720 721 private final @Nullable ComponentName mIntentFilterVerifierComponent; 722 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 723 724 private int mIntentFilterVerificationToken = 0; 725 726 /** Component that knows whether or not an ephemeral application exists */ 727 final ComponentName mEphemeralResolverComponent; 728 /** The service connection to the ephemeral resolver */ 729 final EphemeralResolverConnection mEphemeralResolverConnection; 730 731 /** Component used to install ephemeral applications */ 732 final ComponentName mEphemeralInstallerComponent; 733 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 734 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 735 736 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 737 = new SparseArray<IntentFilterVerificationState>(); 738 739 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 740 741 // List of packages names to keep cached, even if they are uninstalled for all users 742 private List<String> mKeepUninstalledPackages; 743 744 private UserManagerInternal mUserManagerInternal; 745 746 private static class IFVerificationParams { 747 PackageParser.Package pkg; 748 boolean replacing; 749 int userId; 750 int verifierUid; 751 752 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 753 int _userId, int _verifierUid) { 754 pkg = _pkg; 755 replacing = _replacing; 756 userId = _userId; 757 replacing = _replacing; 758 verifierUid = _verifierUid; 759 } 760 } 761 762 private interface IntentFilterVerifier<T extends IntentFilter> { 763 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 764 T filter, String packageName); 765 void startVerifications(int userId); 766 void receiveVerificationResponse(int verificationId); 767 } 768 769 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 770 private Context mContext; 771 private ComponentName mIntentFilterVerifierComponent; 772 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 773 774 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 775 mContext = context; 776 mIntentFilterVerifierComponent = verifierComponent; 777 } 778 779 private String getDefaultScheme() { 780 return IntentFilter.SCHEME_HTTPS; 781 } 782 783 @Override 784 public void startVerifications(int userId) { 785 // Launch verifications requests 786 int count = mCurrentIntentFilterVerifications.size(); 787 for (int n=0; n<count; n++) { 788 int verificationId = mCurrentIntentFilterVerifications.get(n); 789 final IntentFilterVerificationState ivs = 790 mIntentFilterVerificationStates.get(verificationId); 791 792 String packageName = ivs.getPackageName(); 793 794 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 795 final int filterCount = filters.size(); 796 ArraySet<String> domainsSet = new ArraySet<>(); 797 for (int m=0; m<filterCount; m++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(m); 799 domainsSet.addAll(filter.getHostsList()); 800 } 801 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 802 synchronized (mPackages) { 803 if (mSettings.createIntentFilterVerificationIfNeededLPw( 804 packageName, domainsList) != null) { 805 scheduleWriteSettingsLocked(); 806 } 807 } 808 sendVerificationRequest(userId, verificationId, ivs); 809 } 810 mCurrentIntentFilterVerifications.clear(); 811 } 812 813 private void sendVerificationRequest(int userId, int verificationId, 814 IntentFilterVerificationState ivs) { 815 816 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 819 verificationId); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 822 getDefaultScheme()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 825 ivs.getHostsString()); 826 verificationIntent.putExtra( 827 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 828 ivs.getPackageName()); 829 verificationIntent.setComponent(mIntentFilterVerifierComponent); 830 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 831 832 UserHandle user = new UserHandle(userId); 833 mContext.sendBroadcastAsUser(verificationIntent, user); 834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 835 "Sending IntentFilter verification broadcast"); 836 } 837 838 public void receiveVerificationResponse(int verificationId) { 839 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 840 841 final boolean verified = ivs.isVerified(); 842 843 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 844 final int count = filters.size(); 845 if (DEBUG_DOMAIN_VERIFICATION) { 846 Slog.i(TAG, "Received verification response " + verificationId 847 + " for " + count + " filters, verified=" + verified); 848 } 849 for (int n=0; n<count; n++) { 850 PackageParser.ActivityIntentInfo filter = filters.get(n); 851 filter.setVerified(verified); 852 853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 854 + " verified with result:" + verified + " and hosts:" 855 + ivs.getHostsString()); 856 } 857 858 mIntentFilterVerificationStates.remove(verificationId); 859 860 final String packageName = ivs.getPackageName(); 861 IntentFilterVerificationInfo ivi = null; 862 863 synchronized (mPackages) { 864 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 865 } 866 if (ivi == null) { 867 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 868 + verificationId + " packageName:" + packageName); 869 return; 870 } 871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 872 "Updating IntentFilterVerificationInfo for package " + packageName 873 +" verificationId:" + verificationId); 874 875 synchronized (mPackages) { 876 if (verified) { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 878 } else { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 880 } 881 scheduleWriteSettingsLocked(); 882 883 final int userId = ivs.getUserId(); 884 if (userId != UserHandle.USER_ALL) { 885 final int userStatus = 886 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 887 888 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 889 boolean needUpdate = false; 890 891 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 892 // already been set by the User thru the Disambiguation dialog 893 switch (userStatus) { 894 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 895 if (verified) { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 897 } else { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 899 } 900 needUpdate = true; 901 break; 902 903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 904 if (verified) { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 906 needUpdate = true; 907 } 908 break; 909 910 default: 911 // Nothing to do 912 } 913 914 if (needUpdate) { 915 mSettings.updateIntentFilterVerificationStatusLPw( 916 packageName, updatedStatus, userId); 917 scheduleWritePackageRestrictionsLocked(userId); 918 } 919 } 920 } 921 } 922 923 @Override 924 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 925 ActivityIntentInfo filter, String packageName) { 926 if (!hasValidDomains(filter)) { 927 return false; 928 } 929 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 930 if (ivs == null) { 931 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 932 packageName); 933 } 934 if (DEBUG_DOMAIN_VERIFICATION) { 935 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 936 } 937 ivs.addFilter(filter); 938 return true; 939 } 940 941 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 942 int userId, int verificationId, String packageName) { 943 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 944 verifierUid, userId, packageName); 945 ivs.setPendingState(); 946 synchronized (mPackages) { 947 mIntentFilterVerificationStates.append(verificationId, ivs); 948 mCurrentIntentFilterVerifications.add(verificationId); 949 } 950 return ivs; 951 } 952 } 953 954 private static boolean hasValidDomains(ActivityIntentInfo filter) { 955 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 956 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 957 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 958 } 959 960 // Set of pending broadcasts for aggregating enable/disable of components. 961 static class PendingPackageBroadcasts { 962 // for each user id, a map of <package name -> components within that package> 963 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 964 965 public PendingPackageBroadcasts() { 966 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 967 } 968 969 public ArrayList<String> get(int userId, String packageName) { 970 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 971 return packages.get(packageName); 972 } 973 974 public void put(int userId, String packageName, ArrayList<String> components) { 975 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 976 packages.put(packageName, components); 977 } 978 979 public void remove(int userId, String packageName) { 980 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 981 if (packages != null) { 982 packages.remove(packageName); 983 } 984 } 985 986 public void remove(int userId) { 987 mUidMap.remove(userId); 988 } 989 990 public int userIdCount() { 991 return mUidMap.size(); 992 } 993 994 public int userIdAt(int n) { 995 return mUidMap.keyAt(n); 996 } 997 998 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 999 return mUidMap.get(userId); 1000 } 1001 1002 public int size() { 1003 // total number of pending broadcast entries across all userIds 1004 int num = 0; 1005 for (int i = 0; i< mUidMap.size(); i++) { 1006 num += mUidMap.valueAt(i).size(); 1007 } 1008 return num; 1009 } 1010 1011 public void clear() { 1012 mUidMap.clear(); 1013 } 1014 1015 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1016 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1017 if (map == null) { 1018 map = new ArrayMap<String, ArrayList<String>>(); 1019 mUidMap.put(userId, map); 1020 } 1021 return map; 1022 } 1023 } 1024 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1025 1026 // Service Connection to remote media container service to copy 1027 // package uri's from external media onto secure containers 1028 // or internal storage. 1029 private IMediaContainerService mContainerService = null; 1030 1031 static final int SEND_PENDING_BROADCAST = 1; 1032 static final int MCS_BOUND = 3; 1033 static final int END_COPY = 4; 1034 static final int INIT_COPY = 5; 1035 static final int MCS_UNBIND = 6; 1036 static final int START_CLEANING_PACKAGE = 7; 1037 static final int FIND_INSTALL_LOC = 8; 1038 static final int POST_INSTALL = 9; 1039 static final int MCS_RECONNECT = 10; 1040 static final int MCS_GIVE_UP = 11; 1041 static final int UPDATED_MEDIA_STATUS = 12; 1042 static final int WRITE_SETTINGS = 13; 1043 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1044 static final int PACKAGE_VERIFIED = 15; 1045 static final int CHECK_PENDING_VERIFICATION = 16; 1046 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1047 static final int INTENT_FILTER_VERIFIED = 18; 1048 static final int WRITE_PACKAGE_LIST = 19; 1049 1050 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1051 1052 // Delay time in millisecs 1053 static final int BROADCAST_DELAY = 10 * 1000; 1054 1055 static UserManagerService sUserManager; 1056 1057 // Stores a list of users whose package restrictions file needs to be updated 1058 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1059 1060 final private DefaultContainerConnection mDefContainerConn = 1061 new DefaultContainerConnection(); 1062 class DefaultContainerConnection implements ServiceConnection { 1063 public void onServiceConnected(ComponentName name, IBinder service) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1065 IMediaContainerService imcs = 1066 IMediaContainerService.Stub.asInterface(service); 1067 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1068 } 1069 1070 public void onServiceDisconnected(ComponentName name) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1072 } 1073 } 1074 1075 // Recordkeeping of restore-after-install operations that are currently in flight 1076 // between the Package Manager and the Backup Manager 1077 static class PostInstallData { 1078 public InstallArgs args; 1079 public PackageInstalledInfo res; 1080 1081 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1082 args = _a; 1083 res = _r; 1084 } 1085 } 1086 1087 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1088 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1089 1090 // XML tags for backup/restore of various bits of state 1091 private static final String TAG_PREFERRED_BACKUP = "pa"; 1092 private static final String TAG_DEFAULT_APPS = "da"; 1093 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1094 1095 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1096 private static final String TAG_ALL_GRANTS = "rt-grants"; 1097 private static final String TAG_GRANT = "grant"; 1098 private static final String ATTR_PACKAGE_NAME = "pkg"; 1099 1100 private static final String TAG_PERMISSION = "perm"; 1101 private static final String ATTR_PERMISSION_NAME = "name"; 1102 private static final String ATTR_IS_GRANTED = "g"; 1103 private static final String ATTR_USER_SET = "set"; 1104 private static final String ATTR_USER_FIXED = "fixed"; 1105 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1106 1107 // System/policy permission grants are not backed up 1108 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1109 FLAG_PERMISSION_POLICY_FIXED 1110 | FLAG_PERMISSION_SYSTEM_FIXED 1111 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1112 1113 // And we back up these user-adjusted states 1114 private static final int USER_RUNTIME_GRANT_MASK = 1115 FLAG_PERMISSION_USER_SET 1116 | FLAG_PERMISSION_USER_FIXED 1117 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1118 1119 final @Nullable String mRequiredVerifierPackage; 1120 final @NonNull String mRequiredInstallerPackage; 1121 final @Nullable String mSetupWizardPackage; 1122 final @NonNull String mServicesSystemSharedLibraryPackageName; 1123 final @NonNull String mSharedSystemSharedLibraryPackageName; 1124 1125 private final PackageUsage mPackageUsage = new PackageUsage(); 1126 private final CompilerStats mCompilerStats = new CompilerStats(); 1127 1128 class PackageHandler extends Handler { 1129 private boolean mBound = false; 1130 final ArrayList<HandlerParams> mPendingInstalls = 1131 new ArrayList<HandlerParams>(); 1132 1133 private boolean connectToService() { 1134 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1135 " DefaultContainerService"); 1136 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1138 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1139 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1140 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1141 mBound = true; 1142 return true; 1143 } 1144 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1145 return false; 1146 } 1147 1148 private void disconnectService() { 1149 mContainerService = null; 1150 mBound = false; 1151 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1152 mContext.unbindService(mDefContainerConn); 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1154 } 1155 1156 PackageHandler(Looper looper) { 1157 super(looper); 1158 } 1159 1160 public void handleMessage(Message msg) { 1161 try { 1162 doHandleMessage(msg); 1163 } finally { 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1165 } 1166 } 1167 1168 void doHandleMessage(Message msg) { 1169 switch (msg.what) { 1170 case INIT_COPY: { 1171 HandlerParams params = (HandlerParams) msg.obj; 1172 int idx = mPendingInstalls.size(); 1173 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1174 // If a bind was already initiated we dont really 1175 // need to do anything. The pending install 1176 // will be processed later on. 1177 if (!mBound) { 1178 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1179 System.identityHashCode(mHandler)); 1180 // If this is the only one pending we might 1181 // have to bind to the service again. 1182 if (!connectToService()) { 1183 Slog.e(TAG, "Failed to bind to media container service"); 1184 params.serviceError(); 1185 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1186 System.identityHashCode(mHandler)); 1187 if (params.traceMethod != null) { 1188 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1189 params.traceCookie); 1190 } 1191 return; 1192 } else { 1193 // Once we bind to the service, the first 1194 // pending request will be processed. 1195 mPendingInstalls.add(idx, params); 1196 } 1197 } else { 1198 mPendingInstalls.add(idx, params); 1199 // Already bound to the service. Just make 1200 // sure we trigger off processing the first request. 1201 if (idx == 0) { 1202 mHandler.sendEmptyMessage(MCS_BOUND); 1203 } 1204 } 1205 break; 1206 } 1207 case MCS_BOUND: { 1208 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1209 if (msg.obj != null) { 1210 mContainerService = (IMediaContainerService) msg.obj; 1211 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1212 System.identityHashCode(mHandler)); 1213 } 1214 if (mContainerService == null) { 1215 if (!mBound) { 1216 // Something seriously wrong since we are not bound and we are not 1217 // waiting for connection. Bail out. 1218 Slog.e(TAG, "Cannot bind to media container service"); 1219 for (HandlerParams params : mPendingInstalls) { 1220 // Indicate service bind error 1221 params.serviceError(); 1222 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1223 System.identityHashCode(params)); 1224 if (params.traceMethod != null) { 1225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1226 params.traceMethod, params.traceCookie); 1227 } 1228 return; 1229 } 1230 mPendingInstalls.clear(); 1231 } else { 1232 Slog.w(TAG, "Waiting to connect to media container service"); 1233 } 1234 } else if (mPendingInstalls.size() > 0) { 1235 HandlerParams params = mPendingInstalls.get(0); 1236 if (params != null) { 1237 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1238 System.identityHashCode(params)); 1239 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1240 if (params.startCopy()) { 1241 // We are done... look for more work or to 1242 // go idle. 1243 if (DEBUG_SD_INSTALL) Log.i(TAG, 1244 "Checking for more work or unbind..."); 1245 // Delete pending install 1246 if (mPendingInstalls.size() > 0) { 1247 mPendingInstalls.remove(0); 1248 } 1249 if (mPendingInstalls.size() == 0) { 1250 if (mBound) { 1251 if (DEBUG_SD_INSTALL) Log.i(TAG, 1252 "Posting delayed MCS_UNBIND"); 1253 removeMessages(MCS_UNBIND); 1254 Message ubmsg = obtainMessage(MCS_UNBIND); 1255 // Unbind after a little delay, to avoid 1256 // continual thrashing. 1257 sendMessageDelayed(ubmsg, 10000); 1258 } 1259 } else { 1260 // There are more pending requests in queue. 1261 // Just post MCS_BOUND message to trigger processing 1262 // of next pending install. 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, 1264 "Posting MCS_BOUND for next work"); 1265 mHandler.sendEmptyMessage(MCS_BOUND); 1266 } 1267 } 1268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1269 } 1270 } else { 1271 // Should never happen ideally. 1272 Slog.w(TAG, "Empty queue"); 1273 } 1274 break; 1275 } 1276 case MCS_RECONNECT: { 1277 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1278 if (mPendingInstalls.size() > 0) { 1279 if (mBound) { 1280 disconnectService(); 1281 } 1282 if (!connectToService()) { 1283 Slog.e(TAG, "Failed to bind to media container service"); 1284 for (HandlerParams params : mPendingInstalls) { 1285 // Indicate service bind error 1286 params.serviceError(); 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1288 System.identityHashCode(params)); 1289 } 1290 mPendingInstalls.clear(); 1291 } 1292 } 1293 break; 1294 } 1295 case MCS_UNBIND: { 1296 // If there is no actual work left, then time to unbind. 1297 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1298 1299 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1300 if (mBound) { 1301 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1302 1303 disconnectService(); 1304 } 1305 } else if (mPendingInstalls.size() > 0) { 1306 // There are more pending requests in queue. 1307 // Just post MCS_BOUND message to trigger processing 1308 // of next pending install. 1309 mHandler.sendEmptyMessage(MCS_BOUND); 1310 } 1311 1312 break; 1313 } 1314 case MCS_GIVE_UP: { 1315 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1316 HandlerParams params = mPendingInstalls.remove(0); 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1318 System.identityHashCode(params)); 1319 break; 1320 } 1321 case SEND_PENDING_BROADCAST: { 1322 String packages[]; 1323 ArrayList<String> components[]; 1324 int size = 0; 1325 int uids[]; 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1327 synchronized (mPackages) { 1328 if (mPendingBroadcasts == null) { 1329 return; 1330 } 1331 size = mPendingBroadcasts.size(); 1332 if (size <= 0) { 1333 // Nothing to be done. Just return 1334 return; 1335 } 1336 packages = new String[size]; 1337 components = new ArrayList[size]; 1338 uids = new int[size]; 1339 int i = 0; // filling out the above arrays 1340 1341 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1342 int packageUserId = mPendingBroadcasts.userIdAt(n); 1343 Iterator<Map.Entry<String, ArrayList<String>>> it 1344 = mPendingBroadcasts.packagesForUserId(packageUserId) 1345 .entrySet().iterator(); 1346 while (it.hasNext() && i < size) { 1347 Map.Entry<String, ArrayList<String>> ent = it.next(); 1348 packages[i] = ent.getKey(); 1349 components[i] = ent.getValue(); 1350 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1351 uids[i] = (ps != null) 1352 ? UserHandle.getUid(packageUserId, ps.appId) 1353 : -1; 1354 i++; 1355 } 1356 } 1357 size = i; 1358 mPendingBroadcasts.clear(); 1359 } 1360 // Send broadcasts 1361 for (int i = 0; i < size; i++) { 1362 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1363 } 1364 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1365 break; 1366 } 1367 case START_CLEANING_PACKAGE: { 1368 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1369 final String packageName = (String)msg.obj; 1370 final int userId = msg.arg1; 1371 final boolean andCode = msg.arg2 != 0; 1372 synchronized (mPackages) { 1373 if (userId == UserHandle.USER_ALL) { 1374 int[] users = sUserManager.getUserIds(); 1375 for (int user : users) { 1376 mSettings.addPackageToCleanLPw( 1377 new PackageCleanItem(user, packageName, andCode)); 1378 } 1379 } else { 1380 mSettings.addPackageToCleanLPw( 1381 new PackageCleanItem(userId, packageName, andCode)); 1382 } 1383 } 1384 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1385 startCleaningPackages(); 1386 } break; 1387 case POST_INSTALL: { 1388 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1389 1390 PostInstallData data = mRunningInstalls.get(msg.arg1); 1391 final boolean didRestore = (msg.arg2 != 0); 1392 mRunningInstalls.delete(msg.arg1); 1393 1394 if (data != null) { 1395 InstallArgs args = data.args; 1396 PackageInstalledInfo parentRes = data.res; 1397 1398 final boolean grantPermissions = (args.installFlags 1399 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1400 final boolean killApp = (args.installFlags 1401 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1402 final String[] grantedPermissions = args.installGrantPermissions; 1403 1404 // Handle the parent package 1405 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1406 grantedPermissions, didRestore, args.installerPackageName, 1407 args.observer); 1408 1409 // Handle the child packages 1410 final int childCount = (parentRes.addedChildPackages != null) 1411 ? parentRes.addedChildPackages.size() : 0; 1412 for (int i = 0; i < childCount; i++) { 1413 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1414 handlePackagePostInstall(childRes, grantPermissions, killApp, 1415 grantedPermissions, false, args.installerPackageName, 1416 args.observer); 1417 } 1418 1419 // Log tracing if needed 1420 if (args.traceMethod != null) { 1421 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1422 args.traceCookie); 1423 } 1424 } else { 1425 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1426 } 1427 1428 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1429 } break; 1430 case UPDATED_MEDIA_STATUS: { 1431 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1432 boolean reportStatus = msg.arg1 == 1; 1433 boolean doGc = msg.arg2 == 1; 1434 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1435 if (doGc) { 1436 // Force a gc to clear up stale containers. 1437 Runtime.getRuntime().gc(); 1438 } 1439 if (msg.obj != null) { 1440 @SuppressWarnings("unchecked") 1441 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1443 // Unload containers 1444 unloadAllContainers(args); 1445 } 1446 if (reportStatus) { 1447 try { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1449 PackageHelper.getMountService().finishMediaUpdate(); 1450 } catch (RemoteException e) { 1451 Log.e(TAG, "MountService not running?"); 1452 } 1453 } 1454 } break; 1455 case WRITE_SETTINGS: { 1456 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1457 synchronized (mPackages) { 1458 removeMessages(WRITE_SETTINGS); 1459 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1460 mSettings.writeLPr(); 1461 mDirtyUsers.clear(); 1462 } 1463 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1464 } break; 1465 case WRITE_PACKAGE_RESTRICTIONS: { 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1467 synchronized (mPackages) { 1468 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1469 for (int userId : mDirtyUsers) { 1470 mSettings.writePackageRestrictionsLPr(userId); 1471 } 1472 mDirtyUsers.clear(); 1473 } 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1475 } break; 1476 case WRITE_PACKAGE_LIST: { 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1478 synchronized (mPackages) { 1479 removeMessages(WRITE_PACKAGE_LIST); 1480 mSettings.writePackageListLPr(msg.arg1); 1481 } 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1483 } break; 1484 case CHECK_PENDING_VERIFICATION: { 1485 final int verificationId = msg.arg1; 1486 final PackageVerificationState state = mPendingVerification.get(verificationId); 1487 1488 if ((state != null) && !state.timeoutExtended()) { 1489 final InstallArgs args = state.getInstallArgs(); 1490 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1491 1492 Slog.i(TAG, "Verification timed out for " + originUri); 1493 mPendingVerification.remove(verificationId); 1494 1495 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1496 1497 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1498 Slog.i(TAG, "Continuing with installation of " + originUri); 1499 state.setVerifierResponse(Binder.getCallingUid(), 1500 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1501 broadcastPackageVerified(verificationId, originUri, 1502 PackageManager.VERIFICATION_ALLOW, 1503 state.getInstallArgs().getUser()); 1504 try { 1505 ret = args.copyApk(mContainerService, true); 1506 } catch (RemoteException e) { 1507 Slog.e(TAG, "Could not contact the ContainerService"); 1508 } 1509 } else { 1510 broadcastPackageVerified(verificationId, originUri, 1511 PackageManager.VERIFICATION_REJECT, 1512 state.getInstallArgs().getUser()); 1513 } 1514 1515 Trace.asyncTraceEnd( 1516 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1517 1518 processPendingInstall(args, ret); 1519 mHandler.sendEmptyMessage(MCS_UNBIND); 1520 } 1521 break; 1522 } 1523 case PACKAGE_VERIFIED: { 1524 final int verificationId = msg.arg1; 1525 1526 final PackageVerificationState state = mPendingVerification.get(verificationId); 1527 if (state == null) { 1528 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1529 break; 1530 } 1531 1532 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1533 1534 state.setVerifierResponse(response.callerUid, response.code); 1535 1536 if (state.isVerificationComplete()) { 1537 mPendingVerification.remove(verificationId); 1538 1539 final InstallArgs args = state.getInstallArgs(); 1540 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1541 1542 int ret; 1543 if (state.isInstallAllowed()) { 1544 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1545 broadcastPackageVerified(verificationId, originUri, 1546 response.code, state.getInstallArgs().getUser()); 1547 try { 1548 ret = args.copyApk(mContainerService, true); 1549 } catch (RemoteException e) { 1550 Slog.e(TAG, "Could not contact the ContainerService"); 1551 } 1552 } else { 1553 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1554 } 1555 1556 Trace.asyncTraceEnd( 1557 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1558 1559 processPendingInstall(args, ret); 1560 mHandler.sendEmptyMessage(MCS_UNBIND); 1561 } 1562 1563 break; 1564 } 1565 case START_INTENT_FILTER_VERIFICATIONS: { 1566 IFVerificationParams params = (IFVerificationParams) msg.obj; 1567 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1568 params.replacing, params.pkg); 1569 break; 1570 } 1571 case INTENT_FILTER_VERIFIED: { 1572 final int verificationId = msg.arg1; 1573 1574 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1575 verificationId); 1576 if (state == null) { 1577 Slog.w(TAG, "Invalid IntentFilter verification token " 1578 + verificationId + " received"); 1579 break; 1580 } 1581 1582 final int userId = state.getUserId(); 1583 1584 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1585 "Processing IntentFilter verification with token:" 1586 + verificationId + " and userId:" + userId); 1587 1588 final IntentFilterVerificationResponse response = 1589 (IntentFilterVerificationResponse) msg.obj; 1590 1591 state.setVerifierResponse(response.callerUid, response.code); 1592 1593 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1594 "IntentFilter verification with token:" + verificationId 1595 + " and userId:" + userId 1596 + " is settings verifier response with response code:" 1597 + response.code); 1598 1599 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1601 + response.getFailedDomainsString()); 1602 } 1603 1604 if (state.isVerificationComplete()) { 1605 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1606 } else { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1608 "IntentFilter verification with token:" + verificationId 1609 + " was not said to be complete"); 1610 } 1611 1612 break; 1613 } 1614 } 1615 } 1616 } 1617 1618 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1619 boolean killApp, String[] grantedPermissions, 1620 boolean launchedForRestore, String installerPackage, 1621 IPackageInstallObserver2 installObserver) { 1622 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1623 // Send the removed broadcasts 1624 if (res.removedInfo != null) { 1625 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1626 } 1627 1628 // Now that we successfully installed the package, grant runtime 1629 // permissions if requested before broadcasting the install. 1630 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1631 >= Build.VERSION_CODES.M) { 1632 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1633 } 1634 1635 final boolean update = res.removedInfo != null 1636 && res.removedInfo.removedPackage != null; 1637 1638 // If this is the first time we have child packages for a disabled privileged 1639 // app that had no children, we grant requested runtime permissions to the new 1640 // children if the parent on the system image had them already granted. 1641 if (res.pkg.parentPackage != null) { 1642 synchronized (mPackages) { 1643 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1644 } 1645 } 1646 1647 synchronized (mPackages) { 1648 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1649 } 1650 1651 final String packageName = res.pkg.applicationInfo.packageName; 1652 Bundle extras = new Bundle(1); 1653 extras.putInt(Intent.EXTRA_UID, res.uid); 1654 1655 // Determine the set of users who are adding this package for 1656 // the first time vs. those who are seeing an update. 1657 int[] firstUsers = EMPTY_INT_ARRAY; 1658 int[] updateUsers = EMPTY_INT_ARRAY; 1659 if (res.origUsers == null || res.origUsers.length == 0) { 1660 firstUsers = res.newUsers; 1661 } else { 1662 for (int newUser : res.newUsers) { 1663 boolean isNew = true; 1664 for (int origUser : res.origUsers) { 1665 if (origUser == newUser) { 1666 isNew = false; 1667 break; 1668 } 1669 } 1670 if (isNew) { 1671 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1672 } else { 1673 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1674 } 1675 } 1676 } 1677 1678 // Send installed broadcasts if the install/update is not ephemeral 1679 if (!isEphemeral(res.pkg)) { 1680 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1681 1682 // Send added for users that see the package for the first time 1683 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1684 extras, 0 /*flags*/, null /*targetPackage*/, 1685 null /*finishedReceiver*/, firstUsers); 1686 1687 // Send added for users that don't see the package for the first time 1688 if (update) { 1689 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1690 } 1691 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1692 extras, 0 /*flags*/, null /*targetPackage*/, 1693 null /*finishedReceiver*/, updateUsers); 1694 1695 // Send replaced for users that don't see the package for the first time 1696 if (update) { 1697 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1698 packageName, extras, 0 /*flags*/, 1699 null /*targetPackage*/, null /*finishedReceiver*/, 1700 updateUsers); 1701 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1702 null /*package*/, null /*extras*/, 0 /*flags*/, 1703 packageName /*targetPackage*/, 1704 null /*finishedReceiver*/, updateUsers); 1705 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1706 // First-install and we did a restore, so we're responsible for the 1707 // first-launch broadcast. 1708 if (DEBUG_BACKUP) { 1709 Slog.i(TAG, "Post-restore of " + packageName 1710 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1711 } 1712 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1713 } 1714 1715 // Send broadcast package appeared if forward locked/external for all users 1716 // treat asec-hosted packages like removable media on upgrade 1717 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1718 if (DEBUG_INSTALL) { 1719 Slog.i(TAG, "upgrading pkg " + res.pkg 1720 + " is ASEC-hosted -> AVAILABLE"); 1721 } 1722 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1723 ArrayList<String> pkgList = new ArrayList<>(1); 1724 pkgList.add(packageName); 1725 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1726 } 1727 } 1728 1729 // Work that needs to happen on first install within each user 1730 if (firstUsers != null && firstUsers.length > 0) { 1731 synchronized (mPackages) { 1732 for (int userId : firstUsers) { 1733 // If this app is a browser and it's newly-installed for some 1734 // users, clear any default-browser state in those users. The 1735 // app's nature doesn't depend on the user, so we can just check 1736 // its browser nature in any user and generalize. 1737 if (packageIsBrowser(packageName, userId)) { 1738 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1739 } 1740 1741 // We may also need to apply pending (restored) runtime 1742 // permission grants within these users. 1743 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1744 } 1745 } 1746 } 1747 1748 // Log current value of "unknown sources" setting 1749 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1750 getUnknownSourcesSettings()); 1751 1752 // Force a gc to clear up things 1753 Runtime.getRuntime().gc(); 1754 1755 // Remove the replaced package's older resources safely now 1756 // We delete after a gc for applications on sdcard. 1757 if (res.removedInfo != null && res.removedInfo.args != null) { 1758 synchronized (mInstallLock) { 1759 res.removedInfo.args.doPostDeleteLI(true); 1760 } 1761 } 1762 } 1763 1764 // If someone is watching installs - notify them 1765 if (installObserver != null) { 1766 try { 1767 Bundle extras = extrasForInstallResult(res); 1768 installObserver.onPackageInstalled(res.name, res.returnCode, 1769 res.returnMsg, extras); 1770 } catch (RemoteException e) { 1771 Slog.i(TAG, "Observer no longer exists."); 1772 } 1773 } 1774 } 1775 1776 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1777 PackageParser.Package pkg) { 1778 if (pkg.parentPackage == null) { 1779 return; 1780 } 1781 if (pkg.requestedPermissions == null) { 1782 return; 1783 } 1784 final PackageSetting disabledSysParentPs = mSettings 1785 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1786 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1787 || !disabledSysParentPs.isPrivileged() 1788 || (disabledSysParentPs.childPackageNames != null 1789 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1790 return; 1791 } 1792 final int[] allUserIds = sUserManager.getUserIds(); 1793 final int permCount = pkg.requestedPermissions.size(); 1794 for (int i = 0; i < permCount; i++) { 1795 String permission = pkg.requestedPermissions.get(i); 1796 BasePermission bp = mSettings.mPermissions.get(permission); 1797 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1798 continue; 1799 } 1800 for (int userId : allUserIds) { 1801 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1802 permission, userId)) { 1803 grantRuntimePermission(pkg.packageName, permission, userId); 1804 } 1805 } 1806 } 1807 } 1808 1809 private StorageEventListener mStorageListener = new StorageEventListener() { 1810 @Override 1811 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1812 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1813 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1814 final String volumeUuid = vol.getFsUuid(); 1815 1816 // Clean up any users or apps that were removed or recreated 1817 // while this volume was missing 1818 reconcileUsers(volumeUuid); 1819 reconcileApps(volumeUuid); 1820 1821 // Clean up any install sessions that expired or were 1822 // cancelled while this volume was missing 1823 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1824 1825 loadPrivatePackages(vol); 1826 1827 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1828 unloadPrivatePackages(vol); 1829 } 1830 } 1831 1832 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1833 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1834 updateExternalMediaStatus(true, false); 1835 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1836 updateExternalMediaStatus(false, false); 1837 } 1838 } 1839 } 1840 1841 @Override 1842 public void onVolumeForgotten(String fsUuid) { 1843 if (TextUtils.isEmpty(fsUuid)) { 1844 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1845 return; 1846 } 1847 1848 // Remove any apps installed on the forgotten volume 1849 synchronized (mPackages) { 1850 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1851 for (PackageSetting ps : packages) { 1852 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1853 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1854 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1855 } 1856 1857 mSettings.onVolumeForgotten(fsUuid); 1858 mSettings.writeLPr(); 1859 } 1860 } 1861 }; 1862 1863 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1864 String[] grantedPermissions) { 1865 for (int userId : userIds) { 1866 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1867 } 1868 1869 // We could have touched GID membership, so flush out packages.list 1870 synchronized (mPackages) { 1871 mSettings.writePackageListLPr(); 1872 } 1873 } 1874 1875 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1876 String[] grantedPermissions) { 1877 SettingBase sb = (SettingBase) pkg.mExtras; 1878 if (sb == null) { 1879 return; 1880 } 1881 1882 PermissionsState permissionsState = sb.getPermissionsState(); 1883 1884 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1885 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1886 1887 for (String permission : pkg.requestedPermissions) { 1888 final BasePermission bp; 1889 synchronized (mPackages) { 1890 bp = mSettings.mPermissions.get(permission); 1891 } 1892 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1893 && (grantedPermissions == null 1894 || ArrayUtils.contains(grantedPermissions, permission))) { 1895 final int flags = permissionsState.getPermissionFlags(permission, userId); 1896 // Installer cannot change immutable permissions. 1897 if ((flags & immutableFlags) == 0) { 1898 grantRuntimePermission(pkg.packageName, permission, userId); 1899 } 1900 } 1901 } 1902 } 1903 1904 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1905 Bundle extras = null; 1906 switch (res.returnCode) { 1907 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1908 extras = new Bundle(); 1909 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1910 res.origPermission); 1911 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1912 res.origPackage); 1913 break; 1914 } 1915 case PackageManager.INSTALL_SUCCEEDED: { 1916 extras = new Bundle(); 1917 extras.putBoolean(Intent.EXTRA_REPLACING, 1918 res.removedInfo != null && res.removedInfo.removedPackage != null); 1919 break; 1920 } 1921 } 1922 return extras; 1923 } 1924 1925 void scheduleWriteSettingsLocked() { 1926 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1927 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1928 } 1929 } 1930 1931 void scheduleWritePackageListLocked(int userId) { 1932 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1933 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1934 msg.arg1 = userId; 1935 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1936 } 1937 } 1938 1939 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1940 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1941 scheduleWritePackageRestrictionsLocked(userId); 1942 } 1943 1944 void scheduleWritePackageRestrictionsLocked(int userId) { 1945 final int[] userIds = (userId == UserHandle.USER_ALL) 1946 ? sUserManager.getUserIds() : new int[]{userId}; 1947 for (int nextUserId : userIds) { 1948 if (!sUserManager.exists(nextUserId)) return; 1949 mDirtyUsers.add(nextUserId); 1950 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1951 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1952 } 1953 } 1954 } 1955 1956 public static PackageManagerService main(Context context, Installer installer, 1957 boolean factoryTest, boolean onlyCore) { 1958 // Self-check for initial settings. 1959 PackageManagerServiceCompilerMapping.checkProperties(); 1960 1961 PackageManagerService m = new PackageManagerService(context, installer, 1962 factoryTest, onlyCore); 1963 m.enableSystemUserPackages(); 1964 ServiceManager.addService("package", m); 1965 return m; 1966 } 1967 1968 private void enableSystemUserPackages() { 1969 if (!UserManager.isSplitSystemUser()) { 1970 return; 1971 } 1972 // For system user, enable apps based on the following conditions: 1973 // - app is whitelisted or belong to one of these groups: 1974 // -- system app which has no launcher icons 1975 // -- system app which has INTERACT_ACROSS_USERS permission 1976 // -- system IME app 1977 // - app is not in the blacklist 1978 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1979 Set<String> enableApps = new ArraySet<>(); 1980 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1981 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1982 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1983 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1984 enableApps.addAll(wlApps); 1985 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1986 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1987 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1988 enableApps.removeAll(blApps); 1989 Log.i(TAG, "Applications installed for system user: " + enableApps); 1990 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1991 UserHandle.SYSTEM); 1992 final int allAppsSize = allAps.size(); 1993 synchronized (mPackages) { 1994 for (int i = 0; i < allAppsSize; i++) { 1995 String pName = allAps.get(i); 1996 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1997 // Should not happen, but we shouldn't be failing if it does 1998 if (pkgSetting == null) { 1999 continue; 2000 } 2001 boolean install = enableApps.contains(pName); 2002 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2003 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2004 + " for system user"); 2005 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2006 } 2007 } 2008 } 2009 } 2010 2011 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2012 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2013 Context.DISPLAY_SERVICE); 2014 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2015 } 2016 2017 /** 2018 * Requests that files preopted on a secondary system partition be copied to the data partition 2019 * if possible. Note that the actual copying of the files is accomplished by init for security 2020 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2021 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2022 */ 2023 private static void requestCopyPreoptedFiles() { 2024 final int WAIT_TIME_MS = 100; 2025 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2026 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2027 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2028 // We will wait for up to 100 seconds. 2029 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2030 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2031 try { 2032 Thread.sleep(WAIT_TIME_MS); 2033 } catch (InterruptedException e) { 2034 // Do nothing 2035 } 2036 if (SystemClock.uptimeMillis() > timeEnd) { 2037 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2038 Slog.wtf(TAG, "cppreopt did not finish!"); 2039 break; 2040 } 2041 } 2042 } 2043 } 2044 2045 public PackageManagerService(Context context, Installer installer, 2046 boolean factoryTest, boolean onlyCore) { 2047 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2048 SystemClock.uptimeMillis()); 2049 2050 if (mSdkVersion <= 0) { 2051 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2052 } 2053 2054 mContext = context; 2055 mFactoryTest = factoryTest; 2056 mOnlyCore = onlyCore; 2057 mMetrics = new DisplayMetrics(); 2058 mSettings = new Settings(mPackages); 2059 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2060 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2061 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2062 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2063 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2064 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2065 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2066 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2067 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2068 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2069 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2070 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2071 2072 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2073 if (separateProcesses != null && separateProcesses.length() > 0) { 2074 if ("*".equals(separateProcesses)) { 2075 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2076 mSeparateProcesses = null; 2077 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2078 } else { 2079 mDefParseFlags = 0; 2080 mSeparateProcesses = separateProcesses.split(","); 2081 Slog.w(TAG, "Running with debug.separate_processes: " 2082 + separateProcesses); 2083 } 2084 } else { 2085 mDefParseFlags = 0; 2086 mSeparateProcesses = null; 2087 } 2088 2089 mInstaller = installer; 2090 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2091 "*dexopt*"); 2092 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2093 2094 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2095 FgThread.get().getLooper()); 2096 2097 getDefaultDisplayMetrics(context, mMetrics); 2098 2099 SystemConfig systemConfig = SystemConfig.getInstance(); 2100 mGlobalGids = systemConfig.getGlobalGids(); 2101 mSystemPermissions = systemConfig.getSystemPermissions(); 2102 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2103 2104 mProtectedPackages = new ProtectedPackages(mContext); 2105 2106 synchronized (mInstallLock) { 2107 // writer 2108 synchronized (mPackages) { 2109 mHandlerThread = new ServiceThread(TAG, 2110 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2111 mHandlerThread.start(); 2112 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2113 mProcessLoggingHandler = new ProcessLoggingHandler(); 2114 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2115 2116 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 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 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2243 2244 // save off the names of pre-existing system packages prior to scanning; we don't 2245 // want to automatically grant runtime permissions for new system apps 2246 if (mPromoteSystemApps) { 2247 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2248 while (pkgSettingIter.hasNext()) { 2249 PackageSetting ps = pkgSettingIter.next(); 2250 if (isSystemApp(ps)) { 2251 mExistingSystemPackages.add(ps.name); 2252 } 2253 } 2254 } 2255 2256 // Collect vendor overlay packages. 2257 // (Do this before scanning any apps.) 2258 // For security and version matching reason, only consider 2259 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2260 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2261 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2262 | PackageParser.PARSE_IS_SYSTEM 2263 | PackageParser.PARSE_IS_SYSTEM_DIR 2264 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2265 2266 // Find base frameworks (resource packages without code). 2267 scanDirTracedLI(frameworkDir, mDefParseFlags 2268 | PackageParser.PARSE_IS_SYSTEM 2269 | PackageParser.PARSE_IS_SYSTEM_DIR 2270 | PackageParser.PARSE_IS_PRIVILEGED, 2271 scanFlags | SCAN_NO_DEX, 0); 2272 2273 // Collected privileged system packages. 2274 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2275 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2276 | PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR 2278 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2279 2280 // Collect ordinary system packages. 2281 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2282 scanDirTracedLI(systemAppDir, mDefParseFlags 2283 | PackageParser.PARSE_IS_SYSTEM 2284 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2285 2286 // Collect all vendor packages. 2287 File vendorAppDir = new File("/vendor/app"); 2288 try { 2289 vendorAppDir = vendorAppDir.getCanonicalFile(); 2290 } catch (IOException e) { 2291 // failed to look up canonical path, continue with original one 2292 } 2293 scanDirTracedLI(vendorAppDir, mDefParseFlags 2294 | PackageParser.PARSE_IS_SYSTEM 2295 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2296 2297 // Collect all OEM packages. 2298 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2299 scanDirTracedLI(oemAppDir, mDefParseFlags 2300 | PackageParser.PARSE_IS_SYSTEM 2301 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2302 2303 // Prune any system packages that no longer exist. 2304 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2305 if (!mOnlyCore) { 2306 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2307 while (psit.hasNext()) { 2308 PackageSetting ps = psit.next(); 2309 2310 /* 2311 * If this is not a system app, it can't be a 2312 * disable system app. 2313 */ 2314 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2315 continue; 2316 } 2317 2318 /* 2319 * If the package is scanned, it's not erased. 2320 */ 2321 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2322 if (scannedPkg != null) { 2323 /* 2324 * If the system app is both scanned and in the 2325 * disabled packages list, then it must have been 2326 * added via OTA. Remove it from the currently 2327 * scanned package so the previously user-installed 2328 * application can be scanned. 2329 */ 2330 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2331 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2332 + ps.name + "; removing system app. Last known codePath=" 2333 + ps.codePathString + ", installStatus=" + ps.installStatus 2334 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2335 + scannedPkg.mVersionCode); 2336 removePackageLI(scannedPkg, true); 2337 mExpectingBetter.put(ps.name, ps.codePath); 2338 } 2339 2340 continue; 2341 } 2342 2343 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2344 psit.remove(); 2345 logCriticalInfo(Log.WARN, "System package " + ps.name 2346 + " no longer exists; it's data will be wiped"); 2347 // Actual deletion of code and data will be handled by later 2348 // reconciliation step 2349 } else { 2350 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2351 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2352 possiblyDeletedUpdatedSystemApps.add(ps.name); 2353 } 2354 } 2355 } 2356 } 2357 2358 //look for any incomplete package installations 2359 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2360 for (int i = 0; i < deletePkgsList.size(); i++) { 2361 // Actual deletion of code and data will be handled by later 2362 // reconciliation step 2363 final String packageName = deletePkgsList.get(i).name; 2364 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2365 synchronized (mPackages) { 2366 mSettings.removePackageLPw(packageName); 2367 } 2368 } 2369 2370 //delete tmp files 2371 deleteTempPackageFiles(); 2372 2373 // Remove any shared userIDs that have no associated packages 2374 mSettings.pruneSharedUsersLPw(); 2375 2376 if (!mOnlyCore) { 2377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2378 SystemClock.uptimeMillis()); 2379 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2380 2381 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2382 | PackageParser.PARSE_FORWARD_LOCK, 2383 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2384 2385 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2386 | PackageParser.PARSE_IS_EPHEMERAL, 2387 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2388 2389 /** 2390 * Remove disable package settings for any updated system 2391 * apps that were removed via an OTA. If they're not a 2392 * previously-updated app, remove them completely. 2393 * Otherwise, just revoke their system-level permissions. 2394 */ 2395 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2396 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2397 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2398 2399 String msg; 2400 if (deletedPkg == null) { 2401 msg = "Updated system package " + deletedAppName 2402 + " no longer exists; it's data will be wiped"; 2403 // Actual deletion of code and data will be handled by later 2404 // reconciliation step 2405 } else { 2406 msg = "Updated system app + " + deletedAppName 2407 + " no longer present; removing system privileges for " 2408 + deletedAppName; 2409 2410 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2411 2412 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2413 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2414 } 2415 logCriticalInfo(Log.WARN, msg); 2416 } 2417 2418 /** 2419 * Make sure all system apps that we expected to appear on 2420 * the userdata partition actually showed up. If they never 2421 * appeared, crawl back and revive the system version. 2422 */ 2423 for (int i = 0; i < mExpectingBetter.size(); i++) { 2424 final String packageName = mExpectingBetter.keyAt(i); 2425 if (!mPackages.containsKey(packageName)) { 2426 final File scanFile = mExpectingBetter.valueAt(i); 2427 2428 logCriticalInfo(Log.WARN, "Expected better " + packageName 2429 + " but never showed up; reverting to system"); 2430 2431 int reparseFlags = mDefParseFlags; 2432 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2433 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2434 | PackageParser.PARSE_IS_SYSTEM_DIR 2435 | PackageParser.PARSE_IS_PRIVILEGED; 2436 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2437 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR; 2439 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2440 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR; 2442 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2443 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR; 2445 } else { 2446 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2447 continue; 2448 } 2449 2450 mSettings.enableSystemPackageLPw(packageName); 2451 2452 try { 2453 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2454 } catch (PackageManagerException e) { 2455 Slog.e(TAG, "Failed to parse original system package: " 2456 + e.getMessage()); 2457 } 2458 } 2459 } 2460 } 2461 mExpectingBetter.clear(); 2462 2463 // Resolve protected action filters. Only the setup wizard is allowed to 2464 // have a high priority filter for these actions. 2465 mSetupWizardPackage = getSetupWizardPackageName(); 2466 if (mProtectedFilters.size() > 0) { 2467 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2468 Slog.i(TAG, "No setup wizard;" 2469 + " All protected intents capped to priority 0"); 2470 } 2471 for (ActivityIntentInfo filter : mProtectedFilters) { 2472 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2473 if (DEBUG_FILTERS) { 2474 Slog.i(TAG, "Found setup wizard;" 2475 + " allow priority " + filter.getPriority() + ";" 2476 + " package: " + filter.activity.info.packageName 2477 + " activity: " + filter.activity.className 2478 + " priority: " + filter.getPriority()); 2479 } 2480 // skip setup wizard; allow it to keep the high priority filter 2481 continue; 2482 } 2483 Slog.w(TAG, "Protected action; cap priority to 0;" 2484 + " package: " + filter.activity.info.packageName 2485 + " activity: " + filter.activity.className 2486 + " origPrio: " + filter.getPriority()); 2487 filter.setPriority(0); 2488 } 2489 } 2490 mDeferProtectedFilters = false; 2491 mProtectedFilters.clear(); 2492 2493 // Now that we know all of the shared libraries, update all clients to have 2494 // the correct library paths. 2495 updateAllSharedLibrariesLPw(); 2496 2497 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2498 // NOTE: We ignore potential failures here during a system scan (like 2499 // the rest of the commands above) because there's precious little we 2500 // can do about it. A settings error is reported, though. 2501 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2502 false /* boot complete */); 2503 } 2504 2505 // Now that we know all the packages we are keeping, 2506 // read and update their last usage times. 2507 mPackageUsage.read(mPackages); 2508 mCompilerStats.read(); 2509 2510 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2511 SystemClock.uptimeMillis()); 2512 Slog.i(TAG, "Time to scan packages: " 2513 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2514 + " seconds"); 2515 2516 // If the platform SDK has changed since the last time we booted, 2517 // we need to re-grant app permission to catch any new ones that 2518 // appear. This is really a hack, and means that apps can in some 2519 // cases get permissions that the user didn't initially explicitly 2520 // allow... it would be nice to have some better way to handle 2521 // this situation. 2522 int updateFlags = UPDATE_PERMISSIONS_ALL; 2523 if (ver.sdkVersion != mSdkVersion) { 2524 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2525 + mSdkVersion + "; regranting permissions for internal storage"); 2526 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2527 } 2528 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2529 ver.sdkVersion = mSdkVersion; 2530 2531 // If this is the first boot or an update from pre-M, and it is a normal 2532 // boot, then we need to initialize the default preferred apps across 2533 // all defined users. 2534 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2535 for (UserInfo user : sUserManager.getUsers(true)) { 2536 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2537 applyFactoryDefaultBrowserLPw(user.id); 2538 primeDomainVerificationsLPw(user.id); 2539 } 2540 } 2541 2542 // Prepare storage for system user really early during boot, 2543 // since core system apps like SettingsProvider and SystemUI 2544 // can't wait for user to start 2545 final int storageFlags; 2546 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2547 storageFlags = StorageManager.FLAG_STORAGE_DE; 2548 } else { 2549 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2550 } 2551 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2552 storageFlags); 2553 2554 // If this is first boot after an OTA, and a normal boot, then 2555 // we need to clear code cache directories. 2556 // Note that we do *not* clear the application profiles. These remain valid 2557 // across OTAs and are used to drive profile verification (post OTA) and 2558 // profile compilation (without waiting to collect a fresh set of profiles). 2559 if (mIsUpgrade && !onlyCore) { 2560 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2561 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2562 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2563 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2564 // No apps are running this early, so no need to freeze 2565 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2566 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2567 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2568 } 2569 } 2570 ver.fingerprint = Build.FINGERPRINT; 2571 } 2572 2573 checkDefaultBrowser(); 2574 2575 // clear only after permissions and other defaults have been updated 2576 mExistingSystemPackages.clear(); 2577 mPromoteSystemApps = false; 2578 2579 // All the changes are done during package scanning. 2580 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2581 2582 // can downgrade to reader 2583 mSettings.writeLPr(); 2584 2585 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2586 // early on (before the package manager declares itself as early) because other 2587 // components in the system server might ask for package contexts for these apps. 2588 // 2589 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2590 // (i.e, that the data partition is unavailable). 2591 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2592 long start = System.nanoTime(); 2593 List<PackageParser.Package> coreApps = new ArrayList<>(); 2594 for (PackageParser.Package pkg : mPackages.values()) { 2595 if (pkg.coreApp) { 2596 coreApps.add(pkg); 2597 } 2598 } 2599 2600 int[] stats = performDexOptUpgrade(coreApps, false, 2601 getCompilerFilterForReason(REASON_CORE_APP)); 2602 2603 final int elapsedTimeSeconds = 2604 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2605 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2606 2607 if (DEBUG_DEXOPT) { 2608 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2609 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2610 } 2611 2612 2613 // TODO: Should we log these stats to tron too ? 2614 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2615 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2616 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2617 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2618 } 2619 2620 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2621 SystemClock.uptimeMillis()); 2622 2623 if (!mOnlyCore) { 2624 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2625 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2626 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2627 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2628 mIntentFilterVerifierComponent); 2629 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2630 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2631 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2632 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2633 } else { 2634 mRequiredVerifierPackage = null; 2635 mRequiredInstallerPackage = null; 2636 mIntentFilterVerifierComponent = null; 2637 mIntentFilterVerifier = null; 2638 mServicesSystemSharedLibraryPackageName = null; 2639 mSharedSystemSharedLibraryPackageName = null; 2640 } 2641 2642 mInstallerService = new PackageInstallerService(context, this); 2643 2644 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2645 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2646 // both the installer and resolver must be present to enable ephemeral 2647 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2648 if (DEBUG_EPHEMERAL) { 2649 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2650 + " installer:" + ephemeralInstallerComponent); 2651 } 2652 mEphemeralResolverComponent = ephemeralResolverComponent; 2653 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2654 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2655 mEphemeralResolverConnection = 2656 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2657 } else { 2658 if (DEBUG_EPHEMERAL) { 2659 final String missingComponent = 2660 (ephemeralResolverComponent == null) 2661 ? (ephemeralInstallerComponent == null) 2662 ? "resolver and installer" 2663 : "resolver" 2664 : "installer"; 2665 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2666 } 2667 mEphemeralResolverComponent = null; 2668 mEphemeralInstallerComponent = null; 2669 mEphemeralResolverConnection = null; 2670 } 2671 2672 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2673 } // synchronized (mPackages) 2674 } // synchronized (mInstallLock) 2675 2676 // Now after opening every single application zip, make sure they 2677 // are all flushed. Not really needed, but keeps things nice and 2678 // tidy. 2679 Runtime.getRuntime().gc(); 2680 2681 // The initial scanning above does many calls into installd while 2682 // holding the mPackages lock, but we're mostly interested in yelling 2683 // once we have a booted system. 2684 mInstaller.setWarnIfHeld(mPackages); 2685 2686 // Expose private service for system components to use. 2687 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2688 } 2689 2690 @Override 2691 public boolean isFirstBoot() { 2692 return mFirstBoot; 2693 } 2694 2695 @Override 2696 public boolean isOnlyCoreApps() { 2697 return mOnlyCore; 2698 } 2699 2700 @Override 2701 public boolean isUpgrade() { 2702 return mIsUpgrade; 2703 } 2704 2705 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2706 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2707 2708 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2709 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2710 UserHandle.USER_SYSTEM); 2711 if (matches.size() == 1) { 2712 return matches.get(0).getComponentInfo().packageName; 2713 } else if (matches.size() == 0) { 2714 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2715 return null; 2716 } 2717 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2718 } 2719 2720 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2721 synchronized (mPackages) { 2722 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2723 if (libraryEntry == null) { 2724 throw new IllegalStateException("Missing required shared library:" + libraryName); 2725 } 2726 return libraryEntry.apk; 2727 } 2728 } 2729 2730 private @NonNull String getRequiredInstallerLPr() { 2731 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2732 intent.addCategory(Intent.CATEGORY_DEFAULT); 2733 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2734 2735 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2736 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2737 UserHandle.USER_SYSTEM); 2738 if (matches.size() == 1) { 2739 ResolveInfo resolveInfo = matches.get(0); 2740 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2741 throw new RuntimeException("The installer must be a privileged app"); 2742 } 2743 return matches.get(0).getComponentInfo().packageName; 2744 } else { 2745 throw new RuntimeException("There must be exactly one installer; found " + matches); 2746 } 2747 } 2748 2749 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2750 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2751 2752 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2753 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2754 UserHandle.USER_SYSTEM); 2755 ResolveInfo best = null; 2756 final int N = matches.size(); 2757 for (int i = 0; i < N; i++) { 2758 final ResolveInfo cur = matches.get(i); 2759 final String packageName = cur.getComponentInfo().packageName; 2760 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2761 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2762 continue; 2763 } 2764 2765 if (best == null || cur.priority > best.priority) { 2766 best = cur; 2767 } 2768 } 2769 2770 if (best != null) { 2771 return best.getComponentInfo().getComponentName(); 2772 } else { 2773 throw new RuntimeException("There must be at least one intent filter verifier"); 2774 } 2775 } 2776 2777 private @Nullable ComponentName getEphemeralResolverLPr() { 2778 final String[] packageArray = 2779 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2780 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2781 if (DEBUG_EPHEMERAL) { 2782 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2783 } 2784 return null; 2785 } 2786 2787 final int resolveFlags = 2788 MATCH_DIRECT_BOOT_AWARE 2789 | MATCH_DIRECT_BOOT_UNAWARE 2790 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2791 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2792 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2793 resolveFlags, UserHandle.USER_SYSTEM); 2794 2795 final int N = resolvers.size(); 2796 if (N == 0) { 2797 if (DEBUG_EPHEMERAL) { 2798 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2799 } 2800 return null; 2801 } 2802 2803 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2804 for (int i = 0; i < N; i++) { 2805 final ResolveInfo info = resolvers.get(i); 2806 2807 if (info.serviceInfo == null) { 2808 continue; 2809 } 2810 2811 final String packageName = info.serviceInfo.packageName; 2812 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2813 if (DEBUG_EPHEMERAL) { 2814 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2815 + " pkg: " + packageName + ", info:" + info); 2816 } 2817 continue; 2818 } 2819 2820 if (DEBUG_EPHEMERAL) { 2821 Slog.v(TAG, "Ephemeral resolver found;" 2822 + " pkg: " + packageName + ", info:" + info); 2823 } 2824 return new ComponentName(packageName, info.serviceInfo.name); 2825 } 2826 if (DEBUG_EPHEMERAL) { 2827 Slog.v(TAG, "Ephemeral resolver NOT found"); 2828 } 2829 return null; 2830 } 2831 2832 private @Nullable ComponentName getEphemeralInstallerLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2834 intent.addCategory(Intent.CATEGORY_DEFAULT); 2835 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2836 2837 final int resolveFlags = 2838 MATCH_DIRECT_BOOT_AWARE 2839 | MATCH_DIRECT_BOOT_UNAWARE 2840 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2841 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2842 resolveFlags, UserHandle.USER_SYSTEM); 2843 if (matches.size() == 0) { 2844 return null; 2845 } else if (matches.size() == 1) { 2846 return matches.get(0).getComponentInfo().getComponentName(); 2847 } else { 2848 throw new RuntimeException( 2849 "There must be at most one ephemeral installer; found " + matches); 2850 } 2851 } 2852 2853 private void primeDomainVerificationsLPw(int userId) { 2854 if (DEBUG_DOMAIN_VERIFICATION) { 2855 Slog.d(TAG, "Priming domain verifications in user " + userId); 2856 } 2857 2858 SystemConfig systemConfig = SystemConfig.getInstance(); 2859 ArraySet<String> packages = systemConfig.getLinkedApps(); 2860 ArraySet<String> domains = new ArraySet<String>(); 2861 2862 for (String packageName : packages) { 2863 PackageParser.Package pkg = mPackages.get(packageName); 2864 if (pkg != null) { 2865 if (!pkg.isSystemApp()) { 2866 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2867 continue; 2868 } 2869 2870 domains.clear(); 2871 for (PackageParser.Activity a : pkg.activities) { 2872 for (ActivityIntentInfo filter : a.intents) { 2873 if (hasValidDomains(filter)) { 2874 domains.addAll(filter.getHostsList()); 2875 } 2876 } 2877 } 2878 2879 if (domains.size() > 0) { 2880 if (DEBUG_DOMAIN_VERIFICATION) { 2881 Slog.v(TAG, " + " + packageName); 2882 } 2883 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2884 // state w.r.t. the formal app-linkage "no verification attempted" state; 2885 // and then 'always' in the per-user state actually used for intent resolution. 2886 final IntentFilterVerificationInfo ivi; 2887 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2888 new ArrayList<String>(domains)); 2889 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2890 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2891 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2892 } else { 2893 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2894 + "' does not handle web links"); 2895 } 2896 } else { 2897 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2898 } 2899 } 2900 2901 scheduleWritePackageRestrictionsLocked(userId); 2902 scheduleWriteSettingsLocked(); 2903 } 2904 2905 private void applyFactoryDefaultBrowserLPw(int userId) { 2906 // The default browser app's package name is stored in a string resource, 2907 // with a product-specific overlay used for vendor customization. 2908 String browserPkg = mContext.getResources().getString( 2909 com.android.internal.R.string.default_browser); 2910 if (!TextUtils.isEmpty(browserPkg)) { 2911 // non-empty string => required to be a known package 2912 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2913 if (ps == null) { 2914 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2915 browserPkg = null; 2916 } else { 2917 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2918 } 2919 } 2920 2921 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2922 // default. If there's more than one, just leave everything alone. 2923 if (browserPkg == null) { 2924 calculateDefaultBrowserLPw(userId); 2925 } 2926 } 2927 2928 private void calculateDefaultBrowserLPw(int userId) { 2929 List<String> allBrowsers = resolveAllBrowserApps(userId); 2930 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2931 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2932 } 2933 2934 private List<String> resolveAllBrowserApps(int userId) { 2935 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2936 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2937 PackageManager.MATCH_ALL, userId); 2938 2939 final int count = list.size(); 2940 List<String> result = new ArrayList<String>(count); 2941 for (int i=0; i<count; i++) { 2942 ResolveInfo info = list.get(i); 2943 if (info.activityInfo == null 2944 || !info.handleAllWebDataURI 2945 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2946 || result.contains(info.activityInfo.packageName)) { 2947 continue; 2948 } 2949 result.add(info.activityInfo.packageName); 2950 } 2951 2952 return result; 2953 } 2954 2955 private boolean packageIsBrowser(String packageName, int userId) { 2956 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2957 PackageManager.MATCH_ALL, userId); 2958 final int N = list.size(); 2959 for (int i = 0; i < N; i++) { 2960 ResolveInfo info = list.get(i); 2961 if (packageName.equals(info.activityInfo.packageName)) { 2962 return true; 2963 } 2964 } 2965 return false; 2966 } 2967 2968 private void checkDefaultBrowser() { 2969 final int myUserId = UserHandle.myUserId(); 2970 final String packageName = getDefaultBrowserPackageName(myUserId); 2971 if (packageName != null) { 2972 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2973 if (info == null) { 2974 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2975 synchronized (mPackages) { 2976 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2977 } 2978 } 2979 } 2980 } 2981 2982 @Override 2983 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2984 throws RemoteException { 2985 try { 2986 return super.onTransact(code, data, reply, flags); 2987 } catch (RuntimeException e) { 2988 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2989 Slog.wtf(TAG, "Package Manager Crash", e); 2990 } 2991 throw e; 2992 } 2993 } 2994 2995 static int[] appendInts(int[] cur, int[] add) { 2996 if (add == null) return cur; 2997 if (cur == null) return add; 2998 final int N = add.length; 2999 for (int i=0; i<N; i++) { 3000 cur = appendInt(cur, add[i]); 3001 } 3002 return cur; 3003 } 3004 3005 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 if (ps == null) { 3008 return null; 3009 } 3010 final PackageParser.Package p = ps.pkg; 3011 if (p == null) { 3012 return null; 3013 } 3014 3015 final PermissionsState permissionsState = ps.getPermissionsState(); 3016 3017 // Compute GIDs only if requested 3018 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3019 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3020 // Compute granted permissions only if package has requested permissions 3021 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3022 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3023 final PackageUserState state = ps.readUserState(userId); 3024 3025 return PackageParser.generatePackageInfo(p, gids, flags, 3026 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3027 } 3028 3029 @Override 3030 public void checkPackageStartable(String packageName, int userId) { 3031 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3032 3033 synchronized (mPackages) { 3034 final PackageSetting ps = mSettings.mPackages.get(packageName); 3035 if (ps == null) { 3036 throw new SecurityException("Package " + packageName + " was not found!"); 3037 } 3038 3039 if (!ps.getInstalled(userId)) { 3040 throw new SecurityException( 3041 "Package " + packageName + " was not installed for user " + userId + "!"); 3042 } 3043 3044 if (mSafeMode && !ps.isSystem()) { 3045 throw new SecurityException("Package " + packageName + " not a system app!"); 3046 } 3047 3048 if (mFrozenPackages.contains(packageName)) { 3049 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3050 } 3051 3052 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3053 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3054 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3055 } 3056 } 3057 } 3058 3059 @Override 3060 public boolean isPackageAvailable(String packageName, int userId) { 3061 if (!sUserManager.exists(userId)) return false; 3062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3063 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3064 synchronized (mPackages) { 3065 PackageParser.Package p = mPackages.get(packageName); 3066 if (p != null) { 3067 final PackageSetting ps = (PackageSetting) p.mExtras; 3068 if (ps != null) { 3069 final PackageUserState state = ps.readUserState(userId); 3070 if (state != null) { 3071 return PackageParser.isAvailable(state); 3072 } 3073 } 3074 } 3075 } 3076 return false; 3077 } 3078 3079 @Override 3080 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3081 if (!sUserManager.exists(userId)) return null; 3082 flags = updateFlagsForPackage(flags, userId, packageName); 3083 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3084 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3085 // reader 3086 synchronized (mPackages) { 3087 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3088 PackageParser.Package p = null; 3089 if (matchFactoryOnly) { 3090 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3091 if (ps != null) { 3092 return generatePackageInfo(ps, flags, userId); 3093 } 3094 } 3095 if (p == null) { 3096 p = mPackages.get(packageName); 3097 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3098 return null; 3099 } 3100 } 3101 if (DEBUG_PACKAGE_INFO) 3102 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3103 if (p != null) { 3104 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3105 } 3106 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3107 final PackageSetting ps = mSettings.mPackages.get(packageName); 3108 return generatePackageInfo(ps, flags, userId); 3109 } 3110 } 3111 return null; 3112 } 3113 3114 @Override 3115 public String[] currentToCanonicalPackageNames(String[] names) { 3116 String[] out = new String[names.length]; 3117 // reader 3118 synchronized (mPackages) { 3119 for (int i=names.length-1; i>=0; i--) { 3120 PackageSetting ps = mSettings.mPackages.get(names[i]); 3121 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3122 } 3123 } 3124 return out; 3125 } 3126 3127 @Override 3128 public String[] canonicalToCurrentPackageNames(String[] names) { 3129 String[] out = new String[names.length]; 3130 // reader 3131 synchronized (mPackages) { 3132 for (int i=names.length-1; i>=0; i--) { 3133 String cur = mSettings.mRenamedPackages.get(names[i]); 3134 out[i] = cur != null ? cur : names[i]; 3135 } 3136 } 3137 return out; 3138 } 3139 3140 @Override 3141 public int getPackageUid(String packageName, int flags, int userId) { 3142 if (!sUserManager.exists(userId)) return -1; 3143 flags = updateFlagsForPackage(flags, userId, packageName); 3144 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3145 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3146 3147 // reader 3148 synchronized (mPackages) { 3149 final PackageParser.Package p = mPackages.get(packageName); 3150 if (p != null && p.isMatch(flags)) { 3151 return UserHandle.getUid(userId, p.applicationInfo.uid); 3152 } 3153 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3154 final PackageSetting ps = mSettings.mPackages.get(packageName); 3155 if (ps != null && ps.isMatch(flags)) { 3156 return UserHandle.getUid(userId, ps.appId); 3157 } 3158 } 3159 } 3160 3161 return -1; 3162 } 3163 3164 @Override 3165 public int[] getPackageGids(String packageName, int flags, int userId) { 3166 if (!sUserManager.exists(userId)) return null; 3167 flags = updateFlagsForPackage(flags, userId, packageName); 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3169 false /* requireFullPermission */, false /* checkShell */, 3170 "getPackageGids"); 3171 3172 // reader 3173 synchronized (mPackages) { 3174 final PackageParser.Package p = mPackages.get(packageName); 3175 if (p != null && p.isMatch(flags)) { 3176 PackageSetting ps = (PackageSetting) p.mExtras; 3177 return ps.getPermissionsState().computeGids(userId); 3178 } 3179 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3180 final PackageSetting ps = mSettings.mPackages.get(packageName); 3181 if (ps != null && ps.isMatch(flags)) { 3182 return ps.getPermissionsState().computeGids(userId); 3183 } 3184 } 3185 } 3186 3187 return null; 3188 } 3189 3190 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3191 if (bp.perm != null) { 3192 return PackageParser.generatePermissionInfo(bp.perm, flags); 3193 } 3194 PermissionInfo pi = new PermissionInfo(); 3195 pi.name = bp.name; 3196 pi.packageName = bp.sourcePackage; 3197 pi.nonLocalizedLabel = bp.name; 3198 pi.protectionLevel = bp.protectionLevel; 3199 return pi; 3200 } 3201 3202 @Override 3203 public PermissionInfo getPermissionInfo(String name, int flags) { 3204 // reader 3205 synchronized (mPackages) { 3206 final BasePermission p = mSettings.mPermissions.get(name); 3207 if (p != null) { 3208 return generatePermissionInfo(p, flags); 3209 } 3210 return null; 3211 } 3212 } 3213 3214 @Override 3215 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3216 int flags) { 3217 // reader 3218 synchronized (mPackages) { 3219 if (group != null && !mPermissionGroups.containsKey(group)) { 3220 // This is thrown as NameNotFoundException 3221 return null; 3222 } 3223 3224 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3225 for (BasePermission p : mSettings.mPermissions.values()) { 3226 if (group == null) { 3227 if (p.perm == null || p.perm.info.group == null) { 3228 out.add(generatePermissionInfo(p, flags)); 3229 } 3230 } else { 3231 if (p.perm != null && group.equals(p.perm.info.group)) { 3232 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3233 } 3234 } 3235 } 3236 return new ParceledListSlice<>(out); 3237 } 3238 } 3239 3240 @Override 3241 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3242 // reader 3243 synchronized (mPackages) { 3244 return PackageParser.generatePermissionGroupInfo( 3245 mPermissionGroups.get(name), flags); 3246 } 3247 } 3248 3249 @Override 3250 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3251 // reader 3252 synchronized (mPackages) { 3253 final int N = mPermissionGroups.size(); 3254 ArrayList<PermissionGroupInfo> out 3255 = new ArrayList<PermissionGroupInfo>(N); 3256 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3257 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3258 } 3259 return new ParceledListSlice<>(out); 3260 } 3261 } 3262 3263 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3264 int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 PackageSetting ps = mSettings.mPackages.get(packageName); 3267 if (ps != null) { 3268 if (ps.pkg == null) { 3269 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3270 if (pInfo != null) { 3271 return pInfo.applicationInfo; 3272 } 3273 return null; 3274 } 3275 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3276 ps.readUserState(userId), userId); 3277 } 3278 return null; 3279 } 3280 3281 @Override 3282 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3283 if (!sUserManager.exists(userId)) return null; 3284 flags = updateFlagsForApplication(flags, userId, packageName); 3285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3286 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3287 // writer 3288 synchronized (mPackages) { 3289 PackageParser.Package p = mPackages.get(packageName); 3290 if (DEBUG_PACKAGE_INFO) Log.v( 3291 TAG, "getApplicationInfo " + packageName 3292 + ": " + p); 3293 if (p != null) { 3294 PackageSetting ps = mSettings.mPackages.get(packageName); 3295 if (ps == null) return null; 3296 // Note: isEnabledLP() does not apply here - always return info 3297 return PackageParser.generateApplicationInfo( 3298 p, flags, ps.readUserState(userId), userId); 3299 } 3300 if ("android".equals(packageName)||"system".equals(packageName)) { 3301 return mAndroidApplication; 3302 } 3303 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3304 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3305 } 3306 } 3307 return null; 3308 } 3309 3310 @Override 3311 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3312 final IPackageDataObserver observer) { 3313 mContext.enforceCallingOrSelfPermission( 3314 android.Manifest.permission.CLEAR_APP_CACHE, null); 3315 // Queue up an async operation since clearing cache may take a little while. 3316 mHandler.post(new Runnable() { 3317 public void run() { 3318 mHandler.removeCallbacks(this); 3319 boolean success = true; 3320 synchronized (mInstallLock) { 3321 try { 3322 mInstaller.freeCache(volumeUuid, freeStorageSize); 3323 } catch (InstallerException e) { 3324 Slog.w(TAG, "Couldn't clear application caches: " + e); 3325 success = false; 3326 } 3327 } 3328 if (observer != null) { 3329 try { 3330 observer.onRemoveCompleted(null, success); 3331 } catch (RemoteException e) { 3332 Slog.w(TAG, "RemoveException when invoking call back"); 3333 } 3334 } 3335 } 3336 }); 3337 } 3338 3339 @Override 3340 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3341 final IntentSender pi) { 3342 mContext.enforceCallingOrSelfPermission( 3343 android.Manifest.permission.CLEAR_APP_CACHE, null); 3344 // Queue up an async operation since clearing cache may take a little while. 3345 mHandler.post(new Runnable() { 3346 public void run() { 3347 mHandler.removeCallbacks(this); 3348 boolean success = true; 3349 synchronized (mInstallLock) { 3350 try { 3351 mInstaller.freeCache(volumeUuid, freeStorageSize); 3352 } catch (InstallerException e) { 3353 Slog.w(TAG, "Couldn't clear application caches: " + e); 3354 success = false; 3355 } 3356 } 3357 if(pi != null) { 3358 try { 3359 // Callback via pending intent 3360 int code = success ? 1 : 0; 3361 pi.sendIntent(null, code, null, 3362 null, null); 3363 } catch (SendIntentException e1) { 3364 Slog.i(TAG, "Failed to send pending intent"); 3365 } 3366 } 3367 } 3368 }); 3369 } 3370 3371 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3372 synchronized (mInstallLock) { 3373 try { 3374 mInstaller.freeCache(volumeUuid, freeStorageSize); 3375 } catch (InstallerException e) { 3376 throw new IOException("Failed to free enough space", e); 3377 } 3378 } 3379 } 3380 3381 /** 3382 * Update given flags based on encryption status of current user. 3383 */ 3384 private int updateFlags(int flags, int userId) { 3385 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3386 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3387 // Caller expressed an explicit opinion about what encryption 3388 // aware/unaware components they want to see, so fall through and 3389 // give them what they want 3390 } else { 3391 // Caller expressed no opinion, so match based on user state 3392 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3393 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3394 } else { 3395 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3396 } 3397 } 3398 return flags; 3399 } 3400 3401 private UserManagerInternal getUserManagerInternal() { 3402 if (mUserManagerInternal == null) { 3403 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3404 } 3405 return mUserManagerInternal; 3406 } 3407 3408 /** 3409 * Update given flags when being used to request {@link PackageInfo}. 3410 */ 3411 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3412 boolean triaged = true; 3413 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3414 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3415 // Caller is asking for component details, so they'd better be 3416 // asking for specific encryption matching behavior, or be triaged 3417 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3418 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3419 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3420 triaged = false; 3421 } 3422 } 3423 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3424 | PackageManager.MATCH_SYSTEM_ONLY 3425 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3426 triaged = false; 3427 } 3428 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3429 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3430 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3431 } 3432 return updateFlags(flags, userId); 3433 } 3434 3435 /** 3436 * Update given flags when being used to request {@link ApplicationInfo}. 3437 */ 3438 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3439 return updateFlagsForPackage(flags, userId, cookie); 3440 } 3441 3442 /** 3443 * Update given flags when being used to request {@link ComponentInfo}. 3444 */ 3445 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3446 if (cookie instanceof Intent) { 3447 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3448 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3449 } 3450 } 3451 3452 boolean triaged = true; 3453 // Caller is asking for component details, so they'd better be 3454 // asking for specific encryption matching behavior, or be triaged 3455 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3456 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3457 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3458 triaged = false; 3459 } 3460 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3461 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3462 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3463 } 3464 3465 return updateFlags(flags, userId); 3466 } 3467 3468 /** 3469 * Update given flags when being used to request {@link ResolveInfo}. 3470 */ 3471 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3472 // Safe mode means we shouldn't match any third-party components 3473 if (mSafeMode) { 3474 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3475 } 3476 3477 return updateFlagsForComponent(flags, userId, cookie); 3478 } 3479 3480 @Override 3481 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3482 if (!sUserManager.exists(userId)) return null; 3483 flags = updateFlagsForComponent(flags, userId, component); 3484 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3485 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3486 synchronized (mPackages) { 3487 PackageParser.Activity a = mActivities.mActivities.get(component); 3488 3489 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3490 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3491 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3492 if (ps == null) return null; 3493 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3494 userId); 3495 } 3496 if (mResolveComponentName.equals(component)) { 3497 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3498 new PackageUserState(), userId); 3499 } 3500 } 3501 return null; 3502 } 3503 3504 @Override 3505 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3506 String resolvedType) { 3507 synchronized (mPackages) { 3508 if (component.equals(mResolveComponentName)) { 3509 // The resolver supports EVERYTHING! 3510 return true; 3511 } 3512 PackageParser.Activity a = mActivities.mActivities.get(component); 3513 if (a == null) { 3514 return false; 3515 } 3516 for (int i=0; i<a.intents.size(); i++) { 3517 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3518 intent.getData(), intent.getCategories(), TAG) >= 0) { 3519 return true; 3520 } 3521 } 3522 return false; 3523 } 3524 } 3525 3526 @Override 3527 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3528 if (!sUserManager.exists(userId)) return null; 3529 flags = updateFlagsForComponent(flags, userId, component); 3530 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3531 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3532 synchronized (mPackages) { 3533 PackageParser.Activity a = mReceivers.mActivities.get(component); 3534 if (DEBUG_PACKAGE_INFO) Log.v( 3535 TAG, "getReceiverInfo " + component + ": " + a); 3536 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3537 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3538 if (ps == null) return null; 3539 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3540 userId); 3541 } 3542 } 3543 return null; 3544 } 3545 3546 @Override 3547 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3548 if (!sUserManager.exists(userId)) return null; 3549 flags = updateFlagsForComponent(flags, userId, component); 3550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3551 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3552 synchronized (mPackages) { 3553 PackageParser.Service s = mServices.mServices.get(component); 3554 if (DEBUG_PACKAGE_INFO) Log.v( 3555 TAG, "getServiceInfo " + component + ": " + s); 3556 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3557 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3558 if (ps == null) return null; 3559 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3560 userId); 3561 } 3562 } 3563 return null; 3564 } 3565 3566 @Override 3567 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3568 if (!sUserManager.exists(userId)) return null; 3569 flags = updateFlagsForComponent(flags, userId, component); 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3571 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3572 synchronized (mPackages) { 3573 PackageParser.Provider p = mProviders.mProviders.get(component); 3574 if (DEBUG_PACKAGE_INFO) Log.v( 3575 TAG, "getProviderInfo " + component + ": " + p); 3576 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3577 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3578 if (ps == null) return null; 3579 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3580 userId); 3581 } 3582 } 3583 return null; 3584 } 3585 3586 @Override 3587 public String[] getSystemSharedLibraryNames() { 3588 Set<String> libSet; 3589 synchronized (mPackages) { 3590 libSet = mSharedLibraries.keySet(); 3591 int size = libSet.size(); 3592 if (size > 0) { 3593 String[] libs = new String[size]; 3594 libSet.toArray(libs); 3595 return libs; 3596 } 3597 } 3598 return null; 3599 } 3600 3601 @Override 3602 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3603 synchronized (mPackages) { 3604 return mServicesSystemSharedLibraryPackageName; 3605 } 3606 } 3607 3608 @Override 3609 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3610 synchronized (mPackages) { 3611 return mSharedSystemSharedLibraryPackageName; 3612 } 3613 } 3614 3615 @Override 3616 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3617 synchronized (mPackages) { 3618 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3619 3620 final FeatureInfo fi = new FeatureInfo(); 3621 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3622 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3623 res.add(fi); 3624 3625 return new ParceledListSlice<>(res); 3626 } 3627 } 3628 3629 @Override 3630 public boolean hasSystemFeature(String name, int version) { 3631 synchronized (mPackages) { 3632 final FeatureInfo feat = mAvailableFeatures.get(name); 3633 if (feat == null) { 3634 return false; 3635 } else { 3636 return feat.version >= version; 3637 } 3638 } 3639 } 3640 3641 @Override 3642 public int checkPermission(String permName, String pkgName, int userId) { 3643 if (!sUserManager.exists(userId)) { 3644 return PackageManager.PERMISSION_DENIED; 3645 } 3646 3647 synchronized (mPackages) { 3648 final PackageParser.Package p = mPackages.get(pkgName); 3649 if (p != null && p.mExtras != null) { 3650 final PackageSetting ps = (PackageSetting) p.mExtras; 3651 final PermissionsState permissionsState = ps.getPermissionsState(); 3652 if (permissionsState.hasPermission(permName, userId)) { 3653 return PackageManager.PERMISSION_GRANTED; 3654 } 3655 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3656 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3657 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3658 return PackageManager.PERMISSION_GRANTED; 3659 } 3660 } 3661 } 3662 3663 return PackageManager.PERMISSION_DENIED; 3664 } 3665 3666 @Override 3667 public int checkUidPermission(String permName, int uid) { 3668 final int userId = UserHandle.getUserId(uid); 3669 3670 if (!sUserManager.exists(userId)) { 3671 return PackageManager.PERMISSION_DENIED; 3672 } 3673 3674 synchronized (mPackages) { 3675 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3676 if (obj != null) { 3677 final SettingBase ps = (SettingBase) obj; 3678 final PermissionsState permissionsState = ps.getPermissionsState(); 3679 if (permissionsState.hasPermission(permName, userId)) { 3680 return PackageManager.PERMISSION_GRANTED; 3681 } 3682 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3683 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3684 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3685 return PackageManager.PERMISSION_GRANTED; 3686 } 3687 } else { 3688 ArraySet<String> perms = mSystemPermissions.get(uid); 3689 if (perms != null) { 3690 if (perms.contains(permName)) { 3691 return PackageManager.PERMISSION_GRANTED; 3692 } 3693 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3694 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3695 return PackageManager.PERMISSION_GRANTED; 3696 } 3697 } 3698 } 3699 } 3700 3701 return PackageManager.PERMISSION_DENIED; 3702 } 3703 3704 @Override 3705 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3706 if (UserHandle.getCallingUserId() != userId) { 3707 mContext.enforceCallingPermission( 3708 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3709 "isPermissionRevokedByPolicy for user " + userId); 3710 } 3711 3712 if (checkPermission(permission, packageName, userId) 3713 == PackageManager.PERMISSION_GRANTED) { 3714 return false; 3715 } 3716 3717 final long identity = Binder.clearCallingIdentity(); 3718 try { 3719 final int flags = getPermissionFlags(permission, packageName, userId); 3720 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3721 } finally { 3722 Binder.restoreCallingIdentity(identity); 3723 } 3724 } 3725 3726 @Override 3727 public String getPermissionControllerPackageName() { 3728 synchronized (mPackages) { 3729 return mRequiredInstallerPackage; 3730 } 3731 } 3732 3733 /** 3734 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3735 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3736 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3737 * @param message the message to log on security exception 3738 */ 3739 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3740 boolean checkShell, String message) { 3741 if (userId < 0) { 3742 throw new IllegalArgumentException("Invalid userId " + userId); 3743 } 3744 if (checkShell) { 3745 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3746 } 3747 if (userId == UserHandle.getUserId(callingUid)) return; 3748 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3749 if (requireFullPermission) { 3750 mContext.enforceCallingOrSelfPermission( 3751 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3752 } else { 3753 try { 3754 mContext.enforceCallingOrSelfPermission( 3755 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3756 } catch (SecurityException se) { 3757 mContext.enforceCallingOrSelfPermission( 3758 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3759 } 3760 } 3761 } 3762 } 3763 3764 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3765 if (callingUid == Process.SHELL_UID) { 3766 if (userHandle >= 0 3767 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3768 throw new SecurityException("Shell does not have permission to access user " 3769 + userHandle); 3770 } else if (userHandle < 0) { 3771 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3772 + Debug.getCallers(3)); 3773 } 3774 } 3775 } 3776 3777 private BasePermission findPermissionTreeLP(String permName) { 3778 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3779 if (permName.startsWith(bp.name) && 3780 permName.length() > bp.name.length() && 3781 permName.charAt(bp.name.length()) == '.') { 3782 return bp; 3783 } 3784 } 3785 return null; 3786 } 3787 3788 private BasePermission checkPermissionTreeLP(String permName) { 3789 if (permName != null) { 3790 BasePermission bp = findPermissionTreeLP(permName); 3791 if (bp != null) { 3792 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3793 return bp; 3794 } 3795 throw new SecurityException("Calling uid " 3796 + Binder.getCallingUid() 3797 + " is not allowed to add to permission tree " 3798 + bp.name + " owned by uid " + bp.uid); 3799 } 3800 } 3801 throw new SecurityException("No permission tree found for " + permName); 3802 } 3803 3804 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3805 if (s1 == null) { 3806 return s2 == null; 3807 } 3808 if (s2 == null) { 3809 return false; 3810 } 3811 if (s1.getClass() != s2.getClass()) { 3812 return false; 3813 } 3814 return s1.equals(s2); 3815 } 3816 3817 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3818 if (pi1.icon != pi2.icon) return false; 3819 if (pi1.logo != pi2.logo) return false; 3820 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3821 if (!compareStrings(pi1.name, pi2.name)) return false; 3822 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3823 // We'll take care of setting this one. 3824 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3825 // These are not currently stored in settings. 3826 //if (!compareStrings(pi1.group, pi2.group)) return false; 3827 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3828 //if (pi1.labelRes != pi2.labelRes) return false; 3829 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3830 return true; 3831 } 3832 3833 int permissionInfoFootprint(PermissionInfo info) { 3834 int size = info.name.length(); 3835 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3836 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3837 return size; 3838 } 3839 3840 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3841 int size = 0; 3842 for (BasePermission perm : mSettings.mPermissions.values()) { 3843 if (perm.uid == tree.uid) { 3844 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3845 } 3846 } 3847 return size; 3848 } 3849 3850 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3851 // We calculate the max size of permissions defined by this uid and throw 3852 // if that plus the size of 'info' would exceed our stated maximum. 3853 if (tree.uid != Process.SYSTEM_UID) { 3854 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3855 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3856 throw new SecurityException("Permission tree size cap exceeded"); 3857 } 3858 } 3859 } 3860 3861 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3862 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3863 throw new SecurityException("Label must be specified in permission"); 3864 } 3865 BasePermission tree = checkPermissionTreeLP(info.name); 3866 BasePermission bp = mSettings.mPermissions.get(info.name); 3867 boolean added = bp == null; 3868 boolean changed = true; 3869 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3870 if (added) { 3871 enforcePermissionCapLocked(info, tree); 3872 bp = new BasePermission(info.name, tree.sourcePackage, 3873 BasePermission.TYPE_DYNAMIC); 3874 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3875 throw new SecurityException( 3876 "Not allowed to modify non-dynamic permission " 3877 + info.name); 3878 } else { 3879 if (bp.protectionLevel == fixedLevel 3880 && bp.perm.owner.equals(tree.perm.owner) 3881 && bp.uid == tree.uid 3882 && comparePermissionInfos(bp.perm.info, info)) { 3883 changed = false; 3884 } 3885 } 3886 bp.protectionLevel = fixedLevel; 3887 info = new PermissionInfo(info); 3888 info.protectionLevel = fixedLevel; 3889 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3890 bp.perm.info.packageName = tree.perm.info.packageName; 3891 bp.uid = tree.uid; 3892 if (added) { 3893 mSettings.mPermissions.put(info.name, bp); 3894 } 3895 if (changed) { 3896 if (!async) { 3897 mSettings.writeLPr(); 3898 } else { 3899 scheduleWriteSettingsLocked(); 3900 } 3901 } 3902 return added; 3903 } 3904 3905 @Override 3906 public boolean addPermission(PermissionInfo info) { 3907 synchronized (mPackages) { 3908 return addPermissionLocked(info, false); 3909 } 3910 } 3911 3912 @Override 3913 public boolean addPermissionAsync(PermissionInfo info) { 3914 synchronized (mPackages) { 3915 return addPermissionLocked(info, true); 3916 } 3917 } 3918 3919 @Override 3920 public void removePermission(String name) { 3921 synchronized (mPackages) { 3922 checkPermissionTreeLP(name); 3923 BasePermission bp = mSettings.mPermissions.get(name); 3924 if (bp != null) { 3925 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3926 throw new SecurityException( 3927 "Not allowed to modify non-dynamic permission " 3928 + name); 3929 } 3930 mSettings.mPermissions.remove(name); 3931 mSettings.writeLPr(); 3932 } 3933 } 3934 } 3935 3936 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3937 BasePermission bp) { 3938 int index = pkg.requestedPermissions.indexOf(bp.name); 3939 if (index == -1) { 3940 throw new SecurityException("Package " + pkg.packageName 3941 + " has not requested permission " + bp.name); 3942 } 3943 if (!bp.isRuntime() && !bp.isDevelopment()) { 3944 throw new SecurityException("Permission " + bp.name 3945 + " is not a changeable permission type"); 3946 } 3947 } 3948 3949 @Override 3950 public void grantRuntimePermission(String packageName, String name, final int userId) { 3951 if (!sUserManager.exists(userId)) { 3952 Log.e(TAG, "No such user:" + userId); 3953 return; 3954 } 3955 3956 mContext.enforceCallingOrSelfPermission( 3957 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3958 "grantRuntimePermission"); 3959 3960 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3961 true /* requireFullPermission */, true /* checkShell */, 3962 "grantRuntimePermission"); 3963 3964 final int uid; 3965 final SettingBase sb; 3966 3967 synchronized (mPackages) { 3968 final PackageParser.Package pkg = mPackages.get(packageName); 3969 if (pkg == null) { 3970 throw new IllegalArgumentException("Unknown package: " + packageName); 3971 } 3972 3973 final BasePermission bp = mSettings.mPermissions.get(name); 3974 if (bp == null) { 3975 throw new IllegalArgumentException("Unknown permission: " + name); 3976 } 3977 3978 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3979 3980 // If a permission review is required for legacy apps we represent 3981 // their permissions as always granted runtime ones since we need 3982 // to keep the review required permission flag per user while an 3983 // install permission's state is shared across all users. 3984 if (Build.PERMISSIONS_REVIEW_REQUIRED 3985 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3986 && bp.isRuntime()) { 3987 return; 3988 } 3989 3990 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3991 sb = (SettingBase) pkg.mExtras; 3992 if (sb == null) { 3993 throw new IllegalArgumentException("Unknown package: " + packageName); 3994 } 3995 3996 final PermissionsState permissionsState = sb.getPermissionsState(); 3997 3998 final int flags = permissionsState.getPermissionFlags(name, userId); 3999 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4000 throw new SecurityException("Cannot grant system fixed permission " 4001 + name + " for package " + packageName); 4002 } 4003 4004 if (bp.isDevelopment()) { 4005 // Development permissions must be handled specially, since they are not 4006 // normal runtime permissions. For now they apply to all users. 4007 if (permissionsState.grantInstallPermission(bp) != 4008 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4009 scheduleWriteSettingsLocked(); 4010 } 4011 return; 4012 } 4013 4014 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4015 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4016 return; 4017 } 4018 4019 final int result = permissionsState.grantRuntimePermission(bp, userId); 4020 switch (result) { 4021 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4022 return; 4023 } 4024 4025 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4026 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4027 mHandler.post(new Runnable() { 4028 @Override 4029 public void run() { 4030 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4031 } 4032 }); 4033 } 4034 break; 4035 } 4036 4037 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4038 4039 // Not critical if that is lost - app has to request again. 4040 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4041 } 4042 4043 // Only need to do this if user is initialized. Otherwise it's a new user 4044 // and there are no processes running as the user yet and there's no need 4045 // to make an expensive call to remount processes for the changed permissions. 4046 if (READ_EXTERNAL_STORAGE.equals(name) 4047 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4048 final long token = Binder.clearCallingIdentity(); 4049 try { 4050 if (sUserManager.isInitialized(userId)) { 4051 MountServiceInternal mountServiceInternal = LocalServices.getService( 4052 MountServiceInternal.class); 4053 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4054 } 4055 } finally { 4056 Binder.restoreCallingIdentity(token); 4057 } 4058 } 4059 } 4060 4061 @Override 4062 public void revokeRuntimePermission(String packageName, String name, int userId) { 4063 if (!sUserManager.exists(userId)) { 4064 Log.e(TAG, "No such user:" + userId); 4065 return; 4066 } 4067 4068 mContext.enforceCallingOrSelfPermission( 4069 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4070 "revokeRuntimePermission"); 4071 4072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4073 true /* requireFullPermission */, true /* checkShell */, 4074 "revokeRuntimePermission"); 4075 4076 final int appId; 4077 4078 synchronized (mPackages) { 4079 final PackageParser.Package pkg = mPackages.get(packageName); 4080 if (pkg == null) { 4081 throw new IllegalArgumentException("Unknown package: " + packageName); 4082 } 4083 4084 final BasePermission bp = mSettings.mPermissions.get(name); 4085 if (bp == null) { 4086 throw new IllegalArgumentException("Unknown permission: " + name); 4087 } 4088 4089 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4090 4091 // If a permission review is required for legacy apps we represent 4092 // their permissions as always granted runtime ones since we need 4093 // to keep the review required permission flag per user while an 4094 // install permission's state is shared across all users. 4095 if (Build.PERMISSIONS_REVIEW_REQUIRED 4096 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4097 && bp.isRuntime()) { 4098 return; 4099 } 4100 4101 SettingBase sb = (SettingBase) pkg.mExtras; 4102 if (sb == null) { 4103 throw new IllegalArgumentException("Unknown package: " + packageName); 4104 } 4105 4106 final PermissionsState permissionsState = sb.getPermissionsState(); 4107 4108 final int flags = permissionsState.getPermissionFlags(name, userId); 4109 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4110 throw new SecurityException("Cannot revoke system fixed permission " 4111 + name + " for package " + packageName); 4112 } 4113 4114 if (bp.isDevelopment()) { 4115 // Development permissions must be handled specially, since they are not 4116 // normal runtime permissions. For now they apply to all users. 4117 if (permissionsState.revokeInstallPermission(bp) != 4118 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4119 scheduleWriteSettingsLocked(); 4120 } 4121 return; 4122 } 4123 4124 if (permissionsState.revokeRuntimePermission(bp, userId) == 4125 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4126 return; 4127 } 4128 4129 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4130 4131 // Critical, after this call app should never have the permission. 4132 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4133 4134 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4135 } 4136 4137 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4138 } 4139 4140 @Override 4141 public void resetRuntimePermissions() { 4142 mContext.enforceCallingOrSelfPermission( 4143 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4144 "revokeRuntimePermission"); 4145 4146 int callingUid = Binder.getCallingUid(); 4147 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4148 mContext.enforceCallingOrSelfPermission( 4149 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4150 "resetRuntimePermissions"); 4151 } 4152 4153 synchronized (mPackages) { 4154 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4155 for (int userId : UserManagerService.getInstance().getUserIds()) { 4156 final int packageCount = mPackages.size(); 4157 for (int i = 0; i < packageCount; i++) { 4158 PackageParser.Package pkg = mPackages.valueAt(i); 4159 if (!(pkg.mExtras instanceof PackageSetting)) { 4160 continue; 4161 } 4162 PackageSetting ps = (PackageSetting) pkg.mExtras; 4163 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4164 } 4165 } 4166 } 4167 } 4168 4169 @Override 4170 public int getPermissionFlags(String name, String packageName, int userId) { 4171 if (!sUserManager.exists(userId)) { 4172 return 0; 4173 } 4174 4175 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4176 4177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4178 true /* requireFullPermission */, false /* checkShell */, 4179 "getPermissionFlags"); 4180 4181 synchronized (mPackages) { 4182 final PackageParser.Package pkg = mPackages.get(packageName); 4183 if (pkg == null) { 4184 return 0; 4185 } 4186 4187 final BasePermission bp = mSettings.mPermissions.get(name); 4188 if (bp == null) { 4189 return 0; 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 return 0; 4195 } 4196 4197 PermissionsState permissionsState = sb.getPermissionsState(); 4198 return permissionsState.getPermissionFlags(name, userId); 4199 } 4200 } 4201 4202 @Override 4203 public void updatePermissionFlags(String name, String packageName, int flagMask, 4204 int flagValues, int userId) { 4205 if (!sUserManager.exists(userId)) { 4206 return; 4207 } 4208 4209 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4210 4211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4212 true /* requireFullPermission */, true /* checkShell */, 4213 "updatePermissionFlags"); 4214 4215 // Only the system can change these flags and nothing else. 4216 if (getCallingUid() != Process.SYSTEM_UID) { 4217 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4218 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4219 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4220 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4221 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4222 } 4223 4224 synchronized (mPackages) { 4225 final PackageParser.Package pkg = mPackages.get(packageName); 4226 if (pkg == null) { 4227 throw new IllegalArgumentException("Unknown package: " + packageName); 4228 } 4229 4230 final BasePermission bp = mSettings.mPermissions.get(name); 4231 if (bp == null) { 4232 throw new IllegalArgumentException("Unknown permission: " + name); 4233 } 4234 4235 SettingBase sb = (SettingBase) pkg.mExtras; 4236 if (sb == null) { 4237 throw new IllegalArgumentException("Unknown package: " + packageName); 4238 } 4239 4240 PermissionsState permissionsState = sb.getPermissionsState(); 4241 4242 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4243 4244 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4245 // Install and runtime permissions are stored in different places, 4246 // so figure out what permission changed and persist the change. 4247 if (permissionsState.getInstallPermissionState(name) != null) { 4248 scheduleWriteSettingsLocked(); 4249 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4250 || hadState) { 4251 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4252 } 4253 } 4254 } 4255 } 4256 4257 /** 4258 * Update the permission flags for all packages and runtime permissions of a user in order 4259 * to allow device or profile owner to remove POLICY_FIXED. 4260 */ 4261 @Override 4262 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4263 if (!sUserManager.exists(userId)) { 4264 return; 4265 } 4266 4267 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4268 4269 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4270 true /* requireFullPermission */, true /* checkShell */, 4271 "updatePermissionFlagsForAllApps"); 4272 4273 // Only the system can change system fixed flags. 4274 if (getCallingUid() != Process.SYSTEM_UID) { 4275 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4276 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4277 } 4278 4279 synchronized (mPackages) { 4280 boolean changed = false; 4281 final int packageCount = mPackages.size(); 4282 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4283 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4284 SettingBase sb = (SettingBase) pkg.mExtras; 4285 if (sb == null) { 4286 continue; 4287 } 4288 PermissionsState permissionsState = sb.getPermissionsState(); 4289 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4290 userId, flagMask, flagValues); 4291 } 4292 if (changed) { 4293 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4294 } 4295 } 4296 } 4297 4298 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4299 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4300 != PackageManager.PERMISSION_GRANTED 4301 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4302 != PackageManager.PERMISSION_GRANTED) { 4303 throw new SecurityException(message + " requires " 4304 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4305 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4306 } 4307 } 4308 4309 @Override 4310 public boolean shouldShowRequestPermissionRationale(String permissionName, 4311 String packageName, int userId) { 4312 if (UserHandle.getCallingUserId() != userId) { 4313 mContext.enforceCallingPermission( 4314 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4315 "canShowRequestPermissionRationale for user " + userId); 4316 } 4317 4318 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4319 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4320 return false; 4321 } 4322 4323 if (checkPermission(permissionName, packageName, userId) 4324 == PackageManager.PERMISSION_GRANTED) { 4325 return false; 4326 } 4327 4328 final int flags; 4329 4330 final long identity = Binder.clearCallingIdentity(); 4331 try { 4332 flags = getPermissionFlags(permissionName, 4333 packageName, userId); 4334 } finally { 4335 Binder.restoreCallingIdentity(identity); 4336 } 4337 4338 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4339 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4340 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4341 4342 if ((flags & fixedFlags) != 0) { 4343 return false; 4344 } 4345 4346 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4347 } 4348 4349 @Override 4350 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4351 mContext.enforceCallingOrSelfPermission( 4352 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4353 "addOnPermissionsChangeListener"); 4354 4355 synchronized (mPackages) { 4356 mOnPermissionChangeListeners.addListenerLocked(listener); 4357 } 4358 } 4359 4360 @Override 4361 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4362 synchronized (mPackages) { 4363 mOnPermissionChangeListeners.removeListenerLocked(listener); 4364 } 4365 } 4366 4367 @Override 4368 public boolean isProtectedBroadcast(String actionName) { 4369 synchronized (mPackages) { 4370 if (mProtectedBroadcasts.contains(actionName)) { 4371 return true; 4372 } else if (actionName != null) { 4373 // TODO: remove these terrible hacks 4374 if (actionName.startsWith("android.net.netmon.lingerExpired") 4375 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4376 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4377 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4378 return true; 4379 } 4380 } 4381 } 4382 return false; 4383 } 4384 4385 @Override 4386 public int checkSignatures(String pkg1, String pkg2) { 4387 synchronized (mPackages) { 4388 final PackageParser.Package p1 = mPackages.get(pkg1); 4389 final PackageParser.Package p2 = mPackages.get(pkg2); 4390 if (p1 == null || p1.mExtras == null 4391 || p2 == null || p2.mExtras == null) { 4392 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4393 } 4394 return compareSignatures(p1.mSignatures, p2.mSignatures); 4395 } 4396 } 4397 4398 @Override 4399 public int checkUidSignatures(int uid1, int uid2) { 4400 // Map to base uids. 4401 uid1 = UserHandle.getAppId(uid1); 4402 uid2 = UserHandle.getAppId(uid2); 4403 // reader 4404 synchronized (mPackages) { 4405 Signature[] s1; 4406 Signature[] s2; 4407 Object obj = mSettings.getUserIdLPr(uid1); 4408 if (obj != null) { 4409 if (obj instanceof SharedUserSetting) { 4410 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4411 } else if (obj instanceof PackageSetting) { 4412 s1 = ((PackageSetting)obj).signatures.mSignatures; 4413 } else { 4414 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4415 } 4416 } else { 4417 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4418 } 4419 obj = mSettings.getUserIdLPr(uid2); 4420 if (obj != null) { 4421 if (obj instanceof SharedUserSetting) { 4422 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4423 } else if (obj instanceof PackageSetting) { 4424 s2 = ((PackageSetting)obj).signatures.mSignatures; 4425 } else { 4426 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4427 } 4428 } else { 4429 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4430 } 4431 return compareSignatures(s1, s2); 4432 } 4433 } 4434 4435 /** 4436 * This method should typically only be used when granting or revoking 4437 * permissions, since the app may immediately restart after this call. 4438 * <p> 4439 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4440 * guard your work against the app being relaunched. 4441 */ 4442 private void killUid(int appId, int userId, String reason) { 4443 final long identity = Binder.clearCallingIdentity(); 4444 try { 4445 IActivityManager am = ActivityManagerNative.getDefault(); 4446 if (am != null) { 4447 try { 4448 am.killUid(appId, userId, reason); 4449 } catch (RemoteException e) { 4450 /* ignore - same process */ 4451 } 4452 } 4453 } finally { 4454 Binder.restoreCallingIdentity(identity); 4455 } 4456 } 4457 4458 /** 4459 * Compares two sets of signatures. Returns: 4460 * <br /> 4461 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4462 * <br /> 4463 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4464 * <br /> 4465 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4466 * <br /> 4467 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4468 * <br /> 4469 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4470 */ 4471 static int compareSignatures(Signature[] s1, Signature[] s2) { 4472 if (s1 == null) { 4473 return s2 == null 4474 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4475 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4476 } 4477 4478 if (s2 == null) { 4479 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4480 } 4481 4482 if (s1.length != s2.length) { 4483 return PackageManager.SIGNATURE_NO_MATCH; 4484 } 4485 4486 // Since both signature sets are of size 1, we can compare without HashSets. 4487 if (s1.length == 1) { 4488 return s1[0].equals(s2[0]) ? 4489 PackageManager.SIGNATURE_MATCH : 4490 PackageManager.SIGNATURE_NO_MATCH; 4491 } 4492 4493 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4494 for (Signature sig : s1) { 4495 set1.add(sig); 4496 } 4497 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4498 for (Signature sig : s2) { 4499 set2.add(sig); 4500 } 4501 // Make sure s2 contains all signatures in s1. 4502 if (set1.equals(set2)) { 4503 return PackageManager.SIGNATURE_MATCH; 4504 } 4505 return PackageManager.SIGNATURE_NO_MATCH; 4506 } 4507 4508 /** 4509 * If the database version for this type of package (internal storage or 4510 * external storage) is less than the version where package signatures 4511 * were updated, return true. 4512 */ 4513 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4514 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4515 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4516 } 4517 4518 /** 4519 * Used for backward compatibility to make sure any packages with 4520 * certificate chains get upgraded to the new style. {@code existingSigs} 4521 * will be in the old format (since they were stored on disk from before the 4522 * system upgrade) and {@code scannedSigs} will be in the newer format. 4523 */ 4524 private int compareSignaturesCompat(PackageSignatures existingSigs, 4525 PackageParser.Package scannedPkg) { 4526 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4527 return PackageManager.SIGNATURE_NO_MATCH; 4528 } 4529 4530 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4531 for (Signature sig : existingSigs.mSignatures) { 4532 existingSet.add(sig); 4533 } 4534 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4535 for (Signature sig : scannedPkg.mSignatures) { 4536 try { 4537 Signature[] chainSignatures = sig.getChainSignatures(); 4538 for (Signature chainSig : chainSignatures) { 4539 scannedCompatSet.add(chainSig); 4540 } 4541 } catch (CertificateEncodingException e) { 4542 scannedCompatSet.add(sig); 4543 } 4544 } 4545 /* 4546 * Make sure the expanded scanned set contains all signatures in the 4547 * existing one. 4548 */ 4549 if (scannedCompatSet.equals(existingSet)) { 4550 // Migrate the old signatures to the new scheme. 4551 existingSigs.assignSignatures(scannedPkg.mSignatures); 4552 // The new KeySets will be re-added later in the scanning process. 4553 synchronized (mPackages) { 4554 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4555 } 4556 return PackageManager.SIGNATURE_MATCH; 4557 } 4558 return PackageManager.SIGNATURE_NO_MATCH; 4559 } 4560 4561 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4562 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4563 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4564 } 4565 4566 private int compareSignaturesRecover(PackageSignatures existingSigs, 4567 PackageParser.Package scannedPkg) { 4568 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4569 return PackageManager.SIGNATURE_NO_MATCH; 4570 } 4571 4572 String msg = null; 4573 try { 4574 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4575 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4576 + scannedPkg.packageName); 4577 return PackageManager.SIGNATURE_MATCH; 4578 } 4579 } catch (CertificateException e) { 4580 msg = e.getMessage(); 4581 } 4582 4583 logCriticalInfo(Log.INFO, 4584 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4585 return PackageManager.SIGNATURE_NO_MATCH; 4586 } 4587 4588 @Override 4589 public List<String> getAllPackages() { 4590 synchronized (mPackages) { 4591 return new ArrayList<String>(mPackages.keySet()); 4592 } 4593 } 4594 4595 @Override 4596 public String[] getPackagesForUid(int uid) { 4597 uid = UserHandle.getAppId(uid); 4598 // reader 4599 synchronized (mPackages) { 4600 Object obj = mSettings.getUserIdLPr(uid); 4601 if (obj instanceof SharedUserSetting) { 4602 final SharedUserSetting sus = (SharedUserSetting) obj; 4603 final int N = sus.packages.size(); 4604 final String[] res = new String[N]; 4605 for (int i = 0; i < N; i++) { 4606 res[i] = sus.packages.valueAt(i).name; 4607 } 4608 return res; 4609 } else if (obj instanceof PackageSetting) { 4610 final PackageSetting ps = (PackageSetting) obj; 4611 return new String[] { ps.name }; 4612 } 4613 } 4614 return null; 4615 } 4616 4617 @Override 4618 public String getNameForUid(int uid) { 4619 // reader 4620 synchronized (mPackages) { 4621 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4622 if (obj instanceof SharedUserSetting) { 4623 final SharedUserSetting sus = (SharedUserSetting) obj; 4624 return sus.name + ":" + sus.userId; 4625 } else if (obj instanceof PackageSetting) { 4626 final PackageSetting ps = (PackageSetting) obj; 4627 return ps.name; 4628 } 4629 } 4630 return null; 4631 } 4632 4633 @Override 4634 public int getUidForSharedUser(String sharedUserName) { 4635 if(sharedUserName == null) { 4636 return -1; 4637 } 4638 // reader 4639 synchronized (mPackages) { 4640 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4641 if (suid == null) { 4642 return -1; 4643 } 4644 return suid.userId; 4645 } 4646 } 4647 4648 @Override 4649 public int getFlagsForUid(int uid) { 4650 synchronized (mPackages) { 4651 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4652 if (obj instanceof SharedUserSetting) { 4653 final SharedUserSetting sus = (SharedUserSetting) obj; 4654 return sus.pkgFlags; 4655 } else if (obj instanceof PackageSetting) { 4656 final PackageSetting ps = (PackageSetting) obj; 4657 return ps.pkgFlags; 4658 } 4659 } 4660 return 0; 4661 } 4662 4663 @Override 4664 public int getPrivateFlagsForUid(int uid) { 4665 synchronized (mPackages) { 4666 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4667 if (obj instanceof SharedUserSetting) { 4668 final SharedUserSetting sus = (SharedUserSetting) obj; 4669 return sus.pkgPrivateFlags; 4670 } else if (obj instanceof PackageSetting) { 4671 final PackageSetting ps = (PackageSetting) obj; 4672 return ps.pkgPrivateFlags; 4673 } 4674 } 4675 return 0; 4676 } 4677 4678 @Override 4679 public boolean isUidPrivileged(int uid) { 4680 uid = UserHandle.getAppId(uid); 4681 // reader 4682 synchronized (mPackages) { 4683 Object obj = mSettings.getUserIdLPr(uid); 4684 if (obj instanceof SharedUserSetting) { 4685 final SharedUserSetting sus = (SharedUserSetting) obj; 4686 final Iterator<PackageSetting> it = sus.packages.iterator(); 4687 while (it.hasNext()) { 4688 if (it.next().isPrivileged()) { 4689 return true; 4690 } 4691 } 4692 } else if (obj instanceof PackageSetting) { 4693 final PackageSetting ps = (PackageSetting) obj; 4694 return ps.isPrivileged(); 4695 } 4696 } 4697 return false; 4698 } 4699 4700 @Override 4701 public String[] getAppOpPermissionPackages(String permissionName) { 4702 synchronized (mPackages) { 4703 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4704 if (pkgs == null) { 4705 return null; 4706 } 4707 return pkgs.toArray(new String[pkgs.size()]); 4708 } 4709 } 4710 4711 @Override 4712 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4713 int flags, int userId) { 4714 try { 4715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4716 4717 if (!sUserManager.exists(userId)) return null; 4718 flags = updateFlagsForResolve(flags, userId, intent); 4719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4720 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4721 4722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4723 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4724 flags, userId); 4725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4726 4727 final ResolveInfo bestChoice = 4728 chooseBestActivity(intent, resolvedType, flags, query, userId); 4729 4730 if (isEphemeralAllowed(intent, query, userId)) { 4731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4732 final EphemeralResolveInfo ai = 4733 getEphemeralResolveInfo(intent, resolvedType, userId); 4734 if (ai != null) { 4735 if (DEBUG_EPHEMERAL) { 4736 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4737 } 4738 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4739 bestChoice.ephemeralResolveInfo = ai; 4740 } 4741 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4742 } 4743 return bestChoice; 4744 } finally { 4745 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4746 } 4747 } 4748 4749 @Override 4750 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4751 IntentFilter filter, int match, ComponentName activity) { 4752 final int userId = UserHandle.getCallingUserId(); 4753 if (DEBUG_PREFERRED) { 4754 Log.v(TAG, "setLastChosenActivity intent=" + intent 4755 + " resolvedType=" + resolvedType 4756 + " flags=" + flags 4757 + " filter=" + filter 4758 + " match=" + match 4759 + " activity=" + activity); 4760 filter.dump(new PrintStreamPrinter(System.out), " "); 4761 } 4762 intent.setComponent(null); 4763 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4764 userId); 4765 // Find any earlier preferred or last chosen entries and nuke them 4766 findPreferredActivity(intent, resolvedType, 4767 flags, query, 0, false, true, false, userId); 4768 // Add the new activity as the last chosen for this filter 4769 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4770 "Setting last chosen"); 4771 } 4772 4773 @Override 4774 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4775 final int userId = UserHandle.getCallingUserId(); 4776 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4777 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4778 userId); 4779 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4780 false, false, false, userId); 4781 } 4782 4783 4784 private boolean isEphemeralAllowed( 4785 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4786 // Short circuit and return early if possible. 4787 if (DISABLE_EPHEMERAL_APPS) { 4788 return false; 4789 } 4790 final int callingUser = UserHandle.getCallingUserId(); 4791 if (callingUser != UserHandle.USER_SYSTEM) { 4792 return false; 4793 } 4794 if (mEphemeralResolverConnection == null) { 4795 return false; 4796 } 4797 if (intent.getComponent() != null) { 4798 return false; 4799 } 4800 if (intent.getPackage() != null) { 4801 return false; 4802 } 4803 final boolean isWebUri = hasWebURI(intent); 4804 if (!isWebUri) { 4805 return false; 4806 } 4807 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4808 synchronized (mPackages) { 4809 final int count = resolvedActivites.size(); 4810 for (int n = 0; n < count; n++) { 4811 ResolveInfo info = resolvedActivites.get(n); 4812 String packageName = info.activityInfo.packageName; 4813 PackageSetting ps = mSettings.mPackages.get(packageName); 4814 if (ps != null) { 4815 // Try to get the status from User settings first 4816 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4817 int status = (int) (packedStatus >> 32); 4818 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4819 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4820 if (DEBUG_EPHEMERAL) { 4821 Slog.v(TAG, "DENY ephemeral apps;" 4822 + " pkg: " + packageName + ", status: " + status); 4823 } 4824 return false; 4825 } 4826 } 4827 } 4828 } 4829 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4830 return true; 4831 } 4832 4833 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4834 int userId) { 4835 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4836 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4837 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 4838 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4839 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4840 ephemeralPrefixCount); 4841 final int[] shaPrefix = digest.getDigestPrefix(); 4842 final byte[][] digestBytes = digest.getDigestBytes(); 4843 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4844 mEphemeralResolverConnection.getEphemeralResolveInfoList( 4845 shaPrefix, ephemeralPrefixMask); 4846 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4847 // No hash prefix match; there are no ephemeral apps for this domain. 4848 return null; 4849 } 4850 4851 // Go in reverse order so we match the narrowest scope first. 4852 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4853 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4854 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4855 continue; 4856 } 4857 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4858 // No filters; this should never happen. 4859 if (filters.isEmpty()) { 4860 continue; 4861 } 4862 // We have a domain match; resolve the filters to see if anything matches. 4863 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4864 for (int j = filters.size() - 1; j >= 0; --j) { 4865 final EphemeralResolveIntentInfo intentInfo = 4866 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4867 ephemeralResolver.addFilter(intentInfo); 4868 } 4869 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4870 intent, resolvedType, false /*defaultOnly*/, userId); 4871 if (!matchedResolveInfoList.isEmpty()) { 4872 return matchedResolveInfoList.get(0); 4873 } 4874 } 4875 } 4876 // Hash or filter mis-match; no ephemeral apps for this domain. 4877 return null; 4878 } 4879 4880 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4881 int flags, List<ResolveInfo> query, int userId) { 4882 if (query != null) { 4883 final int N = query.size(); 4884 if (N == 1) { 4885 return query.get(0); 4886 } else if (N > 1) { 4887 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4888 // If there is more than one activity with the same priority, 4889 // then let the user decide between them. 4890 ResolveInfo r0 = query.get(0); 4891 ResolveInfo r1 = query.get(1); 4892 if (DEBUG_INTENT_MATCHING || debug) { 4893 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4894 + r1.activityInfo.name + "=" + r1.priority); 4895 } 4896 // If the first activity has a higher priority, or a different 4897 // default, then it is always desirable to pick it. 4898 if (r0.priority != r1.priority 4899 || r0.preferredOrder != r1.preferredOrder 4900 || r0.isDefault != r1.isDefault) { 4901 return query.get(0); 4902 } 4903 // If we have saved a preference for a preferred activity for 4904 // this Intent, use that. 4905 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4906 flags, query, r0.priority, true, false, debug, userId); 4907 if (ri != null) { 4908 return ri; 4909 } 4910 ri = new ResolveInfo(mResolveInfo); 4911 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4912 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4913 // If all of the options come from the same package, show the application's 4914 // label and icon instead of the generic resolver's. 4915 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4916 // and then throw away the ResolveInfo itself, meaning that the caller loses 4917 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4918 // a fallback for this case; we only set the target package's resources on 4919 // the ResolveInfo, not the ActivityInfo. 4920 final String intentPackage = intent.getPackage(); 4921 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4922 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4923 ri.resolvePackageName = intentPackage; 4924 if (userNeedsBadging(userId)) { 4925 ri.noResourceId = true; 4926 } else { 4927 ri.icon = appi.icon; 4928 } 4929 ri.iconResourceId = appi.icon; 4930 ri.labelRes = appi.labelRes; 4931 } 4932 ri.activityInfo.applicationInfo = new ApplicationInfo( 4933 ri.activityInfo.applicationInfo); 4934 if (userId != 0) { 4935 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4936 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4937 } 4938 // Make sure that the resolver is displayable in car mode 4939 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4940 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4941 return ri; 4942 } 4943 } 4944 return null; 4945 } 4946 4947 /** 4948 * Return true if the given list is not empty and all of its contents have 4949 * an activityInfo with the given package name. 4950 */ 4951 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4952 if (ArrayUtils.isEmpty(list)) { 4953 return false; 4954 } 4955 for (int i = 0, N = list.size(); i < N; i++) { 4956 final ResolveInfo ri = list.get(i); 4957 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4958 if (ai == null || !packageName.equals(ai.packageName)) { 4959 return false; 4960 } 4961 } 4962 return true; 4963 } 4964 4965 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4966 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4967 final int N = query.size(); 4968 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4969 .get(userId); 4970 // Get the list of persistent preferred activities that handle the intent 4971 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4972 List<PersistentPreferredActivity> pprefs = ppir != null 4973 ? ppir.queryIntent(intent, resolvedType, 4974 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4975 : null; 4976 if (pprefs != null && pprefs.size() > 0) { 4977 final int M = pprefs.size(); 4978 for (int i=0; i<M; i++) { 4979 final PersistentPreferredActivity ppa = pprefs.get(i); 4980 if (DEBUG_PREFERRED || debug) { 4981 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4982 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4983 + "\n component=" + ppa.mComponent); 4984 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4985 } 4986 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4987 flags | MATCH_DISABLED_COMPONENTS, userId); 4988 if (DEBUG_PREFERRED || debug) { 4989 Slog.v(TAG, "Found persistent preferred activity:"); 4990 if (ai != null) { 4991 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4992 } else { 4993 Slog.v(TAG, " null"); 4994 } 4995 } 4996 if (ai == null) { 4997 // This previously registered persistent preferred activity 4998 // component is no longer known. Ignore it and do NOT remove it. 4999 continue; 5000 } 5001 for (int j=0; j<N; j++) { 5002 final ResolveInfo ri = query.get(j); 5003 if (!ri.activityInfo.applicationInfo.packageName 5004 .equals(ai.applicationInfo.packageName)) { 5005 continue; 5006 } 5007 if (!ri.activityInfo.name.equals(ai.name)) { 5008 continue; 5009 } 5010 // Found a persistent preference that can handle the intent. 5011 if (DEBUG_PREFERRED || debug) { 5012 Slog.v(TAG, "Returning persistent preferred activity: " + 5013 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5014 } 5015 return ri; 5016 } 5017 } 5018 } 5019 return null; 5020 } 5021 5022 // TODO: handle preferred activities missing while user has amnesia 5023 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5024 List<ResolveInfo> query, int priority, boolean always, 5025 boolean removeMatches, boolean debug, int userId) { 5026 if (!sUserManager.exists(userId)) return null; 5027 flags = updateFlagsForResolve(flags, userId, intent); 5028 // writer 5029 synchronized (mPackages) { 5030 if (intent.getSelector() != null) { 5031 intent = intent.getSelector(); 5032 } 5033 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5034 5035 // Try to find a matching persistent preferred activity. 5036 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5037 debug, userId); 5038 5039 // If a persistent preferred activity matched, use it. 5040 if (pri != null) { 5041 return pri; 5042 } 5043 5044 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5045 // Get the list of preferred activities that handle the intent 5046 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5047 List<PreferredActivity> prefs = pir != null 5048 ? pir.queryIntent(intent, resolvedType, 5049 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5050 : null; 5051 if (prefs != null && prefs.size() > 0) { 5052 boolean changed = false; 5053 try { 5054 // First figure out how good the original match set is. 5055 // We will only allow preferred activities that came 5056 // from the same match quality. 5057 int match = 0; 5058 5059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5060 5061 final int N = query.size(); 5062 for (int j=0; j<N; j++) { 5063 final ResolveInfo ri = query.get(j); 5064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5065 + ": 0x" + Integer.toHexString(match)); 5066 if (ri.match > match) { 5067 match = ri.match; 5068 } 5069 } 5070 5071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5072 + Integer.toHexString(match)); 5073 5074 match &= IntentFilter.MATCH_CATEGORY_MASK; 5075 final int M = prefs.size(); 5076 for (int i=0; i<M; i++) { 5077 final PreferredActivity pa = prefs.get(i); 5078 if (DEBUG_PREFERRED || debug) { 5079 Slog.v(TAG, "Checking PreferredActivity ds=" 5080 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5081 + "\n component=" + pa.mPref.mComponent); 5082 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5083 } 5084 if (pa.mPref.mMatch != match) { 5085 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5086 + Integer.toHexString(pa.mPref.mMatch)); 5087 continue; 5088 } 5089 // If it's not an "always" type preferred activity and that's what we're 5090 // looking for, skip it. 5091 if (always && !pa.mPref.mAlways) { 5092 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5093 continue; 5094 } 5095 final ActivityInfo ai = getActivityInfo( 5096 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5097 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5098 userId); 5099 if (DEBUG_PREFERRED || debug) { 5100 Slog.v(TAG, "Found preferred activity:"); 5101 if (ai != null) { 5102 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5103 } else { 5104 Slog.v(TAG, " null"); 5105 } 5106 } 5107 if (ai == null) { 5108 // This previously registered preferred activity 5109 // component is no longer known. Most likely an update 5110 // to the app was installed and in the new version this 5111 // component no longer exists. Clean it up by removing 5112 // it from the preferred activities list, and skip it. 5113 Slog.w(TAG, "Removing dangling preferred activity: " 5114 + pa.mPref.mComponent); 5115 pir.removeFilter(pa); 5116 changed = true; 5117 continue; 5118 } 5119 for (int j=0; j<N; j++) { 5120 final ResolveInfo ri = query.get(j); 5121 if (!ri.activityInfo.applicationInfo.packageName 5122 .equals(ai.applicationInfo.packageName)) { 5123 continue; 5124 } 5125 if (!ri.activityInfo.name.equals(ai.name)) { 5126 continue; 5127 } 5128 5129 if (removeMatches) { 5130 pir.removeFilter(pa); 5131 changed = true; 5132 if (DEBUG_PREFERRED) { 5133 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5134 } 5135 break; 5136 } 5137 5138 // Okay we found a previously set preferred or last chosen app. 5139 // If the result set is different from when this 5140 // was created, we need to clear it and re-ask the 5141 // user their preference, if we're looking for an "always" type entry. 5142 if (always && !pa.mPref.sameSet(query)) { 5143 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5144 + intent + " type " + resolvedType); 5145 if (DEBUG_PREFERRED) { 5146 Slog.v(TAG, "Removing preferred activity since set changed " 5147 + pa.mPref.mComponent); 5148 } 5149 pir.removeFilter(pa); 5150 // Re-add the filter as a "last chosen" entry (!always) 5151 PreferredActivity lastChosen = new PreferredActivity( 5152 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5153 pir.addFilter(lastChosen); 5154 changed = true; 5155 return null; 5156 } 5157 5158 // Yay! Either the set matched or we're looking for the last chosen 5159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5160 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5161 return ri; 5162 } 5163 } 5164 } finally { 5165 if (changed) { 5166 if (DEBUG_PREFERRED) { 5167 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5168 } 5169 scheduleWritePackageRestrictionsLocked(userId); 5170 } 5171 } 5172 } 5173 } 5174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5175 return null; 5176 } 5177 5178 /* 5179 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5180 */ 5181 @Override 5182 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5183 int targetUserId) { 5184 mContext.enforceCallingOrSelfPermission( 5185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5186 List<CrossProfileIntentFilter> matches = 5187 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5188 if (matches != null) { 5189 int size = matches.size(); 5190 for (int i = 0; i < size; i++) { 5191 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5192 } 5193 } 5194 if (hasWebURI(intent)) { 5195 // cross-profile app linking works only towards the parent. 5196 final UserInfo parent = getProfileParent(sourceUserId); 5197 synchronized(mPackages) { 5198 int flags = updateFlagsForResolve(0, parent.id, intent); 5199 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5200 intent, resolvedType, flags, sourceUserId, parent.id); 5201 return xpDomainInfo != null; 5202 } 5203 } 5204 return false; 5205 } 5206 5207 private UserInfo getProfileParent(int userId) { 5208 final long identity = Binder.clearCallingIdentity(); 5209 try { 5210 return sUserManager.getProfileParent(userId); 5211 } finally { 5212 Binder.restoreCallingIdentity(identity); 5213 } 5214 } 5215 5216 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5217 String resolvedType, int userId) { 5218 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5219 if (resolver != null) { 5220 return resolver.queryIntent(intent, resolvedType, false, userId); 5221 } 5222 return null; 5223 } 5224 5225 @Override 5226 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5227 String resolvedType, int flags, int userId) { 5228 try { 5229 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5230 5231 return new ParceledListSlice<>( 5232 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5233 } finally { 5234 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5235 } 5236 } 5237 5238 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5239 String resolvedType, int flags, int userId) { 5240 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5241 flags = updateFlagsForResolve(flags, userId, intent); 5242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5243 false /* requireFullPermission */, false /* checkShell */, 5244 "query intent activities"); 5245 ComponentName comp = intent.getComponent(); 5246 if (comp == null) { 5247 if (intent.getSelector() != null) { 5248 intent = intent.getSelector(); 5249 comp = intent.getComponent(); 5250 } 5251 } 5252 5253 if (comp != null) { 5254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5255 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5256 if (ai != null) { 5257 final ResolveInfo ri = new ResolveInfo(); 5258 ri.activityInfo = ai; 5259 list.add(ri); 5260 } 5261 return list; 5262 } 5263 5264 // reader 5265 synchronized (mPackages) { 5266 final String pkgName = intent.getPackage(); 5267 if (pkgName == null) { 5268 List<CrossProfileIntentFilter> matchingFilters = 5269 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5270 // Check for results that need to skip the current profile. 5271 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5272 resolvedType, flags, userId); 5273 if (xpResolveInfo != null) { 5274 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5275 result.add(xpResolveInfo); 5276 return filterIfNotSystemUser(result, userId); 5277 } 5278 5279 // Check for results in the current profile. 5280 List<ResolveInfo> result = mActivities.queryIntent( 5281 intent, resolvedType, flags, userId); 5282 result = filterIfNotSystemUser(result, userId); 5283 5284 // Check for cross profile results. 5285 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5286 xpResolveInfo = queryCrossProfileIntents( 5287 matchingFilters, intent, resolvedType, flags, userId, 5288 hasNonNegativePriorityResult); 5289 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5290 boolean isVisibleToUser = filterIfNotSystemUser( 5291 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5292 if (isVisibleToUser) { 5293 result.add(xpResolveInfo); 5294 Collections.sort(result, mResolvePrioritySorter); 5295 } 5296 } 5297 if (hasWebURI(intent)) { 5298 CrossProfileDomainInfo xpDomainInfo = null; 5299 final UserInfo parent = getProfileParent(userId); 5300 if (parent != null) { 5301 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5302 flags, userId, parent.id); 5303 } 5304 if (xpDomainInfo != null) { 5305 if (xpResolveInfo != null) { 5306 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5307 // in the result. 5308 result.remove(xpResolveInfo); 5309 } 5310 if (result.size() == 0) { 5311 result.add(xpDomainInfo.resolveInfo); 5312 return result; 5313 } 5314 } else if (result.size() <= 1) { 5315 return result; 5316 } 5317 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5318 xpDomainInfo, userId); 5319 Collections.sort(result, mResolvePrioritySorter); 5320 } 5321 return result; 5322 } 5323 final PackageParser.Package pkg = mPackages.get(pkgName); 5324 if (pkg != null) { 5325 return filterIfNotSystemUser( 5326 mActivities.queryIntentForPackage( 5327 intent, resolvedType, flags, pkg.activities, userId), 5328 userId); 5329 } 5330 return new ArrayList<ResolveInfo>(); 5331 } 5332 } 5333 5334 private static class CrossProfileDomainInfo { 5335 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5336 ResolveInfo resolveInfo; 5337 /* Best domain verification status of the activities found in the other profile */ 5338 int bestDomainVerificationStatus; 5339 } 5340 5341 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5342 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5343 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5344 sourceUserId)) { 5345 return null; 5346 } 5347 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5348 resolvedType, flags, parentUserId); 5349 5350 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5351 return null; 5352 } 5353 CrossProfileDomainInfo result = null; 5354 int size = resultTargetUser.size(); 5355 for (int i = 0; i < size; i++) { 5356 ResolveInfo riTargetUser = resultTargetUser.get(i); 5357 // Intent filter verification is only for filters that specify a host. So don't return 5358 // those that handle all web uris. 5359 if (riTargetUser.handleAllWebDataURI) { 5360 continue; 5361 } 5362 String packageName = riTargetUser.activityInfo.packageName; 5363 PackageSetting ps = mSettings.mPackages.get(packageName); 5364 if (ps == null) { 5365 continue; 5366 } 5367 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5368 int status = (int)(verificationState >> 32); 5369 if (result == null) { 5370 result = new CrossProfileDomainInfo(); 5371 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5372 sourceUserId, parentUserId); 5373 result.bestDomainVerificationStatus = status; 5374 } else { 5375 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5376 result.bestDomainVerificationStatus); 5377 } 5378 } 5379 // Don't consider matches with status NEVER across profiles. 5380 if (result != null && result.bestDomainVerificationStatus 5381 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5382 return null; 5383 } 5384 return result; 5385 } 5386 5387 /** 5388 * Verification statuses are ordered from the worse to the best, except for 5389 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5390 */ 5391 private int bestDomainVerificationStatus(int status1, int status2) { 5392 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5393 return status2; 5394 } 5395 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5396 return status1; 5397 } 5398 return (int) MathUtils.max(status1, status2); 5399 } 5400 5401 private boolean isUserEnabled(int userId) { 5402 long callingId = Binder.clearCallingIdentity(); 5403 try { 5404 UserInfo userInfo = sUserManager.getUserInfo(userId); 5405 return userInfo != null && userInfo.isEnabled(); 5406 } finally { 5407 Binder.restoreCallingIdentity(callingId); 5408 } 5409 } 5410 5411 /** 5412 * Filter out activities with systemUserOnly flag set, when current user is not System. 5413 * 5414 * @return filtered list 5415 */ 5416 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5417 if (userId == UserHandle.USER_SYSTEM) { 5418 return resolveInfos; 5419 } 5420 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5421 ResolveInfo info = resolveInfos.get(i); 5422 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5423 resolveInfos.remove(i); 5424 } 5425 } 5426 return resolveInfos; 5427 } 5428 5429 /** 5430 * @param resolveInfos list of resolve infos in descending priority order 5431 * @return if the list contains a resolve info with non-negative priority 5432 */ 5433 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5434 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5435 } 5436 5437 private static boolean hasWebURI(Intent intent) { 5438 if (intent.getData() == null) { 5439 return false; 5440 } 5441 final String scheme = intent.getScheme(); 5442 if (TextUtils.isEmpty(scheme)) { 5443 return false; 5444 } 5445 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5446 } 5447 5448 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5449 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5450 int userId) { 5451 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5452 5453 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5454 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5455 candidates.size()); 5456 } 5457 5458 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5459 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5460 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5461 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5462 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5463 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5464 5465 synchronized (mPackages) { 5466 final int count = candidates.size(); 5467 // First, try to use linked apps. Partition the candidates into four lists: 5468 // one for the final results, one for the "do not use ever", one for "undefined status" 5469 // and finally one for "browser app type". 5470 for (int n=0; n<count; n++) { 5471 ResolveInfo info = candidates.get(n); 5472 String packageName = info.activityInfo.packageName; 5473 PackageSetting ps = mSettings.mPackages.get(packageName); 5474 if (ps != null) { 5475 // Add to the special match all list (Browser use case) 5476 if (info.handleAllWebDataURI) { 5477 matchAllList.add(info); 5478 continue; 5479 } 5480 // Try to get the status from User settings first 5481 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5482 int status = (int)(packedStatus >> 32); 5483 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5484 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5485 if (DEBUG_DOMAIN_VERIFICATION) { 5486 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5487 + " : linkgen=" + linkGeneration); 5488 } 5489 // Use link-enabled generation as preferredOrder, i.e. 5490 // prefer newly-enabled over earlier-enabled. 5491 info.preferredOrder = linkGeneration; 5492 alwaysList.add(info); 5493 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5494 if (DEBUG_DOMAIN_VERIFICATION) { 5495 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5496 } 5497 neverList.add(info); 5498 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5499 if (DEBUG_DOMAIN_VERIFICATION) { 5500 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5501 } 5502 alwaysAskList.add(info); 5503 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5504 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5505 if (DEBUG_DOMAIN_VERIFICATION) { 5506 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5507 } 5508 undefinedList.add(info); 5509 } 5510 } 5511 } 5512 5513 // We'll want to include browser possibilities in a few cases 5514 boolean includeBrowser = false; 5515 5516 // First try to add the "always" resolution(s) for the current user, if any 5517 if (alwaysList.size() > 0) { 5518 result.addAll(alwaysList); 5519 } else { 5520 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5521 result.addAll(undefinedList); 5522 // Maybe add one for the other profile. 5523 if (xpDomainInfo != null && ( 5524 xpDomainInfo.bestDomainVerificationStatus 5525 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5526 result.add(xpDomainInfo.resolveInfo); 5527 } 5528 includeBrowser = true; 5529 } 5530 5531 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5532 // If there were 'always' entries their preferred order has been set, so we also 5533 // back that off to make the alternatives equivalent 5534 if (alwaysAskList.size() > 0) { 5535 for (ResolveInfo i : result) { 5536 i.preferredOrder = 0; 5537 } 5538 result.addAll(alwaysAskList); 5539 includeBrowser = true; 5540 } 5541 5542 if (includeBrowser) { 5543 // Also add browsers (all of them or only the default one) 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.v(TAG, " ...including browsers in candidate set"); 5546 } 5547 if ((matchFlags & MATCH_ALL) != 0) { 5548 result.addAll(matchAllList); 5549 } else { 5550 // Browser/generic handling case. If there's a default browser, go straight 5551 // to that (but only if there is no other higher-priority match). 5552 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5553 int maxMatchPrio = 0; 5554 ResolveInfo defaultBrowserMatch = null; 5555 final int numCandidates = matchAllList.size(); 5556 for (int n = 0; n < numCandidates; n++) { 5557 ResolveInfo info = matchAllList.get(n); 5558 // track the highest overall match priority... 5559 if (info.priority > maxMatchPrio) { 5560 maxMatchPrio = info.priority; 5561 } 5562 // ...and the highest-priority default browser match 5563 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5564 if (defaultBrowserMatch == null 5565 || (defaultBrowserMatch.priority < info.priority)) { 5566 if (debug) { 5567 Slog.v(TAG, "Considering default browser match " + info); 5568 } 5569 defaultBrowserMatch = info; 5570 } 5571 } 5572 } 5573 if (defaultBrowserMatch != null 5574 && defaultBrowserMatch.priority >= maxMatchPrio 5575 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5576 { 5577 if (debug) { 5578 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5579 } 5580 result.add(defaultBrowserMatch); 5581 } else { 5582 result.addAll(matchAllList); 5583 } 5584 } 5585 5586 // If there is nothing selected, add all candidates and remove the ones that the user 5587 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5588 if (result.size() == 0) { 5589 result.addAll(candidates); 5590 result.removeAll(neverList); 5591 } 5592 } 5593 } 5594 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5595 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5596 result.size()); 5597 for (ResolveInfo info : result) { 5598 Slog.v(TAG, " + " + info.activityInfo); 5599 } 5600 } 5601 return result; 5602 } 5603 5604 // Returns a packed value as a long: 5605 // 5606 // high 'int'-sized word: link status: undefined/ask/never/always. 5607 // low 'int'-sized word: relative priority among 'always' results. 5608 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5609 long result = ps.getDomainVerificationStatusForUser(userId); 5610 // if none available, get the master status 5611 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5612 if (ps.getIntentFilterVerificationInfo() != null) { 5613 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5614 } 5615 } 5616 return result; 5617 } 5618 5619 private ResolveInfo querySkipCurrentProfileIntents( 5620 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5621 int flags, int sourceUserId) { 5622 if (matchingFilters != null) { 5623 int size = matchingFilters.size(); 5624 for (int i = 0; i < size; i ++) { 5625 CrossProfileIntentFilter filter = matchingFilters.get(i); 5626 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5627 // Checking if there are activities in the target user that can handle the 5628 // intent. 5629 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5630 resolvedType, flags, sourceUserId); 5631 if (resolveInfo != null) { 5632 return resolveInfo; 5633 } 5634 } 5635 } 5636 } 5637 return null; 5638 } 5639 5640 // Return matching ResolveInfo in target user if any. 5641 private ResolveInfo queryCrossProfileIntents( 5642 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5643 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5644 if (matchingFilters != null) { 5645 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5646 // match the same intent. For performance reasons, it is better not to 5647 // run queryIntent twice for the same userId 5648 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5649 int size = matchingFilters.size(); 5650 for (int i = 0; i < size; i++) { 5651 CrossProfileIntentFilter filter = matchingFilters.get(i); 5652 int targetUserId = filter.getTargetUserId(); 5653 boolean skipCurrentProfile = 5654 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5655 boolean skipCurrentProfileIfNoMatchFound = 5656 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5657 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5658 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5659 // Checking if there are activities in the target user that can handle the 5660 // intent. 5661 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5662 resolvedType, flags, sourceUserId); 5663 if (resolveInfo != null) return resolveInfo; 5664 alreadyTriedUserIds.put(targetUserId, true); 5665 } 5666 } 5667 } 5668 return null; 5669 } 5670 5671 /** 5672 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5673 * will forward the intent to the filter's target user. 5674 * Otherwise, returns null. 5675 */ 5676 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5677 String resolvedType, int flags, int sourceUserId) { 5678 int targetUserId = filter.getTargetUserId(); 5679 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5680 resolvedType, flags, targetUserId); 5681 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5682 // If all the matches in the target profile are suspended, return null. 5683 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5684 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5685 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5686 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5687 targetUserId); 5688 } 5689 } 5690 } 5691 return null; 5692 } 5693 5694 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5695 int sourceUserId, int targetUserId) { 5696 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5697 long ident = Binder.clearCallingIdentity(); 5698 boolean targetIsProfile; 5699 try { 5700 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5701 } finally { 5702 Binder.restoreCallingIdentity(ident); 5703 } 5704 String className; 5705 if (targetIsProfile) { 5706 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5707 } else { 5708 className = FORWARD_INTENT_TO_PARENT; 5709 } 5710 ComponentName forwardingActivityComponentName = new ComponentName( 5711 mAndroidApplication.packageName, className); 5712 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5713 sourceUserId); 5714 if (!targetIsProfile) { 5715 forwardingActivityInfo.showUserIcon = targetUserId; 5716 forwardingResolveInfo.noResourceId = true; 5717 } 5718 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5719 forwardingResolveInfo.priority = 0; 5720 forwardingResolveInfo.preferredOrder = 0; 5721 forwardingResolveInfo.match = 0; 5722 forwardingResolveInfo.isDefault = true; 5723 forwardingResolveInfo.filter = filter; 5724 forwardingResolveInfo.targetUserId = targetUserId; 5725 return forwardingResolveInfo; 5726 } 5727 5728 @Override 5729 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5730 Intent[] specifics, String[] specificTypes, Intent intent, 5731 String resolvedType, int flags, int userId) { 5732 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5733 specificTypes, intent, resolvedType, flags, userId)); 5734 } 5735 5736 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5737 Intent[] specifics, String[] specificTypes, Intent intent, 5738 String resolvedType, int flags, int userId) { 5739 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5740 flags = updateFlagsForResolve(flags, userId, intent); 5741 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5742 false /* requireFullPermission */, false /* checkShell */, 5743 "query intent activity options"); 5744 final String resultsAction = intent.getAction(); 5745 5746 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5747 | PackageManager.GET_RESOLVED_FILTER, userId); 5748 5749 if (DEBUG_INTENT_MATCHING) { 5750 Log.v(TAG, "Query " + intent + ": " + results); 5751 } 5752 5753 int specificsPos = 0; 5754 int N; 5755 5756 // todo: note that the algorithm used here is O(N^2). This 5757 // isn't a problem in our current environment, but if we start running 5758 // into situations where we have more than 5 or 10 matches then this 5759 // should probably be changed to something smarter... 5760 5761 // First we go through and resolve each of the specific items 5762 // that were supplied, taking care of removing any corresponding 5763 // duplicate items in the generic resolve list. 5764 if (specifics != null) { 5765 for (int i=0; i<specifics.length; i++) { 5766 final Intent sintent = specifics[i]; 5767 if (sintent == null) { 5768 continue; 5769 } 5770 5771 if (DEBUG_INTENT_MATCHING) { 5772 Log.v(TAG, "Specific #" + i + ": " + sintent); 5773 } 5774 5775 String action = sintent.getAction(); 5776 if (resultsAction != null && resultsAction.equals(action)) { 5777 // If this action was explicitly requested, then don't 5778 // remove things that have it. 5779 action = null; 5780 } 5781 5782 ResolveInfo ri = null; 5783 ActivityInfo ai = null; 5784 5785 ComponentName comp = sintent.getComponent(); 5786 if (comp == null) { 5787 ri = resolveIntent( 5788 sintent, 5789 specificTypes != null ? specificTypes[i] : null, 5790 flags, userId); 5791 if (ri == null) { 5792 continue; 5793 } 5794 if (ri == mResolveInfo) { 5795 // ACK! Must do something better with this. 5796 } 5797 ai = ri.activityInfo; 5798 comp = new ComponentName(ai.applicationInfo.packageName, 5799 ai.name); 5800 } else { 5801 ai = getActivityInfo(comp, flags, userId); 5802 if (ai == null) { 5803 continue; 5804 } 5805 } 5806 5807 // Look for any generic query activities that are duplicates 5808 // of this specific one, and remove them from the results. 5809 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5810 N = results.size(); 5811 int j; 5812 for (j=specificsPos; j<N; j++) { 5813 ResolveInfo sri = results.get(j); 5814 if ((sri.activityInfo.name.equals(comp.getClassName()) 5815 && sri.activityInfo.applicationInfo.packageName.equals( 5816 comp.getPackageName())) 5817 || (action != null && sri.filter.matchAction(action))) { 5818 results.remove(j); 5819 if (DEBUG_INTENT_MATCHING) Log.v( 5820 TAG, "Removing duplicate item from " + j 5821 + " due to specific " + specificsPos); 5822 if (ri == null) { 5823 ri = sri; 5824 } 5825 j--; 5826 N--; 5827 } 5828 } 5829 5830 // Add this specific item to its proper place. 5831 if (ri == null) { 5832 ri = new ResolveInfo(); 5833 ri.activityInfo = ai; 5834 } 5835 results.add(specificsPos, ri); 5836 ri.specificIndex = i; 5837 specificsPos++; 5838 } 5839 } 5840 5841 // Now we go through the remaining generic results and remove any 5842 // duplicate actions that are found here. 5843 N = results.size(); 5844 for (int i=specificsPos; i<N-1; i++) { 5845 final ResolveInfo rii = results.get(i); 5846 if (rii.filter == null) { 5847 continue; 5848 } 5849 5850 // Iterate over all of the actions of this result's intent 5851 // filter... typically this should be just one. 5852 final Iterator<String> it = rii.filter.actionsIterator(); 5853 if (it == null) { 5854 continue; 5855 } 5856 while (it.hasNext()) { 5857 final String action = it.next(); 5858 if (resultsAction != null && resultsAction.equals(action)) { 5859 // If this action was explicitly requested, then don't 5860 // remove things that have it. 5861 continue; 5862 } 5863 for (int j=i+1; j<N; j++) { 5864 final ResolveInfo rij = results.get(j); 5865 if (rij.filter != null && rij.filter.hasAction(action)) { 5866 results.remove(j); 5867 if (DEBUG_INTENT_MATCHING) Log.v( 5868 TAG, "Removing duplicate item from " + j 5869 + " due to action " + action + " at " + i); 5870 j--; 5871 N--; 5872 } 5873 } 5874 } 5875 5876 // If the caller didn't request filter information, drop it now 5877 // so we don't have to marshall/unmarshall it. 5878 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5879 rii.filter = null; 5880 } 5881 } 5882 5883 // Filter out the caller activity if so requested. 5884 if (caller != null) { 5885 N = results.size(); 5886 for (int i=0; i<N; i++) { 5887 ActivityInfo ainfo = results.get(i).activityInfo; 5888 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5889 && caller.getClassName().equals(ainfo.name)) { 5890 results.remove(i); 5891 break; 5892 } 5893 } 5894 } 5895 5896 // If the caller didn't request filter information, 5897 // drop them now so we don't have to 5898 // marshall/unmarshall it. 5899 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5900 N = results.size(); 5901 for (int i=0; i<N; i++) { 5902 results.get(i).filter = null; 5903 } 5904 } 5905 5906 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5907 return results; 5908 } 5909 5910 @Override 5911 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5912 String resolvedType, int flags, int userId) { 5913 return new ParceledListSlice<>( 5914 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5915 } 5916 5917 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5918 String resolvedType, int flags, int userId) { 5919 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5920 flags = updateFlagsForResolve(flags, userId, intent); 5921 ComponentName comp = intent.getComponent(); 5922 if (comp == null) { 5923 if (intent.getSelector() != null) { 5924 intent = intent.getSelector(); 5925 comp = intent.getComponent(); 5926 } 5927 } 5928 if (comp != null) { 5929 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5930 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5931 if (ai != null) { 5932 ResolveInfo ri = new ResolveInfo(); 5933 ri.activityInfo = ai; 5934 list.add(ri); 5935 } 5936 return list; 5937 } 5938 5939 // reader 5940 synchronized (mPackages) { 5941 String pkgName = intent.getPackage(); 5942 if (pkgName == null) { 5943 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5944 } 5945 final PackageParser.Package pkg = mPackages.get(pkgName); 5946 if (pkg != null) { 5947 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5948 userId); 5949 } 5950 return Collections.emptyList(); 5951 } 5952 } 5953 5954 @Override 5955 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5956 if (!sUserManager.exists(userId)) return null; 5957 flags = updateFlagsForResolve(flags, userId, intent); 5958 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5959 if (query != null) { 5960 if (query.size() >= 1) { 5961 // If there is more than one service with the same priority, 5962 // just arbitrarily pick the first one. 5963 return query.get(0); 5964 } 5965 } 5966 return null; 5967 } 5968 5969 @Override 5970 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5971 String resolvedType, int flags, int userId) { 5972 return new ParceledListSlice<>( 5973 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5974 } 5975 5976 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5977 String resolvedType, int flags, int userId) { 5978 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5979 flags = updateFlagsForResolve(flags, userId, intent); 5980 ComponentName comp = intent.getComponent(); 5981 if (comp == null) { 5982 if (intent.getSelector() != null) { 5983 intent = intent.getSelector(); 5984 comp = intent.getComponent(); 5985 } 5986 } 5987 if (comp != null) { 5988 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5989 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5990 if (si != null) { 5991 final ResolveInfo ri = new ResolveInfo(); 5992 ri.serviceInfo = si; 5993 list.add(ri); 5994 } 5995 return list; 5996 } 5997 5998 // reader 5999 synchronized (mPackages) { 6000 String pkgName = intent.getPackage(); 6001 if (pkgName == null) { 6002 return mServices.queryIntent(intent, resolvedType, flags, userId); 6003 } 6004 final PackageParser.Package pkg = mPackages.get(pkgName); 6005 if (pkg != null) { 6006 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6007 userId); 6008 } 6009 return Collections.emptyList(); 6010 } 6011 } 6012 6013 @Override 6014 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6015 String resolvedType, int flags, int userId) { 6016 return new ParceledListSlice<>( 6017 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6018 } 6019 6020 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6021 Intent intent, String resolvedType, int flags, int userId) { 6022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6023 flags = updateFlagsForResolve(flags, userId, intent); 6024 ComponentName comp = intent.getComponent(); 6025 if (comp == null) { 6026 if (intent.getSelector() != null) { 6027 intent = intent.getSelector(); 6028 comp = intent.getComponent(); 6029 } 6030 } 6031 if (comp != null) { 6032 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6033 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6034 if (pi != null) { 6035 final ResolveInfo ri = new ResolveInfo(); 6036 ri.providerInfo = pi; 6037 list.add(ri); 6038 } 6039 return list; 6040 } 6041 6042 // reader 6043 synchronized (mPackages) { 6044 String pkgName = intent.getPackage(); 6045 if (pkgName == null) { 6046 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6047 } 6048 final PackageParser.Package pkg = mPackages.get(pkgName); 6049 if (pkg != null) { 6050 return mProviders.queryIntentForPackage( 6051 intent, resolvedType, flags, pkg.providers, userId); 6052 } 6053 return Collections.emptyList(); 6054 } 6055 } 6056 6057 @Override 6058 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6059 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6060 flags = updateFlagsForPackage(flags, userId, null); 6061 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6063 true /* requireFullPermission */, false /* checkShell */, 6064 "get installed packages"); 6065 6066 // writer 6067 synchronized (mPackages) { 6068 ArrayList<PackageInfo> list; 6069 if (listUninstalled) { 6070 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6071 for (PackageSetting ps : mSettings.mPackages.values()) { 6072 final PackageInfo pi; 6073 if (ps.pkg != null) { 6074 pi = generatePackageInfo(ps, flags, userId); 6075 } else { 6076 pi = generatePackageInfo(ps, flags, userId); 6077 } 6078 if (pi != null) { 6079 list.add(pi); 6080 } 6081 } 6082 } else { 6083 list = new ArrayList<PackageInfo>(mPackages.size()); 6084 for (PackageParser.Package p : mPackages.values()) { 6085 final PackageInfo pi = 6086 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6087 if (pi != null) { 6088 list.add(pi); 6089 } 6090 } 6091 } 6092 6093 return new ParceledListSlice<PackageInfo>(list); 6094 } 6095 } 6096 6097 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6098 String[] permissions, boolean[] tmp, int flags, int userId) { 6099 int numMatch = 0; 6100 final PermissionsState permissionsState = ps.getPermissionsState(); 6101 for (int i=0; i<permissions.length; i++) { 6102 final String permission = permissions[i]; 6103 if (permissionsState.hasPermission(permission, userId)) { 6104 tmp[i] = true; 6105 numMatch++; 6106 } else { 6107 tmp[i] = false; 6108 } 6109 } 6110 if (numMatch == 0) { 6111 return; 6112 } 6113 final PackageInfo pi; 6114 if (ps.pkg != null) { 6115 pi = generatePackageInfo(ps, flags, userId); 6116 } else { 6117 pi = generatePackageInfo(ps, flags, userId); 6118 } 6119 // The above might return null in cases of uninstalled apps or install-state 6120 // skew across users/profiles. 6121 if (pi != null) { 6122 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6123 if (numMatch == permissions.length) { 6124 pi.requestedPermissions = permissions; 6125 } else { 6126 pi.requestedPermissions = new String[numMatch]; 6127 numMatch = 0; 6128 for (int i=0; i<permissions.length; i++) { 6129 if (tmp[i]) { 6130 pi.requestedPermissions[numMatch] = permissions[i]; 6131 numMatch++; 6132 } 6133 } 6134 } 6135 } 6136 list.add(pi); 6137 } 6138 } 6139 6140 @Override 6141 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6142 String[] permissions, int flags, int userId) { 6143 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6144 flags = updateFlagsForPackage(flags, userId, permissions); 6145 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6146 6147 // writer 6148 synchronized (mPackages) { 6149 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6150 boolean[] tmpBools = new boolean[permissions.length]; 6151 if (listUninstalled) { 6152 for (PackageSetting ps : mSettings.mPackages.values()) { 6153 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6154 } 6155 } else { 6156 for (PackageParser.Package pkg : mPackages.values()) { 6157 PackageSetting ps = (PackageSetting)pkg.mExtras; 6158 if (ps != null) { 6159 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6160 userId); 6161 } 6162 } 6163 } 6164 6165 return new ParceledListSlice<PackageInfo>(list); 6166 } 6167 } 6168 6169 @Override 6170 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6171 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6172 flags = updateFlagsForApplication(flags, userId, null); 6173 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6174 6175 // writer 6176 synchronized (mPackages) { 6177 ArrayList<ApplicationInfo> list; 6178 if (listUninstalled) { 6179 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6180 for (PackageSetting ps : mSettings.mPackages.values()) { 6181 ApplicationInfo ai; 6182 if (ps.pkg != null) { 6183 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6184 ps.readUserState(userId), userId); 6185 } else { 6186 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6187 } 6188 if (ai != null) { 6189 list.add(ai); 6190 } 6191 } 6192 } else { 6193 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6194 for (PackageParser.Package p : mPackages.values()) { 6195 if (p.mExtras != null) { 6196 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6197 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6198 if (ai != null) { 6199 list.add(ai); 6200 } 6201 } 6202 } 6203 } 6204 6205 return new ParceledListSlice<ApplicationInfo>(list); 6206 } 6207 } 6208 6209 @Override 6210 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6211 if (DISABLE_EPHEMERAL_APPS) { 6212 return null; 6213 } 6214 6215 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6216 "getEphemeralApplications"); 6217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6218 true /* requireFullPermission */, false /* checkShell */, 6219 "getEphemeralApplications"); 6220 synchronized (mPackages) { 6221 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6222 .getEphemeralApplicationsLPw(userId); 6223 if (ephemeralApps != null) { 6224 return new ParceledListSlice<>(ephemeralApps); 6225 } 6226 } 6227 return null; 6228 } 6229 6230 @Override 6231 public boolean isEphemeralApplication(String packageName, int userId) { 6232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6233 true /* requireFullPermission */, false /* checkShell */, 6234 "isEphemeral"); 6235 if (DISABLE_EPHEMERAL_APPS) { 6236 return false; 6237 } 6238 6239 if (!isCallerSameApp(packageName)) { 6240 return false; 6241 } 6242 synchronized (mPackages) { 6243 PackageParser.Package pkg = mPackages.get(packageName); 6244 if (pkg != null) { 6245 return pkg.applicationInfo.isEphemeralApp(); 6246 } 6247 } 6248 return false; 6249 } 6250 6251 @Override 6252 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6253 if (DISABLE_EPHEMERAL_APPS) { 6254 return null; 6255 } 6256 6257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6258 true /* requireFullPermission */, false /* checkShell */, 6259 "getCookie"); 6260 if (!isCallerSameApp(packageName)) { 6261 return null; 6262 } 6263 synchronized (mPackages) { 6264 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6265 packageName, userId); 6266 } 6267 } 6268 6269 @Override 6270 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6271 if (DISABLE_EPHEMERAL_APPS) { 6272 return true; 6273 } 6274 6275 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6276 true /* requireFullPermission */, true /* checkShell */, 6277 "setCookie"); 6278 if (!isCallerSameApp(packageName)) { 6279 return false; 6280 } 6281 synchronized (mPackages) { 6282 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6283 packageName, cookie, userId); 6284 } 6285 } 6286 6287 @Override 6288 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6289 if (DISABLE_EPHEMERAL_APPS) { 6290 return null; 6291 } 6292 6293 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6294 "getEphemeralApplicationIcon"); 6295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6296 true /* requireFullPermission */, false /* checkShell */, 6297 "getEphemeralApplicationIcon"); 6298 synchronized (mPackages) { 6299 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6300 packageName, userId); 6301 } 6302 } 6303 6304 private boolean isCallerSameApp(String packageName) { 6305 PackageParser.Package pkg = mPackages.get(packageName); 6306 return pkg != null 6307 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6308 } 6309 6310 @Override 6311 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6312 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6313 } 6314 6315 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6316 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6317 6318 // reader 6319 synchronized (mPackages) { 6320 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6321 final int userId = UserHandle.getCallingUserId(); 6322 while (i.hasNext()) { 6323 final PackageParser.Package p = i.next(); 6324 if (p.applicationInfo == null) continue; 6325 6326 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6327 && !p.applicationInfo.isDirectBootAware(); 6328 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6329 && p.applicationInfo.isDirectBootAware(); 6330 6331 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6332 && (!mSafeMode || isSystemApp(p)) 6333 && (matchesUnaware || matchesAware)) { 6334 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6335 if (ps != null) { 6336 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6337 ps.readUserState(userId), userId); 6338 if (ai != null) { 6339 finalList.add(ai); 6340 } 6341 } 6342 } 6343 } 6344 } 6345 6346 return finalList; 6347 } 6348 6349 @Override 6350 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6351 if (!sUserManager.exists(userId)) return null; 6352 flags = updateFlagsForComponent(flags, userId, name); 6353 // reader 6354 synchronized (mPackages) { 6355 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6356 PackageSetting ps = provider != null 6357 ? mSettings.mPackages.get(provider.owner.packageName) 6358 : null; 6359 return ps != null 6360 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6361 ? PackageParser.generateProviderInfo(provider, flags, 6362 ps.readUserState(userId), userId) 6363 : null; 6364 } 6365 } 6366 6367 /** 6368 * @deprecated 6369 */ 6370 @Deprecated 6371 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6372 // reader 6373 synchronized (mPackages) { 6374 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6375 .entrySet().iterator(); 6376 final int userId = UserHandle.getCallingUserId(); 6377 while (i.hasNext()) { 6378 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6379 PackageParser.Provider p = entry.getValue(); 6380 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6381 6382 if (ps != null && p.syncable 6383 && (!mSafeMode || (p.info.applicationInfo.flags 6384 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6385 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6386 ps.readUserState(userId), userId); 6387 if (info != null) { 6388 outNames.add(entry.getKey()); 6389 outInfo.add(info); 6390 } 6391 } 6392 } 6393 } 6394 } 6395 6396 @Override 6397 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6398 int uid, int flags) { 6399 final int userId = processName != null ? UserHandle.getUserId(uid) 6400 : UserHandle.getCallingUserId(); 6401 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6402 flags = updateFlagsForComponent(flags, userId, processName); 6403 6404 ArrayList<ProviderInfo> finalList = null; 6405 // reader 6406 synchronized (mPackages) { 6407 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6408 while (i.hasNext()) { 6409 final PackageParser.Provider p = i.next(); 6410 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6411 if (ps != null && p.info.authority != null 6412 && (processName == null 6413 || (p.info.processName.equals(processName) 6414 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6415 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6416 if (finalList == null) { 6417 finalList = new ArrayList<ProviderInfo>(3); 6418 } 6419 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6420 ps.readUserState(userId), userId); 6421 if (info != null) { 6422 finalList.add(info); 6423 } 6424 } 6425 } 6426 } 6427 6428 if (finalList != null) { 6429 Collections.sort(finalList, mProviderInitOrderSorter); 6430 return new ParceledListSlice<ProviderInfo>(finalList); 6431 } 6432 6433 return ParceledListSlice.emptyList(); 6434 } 6435 6436 @Override 6437 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6438 // reader 6439 synchronized (mPackages) { 6440 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6441 return PackageParser.generateInstrumentationInfo(i, flags); 6442 } 6443 } 6444 6445 @Override 6446 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6447 String targetPackage, int flags) { 6448 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6449 } 6450 6451 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6452 int flags) { 6453 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6454 6455 // reader 6456 synchronized (mPackages) { 6457 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6458 while (i.hasNext()) { 6459 final PackageParser.Instrumentation p = i.next(); 6460 if (targetPackage == null 6461 || targetPackage.equals(p.info.targetPackage)) { 6462 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6463 flags); 6464 if (ii != null) { 6465 finalList.add(ii); 6466 } 6467 } 6468 } 6469 } 6470 6471 return finalList; 6472 } 6473 6474 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6475 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6476 if (overlays == null) { 6477 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6478 return; 6479 } 6480 for (PackageParser.Package opkg : overlays.values()) { 6481 // Not much to do if idmap fails: we already logged the error 6482 // and we certainly don't want to abort installation of pkg simply 6483 // because an overlay didn't fit properly. For these reasons, 6484 // ignore the return value of createIdmapForPackagePairLI. 6485 createIdmapForPackagePairLI(pkg, opkg); 6486 } 6487 } 6488 6489 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6490 PackageParser.Package opkg) { 6491 if (!opkg.mTrustedOverlay) { 6492 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6493 opkg.baseCodePath + ": overlay not trusted"); 6494 return false; 6495 } 6496 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6497 if (overlaySet == null) { 6498 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6499 opkg.baseCodePath + " but target package has no known overlays"); 6500 return false; 6501 } 6502 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6503 // TODO: generate idmap for split APKs 6504 try { 6505 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6506 } catch (InstallerException e) { 6507 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6508 + opkg.baseCodePath); 6509 return false; 6510 } 6511 PackageParser.Package[] overlayArray = 6512 overlaySet.values().toArray(new PackageParser.Package[0]); 6513 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6514 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6515 return p1.mOverlayPriority - p2.mOverlayPriority; 6516 } 6517 }; 6518 Arrays.sort(overlayArray, cmp); 6519 6520 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6521 int i = 0; 6522 for (PackageParser.Package p : overlayArray) { 6523 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6524 } 6525 return true; 6526 } 6527 6528 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6530 try { 6531 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6532 } finally { 6533 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6534 } 6535 } 6536 6537 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6538 final File[] files = dir.listFiles(); 6539 if (ArrayUtils.isEmpty(files)) { 6540 Log.d(TAG, "No files in app dir " + dir); 6541 return; 6542 } 6543 6544 if (DEBUG_PACKAGE_SCANNING) { 6545 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6546 + " flags=0x" + Integer.toHexString(parseFlags)); 6547 } 6548 6549 for (File file : files) { 6550 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6551 && !PackageInstallerService.isStageName(file.getName()); 6552 if (!isPackage) { 6553 // Ignore entries which are not packages 6554 continue; 6555 } 6556 try { 6557 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6558 scanFlags, currentTime, null); 6559 } catch (PackageManagerException e) { 6560 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6561 6562 // Delete invalid userdata apps 6563 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6564 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6565 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6566 removeCodePathLI(file); 6567 } 6568 } 6569 } 6570 } 6571 6572 private static File getSettingsProblemFile() { 6573 File dataDir = Environment.getDataDirectory(); 6574 File systemDir = new File(dataDir, "system"); 6575 File fname = new File(systemDir, "uiderrors.txt"); 6576 return fname; 6577 } 6578 6579 static void reportSettingsProblem(int priority, String msg) { 6580 logCriticalInfo(priority, msg); 6581 } 6582 6583 static void logCriticalInfo(int priority, String msg) { 6584 Slog.println(priority, TAG, msg); 6585 EventLogTags.writePmCriticalInfo(msg); 6586 try { 6587 File fname = getSettingsProblemFile(); 6588 FileOutputStream out = new FileOutputStream(fname, true); 6589 PrintWriter pw = new FastPrintWriter(out); 6590 SimpleDateFormat formatter = new SimpleDateFormat(); 6591 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6592 pw.println(dateString + ": " + msg); 6593 pw.close(); 6594 FileUtils.setPermissions( 6595 fname.toString(), 6596 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6597 -1, -1); 6598 } catch (java.io.IOException e) { 6599 } 6600 } 6601 6602 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6603 if (srcFile.isDirectory()) { 6604 final File baseFile = new File(pkg.baseCodePath); 6605 long maxModifiedTime = baseFile.lastModified(); 6606 if (pkg.splitCodePaths != null) { 6607 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6608 final File splitFile = new File(pkg.splitCodePaths[i]); 6609 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6610 } 6611 } 6612 return maxModifiedTime; 6613 } 6614 return srcFile.lastModified(); 6615 } 6616 6617 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6618 final int policyFlags) throws PackageManagerException { 6619 // When upgrading from pre-N MR1, verify the package time stamp using the package 6620 // directory and not the APK file. 6621 final long lastModifiedTime = mIsPreNMR1Upgrade 6622 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6623 if (ps != null 6624 && ps.codePath.equals(srcFile) 6625 && ps.timeStamp == lastModifiedTime 6626 && !isCompatSignatureUpdateNeeded(pkg) 6627 && !isRecoverSignatureUpdateNeeded(pkg)) { 6628 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6630 ArraySet<PublicKey> signingKs; 6631 synchronized (mPackages) { 6632 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6633 } 6634 if (ps.signatures.mSignatures != null 6635 && ps.signatures.mSignatures.length != 0 6636 && signingKs != null) { 6637 // Optimization: reuse the existing cached certificates 6638 // if the package appears to be unchanged. 6639 pkg.mSignatures = ps.signatures.mSignatures; 6640 pkg.mSigningKeys = signingKs; 6641 return; 6642 } 6643 6644 Slog.w(TAG, "PackageSetting for " + ps.name 6645 + " is missing signatures. Collecting certs again to recover them."); 6646 } else { 6647 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6648 } 6649 6650 try { 6651 PackageParser.collectCertificates(pkg, policyFlags); 6652 } catch (PackageParserException e) { 6653 throw PackageManagerException.from(e); 6654 } 6655 } 6656 6657 /** 6658 * Traces a package scan. 6659 * @see #scanPackageLI(File, int, int, long, UserHandle) 6660 */ 6661 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6662 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6664 try { 6665 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6666 } finally { 6667 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6668 } 6669 } 6670 6671 /** 6672 * Scans a package and returns the newly parsed package. 6673 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6674 */ 6675 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6676 long currentTime, UserHandle user) throws PackageManagerException { 6677 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6678 PackageParser pp = new PackageParser(); 6679 pp.setSeparateProcesses(mSeparateProcesses); 6680 pp.setOnlyCoreApps(mOnlyCore); 6681 pp.setDisplayMetrics(mMetrics); 6682 6683 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6684 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6685 } 6686 6687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6688 final PackageParser.Package pkg; 6689 try { 6690 pkg = pp.parsePackage(scanFile, parseFlags); 6691 } catch (PackageParserException e) { 6692 throw PackageManagerException.from(e); 6693 } finally { 6694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6695 } 6696 6697 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6698 } 6699 6700 /** 6701 * Scans a package and returns the newly parsed package. 6702 * @throws PackageManagerException on a parse error. 6703 */ 6704 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6705 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6706 throws PackageManagerException { 6707 // If the package has children and this is the first dive in the function 6708 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6709 // packages (parent and children) would be successfully scanned before the 6710 // actual scan since scanning mutates internal state and we want to atomically 6711 // install the package and its children. 6712 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6713 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6714 scanFlags |= SCAN_CHECK_ONLY; 6715 } 6716 } else { 6717 scanFlags &= ~SCAN_CHECK_ONLY; 6718 } 6719 6720 // Scan the parent 6721 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6722 scanFlags, currentTime, user); 6723 6724 // Scan the children 6725 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6726 for (int i = 0; i < childCount; i++) { 6727 PackageParser.Package childPackage = pkg.childPackages.get(i); 6728 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6729 currentTime, user); 6730 } 6731 6732 6733 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6734 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6735 } 6736 6737 return scannedPkg; 6738 } 6739 6740 /** 6741 * Scans a package and returns the newly parsed package. 6742 * @throws PackageManagerException on a parse error. 6743 */ 6744 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6745 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6746 throws PackageManagerException { 6747 PackageSetting ps = null; 6748 PackageSetting updatedPkg; 6749 // reader 6750 synchronized (mPackages) { 6751 // Look to see if we already know about this package. 6752 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6753 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6754 // This package has been renamed to its original name. Let's 6755 // use that. 6756 ps = mSettings.peekPackageLPr(oldName); 6757 } 6758 // If there was no original package, see one for the real package name. 6759 if (ps == null) { 6760 ps = mSettings.peekPackageLPr(pkg.packageName); 6761 } 6762 // Check to see if this package could be hiding/updating a system 6763 // package. Must look for it either under the original or real 6764 // package name depending on our state. 6765 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6766 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6767 6768 // If this is a package we don't know about on the system partition, we 6769 // may need to remove disabled child packages on the system partition 6770 // or may need to not add child packages if the parent apk is updated 6771 // on the data partition and no longer defines this child package. 6772 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6773 // If this is a parent package for an updated system app and this system 6774 // app got an OTA update which no longer defines some of the child packages 6775 // we have to prune them from the disabled system packages. 6776 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6777 if (disabledPs != null) { 6778 final int scannedChildCount = (pkg.childPackages != null) 6779 ? pkg.childPackages.size() : 0; 6780 final int disabledChildCount = disabledPs.childPackageNames != null 6781 ? disabledPs.childPackageNames.size() : 0; 6782 for (int i = 0; i < disabledChildCount; i++) { 6783 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6784 boolean disabledPackageAvailable = false; 6785 for (int j = 0; j < scannedChildCount; j++) { 6786 PackageParser.Package childPkg = pkg.childPackages.get(j); 6787 if (childPkg.packageName.equals(disabledChildPackageName)) { 6788 disabledPackageAvailable = true; 6789 break; 6790 } 6791 } 6792 if (!disabledPackageAvailable) { 6793 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6794 } 6795 } 6796 } 6797 } 6798 } 6799 6800 boolean updatedPkgBetter = false; 6801 // First check if this is a system package that may involve an update 6802 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6803 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6804 // it needs to drop FLAG_PRIVILEGED. 6805 if (locationIsPrivileged(scanFile)) { 6806 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6807 } else { 6808 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6809 } 6810 6811 if (ps != null && !ps.codePath.equals(scanFile)) { 6812 // The path has changed from what was last scanned... check the 6813 // version of the new path against what we have stored to determine 6814 // what to do. 6815 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6816 if (pkg.mVersionCode <= ps.versionCode) { 6817 // The system package has been updated and the code path does not match 6818 // Ignore entry. Skip it. 6819 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6820 + " ignored: updated version " + ps.versionCode 6821 + " better than this " + pkg.mVersionCode); 6822 if (!updatedPkg.codePath.equals(scanFile)) { 6823 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6824 + ps.name + " changing from " + updatedPkg.codePathString 6825 + " to " + scanFile); 6826 updatedPkg.codePath = scanFile; 6827 updatedPkg.codePathString = scanFile.toString(); 6828 updatedPkg.resourcePath = scanFile; 6829 updatedPkg.resourcePathString = scanFile.toString(); 6830 } 6831 updatedPkg.pkg = pkg; 6832 updatedPkg.versionCode = pkg.mVersionCode; 6833 6834 // Update the disabled system child packages to point to the package too. 6835 final int childCount = updatedPkg.childPackageNames != null 6836 ? updatedPkg.childPackageNames.size() : 0; 6837 for (int i = 0; i < childCount; i++) { 6838 String childPackageName = updatedPkg.childPackageNames.get(i); 6839 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6840 childPackageName); 6841 if (updatedChildPkg != null) { 6842 updatedChildPkg.pkg = pkg; 6843 updatedChildPkg.versionCode = pkg.mVersionCode; 6844 } 6845 } 6846 6847 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6848 + scanFile + " ignored: updated version " + ps.versionCode 6849 + " better than this " + pkg.mVersionCode); 6850 } else { 6851 // The current app on the system partition is better than 6852 // what we have updated to on the data partition; switch 6853 // back to the system partition version. 6854 // At this point, its safely assumed that package installation for 6855 // apps in system partition will go through. If not there won't be a working 6856 // version of the app 6857 // writer 6858 synchronized (mPackages) { 6859 // Just remove the loaded entries from package lists. 6860 mPackages.remove(ps.name); 6861 } 6862 6863 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6864 + " reverting from " + ps.codePathString 6865 + ": new version " + pkg.mVersionCode 6866 + " better than installed " + ps.versionCode); 6867 6868 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6869 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6870 synchronized (mInstallLock) { 6871 args.cleanUpResourcesLI(); 6872 } 6873 synchronized (mPackages) { 6874 mSettings.enableSystemPackageLPw(ps.name); 6875 } 6876 updatedPkgBetter = true; 6877 } 6878 } 6879 } 6880 6881 if (updatedPkg != null) { 6882 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6883 // initially 6884 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6885 6886 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6887 // flag set initially 6888 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6889 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6890 } 6891 } 6892 6893 // Verify certificates against what was last scanned 6894 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6895 6896 /* 6897 * A new system app appeared, but we already had a non-system one of the 6898 * same name installed earlier. 6899 */ 6900 boolean shouldHideSystemApp = false; 6901 if (updatedPkg == null && ps != null 6902 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6903 /* 6904 * Check to make sure the signatures match first. If they don't, 6905 * wipe the installed application and its data. 6906 */ 6907 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6908 != PackageManager.SIGNATURE_MATCH) { 6909 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6910 + " signatures don't match existing userdata copy; removing"); 6911 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6912 "scanPackageInternalLI")) { 6913 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6914 } 6915 ps = null; 6916 } else { 6917 /* 6918 * If the newly-added system app is an older version than the 6919 * already installed version, hide it. It will be scanned later 6920 * and re-added like an update. 6921 */ 6922 if (pkg.mVersionCode <= ps.versionCode) { 6923 shouldHideSystemApp = true; 6924 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6925 + " but new version " + pkg.mVersionCode + " better than installed " 6926 + ps.versionCode + "; hiding system"); 6927 } else { 6928 /* 6929 * The newly found system app is a newer version that the 6930 * one previously installed. Simply remove the 6931 * already-installed application and replace it with our own 6932 * while keeping the application data. 6933 */ 6934 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6935 + " reverting from " + ps.codePathString + ": new version " 6936 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6937 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6938 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6939 synchronized (mInstallLock) { 6940 args.cleanUpResourcesLI(); 6941 } 6942 } 6943 } 6944 } 6945 6946 // The apk is forward locked (not public) if its code and resources 6947 // are kept in different files. (except for app in either system or 6948 // vendor path). 6949 // TODO grab this value from PackageSettings 6950 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6951 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6952 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6953 } 6954 } 6955 6956 // TODO: extend to support forward-locked splits 6957 String resourcePath = null; 6958 String baseResourcePath = null; 6959 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6960 if (ps != null && ps.resourcePathString != null) { 6961 resourcePath = ps.resourcePathString; 6962 baseResourcePath = ps.resourcePathString; 6963 } else { 6964 // Should not happen at all. Just log an error. 6965 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6966 } 6967 } else { 6968 resourcePath = pkg.codePath; 6969 baseResourcePath = pkg.baseCodePath; 6970 } 6971 6972 // Set application objects path explicitly. 6973 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6974 pkg.setApplicationInfoCodePath(pkg.codePath); 6975 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6976 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6977 pkg.setApplicationInfoResourcePath(resourcePath); 6978 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6979 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6980 6981 // Note that we invoke the following method only if we are about to unpack an application 6982 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6983 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6984 6985 /* 6986 * If the system app should be overridden by a previously installed 6987 * data, hide the system app now and let the /data/app scan pick it up 6988 * again. 6989 */ 6990 if (shouldHideSystemApp) { 6991 synchronized (mPackages) { 6992 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6993 } 6994 } 6995 6996 return scannedPkg; 6997 } 6998 6999 private static String fixProcessName(String defProcessName, 7000 String processName, int uid) { 7001 if (processName == null) { 7002 return defProcessName; 7003 } 7004 return processName; 7005 } 7006 7007 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7008 throws PackageManagerException { 7009 if (pkgSetting.signatures.mSignatures != null) { 7010 // Already existing package. Make sure signatures match 7011 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7012 == PackageManager.SIGNATURE_MATCH; 7013 if (!match) { 7014 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7015 == PackageManager.SIGNATURE_MATCH; 7016 } 7017 if (!match) { 7018 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7019 == PackageManager.SIGNATURE_MATCH; 7020 } 7021 if (!match) { 7022 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7023 + pkg.packageName + " signatures do not match the " 7024 + "previously installed version; ignoring!"); 7025 } 7026 } 7027 7028 // Check for shared user signatures 7029 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7030 // Already existing package. Make sure signatures match 7031 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7032 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7033 if (!match) { 7034 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7035 == PackageManager.SIGNATURE_MATCH; 7036 } 7037 if (!match) { 7038 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7039 == PackageManager.SIGNATURE_MATCH; 7040 } 7041 if (!match) { 7042 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7043 "Package " + pkg.packageName 7044 + " has no signatures that match those in shared user " 7045 + pkgSetting.sharedUser.name + "; ignoring!"); 7046 } 7047 } 7048 } 7049 7050 /** 7051 * Enforces that only the system UID or root's UID can call a method exposed 7052 * via Binder. 7053 * 7054 * @param message used as message if SecurityException is thrown 7055 * @throws SecurityException if the caller is not system or root 7056 */ 7057 private static final void enforceSystemOrRoot(String message) { 7058 final int uid = Binder.getCallingUid(); 7059 if (uid != Process.SYSTEM_UID && uid != 0) { 7060 throw new SecurityException(message); 7061 } 7062 } 7063 7064 @Override 7065 public void performFstrimIfNeeded() { 7066 enforceSystemOrRoot("Only the system can request fstrim"); 7067 7068 // Before everything else, see whether we need to fstrim. 7069 try { 7070 IMountService ms = PackageHelper.getMountService(); 7071 if (ms != null) { 7072 boolean doTrim = false; 7073 final long interval = android.provider.Settings.Global.getLong( 7074 mContext.getContentResolver(), 7075 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7076 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7077 if (interval > 0) { 7078 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7079 if (timeSinceLast > interval) { 7080 doTrim = true; 7081 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7082 + "; running immediately"); 7083 } 7084 } 7085 if (doTrim) { 7086 if (!isFirstBoot()) { 7087 try { 7088 ActivityManagerNative.getDefault().showBootMessage( 7089 mContext.getResources().getString( 7090 R.string.android_upgrading_fstrim), true); 7091 } catch (RemoteException e) { 7092 } 7093 } 7094 ms.runMaintenance(); 7095 } 7096 } else { 7097 Slog.e(TAG, "Mount service unavailable!"); 7098 } 7099 } catch (RemoteException e) { 7100 // Can't happen; MountService is local 7101 } 7102 } 7103 7104 @Override 7105 public void updatePackagesIfNeeded() { 7106 enforceSystemOrRoot("Only the system can request package update"); 7107 7108 // We need to re-extract after an OTA. 7109 boolean causeUpgrade = isUpgrade(); 7110 7111 // First boot or factory reset. 7112 // Note: we also handle devices that are upgrading to N right now as if it is their 7113 // first boot, as they do not have profile data. 7114 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7115 7116 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7117 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7118 7119 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7120 return; 7121 } 7122 7123 List<PackageParser.Package> pkgs; 7124 synchronized (mPackages) { 7125 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7126 } 7127 7128 final long startTime = System.nanoTime(); 7129 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7130 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7131 7132 final int elapsedTimeSeconds = 7133 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7134 7135 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7136 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7137 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7138 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7139 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7140 } 7141 7142 /** 7143 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7144 * containing statistics about the invocation. The array consists of three elements, 7145 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7146 * and {@code numberOfPackagesFailed}. 7147 */ 7148 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7149 String compilerFilter) { 7150 7151 int numberOfPackagesVisited = 0; 7152 int numberOfPackagesOptimized = 0; 7153 int numberOfPackagesSkipped = 0; 7154 int numberOfPackagesFailed = 0; 7155 final int numberOfPackagesToDexopt = pkgs.size(); 7156 7157 for (PackageParser.Package pkg : pkgs) { 7158 numberOfPackagesVisited++; 7159 7160 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7161 if (DEBUG_DEXOPT) { 7162 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7163 } 7164 numberOfPackagesSkipped++; 7165 continue; 7166 } 7167 7168 if (DEBUG_DEXOPT) { 7169 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7170 numberOfPackagesToDexopt + ": " + pkg.packageName); 7171 } 7172 7173 if (showDialog) { 7174 try { 7175 ActivityManagerNative.getDefault().showBootMessage( 7176 mContext.getResources().getString(R.string.android_upgrading_apk, 7177 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7178 } catch (RemoteException e) { 7179 } 7180 } 7181 7182 // If the OTA updates a system app which was previously preopted to a non-preopted state 7183 // the app might end up being verified at runtime. That's because by default the apps 7184 // are verify-profile but for preopted apps there's no profile. 7185 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7186 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7187 // filter (by default interpret-only). 7188 // Note that at this stage unused apps are already filtered. 7189 if (isSystemApp(pkg) && 7190 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7191 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7192 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7193 } 7194 7195 // checkProfiles is false to avoid merging profiles during boot which 7196 // might interfere with background compilation (b/28612421). 7197 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7198 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7199 // trade-off worth doing to save boot time work. 7200 int dexOptStatus = performDexOptTraced(pkg.packageName, 7201 false /* checkProfiles */, 7202 compilerFilter, 7203 false /* force */); 7204 switch (dexOptStatus) { 7205 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7206 numberOfPackagesOptimized++; 7207 break; 7208 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7209 numberOfPackagesSkipped++; 7210 break; 7211 case PackageDexOptimizer.DEX_OPT_FAILED: 7212 numberOfPackagesFailed++; 7213 break; 7214 default: 7215 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7216 break; 7217 } 7218 } 7219 7220 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7221 numberOfPackagesFailed }; 7222 } 7223 7224 @Override 7225 public void notifyPackageUse(String packageName, int reason) { 7226 synchronized (mPackages) { 7227 PackageParser.Package p = mPackages.get(packageName); 7228 if (p == null) { 7229 return; 7230 } 7231 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7232 } 7233 } 7234 7235 // TODO: this is not used nor needed. Delete it. 7236 @Override 7237 public boolean performDexOptIfNeeded(String packageName) { 7238 int dexOptStatus = performDexOptTraced(packageName, 7239 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7240 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7241 } 7242 7243 @Override 7244 public boolean performDexOpt(String packageName, 7245 boolean checkProfiles, int compileReason, boolean force) { 7246 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7247 getCompilerFilterForReason(compileReason), force); 7248 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7249 } 7250 7251 @Override 7252 public boolean performDexOptMode(String packageName, 7253 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7254 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7255 targetCompilerFilter, force); 7256 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7257 } 7258 7259 private int performDexOptTraced(String packageName, 7260 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7262 try { 7263 return performDexOptInternal(packageName, checkProfiles, 7264 targetCompilerFilter, force); 7265 } finally { 7266 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7267 } 7268 } 7269 7270 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7271 // if the package can now be considered up to date for the given filter. 7272 private int performDexOptInternal(String packageName, 7273 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7274 PackageParser.Package p; 7275 synchronized (mPackages) { 7276 p = mPackages.get(packageName); 7277 if (p == null) { 7278 // Package could not be found. Report failure. 7279 return PackageDexOptimizer.DEX_OPT_FAILED; 7280 } 7281 mPackageUsage.maybeWriteAsync(mPackages); 7282 mCompilerStats.maybeWriteAsync(); 7283 } 7284 long callingId = Binder.clearCallingIdentity(); 7285 try { 7286 synchronized (mInstallLock) { 7287 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7288 targetCompilerFilter, force); 7289 } 7290 } finally { 7291 Binder.restoreCallingIdentity(callingId); 7292 } 7293 } 7294 7295 public ArraySet<String> getOptimizablePackages() { 7296 ArraySet<String> pkgs = new ArraySet<String>(); 7297 synchronized (mPackages) { 7298 for (PackageParser.Package p : mPackages.values()) { 7299 if (PackageDexOptimizer.canOptimizePackage(p)) { 7300 pkgs.add(p.packageName); 7301 } 7302 } 7303 } 7304 return pkgs; 7305 } 7306 7307 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7308 boolean checkProfiles, String targetCompilerFilter, 7309 boolean force) { 7310 // Select the dex optimizer based on the force parameter. 7311 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7312 // allocate an object here. 7313 PackageDexOptimizer pdo = force 7314 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7315 : mPackageDexOptimizer; 7316 7317 // Optimize all dependencies first. Note: we ignore the return value and march on 7318 // on errors. 7319 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7320 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7321 if (!deps.isEmpty()) { 7322 for (PackageParser.Package depPackage : deps) { 7323 // TODO: Analyze and investigate if we (should) profile libraries. 7324 // Currently this will do a full compilation of the library by default. 7325 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7326 false /* checkProfiles */, 7327 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7328 getOrCreateCompilerPackageStats(depPackage)); 7329 } 7330 } 7331 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7332 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7333 } 7334 7335 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7336 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7337 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7338 Set<String> collectedNames = new HashSet<>(); 7339 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7340 7341 retValue.remove(p); 7342 7343 return retValue; 7344 } else { 7345 return Collections.emptyList(); 7346 } 7347 } 7348 7349 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7350 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7351 if (!collectedNames.contains(p.packageName)) { 7352 collectedNames.add(p.packageName); 7353 collected.add(p); 7354 7355 if (p.usesLibraries != null) { 7356 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7357 } 7358 if (p.usesOptionalLibraries != null) { 7359 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7360 collectedNames); 7361 } 7362 } 7363 } 7364 7365 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7366 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7367 for (String libName : libs) { 7368 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7369 if (libPkg != null) { 7370 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7371 } 7372 } 7373 } 7374 7375 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7376 synchronized (mPackages) { 7377 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7378 if (lib != null && lib.apk != null) { 7379 return mPackages.get(lib.apk); 7380 } 7381 } 7382 return null; 7383 } 7384 7385 public void shutdown() { 7386 mPackageUsage.writeNow(mPackages); 7387 mCompilerStats.writeNow(); 7388 } 7389 7390 @Override 7391 public void dumpProfiles(String packageName) { 7392 PackageParser.Package pkg; 7393 synchronized (mPackages) { 7394 pkg = mPackages.get(packageName); 7395 if (pkg == null) { 7396 throw new IllegalArgumentException("Unknown package: " + packageName); 7397 } 7398 } 7399 /* Only the shell, root, or the app user should be able to dump profiles. */ 7400 int callingUid = Binder.getCallingUid(); 7401 if (callingUid != Process.SHELL_UID && 7402 callingUid != Process.ROOT_UID && 7403 callingUid != pkg.applicationInfo.uid) { 7404 throw new SecurityException("dumpProfiles"); 7405 } 7406 7407 synchronized (mInstallLock) { 7408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7409 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7410 try { 7411 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7412 String gid = Integer.toString(sharedGid); 7413 String codePaths = TextUtils.join(";", allCodePaths); 7414 mInstaller.dumpProfiles(gid, packageName, codePaths); 7415 } catch (InstallerException e) { 7416 Slog.w(TAG, "Failed to dump profiles", e); 7417 } 7418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7419 } 7420 } 7421 7422 @Override 7423 public void forceDexOpt(String packageName) { 7424 enforceSystemOrRoot("forceDexOpt"); 7425 7426 PackageParser.Package pkg; 7427 synchronized (mPackages) { 7428 pkg = mPackages.get(packageName); 7429 if (pkg == null) { 7430 throw new IllegalArgumentException("Unknown package: " + packageName); 7431 } 7432 } 7433 7434 synchronized (mInstallLock) { 7435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7436 7437 // Whoever is calling forceDexOpt wants a fully compiled package. 7438 // Don't use profiles since that may cause compilation to be skipped. 7439 final int res = performDexOptInternalWithDependenciesLI(pkg, 7440 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7441 true /* force */); 7442 7443 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7444 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7445 throw new IllegalStateException("Failed to dexopt: " + res); 7446 } 7447 } 7448 } 7449 7450 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7451 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7452 Slog.w(TAG, "Unable to update from " + oldPkg.name 7453 + " to " + newPkg.packageName 7454 + ": old package not in system partition"); 7455 return false; 7456 } else if (mPackages.get(oldPkg.name) != null) { 7457 Slog.w(TAG, "Unable to update from " + oldPkg.name 7458 + " to " + newPkg.packageName 7459 + ": old package still exists"); 7460 return false; 7461 } 7462 return true; 7463 } 7464 7465 void removeCodePathLI(File codePath) { 7466 if (codePath.isDirectory()) { 7467 try { 7468 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7469 } catch (InstallerException e) { 7470 Slog.w(TAG, "Failed to remove code path", e); 7471 } 7472 } else { 7473 codePath.delete(); 7474 } 7475 } 7476 7477 private int[] resolveUserIds(int userId) { 7478 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7479 } 7480 7481 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7482 if (pkg == null) { 7483 Slog.wtf(TAG, "Package was null!", new Throwable()); 7484 return; 7485 } 7486 clearAppDataLeafLIF(pkg, userId, flags); 7487 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7488 for (int i = 0; i < childCount; i++) { 7489 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7490 } 7491 } 7492 7493 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7494 final PackageSetting ps; 7495 synchronized (mPackages) { 7496 ps = mSettings.mPackages.get(pkg.packageName); 7497 } 7498 for (int realUserId : resolveUserIds(userId)) { 7499 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7500 try { 7501 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7502 ceDataInode); 7503 } catch (InstallerException e) { 7504 Slog.w(TAG, String.valueOf(e)); 7505 } 7506 } 7507 } 7508 7509 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7510 if (pkg == null) { 7511 Slog.wtf(TAG, "Package was null!", new Throwable()); 7512 return; 7513 } 7514 destroyAppDataLeafLIF(pkg, userId, flags); 7515 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7516 for (int i = 0; i < childCount; i++) { 7517 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7518 } 7519 } 7520 7521 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7522 final PackageSetting ps; 7523 synchronized (mPackages) { 7524 ps = mSettings.mPackages.get(pkg.packageName); 7525 } 7526 for (int realUserId : resolveUserIds(userId)) { 7527 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7528 try { 7529 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7530 ceDataInode); 7531 } catch (InstallerException e) { 7532 Slog.w(TAG, String.valueOf(e)); 7533 } 7534 } 7535 } 7536 7537 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7538 if (pkg == null) { 7539 Slog.wtf(TAG, "Package was null!", new Throwable()); 7540 return; 7541 } 7542 destroyAppProfilesLeafLIF(pkg); 7543 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7544 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7545 for (int i = 0; i < childCount; i++) { 7546 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7547 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7548 true /* removeBaseMarker */); 7549 } 7550 } 7551 7552 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7553 boolean removeBaseMarker) { 7554 if (pkg.isForwardLocked()) { 7555 return; 7556 } 7557 7558 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7559 try { 7560 path = PackageManagerServiceUtils.realpath(new File(path)); 7561 } catch (IOException e) { 7562 // TODO: Should we return early here ? 7563 Slog.w(TAG, "Failed to get canonical path", e); 7564 continue; 7565 } 7566 7567 final String useMarker = path.replace('/', '@'); 7568 for (int realUserId : resolveUserIds(userId)) { 7569 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7570 if (removeBaseMarker) { 7571 File foreignUseMark = new File(profileDir, useMarker); 7572 if (foreignUseMark.exists()) { 7573 if (!foreignUseMark.delete()) { 7574 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7575 + pkg.packageName); 7576 } 7577 } 7578 } 7579 7580 File[] markers = profileDir.listFiles(); 7581 if (markers != null) { 7582 final String searchString = "@" + pkg.packageName + "@"; 7583 // We also delete all markers that contain the package name we're 7584 // uninstalling. These are associated with secondary dex-files belonging 7585 // to the package. Reconstructing the path of these dex files is messy 7586 // in general. 7587 for (File marker : markers) { 7588 if (marker.getName().indexOf(searchString) > 0) { 7589 if (!marker.delete()) { 7590 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7591 + pkg.packageName); 7592 } 7593 } 7594 } 7595 } 7596 } 7597 } 7598 } 7599 7600 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7601 try { 7602 mInstaller.destroyAppProfiles(pkg.packageName); 7603 } catch (InstallerException e) { 7604 Slog.w(TAG, String.valueOf(e)); 7605 } 7606 } 7607 7608 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7609 if (pkg == null) { 7610 Slog.wtf(TAG, "Package was null!", new Throwable()); 7611 return; 7612 } 7613 clearAppProfilesLeafLIF(pkg); 7614 // We don't remove the base foreign use marker when clearing profiles because 7615 // we will rename it when the app is updated. Unlike the actual profile contents, 7616 // the foreign use marker is good across installs. 7617 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7618 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7619 for (int i = 0; i < childCount; i++) { 7620 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7621 } 7622 } 7623 7624 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7625 try { 7626 mInstaller.clearAppProfiles(pkg.packageName); 7627 } catch (InstallerException e) { 7628 Slog.w(TAG, String.valueOf(e)); 7629 } 7630 } 7631 7632 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7633 long lastUpdateTime) { 7634 // Set parent install/update time 7635 PackageSetting ps = (PackageSetting) pkg.mExtras; 7636 if (ps != null) { 7637 ps.firstInstallTime = firstInstallTime; 7638 ps.lastUpdateTime = lastUpdateTime; 7639 } 7640 // Set children install/update time 7641 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7642 for (int i = 0; i < childCount; i++) { 7643 PackageParser.Package childPkg = pkg.childPackages.get(i); 7644 ps = (PackageSetting) childPkg.mExtras; 7645 if (ps != null) { 7646 ps.firstInstallTime = firstInstallTime; 7647 ps.lastUpdateTime = lastUpdateTime; 7648 } 7649 } 7650 } 7651 7652 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7653 PackageParser.Package changingLib) { 7654 if (file.path != null) { 7655 usesLibraryFiles.add(file.path); 7656 return; 7657 } 7658 PackageParser.Package p = mPackages.get(file.apk); 7659 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7660 // If we are doing this while in the middle of updating a library apk, 7661 // then we need to make sure to use that new apk for determining the 7662 // dependencies here. (We haven't yet finished committing the new apk 7663 // to the package manager state.) 7664 if (p == null || p.packageName.equals(changingLib.packageName)) { 7665 p = changingLib; 7666 } 7667 } 7668 if (p != null) { 7669 usesLibraryFiles.addAll(p.getAllCodePaths()); 7670 } 7671 } 7672 7673 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7674 PackageParser.Package changingLib) throws PackageManagerException { 7675 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7676 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7677 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7678 for (int i=0; i<N; i++) { 7679 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7680 if (file == null) { 7681 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7682 "Package " + pkg.packageName + " requires unavailable shared library " 7683 + pkg.usesLibraries.get(i) + "; failing!"); 7684 } 7685 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7686 } 7687 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7688 for (int i=0; i<N; i++) { 7689 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7690 if (file == null) { 7691 Slog.w(TAG, "Package " + pkg.packageName 7692 + " desires unavailable shared library " 7693 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7694 } else { 7695 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7696 } 7697 } 7698 N = usesLibraryFiles.size(); 7699 if (N > 0) { 7700 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7701 } else { 7702 pkg.usesLibraryFiles = null; 7703 } 7704 } 7705 } 7706 7707 private static boolean hasString(List<String> list, List<String> which) { 7708 if (list == null) { 7709 return false; 7710 } 7711 for (int i=list.size()-1; i>=0; i--) { 7712 for (int j=which.size()-1; j>=0; j--) { 7713 if (which.get(j).equals(list.get(i))) { 7714 return true; 7715 } 7716 } 7717 } 7718 return false; 7719 } 7720 7721 private void updateAllSharedLibrariesLPw() { 7722 for (PackageParser.Package pkg : mPackages.values()) { 7723 try { 7724 updateSharedLibrariesLPw(pkg, null); 7725 } catch (PackageManagerException e) { 7726 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7727 } 7728 } 7729 } 7730 7731 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7732 PackageParser.Package changingPkg) { 7733 ArrayList<PackageParser.Package> res = null; 7734 for (PackageParser.Package pkg : mPackages.values()) { 7735 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7736 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7737 if (res == null) { 7738 res = new ArrayList<PackageParser.Package>(); 7739 } 7740 res.add(pkg); 7741 try { 7742 updateSharedLibrariesLPw(pkg, changingPkg); 7743 } catch (PackageManagerException e) { 7744 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7745 } 7746 } 7747 } 7748 return res; 7749 } 7750 7751 /** 7752 * Derive the value of the {@code cpuAbiOverride} based on the provided 7753 * value and an optional stored value from the package settings. 7754 */ 7755 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7756 String cpuAbiOverride = null; 7757 7758 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7759 cpuAbiOverride = null; 7760 } else if (abiOverride != null) { 7761 cpuAbiOverride = abiOverride; 7762 } else if (settings != null) { 7763 cpuAbiOverride = settings.cpuAbiOverrideString; 7764 } 7765 7766 return cpuAbiOverride; 7767 } 7768 7769 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7770 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7771 throws PackageManagerException { 7772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7773 // If the package has children and this is the first dive in the function 7774 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7775 // whether all packages (parent and children) would be successfully scanned 7776 // before the actual scan since scanning mutates internal state and we want 7777 // to atomically install the package and its children. 7778 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7779 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7780 scanFlags |= SCAN_CHECK_ONLY; 7781 } 7782 } else { 7783 scanFlags &= ~SCAN_CHECK_ONLY; 7784 } 7785 7786 final PackageParser.Package scannedPkg; 7787 try { 7788 // Scan the parent 7789 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7790 // Scan the children 7791 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7792 for (int i = 0; i < childCount; i++) { 7793 PackageParser.Package childPkg = pkg.childPackages.get(i); 7794 scanPackageLI(childPkg, policyFlags, 7795 scanFlags, currentTime, user); 7796 } 7797 } finally { 7798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7799 } 7800 7801 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7802 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7803 } 7804 7805 return scannedPkg; 7806 } 7807 7808 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7809 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7810 boolean success = false; 7811 try { 7812 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7813 currentTime, user); 7814 success = true; 7815 return res; 7816 } finally { 7817 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7818 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7819 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7820 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7821 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7822 } 7823 } 7824 } 7825 7826 /** 7827 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7828 */ 7829 private static boolean apkHasCode(String fileName) { 7830 StrictJarFile jarFile = null; 7831 try { 7832 jarFile = new StrictJarFile(fileName, 7833 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7834 return jarFile.findEntry("classes.dex") != null; 7835 } catch (IOException ignore) { 7836 } finally { 7837 try { 7838 if (jarFile != null) { 7839 jarFile.close(); 7840 } 7841 } catch (IOException ignore) {} 7842 } 7843 return false; 7844 } 7845 7846 /** 7847 * Enforces code policy for the package. This ensures that if an APK has 7848 * declared hasCode="true" in its manifest that the APK actually contains 7849 * code. 7850 * 7851 * @throws PackageManagerException If bytecode could not be found when it should exist 7852 */ 7853 private static void enforceCodePolicy(PackageParser.Package pkg) 7854 throws PackageManagerException { 7855 final boolean shouldHaveCode = 7856 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7857 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7858 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7859 "Package " + pkg.baseCodePath + " code is missing"); 7860 } 7861 7862 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7863 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7864 final boolean splitShouldHaveCode = 7865 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7866 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7867 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7868 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7869 } 7870 } 7871 } 7872 } 7873 7874 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7875 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7876 throws PackageManagerException { 7877 final File scanFile = new File(pkg.codePath); 7878 if (pkg.applicationInfo.getCodePath() == null || 7879 pkg.applicationInfo.getResourcePath() == null) { 7880 // Bail out. The resource and code paths haven't been set. 7881 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7882 "Code and resource paths haven't been set correctly"); 7883 } 7884 7885 // Apply policy 7886 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7887 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7888 if (pkg.applicationInfo.isDirectBootAware()) { 7889 // we're direct boot aware; set for all components 7890 for (PackageParser.Service s : pkg.services) { 7891 s.info.encryptionAware = s.info.directBootAware = true; 7892 } 7893 for (PackageParser.Provider p : pkg.providers) { 7894 p.info.encryptionAware = p.info.directBootAware = true; 7895 } 7896 for (PackageParser.Activity a : pkg.activities) { 7897 a.info.encryptionAware = a.info.directBootAware = true; 7898 } 7899 for (PackageParser.Activity r : pkg.receivers) { 7900 r.info.encryptionAware = r.info.directBootAware = true; 7901 } 7902 } 7903 } else { 7904 // Only allow system apps to be flagged as core apps. 7905 pkg.coreApp = false; 7906 // clear flags not applicable to regular apps 7907 pkg.applicationInfo.privateFlags &= 7908 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7909 pkg.applicationInfo.privateFlags &= 7910 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7911 } 7912 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7913 7914 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7915 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7916 } 7917 7918 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7919 enforceCodePolicy(pkg); 7920 } 7921 7922 if (mCustomResolverComponentName != null && 7923 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7924 setUpCustomResolverActivity(pkg); 7925 } 7926 7927 if (pkg.packageName.equals("android")) { 7928 synchronized (mPackages) { 7929 if (mAndroidApplication != null) { 7930 Slog.w(TAG, "*************************************************"); 7931 Slog.w(TAG, "Core android package being redefined. Skipping."); 7932 Slog.w(TAG, " file=" + scanFile); 7933 Slog.w(TAG, "*************************************************"); 7934 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7935 "Core android package being redefined. Skipping."); 7936 } 7937 7938 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7939 // Set up information for our fall-back user intent resolution activity. 7940 mPlatformPackage = pkg; 7941 pkg.mVersionCode = mSdkVersion; 7942 mAndroidApplication = pkg.applicationInfo; 7943 7944 if (!mResolverReplaced) { 7945 mResolveActivity.applicationInfo = mAndroidApplication; 7946 mResolveActivity.name = ResolverActivity.class.getName(); 7947 mResolveActivity.packageName = mAndroidApplication.packageName; 7948 mResolveActivity.processName = "system:ui"; 7949 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7950 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7951 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7952 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7953 mResolveActivity.exported = true; 7954 mResolveActivity.enabled = true; 7955 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7956 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7957 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7958 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7959 | ActivityInfo.CONFIG_ORIENTATION 7960 | ActivityInfo.CONFIG_KEYBOARD 7961 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7962 mResolveInfo.activityInfo = mResolveActivity; 7963 mResolveInfo.priority = 0; 7964 mResolveInfo.preferredOrder = 0; 7965 mResolveInfo.match = 0; 7966 mResolveComponentName = new ComponentName( 7967 mAndroidApplication.packageName, mResolveActivity.name); 7968 } 7969 } 7970 } 7971 } 7972 7973 if (DEBUG_PACKAGE_SCANNING) { 7974 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7975 Log.d(TAG, "Scanning package " + pkg.packageName); 7976 } 7977 7978 synchronized (mPackages) { 7979 if (mPackages.containsKey(pkg.packageName) 7980 || mSharedLibraries.containsKey(pkg.packageName)) { 7981 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7982 "Application package " + pkg.packageName 7983 + " already installed. Skipping duplicate."); 7984 } 7985 7986 // If we're only installing presumed-existing packages, require that the 7987 // scanned APK is both already known and at the path previously established 7988 // for it. Previously unknown packages we pick up normally, but if we have an 7989 // a priori expectation about this package's install presence, enforce it. 7990 // With a singular exception for new system packages. When an OTA contains 7991 // a new system package, we allow the codepath to change from a system location 7992 // to the user-installed location. If we don't allow this change, any newer, 7993 // user-installed version of the application will be ignored. 7994 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7995 if (mExpectingBetter.containsKey(pkg.packageName)) { 7996 logCriticalInfo(Log.WARN, 7997 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7998 } else { 7999 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8000 if (known != null) { 8001 if (DEBUG_PACKAGE_SCANNING) { 8002 Log.d(TAG, "Examining " + pkg.codePath 8003 + " and requiring known paths " + known.codePathString 8004 + " & " + known.resourcePathString); 8005 } 8006 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8007 || !pkg.applicationInfo.getResourcePath().equals( 8008 known.resourcePathString)) { 8009 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8010 "Application package " + pkg.packageName 8011 + " found at " + pkg.applicationInfo.getCodePath() 8012 + " but expected at " + known.codePathString 8013 + "; ignoring."); 8014 } 8015 } 8016 } 8017 } 8018 } 8019 8020 // Initialize package source and resource directories 8021 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8022 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8023 8024 SharedUserSetting suid = null; 8025 PackageSetting pkgSetting = null; 8026 8027 if (!isSystemApp(pkg)) { 8028 // Only system apps can use these features. 8029 pkg.mOriginalPackages = null; 8030 pkg.mRealPackage = null; 8031 pkg.mAdoptPermissions = null; 8032 } 8033 8034 // Getting the package setting may have a side-effect, so if we 8035 // are only checking if scan would succeed, stash a copy of the 8036 // old setting to restore at the end. 8037 PackageSetting nonMutatedPs = null; 8038 8039 // writer 8040 synchronized (mPackages) { 8041 if (pkg.mSharedUserId != null) { 8042 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8043 if (suid == null) { 8044 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8045 "Creating application package " + pkg.packageName 8046 + " for shared user failed"); 8047 } 8048 if (DEBUG_PACKAGE_SCANNING) { 8049 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8050 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8051 + "): packages=" + suid.packages); 8052 } 8053 } 8054 8055 // Check if we are renaming from an original package name. 8056 PackageSetting origPackage = null; 8057 String realName = null; 8058 if (pkg.mOriginalPackages != null) { 8059 // This package may need to be renamed to a previously 8060 // installed name. Let's check on that... 8061 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8062 if (pkg.mOriginalPackages.contains(renamed)) { 8063 // This package had originally been installed as the 8064 // original name, and we have already taken care of 8065 // transitioning to the new one. Just update the new 8066 // one to continue using the old name. 8067 realName = pkg.mRealPackage; 8068 if (!pkg.packageName.equals(renamed)) { 8069 // Callers into this function may have already taken 8070 // care of renaming the package; only do it here if 8071 // it is not already done. 8072 pkg.setPackageName(renamed); 8073 } 8074 8075 } else { 8076 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8077 if ((origPackage = mSettings.peekPackageLPr( 8078 pkg.mOriginalPackages.get(i))) != null) { 8079 // We do have the package already installed under its 8080 // original name... should we use it? 8081 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8082 // New package is not compatible with original. 8083 origPackage = null; 8084 continue; 8085 } else if (origPackage.sharedUser != null) { 8086 // Make sure uid is compatible between packages. 8087 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8088 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8089 + " to " + pkg.packageName + ": old uid " 8090 + origPackage.sharedUser.name 8091 + " differs from " + pkg.mSharedUserId); 8092 origPackage = null; 8093 continue; 8094 } 8095 // TODO: Add case when shared user id is added [b/28144775] 8096 } else { 8097 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8098 + pkg.packageName + " to old name " + origPackage.name); 8099 } 8100 break; 8101 } 8102 } 8103 } 8104 } 8105 8106 if (mTransferedPackages.contains(pkg.packageName)) { 8107 Slog.w(TAG, "Package " + pkg.packageName 8108 + " was transferred to another, but its .apk remains"); 8109 } 8110 8111 // See comments in nonMutatedPs declaration 8112 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8113 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8114 if (foundPs != null) { 8115 nonMutatedPs = new PackageSetting(foundPs); 8116 } 8117 } 8118 8119 // Just create the setting, don't add it yet. For already existing packages 8120 // the PkgSetting exists already and doesn't have to be created. 8121 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8122 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8123 pkg.applicationInfo.primaryCpuAbi, 8124 pkg.applicationInfo.secondaryCpuAbi, 8125 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8126 user, false); 8127 if (pkgSetting == null) { 8128 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8129 "Creating application package " + pkg.packageName + " failed"); 8130 } 8131 8132 if (pkgSetting.origPackage != null) { 8133 // If we are first transitioning from an original package, 8134 // fix up the new package's name now. We need to do this after 8135 // looking up the package under its new name, so getPackageLP 8136 // can take care of fiddling things correctly. 8137 pkg.setPackageName(origPackage.name); 8138 8139 // File a report about this. 8140 String msg = "New package " + pkgSetting.realName 8141 + " renamed to replace old package " + pkgSetting.name; 8142 reportSettingsProblem(Log.WARN, msg); 8143 8144 // Make a note of it. 8145 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8146 mTransferedPackages.add(origPackage.name); 8147 } 8148 8149 // No longer need to retain this. 8150 pkgSetting.origPackage = null; 8151 } 8152 8153 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8154 // Make a note of it. 8155 mTransferedPackages.add(pkg.packageName); 8156 } 8157 8158 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8159 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8160 } 8161 8162 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8163 // Check all shared libraries and map to their actual file path. 8164 // We only do this here for apps not on a system dir, because those 8165 // are the only ones that can fail an install due to this. We 8166 // will take care of the system apps by updating all of their 8167 // library paths after the scan is done. 8168 updateSharedLibrariesLPw(pkg, null); 8169 } 8170 8171 if (mFoundPolicyFile) { 8172 SELinuxMMAC.assignSeinfoValue(pkg); 8173 } 8174 8175 pkg.applicationInfo.uid = pkgSetting.appId; 8176 pkg.mExtras = pkgSetting; 8177 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8178 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8179 // We just determined the app is signed correctly, so bring 8180 // over the latest parsed certs. 8181 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8182 } else { 8183 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8184 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8185 "Package " + pkg.packageName + " upgrade keys do not match the " 8186 + "previously installed version"); 8187 } else { 8188 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8189 String msg = "System package " + pkg.packageName 8190 + " signature changed; retaining data."; 8191 reportSettingsProblem(Log.WARN, msg); 8192 } 8193 } 8194 } else { 8195 try { 8196 verifySignaturesLP(pkgSetting, pkg); 8197 // We just determined the app is signed correctly, so bring 8198 // over the latest parsed certs. 8199 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8200 } catch (PackageManagerException e) { 8201 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8202 throw e; 8203 } 8204 // The signature has changed, but this package is in the system 8205 // image... let's recover! 8206 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8207 // However... if this package is part of a shared user, but it 8208 // doesn't match the signature of the shared user, let's fail. 8209 // What this means is that you can't change the signatures 8210 // associated with an overall shared user, which doesn't seem all 8211 // that unreasonable. 8212 if (pkgSetting.sharedUser != null) { 8213 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8214 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8215 throw new PackageManagerException( 8216 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8217 "Signature mismatch for shared user: " 8218 + pkgSetting.sharedUser); 8219 } 8220 } 8221 // File a report about this. 8222 String msg = "System package " + pkg.packageName 8223 + " signature changed; retaining data."; 8224 reportSettingsProblem(Log.WARN, msg); 8225 } 8226 } 8227 // Verify that this new package doesn't have any content providers 8228 // that conflict with existing packages. Only do this if the 8229 // package isn't already installed, since we don't want to break 8230 // things that are installed. 8231 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8232 final int N = pkg.providers.size(); 8233 int i; 8234 for (i=0; i<N; i++) { 8235 PackageParser.Provider p = pkg.providers.get(i); 8236 if (p.info.authority != null) { 8237 String names[] = p.info.authority.split(";"); 8238 for (int j = 0; j < names.length; j++) { 8239 if (mProvidersByAuthority.containsKey(names[j])) { 8240 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8241 final String otherPackageName = 8242 ((other != null && other.getComponentName() != null) ? 8243 other.getComponentName().getPackageName() : "?"); 8244 throw new PackageManagerException( 8245 INSTALL_FAILED_CONFLICTING_PROVIDER, 8246 "Can't install because provider name " + names[j] 8247 + " (in package " + pkg.applicationInfo.packageName 8248 + ") is already used by " + otherPackageName); 8249 } 8250 } 8251 } 8252 } 8253 } 8254 8255 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8256 // This package wants to adopt ownership of permissions from 8257 // another package. 8258 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8259 final String origName = pkg.mAdoptPermissions.get(i); 8260 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8261 if (orig != null) { 8262 if (verifyPackageUpdateLPr(orig, pkg)) { 8263 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8264 + pkg.packageName); 8265 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8266 } 8267 } 8268 } 8269 } 8270 } 8271 8272 final String pkgName = pkg.packageName; 8273 8274 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8275 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8276 pkg.applicationInfo.processName = fixProcessName( 8277 pkg.applicationInfo.packageName, 8278 pkg.applicationInfo.processName, 8279 pkg.applicationInfo.uid); 8280 8281 if (pkg != mPlatformPackage) { 8282 // Get all of our default paths setup 8283 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8284 } 8285 8286 final String path = scanFile.getPath(); 8287 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8288 8289 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8290 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8291 8292 // Some system apps still use directory structure for native libraries 8293 // in which case we might end up not detecting abi solely based on apk 8294 // structure. Try to detect abi based on directory structure. 8295 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8296 pkg.applicationInfo.primaryCpuAbi == null) { 8297 setBundledAppAbisAndRoots(pkg, pkgSetting); 8298 setNativeLibraryPaths(pkg); 8299 } 8300 8301 } else { 8302 if ((scanFlags & SCAN_MOVE) != 0) { 8303 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8304 // but we already have this packages package info in the PackageSetting. We just 8305 // use that and derive the native library path based on the new codepath. 8306 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8307 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8308 } 8309 8310 // Set native library paths again. For moves, the path will be updated based on the 8311 // ABIs we've determined above. For non-moves, the path will be updated based on the 8312 // ABIs we determined during compilation, but the path will depend on the final 8313 // package path (after the rename away from the stage path). 8314 setNativeLibraryPaths(pkg); 8315 } 8316 8317 // This is a special case for the "system" package, where the ABI is 8318 // dictated by the zygote configuration (and init.rc). We should keep track 8319 // of this ABI so that we can deal with "normal" applications that run under 8320 // the same UID correctly. 8321 if (mPlatformPackage == pkg) { 8322 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8323 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8324 } 8325 8326 // If there's a mismatch between the abi-override in the package setting 8327 // and the abiOverride specified for the install. Warn about this because we 8328 // would've already compiled the app without taking the package setting into 8329 // account. 8330 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8331 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8332 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8333 " for package " + pkg.packageName); 8334 } 8335 } 8336 8337 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8338 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8339 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8340 8341 // Copy the derived override back to the parsed package, so that we can 8342 // update the package settings accordingly. 8343 pkg.cpuAbiOverride = cpuAbiOverride; 8344 8345 if (DEBUG_ABI_SELECTION) { 8346 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8347 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8348 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8349 } 8350 8351 // Push the derived path down into PackageSettings so we know what to 8352 // clean up at uninstall time. 8353 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8354 8355 if (DEBUG_ABI_SELECTION) { 8356 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8357 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8358 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8359 } 8360 8361 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8362 // We don't do this here during boot because we can do it all 8363 // at once after scanning all existing packages. 8364 // 8365 // We also do this *before* we perform dexopt on this package, so that 8366 // we can avoid redundant dexopts, and also to make sure we've got the 8367 // code and package path correct. 8368 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8369 pkg, true /* boot complete */); 8370 } 8371 8372 if (mFactoryTest && pkg.requestedPermissions.contains( 8373 android.Manifest.permission.FACTORY_TEST)) { 8374 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8375 } 8376 8377 if (isSystemApp(pkg)) { 8378 pkgSetting.isOrphaned = true; 8379 } 8380 8381 ArrayList<PackageParser.Package> clientLibPkgs = null; 8382 8383 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8384 if (nonMutatedPs != null) { 8385 synchronized (mPackages) { 8386 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8387 } 8388 } 8389 return pkg; 8390 } 8391 8392 // Only privileged apps and updated privileged apps can add child packages. 8393 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8394 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8395 throw new PackageManagerException("Only privileged apps and updated " 8396 + "privileged apps can add child packages. Ignoring package " 8397 + pkg.packageName); 8398 } 8399 final int childCount = pkg.childPackages.size(); 8400 for (int i = 0; i < childCount; i++) { 8401 PackageParser.Package childPkg = pkg.childPackages.get(i); 8402 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8403 childPkg.packageName)) { 8404 throw new PackageManagerException("Cannot override a child package of " 8405 + "another disabled system app. Ignoring package " + pkg.packageName); 8406 } 8407 } 8408 } 8409 8410 // writer 8411 synchronized (mPackages) { 8412 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8413 // Only system apps can add new shared libraries. 8414 if (pkg.libraryNames != null) { 8415 for (int i=0; i<pkg.libraryNames.size(); i++) { 8416 String name = pkg.libraryNames.get(i); 8417 boolean allowed = false; 8418 if (pkg.isUpdatedSystemApp()) { 8419 // New library entries can only be added through the 8420 // system image. This is important to get rid of a lot 8421 // of nasty edge cases: for example if we allowed a non- 8422 // system update of the app to add a library, then uninstalling 8423 // the update would make the library go away, and assumptions 8424 // we made such as through app install filtering would now 8425 // have allowed apps on the device which aren't compatible 8426 // with it. Better to just have the restriction here, be 8427 // conservative, and create many fewer cases that can negatively 8428 // impact the user experience. 8429 final PackageSetting sysPs = mSettings 8430 .getDisabledSystemPkgLPr(pkg.packageName); 8431 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8432 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8433 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8434 allowed = true; 8435 break; 8436 } 8437 } 8438 } 8439 } else { 8440 allowed = true; 8441 } 8442 if (allowed) { 8443 if (!mSharedLibraries.containsKey(name)) { 8444 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8445 } else if (!name.equals(pkg.packageName)) { 8446 Slog.w(TAG, "Package " + pkg.packageName + " library " 8447 + name + " already exists; skipping"); 8448 } 8449 } else { 8450 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8451 + name + " that is not declared on system image; skipping"); 8452 } 8453 } 8454 if ((scanFlags & SCAN_BOOTING) == 0) { 8455 // If we are not booting, we need to update any applications 8456 // that are clients of our shared library. If we are booting, 8457 // this will all be done once the scan is complete. 8458 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8459 } 8460 } 8461 } 8462 } 8463 8464 if ((scanFlags & SCAN_BOOTING) != 0) { 8465 // No apps can run during boot scan, so they don't need to be frozen 8466 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8467 // Caller asked to not kill app, so it's probably not frozen 8468 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8469 // Caller asked us to ignore frozen check for some reason; they 8470 // probably didn't know the package name 8471 } else { 8472 // We're doing major surgery on this package, so it better be frozen 8473 // right now to keep it from launching 8474 checkPackageFrozen(pkgName); 8475 } 8476 8477 // Also need to kill any apps that are dependent on the library. 8478 if (clientLibPkgs != null) { 8479 for (int i=0; i<clientLibPkgs.size(); i++) { 8480 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8481 killApplication(clientPkg.applicationInfo.packageName, 8482 clientPkg.applicationInfo.uid, "update lib"); 8483 } 8484 } 8485 8486 // Make sure we're not adding any bogus keyset info 8487 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8488 ksms.assertScannedPackageValid(pkg); 8489 8490 // writer 8491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8492 8493 boolean createIdmapFailed = false; 8494 synchronized (mPackages) { 8495 // We don't expect installation to fail beyond this point 8496 8497 if (pkgSetting.pkg != null) { 8498 // Note that |user| might be null during the initial boot scan. If a codePath 8499 // for an app has changed during a boot scan, it's due to an app update that's 8500 // part of the system partition and marker changes must be applied to all users. 8501 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8502 (user != null) ? user : UserHandle.ALL); 8503 } 8504 8505 // Add the new setting to mSettings 8506 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8507 // Add the new setting to mPackages 8508 mPackages.put(pkg.applicationInfo.packageName, pkg); 8509 // Make sure we don't accidentally delete its data. 8510 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8511 while (iter.hasNext()) { 8512 PackageCleanItem item = iter.next(); 8513 if (pkgName.equals(item.packageName)) { 8514 iter.remove(); 8515 } 8516 } 8517 8518 // Take care of first install / last update times. 8519 if (currentTime != 0) { 8520 if (pkgSetting.firstInstallTime == 0) { 8521 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8522 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8523 pkgSetting.lastUpdateTime = currentTime; 8524 } 8525 } else if (pkgSetting.firstInstallTime == 0) { 8526 // We need *something*. Take time time stamp of the file. 8527 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8528 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8529 if (scanFileTime != pkgSetting.timeStamp) { 8530 // A package on the system image has changed; consider this 8531 // to be an update. 8532 pkgSetting.lastUpdateTime = scanFileTime; 8533 } 8534 } 8535 8536 // Add the package's KeySets to the global KeySetManagerService 8537 ksms.addScannedPackageLPw(pkg); 8538 8539 int N = pkg.providers.size(); 8540 StringBuilder r = null; 8541 int i; 8542 for (i=0; i<N; i++) { 8543 PackageParser.Provider p = pkg.providers.get(i); 8544 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8545 p.info.processName, pkg.applicationInfo.uid); 8546 mProviders.addProvider(p); 8547 p.syncable = p.info.isSyncable; 8548 if (p.info.authority != null) { 8549 String names[] = p.info.authority.split(";"); 8550 p.info.authority = null; 8551 for (int j = 0; j < names.length; j++) { 8552 if (j == 1 && p.syncable) { 8553 // We only want the first authority for a provider to possibly be 8554 // syncable, so if we already added this provider using a different 8555 // authority clear the syncable flag. We copy the provider before 8556 // changing it because the mProviders object contains a reference 8557 // to a provider that we don't want to change. 8558 // Only do this for the second authority since the resulting provider 8559 // object can be the same for all future authorities for this provider. 8560 p = new PackageParser.Provider(p); 8561 p.syncable = false; 8562 } 8563 if (!mProvidersByAuthority.containsKey(names[j])) { 8564 mProvidersByAuthority.put(names[j], p); 8565 if (p.info.authority == null) { 8566 p.info.authority = names[j]; 8567 } else { 8568 p.info.authority = p.info.authority + ";" + names[j]; 8569 } 8570 if (DEBUG_PACKAGE_SCANNING) { 8571 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8572 Log.d(TAG, "Registered content provider: " + names[j] 8573 + ", className = " + p.info.name + ", isSyncable = " 8574 + p.info.isSyncable); 8575 } 8576 } else { 8577 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8578 Slog.w(TAG, "Skipping provider name " + names[j] + 8579 " (in package " + pkg.applicationInfo.packageName + 8580 "): name already used by " 8581 + ((other != null && other.getComponentName() != null) 8582 ? other.getComponentName().getPackageName() : "?")); 8583 } 8584 } 8585 } 8586 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8587 if (r == null) { 8588 r = new StringBuilder(256); 8589 } else { 8590 r.append(' '); 8591 } 8592 r.append(p.info.name); 8593 } 8594 } 8595 if (r != null) { 8596 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8597 } 8598 8599 N = pkg.services.size(); 8600 r = null; 8601 for (i=0; i<N; i++) { 8602 PackageParser.Service s = pkg.services.get(i); 8603 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8604 s.info.processName, pkg.applicationInfo.uid); 8605 mServices.addService(s); 8606 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8607 if (r == null) { 8608 r = new StringBuilder(256); 8609 } else { 8610 r.append(' '); 8611 } 8612 r.append(s.info.name); 8613 } 8614 } 8615 if (r != null) { 8616 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8617 } 8618 8619 N = pkg.receivers.size(); 8620 r = null; 8621 for (i=0; i<N; i++) { 8622 PackageParser.Activity a = pkg.receivers.get(i); 8623 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8624 a.info.processName, pkg.applicationInfo.uid); 8625 mReceivers.addActivity(a, "receiver"); 8626 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8627 if (r == null) { 8628 r = new StringBuilder(256); 8629 } else { 8630 r.append(' '); 8631 } 8632 r.append(a.info.name); 8633 } 8634 } 8635 if (r != null) { 8636 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8637 } 8638 8639 N = pkg.activities.size(); 8640 r = null; 8641 for (i=0; i<N; i++) { 8642 PackageParser.Activity a = pkg.activities.get(i); 8643 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8644 a.info.processName, pkg.applicationInfo.uid); 8645 mActivities.addActivity(a, "activity"); 8646 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8647 if (r == null) { 8648 r = new StringBuilder(256); 8649 } else { 8650 r.append(' '); 8651 } 8652 r.append(a.info.name); 8653 } 8654 } 8655 if (r != null) { 8656 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8657 } 8658 8659 N = pkg.permissionGroups.size(); 8660 r = null; 8661 for (i=0; i<N; i++) { 8662 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8663 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8664 final String curPackageName = cur == null ? null : cur.info.packageName; 8665 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8666 if (cur == null || isPackageUpdate) { 8667 mPermissionGroups.put(pg.info.name, pg); 8668 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8669 if (r == null) { 8670 r = new StringBuilder(256); 8671 } else { 8672 r.append(' '); 8673 } 8674 if (isPackageUpdate) { 8675 r.append("UPD:"); 8676 } 8677 r.append(pg.info.name); 8678 } 8679 } else { 8680 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8681 + pg.info.packageName + " ignored: original from " 8682 + cur.info.packageName); 8683 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8684 if (r == null) { 8685 r = new StringBuilder(256); 8686 } else { 8687 r.append(' '); 8688 } 8689 r.append("DUP:"); 8690 r.append(pg.info.name); 8691 } 8692 } 8693 } 8694 if (r != null) { 8695 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8696 } 8697 8698 N = pkg.permissions.size(); 8699 r = null; 8700 for (i=0; i<N; i++) { 8701 PackageParser.Permission p = pkg.permissions.get(i); 8702 8703 // Assume by default that we did not install this permission into the system. 8704 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8705 8706 // Now that permission groups have a special meaning, we ignore permission 8707 // groups for legacy apps to prevent unexpected behavior. In particular, 8708 // permissions for one app being granted to someone just becase they happen 8709 // to be in a group defined by another app (before this had no implications). 8710 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8711 p.group = mPermissionGroups.get(p.info.group); 8712 // Warn for a permission in an unknown group. 8713 if (p.info.group != null && p.group == null) { 8714 Slog.w(TAG, "Permission " + p.info.name + " from package " 8715 + p.info.packageName + " in an unknown group " + p.info.group); 8716 } 8717 } 8718 8719 ArrayMap<String, BasePermission> permissionMap = 8720 p.tree ? mSettings.mPermissionTrees 8721 : mSettings.mPermissions; 8722 BasePermission bp = permissionMap.get(p.info.name); 8723 8724 // Allow system apps to redefine non-system permissions 8725 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8726 final boolean currentOwnerIsSystem = (bp.perm != null 8727 && isSystemApp(bp.perm.owner)); 8728 if (isSystemApp(p.owner)) { 8729 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8730 // It's a built-in permission and no owner, take ownership now 8731 bp.packageSetting = pkgSetting; 8732 bp.perm = p; 8733 bp.uid = pkg.applicationInfo.uid; 8734 bp.sourcePackage = p.info.packageName; 8735 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8736 } else if (!currentOwnerIsSystem) { 8737 String msg = "New decl " + p.owner + " of permission " 8738 + p.info.name + " is system; overriding " + bp.sourcePackage; 8739 reportSettingsProblem(Log.WARN, msg); 8740 bp = null; 8741 } 8742 } 8743 } 8744 8745 if (bp == null) { 8746 bp = new BasePermission(p.info.name, p.info.packageName, 8747 BasePermission.TYPE_NORMAL); 8748 permissionMap.put(p.info.name, bp); 8749 } 8750 8751 if (bp.perm == null) { 8752 if (bp.sourcePackage == null 8753 || bp.sourcePackage.equals(p.info.packageName)) { 8754 BasePermission tree = findPermissionTreeLP(p.info.name); 8755 if (tree == null 8756 || tree.sourcePackage.equals(p.info.packageName)) { 8757 bp.packageSetting = pkgSetting; 8758 bp.perm = p; 8759 bp.uid = pkg.applicationInfo.uid; 8760 bp.sourcePackage = p.info.packageName; 8761 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8762 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8763 if (r == null) { 8764 r = new StringBuilder(256); 8765 } else { 8766 r.append(' '); 8767 } 8768 r.append(p.info.name); 8769 } 8770 } else { 8771 Slog.w(TAG, "Permission " + p.info.name + " from package " 8772 + p.info.packageName + " ignored: base tree " 8773 + tree.name + " is from package " 8774 + tree.sourcePackage); 8775 } 8776 } else { 8777 Slog.w(TAG, "Permission " + p.info.name + " from package " 8778 + p.info.packageName + " ignored: original from " 8779 + bp.sourcePackage); 8780 } 8781 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8782 if (r == null) { 8783 r = new StringBuilder(256); 8784 } else { 8785 r.append(' '); 8786 } 8787 r.append("DUP:"); 8788 r.append(p.info.name); 8789 } 8790 if (bp.perm == p) { 8791 bp.protectionLevel = p.info.protectionLevel; 8792 } 8793 } 8794 8795 if (r != null) { 8796 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8797 } 8798 8799 N = pkg.instrumentation.size(); 8800 r = null; 8801 for (i=0; i<N; i++) { 8802 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8803 a.info.packageName = pkg.applicationInfo.packageName; 8804 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8805 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8806 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8807 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8808 a.info.dataDir = pkg.applicationInfo.dataDir; 8809 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8810 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8811 8812 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8813 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8814 mInstrumentation.put(a.getComponentName(), a); 8815 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8816 if (r == null) { 8817 r = new StringBuilder(256); 8818 } else { 8819 r.append(' '); 8820 } 8821 r.append(a.info.name); 8822 } 8823 } 8824 if (r != null) { 8825 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8826 } 8827 8828 if (pkg.protectedBroadcasts != null) { 8829 N = pkg.protectedBroadcasts.size(); 8830 for (i=0; i<N; i++) { 8831 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8832 } 8833 } 8834 8835 pkgSetting.setTimeStamp(scanFileTime); 8836 8837 // Create idmap files for pairs of (packages, overlay packages). 8838 // Note: "android", ie framework-res.apk, is handled by native layers. 8839 if (pkg.mOverlayTarget != null) { 8840 // This is an overlay package. 8841 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8842 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8843 mOverlays.put(pkg.mOverlayTarget, 8844 new ArrayMap<String, PackageParser.Package>()); 8845 } 8846 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8847 map.put(pkg.packageName, pkg); 8848 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8849 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8850 createIdmapFailed = true; 8851 } 8852 } 8853 } else if (mOverlays.containsKey(pkg.packageName) && 8854 !pkg.packageName.equals("android")) { 8855 // This is a regular package, with one or more known overlay packages. 8856 createIdmapsForPackageLI(pkg); 8857 } 8858 } 8859 8860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8861 8862 if (createIdmapFailed) { 8863 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8864 "scanPackageLI failed to createIdmap"); 8865 } 8866 return pkg; 8867 } 8868 8869 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8870 PackageParser.Package update, UserHandle user) { 8871 if (existing.applicationInfo == null || update.applicationInfo == null) { 8872 // This isn't due to an app installation. 8873 return; 8874 } 8875 8876 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8877 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8878 8879 // The codePath hasn't changed, so there's nothing for us to do. 8880 if (Objects.equals(oldCodePath, newCodePath)) { 8881 return; 8882 } 8883 8884 File canonicalNewCodePath; 8885 try { 8886 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8887 } catch (IOException e) { 8888 Slog.w(TAG, "Failed to get canonical path.", e); 8889 return; 8890 } 8891 8892 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8893 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8894 // that the last component of the path (i.e, the name) doesn't need canonicalization 8895 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8896 // but may change in the future. Hopefully this function won't exist at that point. 8897 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8898 oldCodePath.getName()); 8899 8900 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8901 // with "@". 8902 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8903 if (!oldMarkerPrefix.endsWith("@")) { 8904 oldMarkerPrefix += "@"; 8905 } 8906 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8907 if (!newMarkerPrefix.endsWith("@")) { 8908 newMarkerPrefix += "@"; 8909 } 8910 8911 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8912 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8913 for (String updatedPath : updatedPaths) { 8914 String updatedPathName = new File(updatedPath).getName(); 8915 markerSuffixes.add(updatedPathName.replace('/', '@')); 8916 } 8917 8918 for (int userId : resolveUserIds(user.getIdentifier())) { 8919 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8920 8921 for (String markerSuffix : markerSuffixes) { 8922 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 8923 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 8924 if (oldForeignUseMark.exists()) { 8925 try { 8926 Os.rename(oldForeignUseMark.getAbsolutePath(), 8927 newForeignUseMark.getAbsolutePath()); 8928 } catch (ErrnoException e) { 8929 Slog.w(TAG, "Failed to rename foreign use marker", e); 8930 oldForeignUseMark.delete(); 8931 } 8932 } 8933 } 8934 } 8935 } 8936 8937 /** 8938 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8939 * is derived purely on the basis of the contents of {@code scanFile} and 8940 * {@code cpuAbiOverride}. 8941 * 8942 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8943 */ 8944 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8945 String cpuAbiOverride, boolean extractLibs) 8946 throws PackageManagerException { 8947 // TODO: We can probably be smarter about this stuff. For installed apps, 8948 // we can calculate this information at install time once and for all. For 8949 // system apps, we can probably assume that this information doesn't change 8950 // after the first boot scan. As things stand, we do lots of unnecessary work. 8951 8952 // Give ourselves some initial paths; we'll come back for another 8953 // pass once we've determined ABI below. 8954 setNativeLibraryPaths(pkg); 8955 8956 // We would never need to extract libs for forward-locked and external packages, 8957 // since the container service will do it for us. We shouldn't attempt to 8958 // extract libs from system app when it was not updated. 8959 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8960 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8961 extractLibs = false; 8962 } 8963 8964 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8965 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8966 8967 NativeLibraryHelper.Handle handle = null; 8968 try { 8969 handle = NativeLibraryHelper.Handle.create(pkg); 8970 // TODO(multiArch): This can be null for apps that didn't go through the 8971 // usual installation process. We can calculate it again, like we 8972 // do during install time. 8973 // 8974 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8975 // unnecessary. 8976 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8977 8978 // Null out the abis so that they can be recalculated. 8979 pkg.applicationInfo.primaryCpuAbi = null; 8980 pkg.applicationInfo.secondaryCpuAbi = null; 8981 if (isMultiArch(pkg.applicationInfo)) { 8982 // Warn if we've set an abiOverride for multi-lib packages.. 8983 // By definition, we need to copy both 32 and 64 bit libraries for 8984 // such packages. 8985 if (pkg.cpuAbiOverride != null 8986 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8987 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8988 } 8989 8990 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8991 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8992 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8993 if (extractLibs) { 8994 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8995 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8996 useIsaSpecificSubdirs); 8997 } else { 8998 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8999 } 9000 } 9001 9002 maybeThrowExceptionForMultiArchCopy( 9003 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9004 9005 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9006 if (extractLibs) { 9007 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9008 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9009 useIsaSpecificSubdirs); 9010 } else { 9011 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9012 } 9013 } 9014 9015 maybeThrowExceptionForMultiArchCopy( 9016 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9017 9018 if (abi64 >= 0) { 9019 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9020 } 9021 9022 if (abi32 >= 0) { 9023 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9024 if (abi64 >= 0) { 9025 if (pkg.use32bitAbi) { 9026 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9027 pkg.applicationInfo.primaryCpuAbi = abi; 9028 } else { 9029 pkg.applicationInfo.secondaryCpuAbi = abi; 9030 } 9031 } else { 9032 pkg.applicationInfo.primaryCpuAbi = abi; 9033 } 9034 } 9035 9036 } else { 9037 String[] abiList = (cpuAbiOverride != null) ? 9038 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9039 9040 // Enable gross and lame hacks for apps that are built with old 9041 // SDK tools. We must scan their APKs for renderscript bitcode and 9042 // not launch them if it's present. Don't bother checking on devices 9043 // that don't have 64 bit support. 9044 boolean needsRenderScriptOverride = false; 9045 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9046 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9047 abiList = Build.SUPPORTED_32_BIT_ABIS; 9048 needsRenderScriptOverride = true; 9049 } 9050 9051 final int copyRet; 9052 if (extractLibs) { 9053 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9054 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9055 } else { 9056 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9057 } 9058 9059 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9060 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9061 "Error unpackaging native libs for app, errorCode=" + copyRet); 9062 } 9063 9064 if (copyRet >= 0) { 9065 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9066 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9067 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9068 } else if (needsRenderScriptOverride) { 9069 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9070 } 9071 } 9072 } catch (IOException ioe) { 9073 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9074 } finally { 9075 IoUtils.closeQuietly(handle); 9076 } 9077 9078 // Now that we've calculated the ABIs and determined if it's an internal app, 9079 // we will go ahead and populate the nativeLibraryPath. 9080 setNativeLibraryPaths(pkg); 9081 } 9082 9083 /** 9084 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9085 * i.e, so that all packages can be run inside a single process if required. 9086 * 9087 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9088 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9089 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9090 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9091 * updating a package that belongs to a shared user. 9092 * 9093 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9094 * adds unnecessary complexity. 9095 */ 9096 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9097 PackageParser.Package scannedPackage, boolean bootComplete) { 9098 String requiredInstructionSet = null; 9099 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9100 requiredInstructionSet = VMRuntime.getInstructionSet( 9101 scannedPackage.applicationInfo.primaryCpuAbi); 9102 } 9103 9104 PackageSetting requirer = null; 9105 for (PackageSetting ps : packagesForUser) { 9106 // If packagesForUser contains scannedPackage, we skip it. This will happen 9107 // when scannedPackage is an update of an existing package. Without this check, 9108 // we will never be able to change the ABI of any package belonging to a shared 9109 // user, even if it's compatible with other packages. 9110 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9111 if (ps.primaryCpuAbiString == null) { 9112 continue; 9113 } 9114 9115 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9116 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9117 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9118 // this but there's not much we can do. 9119 String errorMessage = "Instruction set mismatch, " 9120 + ((requirer == null) ? "[caller]" : requirer) 9121 + " requires " + requiredInstructionSet + " whereas " + ps 9122 + " requires " + instructionSet; 9123 Slog.w(TAG, errorMessage); 9124 } 9125 9126 if (requiredInstructionSet == null) { 9127 requiredInstructionSet = instructionSet; 9128 requirer = ps; 9129 } 9130 } 9131 } 9132 9133 if (requiredInstructionSet != null) { 9134 String adjustedAbi; 9135 if (requirer != null) { 9136 // requirer != null implies that either scannedPackage was null or that scannedPackage 9137 // did not require an ABI, in which case we have to adjust scannedPackage to match 9138 // the ABI of the set (which is the same as requirer's ABI) 9139 adjustedAbi = requirer.primaryCpuAbiString; 9140 if (scannedPackage != null) { 9141 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9142 } 9143 } else { 9144 // requirer == null implies that we're updating all ABIs in the set to 9145 // match scannedPackage. 9146 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9147 } 9148 9149 for (PackageSetting ps : packagesForUser) { 9150 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9151 if (ps.primaryCpuAbiString != null) { 9152 continue; 9153 } 9154 9155 ps.primaryCpuAbiString = adjustedAbi; 9156 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9157 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9158 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9159 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9160 + " (requirer=" 9161 + (requirer == null ? "null" : requirer.pkg.packageName) 9162 + ", scannedPackage=" 9163 + (scannedPackage != null ? scannedPackage.packageName : "null") 9164 + ")"); 9165 try { 9166 mInstaller.rmdex(ps.codePathString, 9167 getDexCodeInstructionSet(getPreferredInstructionSet())); 9168 } catch (InstallerException ignored) { 9169 } 9170 } 9171 } 9172 } 9173 } 9174 } 9175 9176 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9177 synchronized (mPackages) { 9178 mResolverReplaced = true; 9179 // Set up information for custom user intent resolution activity. 9180 mResolveActivity.applicationInfo = pkg.applicationInfo; 9181 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9182 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9183 mResolveActivity.processName = pkg.applicationInfo.packageName; 9184 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9185 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9186 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9187 mResolveActivity.theme = 0; 9188 mResolveActivity.exported = true; 9189 mResolveActivity.enabled = true; 9190 mResolveInfo.activityInfo = mResolveActivity; 9191 mResolveInfo.priority = 0; 9192 mResolveInfo.preferredOrder = 0; 9193 mResolveInfo.match = 0; 9194 mResolveComponentName = mCustomResolverComponentName; 9195 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9196 mResolveComponentName); 9197 } 9198 } 9199 9200 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9201 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9202 9203 // Set up information for ephemeral installer activity 9204 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9205 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9206 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9207 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9208 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9209 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9210 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9211 mEphemeralInstallerActivity.theme = 0; 9212 mEphemeralInstallerActivity.exported = true; 9213 mEphemeralInstallerActivity.enabled = true; 9214 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9215 mEphemeralInstallerInfo.priority = 0; 9216 mEphemeralInstallerInfo.preferredOrder = 0; 9217 mEphemeralInstallerInfo.match = 0; 9218 9219 if (DEBUG_EPHEMERAL) { 9220 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9221 } 9222 } 9223 9224 private static String calculateBundledApkRoot(final String codePathString) { 9225 final File codePath = new File(codePathString); 9226 final File codeRoot; 9227 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9228 codeRoot = Environment.getRootDirectory(); 9229 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9230 codeRoot = Environment.getOemDirectory(); 9231 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9232 codeRoot = Environment.getVendorDirectory(); 9233 } else { 9234 // Unrecognized code path; take its top real segment as the apk root: 9235 // e.g. /something/app/blah.apk => /something 9236 try { 9237 File f = codePath.getCanonicalFile(); 9238 File parent = f.getParentFile(); // non-null because codePath is a file 9239 File tmp; 9240 while ((tmp = parent.getParentFile()) != null) { 9241 f = parent; 9242 parent = tmp; 9243 } 9244 codeRoot = f; 9245 Slog.w(TAG, "Unrecognized code path " 9246 + codePath + " - using " + codeRoot); 9247 } catch (IOException e) { 9248 // Can't canonicalize the code path -- shenanigans? 9249 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9250 return Environment.getRootDirectory().getPath(); 9251 } 9252 } 9253 return codeRoot.getPath(); 9254 } 9255 9256 /** 9257 * Derive and set the location of native libraries for the given package, 9258 * which varies depending on where and how the package was installed. 9259 */ 9260 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9261 final ApplicationInfo info = pkg.applicationInfo; 9262 final String codePath = pkg.codePath; 9263 final File codeFile = new File(codePath); 9264 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9265 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9266 9267 info.nativeLibraryRootDir = null; 9268 info.nativeLibraryRootRequiresIsa = false; 9269 info.nativeLibraryDir = null; 9270 info.secondaryNativeLibraryDir = null; 9271 9272 if (isApkFile(codeFile)) { 9273 // Monolithic install 9274 if (bundledApp) { 9275 // If "/system/lib64/apkname" exists, assume that is the per-package 9276 // native library directory to use; otherwise use "/system/lib/apkname". 9277 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9278 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9279 getPrimaryInstructionSet(info)); 9280 9281 // This is a bundled system app so choose the path based on the ABI. 9282 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9283 // is just the default path. 9284 final String apkName = deriveCodePathName(codePath); 9285 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9286 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9287 apkName).getAbsolutePath(); 9288 9289 if (info.secondaryCpuAbi != null) { 9290 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9291 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9292 secondaryLibDir, apkName).getAbsolutePath(); 9293 } 9294 } else if (asecApp) { 9295 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9296 .getAbsolutePath(); 9297 } else { 9298 final String apkName = deriveCodePathName(codePath); 9299 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9300 .getAbsolutePath(); 9301 } 9302 9303 info.nativeLibraryRootRequiresIsa = false; 9304 info.nativeLibraryDir = info.nativeLibraryRootDir; 9305 } else { 9306 // Cluster install 9307 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9308 info.nativeLibraryRootRequiresIsa = true; 9309 9310 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9311 getPrimaryInstructionSet(info)).getAbsolutePath(); 9312 9313 if (info.secondaryCpuAbi != null) { 9314 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9315 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9316 } 9317 } 9318 } 9319 9320 /** 9321 * Calculate the abis and roots for a bundled app. These can uniquely 9322 * be determined from the contents of the system partition, i.e whether 9323 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9324 * of this information, and instead assume that the system was built 9325 * sensibly. 9326 */ 9327 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9328 PackageSetting pkgSetting) { 9329 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9330 9331 // If "/system/lib64/apkname" exists, assume that is the per-package 9332 // native library directory to use; otherwise use "/system/lib/apkname". 9333 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9334 setBundledAppAbi(pkg, apkRoot, apkName); 9335 // pkgSetting might be null during rescan following uninstall of updates 9336 // to a bundled app, so accommodate that possibility. The settings in 9337 // that case will be established later from the parsed package. 9338 // 9339 // If the settings aren't null, sync them up with what we've just derived. 9340 // note that apkRoot isn't stored in the package settings. 9341 if (pkgSetting != null) { 9342 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9343 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9344 } 9345 } 9346 9347 /** 9348 * Deduces the ABI of a bundled app and sets the relevant fields on the 9349 * parsed pkg object. 9350 * 9351 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9352 * under which system libraries are installed. 9353 * @param apkName the name of the installed package. 9354 */ 9355 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9356 final File codeFile = new File(pkg.codePath); 9357 9358 final boolean has64BitLibs; 9359 final boolean has32BitLibs; 9360 if (isApkFile(codeFile)) { 9361 // Monolithic install 9362 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9363 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9364 } else { 9365 // Cluster install 9366 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9367 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9368 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9369 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9370 has64BitLibs = (new File(rootDir, isa)).exists(); 9371 } else { 9372 has64BitLibs = false; 9373 } 9374 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9375 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9376 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9377 has32BitLibs = (new File(rootDir, isa)).exists(); 9378 } else { 9379 has32BitLibs = false; 9380 } 9381 } 9382 9383 if (has64BitLibs && !has32BitLibs) { 9384 // The package has 64 bit libs, but not 32 bit libs. Its primary 9385 // ABI should be 64 bit. We can safely assume here that the bundled 9386 // native libraries correspond to the most preferred ABI in the list. 9387 9388 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9389 pkg.applicationInfo.secondaryCpuAbi = null; 9390 } else if (has32BitLibs && !has64BitLibs) { 9391 // The package has 32 bit libs but not 64 bit libs. Its primary 9392 // ABI should be 32 bit. 9393 9394 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9395 pkg.applicationInfo.secondaryCpuAbi = null; 9396 } else if (has32BitLibs && has64BitLibs) { 9397 // The application has both 64 and 32 bit bundled libraries. We check 9398 // here that the app declares multiArch support, and warn if it doesn't. 9399 // 9400 // We will be lenient here and record both ABIs. The primary will be the 9401 // ABI that's higher on the list, i.e, a device that's configured to prefer 9402 // 64 bit apps will see a 64 bit primary ABI, 9403 9404 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9405 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9406 } 9407 9408 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9409 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9410 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9411 } else { 9412 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9413 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9414 } 9415 } else { 9416 pkg.applicationInfo.primaryCpuAbi = null; 9417 pkg.applicationInfo.secondaryCpuAbi = null; 9418 } 9419 } 9420 9421 private void killApplication(String pkgName, int appId, String reason) { 9422 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9423 } 9424 9425 private void killApplication(String pkgName, int appId, int userId, String reason) { 9426 // Request the ActivityManager to kill the process(only for existing packages) 9427 // so that we do not end up in a confused state while the user is still using the older 9428 // version of the application while the new one gets installed. 9429 final long token = Binder.clearCallingIdentity(); 9430 try { 9431 IActivityManager am = ActivityManagerNative.getDefault(); 9432 if (am != null) { 9433 try { 9434 am.killApplication(pkgName, appId, userId, reason); 9435 } catch (RemoteException e) { 9436 } 9437 } 9438 } finally { 9439 Binder.restoreCallingIdentity(token); 9440 } 9441 } 9442 9443 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9444 // Remove the parent package setting 9445 PackageSetting ps = (PackageSetting) pkg.mExtras; 9446 if (ps != null) { 9447 removePackageLI(ps, chatty); 9448 } 9449 // Remove the child package setting 9450 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9451 for (int i = 0; i < childCount; i++) { 9452 PackageParser.Package childPkg = pkg.childPackages.get(i); 9453 ps = (PackageSetting) childPkg.mExtras; 9454 if (ps != null) { 9455 removePackageLI(ps, chatty); 9456 } 9457 } 9458 } 9459 9460 void removePackageLI(PackageSetting ps, boolean chatty) { 9461 if (DEBUG_INSTALL) { 9462 if (chatty) 9463 Log.d(TAG, "Removing package " + ps.name); 9464 } 9465 9466 // writer 9467 synchronized (mPackages) { 9468 mPackages.remove(ps.name); 9469 final PackageParser.Package pkg = ps.pkg; 9470 if (pkg != null) { 9471 cleanPackageDataStructuresLILPw(pkg, chatty); 9472 } 9473 } 9474 } 9475 9476 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9477 if (DEBUG_INSTALL) { 9478 if (chatty) 9479 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9480 } 9481 9482 // writer 9483 synchronized (mPackages) { 9484 // Remove the parent package 9485 mPackages.remove(pkg.applicationInfo.packageName); 9486 cleanPackageDataStructuresLILPw(pkg, chatty); 9487 9488 // Remove the child packages 9489 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9490 for (int i = 0; i < childCount; i++) { 9491 PackageParser.Package childPkg = pkg.childPackages.get(i); 9492 mPackages.remove(childPkg.applicationInfo.packageName); 9493 cleanPackageDataStructuresLILPw(childPkg, chatty); 9494 } 9495 } 9496 } 9497 9498 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9499 int N = pkg.providers.size(); 9500 StringBuilder r = null; 9501 int i; 9502 for (i=0; i<N; i++) { 9503 PackageParser.Provider p = pkg.providers.get(i); 9504 mProviders.removeProvider(p); 9505 if (p.info.authority == null) { 9506 9507 /* There was another ContentProvider with this authority when 9508 * this app was installed so this authority is null, 9509 * Ignore it as we don't have to unregister the provider. 9510 */ 9511 continue; 9512 } 9513 String names[] = p.info.authority.split(";"); 9514 for (int j = 0; j < names.length; j++) { 9515 if (mProvidersByAuthority.get(names[j]) == p) { 9516 mProvidersByAuthority.remove(names[j]); 9517 if (DEBUG_REMOVE) { 9518 if (chatty) 9519 Log.d(TAG, "Unregistered content provider: " + names[j] 9520 + ", className = " + p.info.name + ", isSyncable = " 9521 + p.info.isSyncable); 9522 } 9523 } 9524 } 9525 if (DEBUG_REMOVE && chatty) { 9526 if (r == null) { 9527 r = new StringBuilder(256); 9528 } else { 9529 r.append(' '); 9530 } 9531 r.append(p.info.name); 9532 } 9533 } 9534 if (r != null) { 9535 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9536 } 9537 9538 N = pkg.services.size(); 9539 r = null; 9540 for (i=0; i<N; i++) { 9541 PackageParser.Service s = pkg.services.get(i); 9542 mServices.removeService(s); 9543 if (chatty) { 9544 if (r == null) { 9545 r = new StringBuilder(256); 9546 } else { 9547 r.append(' '); 9548 } 9549 r.append(s.info.name); 9550 } 9551 } 9552 if (r != null) { 9553 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9554 } 9555 9556 N = pkg.receivers.size(); 9557 r = null; 9558 for (i=0; i<N; i++) { 9559 PackageParser.Activity a = pkg.receivers.get(i); 9560 mReceivers.removeActivity(a, "receiver"); 9561 if (DEBUG_REMOVE && chatty) { 9562 if (r == null) { 9563 r = new StringBuilder(256); 9564 } else { 9565 r.append(' '); 9566 } 9567 r.append(a.info.name); 9568 } 9569 } 9570 if (r != null) { 9571 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9572 } 9573 9574 N = pkg.activities.size(); 9575 r = null; 9576 for (i=0; i<N; i++) { 9577 PackageParser.Activity a = pkg.activities.get(i); 9578 mActivities.removeActivity(a, "activity"); 9579 if (DEBUG_REMOVE && chatty) { 9580 if (r == null) { 9581 r = new StringBuilder(256); 9582 } else { 9583 r.append(' '); 9584 } 9585 r.append(a.info.name); 9586 } 9587 } 9588 if (r != null) { 9589 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9590 } 9591 9592 N = pkg.permissions.size(); 9593 r = null; 9594 for (i=0; i<N; i++) { 9595 PackageParser.Permission p = pkg.permissions.get(i); 9596 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9597 if (bp == null) { 9598 bp = mSettings.mPermissionTrees.get(p.info.name); 9599 } 9600 if (bp != null && bp.perm == p) { 9601 bp.perm = null; 9602 if (DEBUG_REMOVE && chatty) { 9603 if (r == null) { 9604 r = new StringBuilder(256); 9605 } else { 9606 r.append(' '); 9607 } 9608 r.append(p.info.name); 9609 } 9610 } 9611 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9612 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9613 if (appOpPkgs != null) { 9614 appOpPkgs.remove(pkg.packageName); 9615 } 9616 } 9617 } 9618 if (r != null) { 9619 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9620 } 9621 9622 N = pkg.requestedPermissions.size(); 9623 r = null; 9624 for (i=0; i<N; i++) { 9625 String perm = pkg.requestedPermissions.get(i); 9626 BasePermission bp = mSettings.mPermissions.get(perm); 9627 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9628 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9629 if (appOpPkgs != null) { 9630 appOpPkgs.remove(pkg.packageName); 9631 if (appOpPkgs.isEmpty()) { 9632 mAppOpPermissionPackages.remove(perm); 9633 } 9634 } 9635 } 9636 } 9637 if (r != null) { 9638 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9639 } 9640 9641 N = pkg.instrumentation.size(); 9642 r = null; 9643 for (i=0; i<N; i++) { 9644 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9645 mInstrumentation.remove(a.getComponentName()); 9646 if (DEBUG_REMOVE && chatty) { 9647 if (r == null) { 9648 r = new StringBuilder(256); 9649 } else { 9650 r.append(' '); 9651 } 9652 r.append(a.info.name); 9653 } 9654 } 9655 if (r != null) { 9656 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9657 } 9658 9659 r = null; 9660 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9661 // Only system apps can hold shared libraries. 9662 if (pkg.libraryNames != null) { 9663 for (i=0; i<pkg.libraryNames.size(); i++) { 9664 String name = pkg.libraryNames.get(i); 9665 SharedLibraryEntry cur = mSharedLibraries.get(name); 9666 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9667 mSharedLibraries.remove(name); 9668 if (DEBUG_REMOVE && chatty) { 9669 if (r == null) { 9670 r = new StringBuilder(256); 9671 } else { 9672 r.append(' '); 9673 } 9674 r.append(name); 9675 } 9676 } 9677 } 9678 } 9679 } 9680 if (r != null) { 9681 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9682 } 9683 } 9684 9685 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9686 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9687 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9688 return true; 9689 } 9690 } 9691 return false; 9692 } 9693 9694 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9695 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9696 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9697 9698 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9699 // Update the parent permissions 9700 updatePermissionsLPw(pkg.packageName, pkg, flags); 9701 // Update the child permissions 9702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9703 for (int i = 0; i < childCount; i++) { 9704 PackageParser.Package childPkg = pkg.childPackages.get(i); 9705 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9706 } 9707 } 9708 9709 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9710 int flags) { 9711 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9712 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9713 } 9714 9715 private void updatePermissionsLPw(String changingPkg, 9716 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9717 // Make sure there are no dangling permission trees. 9718 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9719 while (it.hasNext()) { 9720 final BasePermission bp = it.next(); 9721 if (bp.packageSetting == null) { 9722 // We may not yet have parsed the package, so just see if 9723 // we still know about its settings. 9724 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9725 } 9726 if (bp.packageSetting == null) { 9727 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9728 + " from package " + bp.sourcePackage); 9729 it.remove(); 9730 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9731 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9732 Slog.i(TAG, "Removing old permission tree: " + bp.name 9733 + " from package " + bp.sourcePackage); 9734 flags |= UPDATE_PERMISSIONS_ALL; 9735 it.remove(); 9736 } 9737 } 9738 } 9739 9740 // Make sure all dynamic permissions have been assigned to a package, 9741 // and make sure there are no dangling permissions. 9742 it = mSettings.mPermissions.values().iterator(); 9743 while (it.hasNext()) { 9744 final BasePermission bp = it.next(); 9745 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9746 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9747 + bp.name + " pkg=" + bp.sourcePackage 9748 + " info=" + bp.pendingInfo); 9749 if (bp.packageSetting == null && bp.pendingInfo != null) { 9750 final BasePermission tree = findPermissionTreeLP(bp.name); 9751 if (tree != null && tree.perm != null) { 9752 bp.packageSetting = tree.packageSetting; 9753 bp.perm = new PackageParser.Permission(tree.perm.owner, 9754 new PermissionInfo(bp.pendingInfo)); 9755 bp.perm.info.packageName = tree.perm.info.packageName; 9756 bp.perm.info.name = bp.name; 9757 bp.uid = tree.uid; 9758 } 9759 } 9760 } 9761 if (bp.packageSetting == null) { 9762 // We may not yet have parsed the package, so just see if 9763 // we still know about its settings. 9764 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9765 } 9766 if (bp.packageSetting == null) { 9767 Slog.w(TAG, "Removing dangling permission: " + bp.name 9768 + " from package " + bp.sourcePackage); 9769 it.remove(); 9770 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9771 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9772 Slog.i(TAG, "Removing old permission: " + bp.name 9773 + " from package " + bp.sourcePackage); 9774 flags |= UPDATE_PERMISSIONS_ALL; 9775 it.remove(); 9776 } 9777 } 9778 } 9779 9780 // Now update the permissions for all packages, in particular 9781 // replace the granted permissions of the system packages. 9782 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9783 for (PackageParser.Package pkg : mPackages.values()) { 9784 if (pkg != pkgInfo) { 9785 // Only replace for packages on requested volume 9786 final String volumeUuid = getVolumeUuidForPackage(pkg); 9787 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9788 && Objects.equals(replaceVolumeUuid, volumeUuid); 9789 grantPermissionsLPw(pkg, replace, changingPkg); 9790 } 9791 } 9792 } 9793 9794 if (pkgInfo != null) { 9795 // Only replace for packages on requested volume 9796 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9797 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9798 && Objects.equals(replaceVolumeUuid, volumeUuid); 9799 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9800 } 9801 } 9802 9803 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9804 String packageOfInterest) { 9805 // IMPORTANT: There are two types of permissions: install and runtime. 9806 // Install time permissions are granted when the app is installed to 9807 // all device users and users added in the future. Runtime permissions 9808 // are granted at runtime explicitly to specific users. Normal and signature 9809 // protected permissions are install time permissions. Dangerous permissions 9810 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9811 // otherwise they are runtime permissions. This function does not manage 9812 // runtime permissions except for the case an app targeting Lollipop MR1 9813 // being upgraded to target a newer SDK, in which case dangerous permissions 9814 // are transformed from install time to runtime ones. 9815 9816 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9817 if (ps == null) { 9818 return; 9819 } 9820 9821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9822 9823 PermissionsState permissionsState = ps.getPermissionsState(); 9824 PermissionsState origPermissions = permissionsState; 9825 9826 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9827 9828 boolean runtimePermissionsRevoked = false; 9829 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9830 9831 boolean changedInstallPermission = false; 9832 9833 if (replace) { 9834 ps.installPermissionsFixed = false; 9835 if (!ps.isSharedUser()) { 9836 origPermissions = new PermissionsState(permissionsState); 9837 permissionsState.reset(); 9838 } else { 9839 // We need to know only about runtime permission changes since the 9840 // calling code always writes the install permissions state but 9841 // the runtime ones are written only if changed. The only cases of 9842 // changed runtime permissions here are promotion of an install to 9843 // runtime and revocation of a runtime from a shared user. 9844 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9845 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9846 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9847 runtimePermissionsRevoked = true; 9848 } 9849 } 9850 } 9851 9852 permissionsState.setGlobalGids(mGlobalGids); 9853 9854 final int N = pkg.requestedPermissions.size(); 9855 for (int i=0; i<N; i++) { 9856 final String name = pkg.requestedPermissions.get(i); 9857 final BasePermission bp = mSettings.mPermissions.get(name); 9858 9859 if (DEBUG_INSTALL) { 9860 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9861 } 9862 9863 if (bp == null || bp.packageSetting == null) { 9864 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9865 Slog.w(TAG, "Unknown permission " + name 9866 + " in package " + pkg.packageName); 9867 } 9868 continue; 9869 } 9870 9871 final String perm = bp.name; 9872 boolean allowedSig = false; 9873 int grant = GRANT_DENIED; 9874 9875 // Keep track of app op permissions. 9876 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9877 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9878 if (pkgs == null) { 9879 pkgs = new ArraySet<>(); 9880 mAppOpPermissionPackages.put(bp.name, pkgs); 9881 } 9882 pkgs.add(pkg.packageName); 9883 } 9884 9885 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9886 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9887 >= Build.VERSION_CODES.M; 9888 switch (level) { 9889 case PermissionInfo.PROTECTION_NORMAL: { 9890 // For all apps normal permissions are install time ones. 9891 grant = GRANT_INSTALL; 9892 } break; 9893 9894 case PermissionInfo.PROTECTION_DANGEROUS: { 9895 // If a permission review is required for legacy apps we represent 9896 // their permissions as always granted runtime ones since we need 9897 // to keep the review required permission flag per user while an 9898 // install permission's state is shared across all users. 9899 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9900 // For legacy apps dangerous permissions are install time ones. 9901 grant = GRANT_INSTALL; 9902 } else if (origPermissions.hasInstallPermission(bp.name)) { 9903 // For legacy apps that became modern, install becomes runtime. 9904 grant = GRANT_UPGRADE; 9905 } else if (mPromoteSystemApps 9906 && isSystemApp(ps) 9907 && mExistingSystemPackages.contains(ps.name)) { 9908 // For legacy system apps, install becomes runtime. 9909 // We cannot check hasInstallPermission() for system apps since those 9910 // permissions were granted implicitly and not persisted pre-M. 9911 grant = GRANT_UPGRADE; 9912 } else { 9913 // For modern apps keep runtime permissions unchanged. 9914 grant = GRANT_RUNTIME; 9915 } 9916 } break; 9917 9918 case PermissionInfo.PROTECTION_SIGNATURE: { 9919 // For all apps signature permissions are install time ones. 9920 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9921 if (allowedSig) { 9922 grant = GRANT_INSTALL; 9923 } 9924 } break; 9925 } 9926 9927 if (DEBUG_INSTALL) { 9928 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9929 } 9930 9931 if (grant != GRANT_DENIED) { 9932 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9933 // If this is an existing, non-system package, then 9934 // we can't add any new permissions to it. 9935 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9936 // Except... if this is a permission that was added 9937 // to the platform (note: need to only do this when 9938 // updating the platform). 9939 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9940 grant = GRANT_DENIED; 9941 } 9942 } 9943 } 9944 9945 switch (grant) { 9946 case GRANT_INSTALL: { 9947 // Revoke this as runtime permission to handle the case of 9948 // a runtime permission being downgraded to an install one. 9949 // Also in permission review mode we keep dangerous permissions 9950 // for legacy apps 9951 for (int userId : UserManagerService.getInstance().getUserIds()) { 9952 if (origPermissions.getRuntimePermissionState( 9953 bp.name, userId) != null) { 9954 // Revoke the runtime permission and clear the flags. 9955 origPermissions.revokeRuntimePermission(bp, userId); 9956 origPermissions.updatePermissionFlags(bp, userId, 9957 PackageManager.MASK_PERMISSION_FLAGS, 0); 9958 // If we revoked a permission permission, we have to write. 9959 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9960 changedRuntimePermissionUserIds, userId); 9961 } 9962 } 9963 // Grant an install permission. 9964 if (permissionsState.grantInstallPermission(bp) != 9965 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9966 changedInstallPermission = true; 9967 } 9968 } break; 9969 9970 case GRANT_RUNTIME: { 9971 // Grant previously granted runtime permissions. 9972 for (int userId : UserManagerService.getInstance().getUserIds()) { 9973 PermissionState permissionState = origPermissions 9974 .getRuntimePermissionState(bp.name, userId); 9975 int flags = permissionState != null 9976 ? permissionState.getFlags() : 0; 9977 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9978 if (permissionsState.grantRuntimePermission(bp, userId) == 9979 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9980 // If we cannot put the permission as it was, we have to write. 9981 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9982 changedRuntimePermissionUserIds, userId); 9983 } 9984 // If the app supports runtime permissions no need for a review. 9985 if (Build.PERMISSIONS_REVIEW_REQUIRED 9986 && appSupportsRuntimePermissions 9987 && (flags & PackageManager 9988 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9989 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9990 // Since we changed the flags, we have to write. 9991 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9992 changedRuntimePermissionUserIds, userId); 9993 } 9994 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9995 && !appSupportsRuntimePermissions) { 9996 // For legacy apps that need a permission review, every new 9997 // runtime permission is granted but it is pending a review. 9998 // We also need to review only platform defined runtime 9999 // permissions as these are the only ones the platform knows 10000 // how to disable the API to simulate revocation as legacy 10001 // apps don't expect to run with revoked permissions. 10002 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10003 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10004 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10005 // We changed the flags, hence have to write. 10006 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10007 changedRuntimePermissionUserIds, userId); 10008 } 10009 } 10010 if (permissionsState.grantRuntimePermission(bp, userId) 10011 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10012 // We changed the permission, hence have to write. 10013 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10014 changedRuntimePermissionUserIds, userId); 10015 } 10016 } 10017 // Propagate the permission flags. 10018 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10019 } 10020 } break; 10021 10022 case GRANT_UPGRADE: { 10023 // Grant runtime permissions for a previously held install permission. 10024 PermissionState permissionState = origPermissions 10025 .getInstallPermissionState(bp.name); 10026 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10027 10028 if (origPermissions.revokeInstallPermission(bp) 10029 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10030 // We will be transferring the permission flags, so clear them. 10031 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10032 PackageManager.MASK_PERMISSION_FLAGS, 0); 10033 changedInstallPermission = true; 10034 } 10035 10036 // If the permission is not to be promoted to runtime we ignore it and 10037 // also its other flags as they are not applicable to install permissions. 10038 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10039 for (int userId : currentUserIds) { 10040 if (permissionsState.grantRuntimePermission(bp, userId) != 10041 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10042 // Transfer the permission flags. 10043 permissionsState.updatePermissionFlags(bp, userId, 10044 flags, flags); 10045 // If we granted the permission, we have to write. 10046 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10047 changedRuntimePermissionUserIds, userId); 10048 } 10049 } 10050 } 10051 } break; 10052 10053 default: { 10054 if (packageOfInterest == null 10055 || packageOfInterest.equals(pkg.packageName)) { 10056 Slog.w(TAG, "Not granting permission " + perm 10057 + " to package " + pkg.packageName 10058 + " because it was previously installed without"); 10059 } 10060 } break; 10061 } 10062 } else { 10063 if (permissionsState.revokeInstallPermission(bp) != 10064 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10065 // Also drop the permission flags. 10066 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10067 PackageManager.MASK_PERMISSION_FLAGS, 0); 10068 changedInstallPermission = true; 10069 Slog.i(TAG, "Un-granting permission " + perm 10070 + " from package " + pkg.packageName 10071 + " (protectionLevel=" + bp.protectionLevel 10072 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10073 + ")"); 10074 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10075 // Don't print warning for app op permissions, since it is fine for them 10076 // not to be granted, there is a UI for the user to decide. 10077 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10078 Slog.w(TAG, "Not granting permission " + perm 10079 + " to package " + pkg.packageName 10080 + " (protectionLevel=" + bp.protectionLevel 10081 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10082 + ")"); 10083 } 10084 } 10085 } 10086 } 10087 10088 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10089 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10090 // This is the first that we have heard about this package, so the 10091 // permissions we have now selected are fixed until explicitly 10092 // changed. 10093 ps.installPermissionsFixed = true; 10094 } 10095 10096 // Persist the runtime permissions state for users with changes. If permissions 10097 // were revoked because no app in the shared user declares them we have to 10098 // write synchronously to avoid losing runtime permissions state. 10099 for (int userId : changedRuntimePermissionUserIds) { 10100 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10101 } 10102 10103 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10104 } 10105 10106 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10107 boolean allowed = false; 10108 final int NP = PackageParser.NEW_PERMISSIONS.length; 10109 for (int ip=0; ip<NP; ip++) { 10110 final PackageParser.NewPermissionInfo npi 10111 = PackageParser.NEW_PERMISSIONS[ip]; 10112 if (npi.name.equals(perm) 10113 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10114 allowed = true; 10115 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10116 + pkg.packageName); 10117 break; 10118 } 10119 } 10120 return allowed; 10121 } 10122 10123 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10124 BasePermission bp, PermissionsState origPermissions) { 10125 boolean allowed; 10126 allowed = (compareSignatures( 10127 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10128 == PackageManager.SIGNATURE_MATCH) 10129 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10130 == PackageManager.SIGNATURE_MATCH); 10131 if (!allowed && (bp.protectionLevel 10132 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10133 if (isSystemApp(pkg)) { 10134 // For updated system applications, a system permission 10135 // is granted only if it had been defined by the original application. 10136 if (pkg.isUpdatedSystemApp()) { 10137 final PackageSetting sysPs = mSettings 10138 .getDisabledSystemPkgLPr(pkg.packageName); 10139 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10140 // If the original was granted this permission, we take 10141 // that grant decision as read and propagate it to the 10142 // update. 10143 if (sysPs.isPrivileged()) { 10144 allowed = true; 10145 } 10146 } else { 10147 // The system apk may have been updated with an older 10148 // version of the one on the data partition, but which 10149 // granted a new system permission that it didn't have 10150 // before. In this case we do want to allow the app to 10151 // now get the new permission if the ancestral apk is 10152 // privileged to get it. 10153 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10154 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10155 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10156 allowed = true; 10157 break; 10158 } 10159 } 10160 } 10161 // Also if a privileged parent package on the system image or any of 10162 // its children requested a privileged permission, the updated child 10163 // packages can also get the permission. 10164 if (pkg.parentPackage != null) { 10165 final PackageSetting disabledSysParentPs = mSettings 10166 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10167 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10168 && disabledSysParentPs.isPrivileged()) { 10169 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10170 allowed = true; 10171 } else if (disabledSysParentPs.pkg.childPackages != null) { 10172 final int count = disabledSysParentPs.pkg.childPackages.size(); 10173 for (int i = 0; i < count; i++) { 10174 PackageParser.Package disabledSysChildPkg = 10175 disabledSysParentPs.pkg.childPackages.get(i); 10176 if (isPackageRequestingPermission(disabledSysChildPkg, 10177 perm)) { 10178 allowed = true; 10179 break; 10180 } 10181 } 10182 } 10183 } 10184 } 10185 } 10186 } else { 10187 allowed = isPrivilegedApp(pkg); 10188 } 10189 } 10190 } 10191 if (!allowed) { 10192 if (!allowed && (bp.protectionLevel 10193 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10194 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10195 // If this was a previously normal/dangerous permission that got moved 10196 // to a system permission as part of the runtime permission redesign, then 10197 // we still want to blindly grant it to old apps. 10198 allowed = true; 10199 } 10200 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10201 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10202 // If this permission is to be granted to the system installer and 10203 // this app is an installer, then it gets the permission. 10204 allowed = true; 10205 } 10206 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10207 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10208 // If this permission is to be granted to the system verifier and 10209 // this app is a verifier, then it gets the permission. 10210 allowed = true; 10211 } 10212 if (!allowed && (bp.protectionLevel 10213 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10214 && isSystemApp(pkg)) { 10215 // Any pre-installed system app is allowed to get this permission. 10216 allowed = true; 10217 } 10218 if (!allowed && (bp.protectionLevel 10219 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10220 // For development permissions, a development permission 10221 // is granted only if it was already granted. 10222 allowed = origPermissions.hasInstallPermission(perm); 10223 } 10224 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10225 && pkg.packageName.equals(mSetupWizardPackage)) { 10226 // If this permission is to be granted to the system setup wizard and 10227 // this app is a setup wizard, then it gets the permission. 10228 allowed = true; 10229 } 10230 } 10231 return allowed; 10232 } 10233 10234 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10235 final int permCount = pkg.requestedPermissions.size(); 10236 for (int j = 0; j < permCount; j++) { 10237 String requestedPermission = pkg.requestedPermissions.get(j); 10238 if (permission.equals(requestedPermission)) { 10239 return true; 10240 } 10241 } 10242 return false; 10243 } 10244 10245 final class ActivityIntentResolver 10246 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10247 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10248 boolean defaultOnly, int userId) { 10249 if (!sUserManager.exists(userId)) return null; 10250 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10251 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10252 } 10253 10254 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10255 int userId) { 10256 if (!sUserManager.exists(userId)) return null; 10257 mFlags = flags; 10258 return super.queryIntent(intent, resolvedType, 10259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10260 } 10261 10262 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10263 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10264 if (!sUserManager.exists(userId)) return null; 10265 if (packageActivities == null) { 10266 return null; 10267 } 10268 mFlags = flags; 10269 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10270 final int N = packageActivities.size(); 10271 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10272 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10273 10274 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10275 for (int i = 0; i < N; ++i) { 10276 intentFilters = packageActivities.get(i).intents; 10277 if (intentFilters != null && intentFilters.size() > 0) { 10278 PackageParser.ActivityIntentInfo[] array = 10279 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10280 intentFilters.toArray(array); 10281 listCut.add(array); 10282 } 10283 } 10284 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10285 } 10286 10287 /** 10288 * Finds a privileged activity that matches the specified activity names. 10289 */ 10290 private PackageParser.Activity findMatchingActivity( 10291 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10292 for (PackageParser.Activity sysActivity : activityList) { 10293 if (sysActivity.info.name.equals(activityInfo.name)) { 10294 return sysActivity; 10295 } 10296 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10297 return sysActivity; 10298 } 10299 if (sysActivity.info.targetActivity != null) { 10300 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10301 return sysActivity; 10302 } 10303 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10304 return sysActivity; 10305 } 10306 } 10307 } 10308 return null; 10309 } 10310 10311 public class IterGenerator<E> { 10312 public Iterator<E> generate(ActivityIntentInfo info) { 10313 return null; 10314 } 10315 } 10316 10317 public class ActionIterGenerator extends IterGenerator<String> { 10318 @Override 10319 public Iterator<String> generate(ActivityIntentInfo info) { 10320 return info.actionsIterator(); 10321 } 10322 } 10323 10324 public class CategoriesIterGenerator extends IterGenerator<String> { 10325 @Override 10326 public Iterator<String> generate(ActivityIntentInfo info) { 10327 return info.categoriesIterator(); 10328 } 10329 } 10330 10331 public class SchemesIterGenerator extends IterGenerator<String> { 10332 @Override 10333 public Iterator<String> generate(ActivityIntentInfo info) { 10334 return info.schemesIterator(); 10335 } 10336 } 10337 10338 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10339 @Override 10340 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10341 return info.authoritiesIterator(); 10342 } 10343 } 10344 10345 /** 10346 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10347 * MODIFIED. Do not pass in a list that should not be changed. 10348 */ 10349 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10350 IterGenerator<T> generator, Iterator<T> searchIterator) { 10351 // loop through the set of actions; every one must be found in the intent filter 10352 while (searchIterator.hasNext()) { 10353 // we must have at least one filter in the list to consider a match 10354 if (intentList.size() == 0) { 10355 break; 10356 } 10357 10358 final T searchAction = searchIterator.next(); 10359 10360 // loop through the set of intent filters 10361 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10362 while (intentIter.hasNext()) { 10363 final ActivityIntentInfo intentInfo = intentIter.next(); 10364 boolean selectionFound = false; 10365 10366 // loop through the intent filter's selection criteria; at least one 10367 // of them must match the searched criteria 10368 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10369 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10370 final T intentSelection = intentSelectionIter.next(); 10371 if (intentSelection != null && intentSelection.equals(searchAction)) { 10372 selectionFound = true; 10373 break; 10374 } 10375 } 10376 10377 // the selection criteria wasn't found in this filter's set; this filter 10378 // is not a potential match 10379 if (!selectionFound) { 10380 intentIter.remove(); 10381 } 10382 } 10383 } 10384 } 10385 10386 private boolean isProtectedAction(ActivityIntentInfo filter) { 10387 final Iterator<String> actionsIter = filter.actionsIterator(); 10388 while (actionsIter != null && actionsIter.hasNext()) { 10389 final String filterAction = actionsIter.next(); 10390 if (PROTECTED_ACTIONS.contains(filterAction)) { 10391 return true; 10392 } 10393 } 10394 return false; 10395 } 10396 10397 /** 10398 * Adjusts the priority of the given intent filter according to policy. 10399 * <p> 10400 * <ul> 10401 * <li>The priority for non privileged applications is capped to '0'</li> 10402 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10403 * <li>The priority for unbundled updates to privileged applications is capped to the 10404 * priority defined on the system partition</li> 10405 * </ul> 10406 * <p> 10407 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10408 * allowed to obtain any priority on any action. 10409 */ 10410 private void adjustPriority( 10411 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10412 // nothing to do; priority is fine as-is 10413 if (intent.getPriority() <= 0) { 10414 return; 10415 } 10416 10417 final ActivityInfo activityInfo = intent.activity.info; 10418 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10419 10420 final boolean privilegedApp = 10421 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10422 if (!privilegedApp) { 10423 // non-privileged applications can never define a priority >0 10424 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10425 + " package: " + applicationInfo.packageName 10426 + " activity: " + intent.activity.className 10427 + " origPrio: " + intent.getPriority()); 10428 intent.setPriority(0); 10429 return; 10430 } 10431 10432 if (systemActivities == null) { 10433 // the system package is not disabled; we're parsing the system partition 10434 if (isProtectedAction(intent)) { 10435 if (mDeferProtectedFilters) { 10436 // We can't deal with these just yet. No component should ever obtain a 10437 // >0 priority for a protected actions, with ONE exception -- the setup 10438 // wizard. The setup wizard, however, cannot be known until we're able to 10439 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10440 // until all intent filters have been processed. Chicken, meet egg. 10441 // Let the filter temporarily have a high priority and rectify the 10442 // priorities after all system packages have been scanned. 10443 mProtectedFilters.add(intent); 10444 if (DEBUG_FILTERS) { 10445 Slog.i(TAG, "Protected action; save for later;" 10446 + " package: " + applicationInfo.packageName 10447 + " activity: " + intent.activity.className 10448 + " origPrio: " + intent.getPriority()); 10449 } 10450 return; 10451 } else { 10452 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10453 Slog.i(TAG, "No setup wizard;" 10454 + " All protected intents capped to priority 0"); 10455 } 10456 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10457 if (DEBUG_FILTERS) { 10458 Slog.i(TAG, "Found setup wizard;" 10459 + " allow priority " + intent.getPriority() + ";" 10460 + " package: " + intent.activity.info.packageName 10461 + " activity: " + intent.activity.className 10462 + " priority: " + intent.getPriority()); 10463 } 10464 // setup wizard gets whatever it wants 10465 return; 10466 } 10467 Slog.w(TAG, "Protected action; cap priority to 0;" 10468 + " package: " + intent.activity.info.packageName 10469 + " activity: " + intent.activity.className 10470 + " origPrio: " + intent.getPriority()); 10471 intent.setPriority(0); 10472 return; 10473 } 10474 } 10475 // privileged apps on the system image get whatever priority they request 10476 return; 10477 } 10478 10479 // privileged app unbundled update ... try to find the same activity 10480 final PackageParser.Activity foundActivity = 10481 findMatchingActivity(systemActivities, activityInfo); 10482 if (foundActivity == null) { 10483 // this is a new activity; it cannot obtain >0 priority 10484 if (DEBUG_FILTERS) { 10485 Slog.i(TAG, "New activity; cap priority to 0;" 10486 + " package: " + applicationInfo.packageName 10487 + " activity: " + intent.activity.className 10488 + " origPrio: " + intent.getPriority()); 10489 } 10490 intent.setPriority(0); 10491 return; 10492 } 10493 10494 // found activity, now check for filter equivalence 10495 10496 // a shallow copy is enough; we modify the list, not its contents 10497 final List<ActivityIntentInfo> intentListCopy = 10498 new ArrayList<>(foundActivity.intents); 10499 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10500 10501 // find matching action subsets 10502 final Iterator<String> actionsIterator = intent.actionsIterator(); 10503 if (actionsIterator != null) { 10504 getIntentListSubset( 10505 intentListCopy, new ActionIterGenerator(), actionsIterator); 10506 if (intentListCopy.size() == 0) { 10507 // no more intents to match; we're not equivalent 10508 if (DEBUG_FILTERS) { 10509 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10510 + " package: " + applicationInfo.packageName 10511 + " activity: " + intent.activity.className 10512 + " origPrio: " + intent.getPriority()); 10513 } 10514 intent.setPriority(0); 10515 return; 10516 } 10517 } 10518 10519 // find matching category subsets 10520 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10521 if (categoriesIterator != null) { 10522 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10523 categoriesIterator); 10524 if (intentListCopy.size() == 0) { 10525 // no more intents to match; we're not equivalent 10526 if (DEBUG_FILTERS) { 10527 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10528 + " package: " + applicationInfo.packageName 10529 + " activity: " + intent.activity.className 10530 + " origPrio: " + intent.getPriority()); 10531 } 10532 intent.setPriority(0); 10533 return; 10534 } 10535 } 10536 10537 // find matching schemes subsets 10538 final Iterator<String> schemesIterator = intent.schemesIterator(); 10539 if (schemesIterator != null) { 10540 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10541 schemesIterator); 10542 if (intentListCopy.size() == 0) { 10543 // no more intents to match; we're not equivalent 10544 if (DEBUG_FILTERS) { 10545 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10546 + " package: " + applicationInfo.packageName 10547 + " activity: " + intent.activity.className 10548 + " origPrio: " + intent.getPriority()); 10549 } 10550 intent.setPriority(0); 10551 return; 10552 } 10553 } 10554 10555 // find matching authorities subsets 10556 final Iterator<IntentFilter.AuthorityEntry> 10557 authoritiesIterator = intent.authoritiesIterator(); 10558 if (authoritiesIterator != null) { 10559 getIntentListSubset(intentListCopy, 10560 new AuthoritiesIterGenerator(), 10561 authoritiesIterator); 10562 if (intentListCopy.size() == 0) { 10563 // no more intents to match; we're not equivalent 10564 if (DEBUG_FILTERS) { 10565 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10566 + " package: " + applicationInfo.packageName 10567 + " activity: " + intent.activity.className 10568 + " origPrio: " + intent.getPriority()); 10569 } 10570 intent.setPriority(0); 10571 return; 10572 } 10573 } 10574 10575 // we found matching filter(s); app gets the max priority of all intents 10576 int cappedPriority = 0; 10577 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10578 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10579 } 10580 if (intent.getPriority() > cappedPriority) { 10581 if (DEBUG_FILTERS) { 10582 Slog.i(TAG, "Found matching filter(s);" 10583 + " cap priority to " + cappedPriority + ";" 10584 + " package: " + applicationInfo.packageName 10585 + " activity: " + intent.activity.className 10586 + " origPrio: " + intent.getPriority()); 10587 } 10588 intent.setPriority(cappedPriority); 10589 return; 10590 } 10591 // all this for nothing; the requested priority was <= what was on the system 10592 } 10593 10594 public final void addActivity(PackageParser.Activity a, String type) { 10595 mActivities.put(a.getComponentName(), a); 10596 if (DEBUG_SHOW_INFO) 10597 Log.v( 10598 TAG, " " + type + " " + 10599 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10600 if (DEBUG_SHOW_INFO) 10601 Log.v(TAG, " Class=" + a.info.name); 10602 final int NI = a.intents.size(); 10603 for (int j=0; j<NI; j++) { 10604 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10605 if ("activity".equals(type)) { 10606 final PackageSetting ps = 10607 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10608 final List<PackageParser.Activity> systemActivities = 10609 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10610 adjustPriority(systemActivities, intent); 10611 } 10612 if (DEBUG_SHOW_INFO) { 10613 Log.v(TAG, " IntentFilter:"); 10614 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10615 } 10616 if (!intent.debugCheck()) { 10617 Log.w(TAG, "==> For Activity " + a.info.name); 10618 } 10619 addFilter(intent); 10620 } 10621 } 10622 10623 public final void removeActivity(PackageParser.Activity a, String type) { 10624 mActivities.remove(a.getComponentName()); 10625 if (DEBUG_SHOW_INFO) { 10626 Log.v(TAG, " " + type + " " 10627 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10628 : a.info.name) + ":"); 10629 Log.v(TAG, " Class=" + a.info.name); 10630 } 10631 final int NI = a.intents.size(); 10632 for (int j=0; j<NI; j++) { 10633 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10634 if (DEBUG_SHOW_INFO) { 10635 Log.v(TAG, " IntentFilter:"); 10636 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10637 } 10638 removeFilter(intent); 10639 } 10640 } 10641 10642 @Override 10643 protected boolean allowFilterResult( 10644 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10645 ActivityInfo filterAi = filter.activity.info; 10646 for (int i=dest.size()-1; i>=0; i--) { 10647 ActivityInfo destAi = dest.get(i).activityInfo; 10648 if (destAi.name == filterAi.name 10649 && destAi.packageName == filterAi.packageName) { 10650 return false; 10651 } 10652 } 10653 return true; 10654 } 10655 10656 @Override 10657 protected ActivityIntentInfo[] newArray(int size) { 10658 return new ActivityIntentInfo[size]; 10659 } 10660 10661 @Override 10662 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10663 if (!sUserManager.exists(userId)) return true; 10664 PackageParser.Package p = filter.activity.owner; 10665 if (p != null) { 10666 PackageSetting ps = (PackageSetting)p.mExtras; 10667 if (ps != null) { 10668 // System apps are never considered stopped for purposes of 10669 // filtering, because there may be no way for the user to 10670 // actually re-launch them. 10671 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10672 && ps.getStopped(userId); 10673 } 10674 } 10675 return false; 10676 } 10677 10678 @Override 10679 protected boolean isPackageForFilter(String packageName, 10680 PackageParser.ActivityIntentInfo info) { 10681 return packageName.equals(info.activity.owner.packageName); 10682 } 10683 10684 @Override 10685 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10686 int match, int userId) { 10687 if (!sUserManager.exists(userId)) return null; 10688 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10689 return null; 10690 } 10691 final PackageParser.Activity activity = info.activity; 10692 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10693 if (ps == null) { 10694 return null; 10695 } 10696 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10697 ps.readUserState(userId), userId); 10698 if (ai == null) { 10699 return null; 10700 } 10701 final ResolveInfo res = new ResolveInfo(); 10702 res.activityInfo = ai; 10703 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10704 res.filter = info; 10705 } 10706 if (info != null) { 10707 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10708 } 10709 res.priority = info.getPriority(); 10710 res.preferredOrder = activity.owner.mPreferredOrder; 10711 //System.out.println("Result: " + res.activityInfo.className + 10712 // " = " + res.priority); 10713 res.match = match; 10714 res.isDefault = info.hasDefault; 10715 res.labelRes = info.labelRes; 10716 res.nonLocalizedLabel = info.nonLocalizedLabel; 10717 if (userNeedsBadging(userId)) { 10718 res.noResourceId = true; 10719 } else { 10720 res.icon = info.icon; 10721 } 10722 res.iconResourceId = info.icon; 10723 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10724 return res; 10725 } 10726 10727 @Override 10728 protected void sortResults(List<ResolveInfo> results) { 10729 Collections.sort(results, mResolvePrioritySorter); 10730 } 10731 10732 @Override 10733 protected void dumpFilter(PrintWriter out, String prefix, 10734 PackageParser.ActivityIntentInfo filter) { 10735 out.print(prefix); out.print( 10736 Integer.toHexString(System.identityHashCode(filter.activity))); 10737 out.print(' '); 10738 filter.activity.printComponentShortName(out); 10739 out.print(" filter "); 10740 out.println(Integer.toHexString(System.identityHashCode(filter))); 10741 } 10742 10743 @Override 10744 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10745 return filter.activity; 10746 } 10747 10748 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10749 PackageParser.Activity activity = (PackageParser.Activity)label; 10750 out.print(prefix); out.print( 10751 Integer.toHexString(System.identityHashCode(activity))); 10752 out.print(' '); 10753 activity.printComponentShortName(out); 10754 if (count > 1) { 10755 out.print(" ("); out.print(count); out.print(" filters)"); 10756 } 10757 out.println(); 10758 } 10759 10760 // Keys are String (activity class name), values are Activity. 10761 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10762 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10763 private int mFlags; 10764 } 10765 10766 private final class ServiceIntentResolver 10767 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10768 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10769 boolean defaultOnly, int userId) { 10770 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10771 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10772 } 10773 10774 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10775 int userId) { 10776 if (!sUserManager.exists(userId)) return null; 10777 mFlags = flags; 10778 return super.queryIntent(intent, resolvedType, 10779 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10780 } 10781 10782 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10783 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10784 if (!sUserManager.exists(userId)) return null; 10785 if (packageServices == null) { 10786 return null; 10787 } 10788 mFlags = flags; 10789 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10790 final int N = packageServices.size(); 10791 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10792 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10793 10794 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10795 for (int i = 0; i < N; ++i) { 10796 intentFilters = packageServices.get(i).intents; 10797 if (intentFilters != null && intentFilters.size() > 0) { 10798 PackageParser.ServiceIntentInfo[] array = 10799 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10800 intentFilters.toArray(array); 10801 listCut.add(array); 10802 } 10803 } 10804 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10805 } 10806 10807 public final void addService(PackageParser.Service s) { 10808 mServices.put(s.getComponentName(), s); 10809 if (DEBUG_SHOW_INFO) { 10810 Log.v(TAG, " " 10811 + (s.info.nonLocalizedLabel != null 10812 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10813 Log.v(TAG, " Class=" + s.info.name); 10814 } 10815 final int NI = s.intents.size(); 10816 int j; 10817 for (j=0; j<NI; j++) { 10818 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10819 if (DEBUG_SHOW_INFO) { 10820 Log.v(TAG, " IntentFilter:"); 10821 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10822 } 10823 if (!intent.debugCheck()) { 10824 Log.w(TAG, "==> For Service " + s.info.name); 10825 } 10826 addFilter(intent); 10827 } 10828 } 10829 10830 public final void removeService(PackageParser.Service s) { 10831 mServices.remove(s.getComponentName()); 10832 if (DEBUG_SHOW_INFO) { 10833 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10834 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10835 Log.v(TAG, " Class=" + s.info.name); 10836 } 10837 final int NI = s.intents.size(); 10838 int j; 10839 for (j=0; j<NI; j++) { 10840 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10841 if (DEBUG_SHOW_INFO) { 10842 Log.v(TAG, " IntentFilter:"); 10843 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10844 } 10845 removeFilter(intent); 10846 } 10847 } 10848 10849 @Override 10850 protected boolean allowFilterResult( 10851 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10852 ServiceInfo filterSi = filter.service.info; 10853 for (int i=dest.size()-1; i>=0; i--) { 10854 ServiceInfo destAi = dest.get(i).serviceInfo; 10855 if (destAi.name == filterSi.name 10856 && destAi.packageName == filterSi.packageName) { 10857 return false; 10858 } 10859 } 10860 return true; 10861 } 10862 10863 @Override 10864 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10865 return new PackageParser.ServiceIntentInfo[size]; 10866 } 10867 10868 @Override 10869 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10870 if (!sUserManager.exists(userId)) return true; 10871 PackageParser.Package p = filter.service.owner; 10872 if (p != null) { 10873 PackageSetting ps = (PackageSetting)p.mExtras; 10874 if (ps != null) { 10875 // System apps are never considered stopped for purposes of 10876 // filtering, because there may be no way for the user to 10877 // actually re-launch them. 10878 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10879 && ps.getStopped(userId); 10880 } 10881 } 10882 return false; 10883 } 10884 10885 @Override 10886 protected boolean isPackageForFilter(String packageName, 10887 PackageParser.ServiceIntentInfo info) { 10888 return packageName.equals(info.service.owner.packageName); 10889 } 10890 10891 @Override 10892 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10893 int match, int userId) { 10894 if (!sUserManager.exists(userId)) return null; 10895 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10896 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10897 return null; 10898 } 10899 final PackageParser.Service service = info.service; 10900 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10901 if (ps == null) { 10902 return null; 10903 } 10904 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10905 ps.readUserState(userId), userId); 10906 if (si == null) { 10907 return null; 10908 } 10909 final ResolveInfo res = new ResolveInfo(); 10910 res.serviceInfo = si; 10911 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10912 res.filter = filter; 10913 } 10914 res.priority = info.getPriority(); 10915 res.preferredOrder = service.owner.mPreferredOrder; 10916 res.match = match; 10917 res.isDefault = info.hasDefault; 10918 res.labelRes = info.labelRes; 10919 res.nonLocalizedLabel = info.nonLocalizedLabel; 10920 res.icon = info.icon; 10921 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10922 return res; 10923 } 10924 10925 @Override 10926 protected void sortResults(List<ResolveInfo> results) { 10927 Collections.sort(results, mResolvePrioritySorter); 10928 } 10929 10930 @Override 10931 protected void dumpFilter(PrintWriter out, String prefix, 10932 PackageParser.ServiceIntentInfo filter) { 10933 out.print(prefix); out.print( 10934 Integer.toHexString(System.identityHashCode(filter.service))); 10935 out.print(' '); 10936 filter.service.printComponentShortName(out); 10937 out.print(" filter "); 10938 out.println(Integer.toHexString(System.identityHashCode(filter))); 10939 } 10940 10941 @Override 10942 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10943 return filter.service; 10944 } 10945 10946 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10947 PackageParser.Service service = (PackageParser.Service)label; 10948 out.print(prefix); out.print( 10949 Integer.toHexString(System.identityHashCode(service))); 10950 out.print(' '); 10951 service.printComponentShortName(out); 10952 if (count > 1) { 10953 out.print(" ("); out.print(count); out.print(" filters)"); 10954 } 10955 out.println(); 10956 } 10957 10958// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10959// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10960// final List<ResolveInfo> retList = Lists.newArrayList(); 10961// while (i.hasNext()) { 10962// final ResolveInfo resolveInfo = (ResolveInfo) i; 10963// if (isEnabledLP(resolveInfo.serviceInfo)) { 10964// retList.add(resolveInfo); 10965// } 10966// } 10967// return retList; 10968// } 10969 10970 // Keys are String (activity class name), values are Activity. 10971 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10972 = new ArrayMap<ComponentName, PackageParser.Service>(); 10973 private int mFlags; 10974 }; 10975 10976 private final class ProviderIntentResolver 10977 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10978 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10979 boolean defaultOnly, int userId) { 10980 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10981 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10982 } 10983 10984 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10985 int userId) { 10986 if (!sUserManager.exists(userId)) 10987 return null; 10988 mFlags = flags; 10989 return super.queryIntent(intent, resolvedType, 10990 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10991 } 10992 10993 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10994 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10995 if (!sUserManager.exists(userId)) 10996 return null; 10997 if (packageProviders == null) { 10998 return null; 10999 } 11000 mFlags = flags; 11001 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11002 final int N = packageProviders.size(); 11003 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11004 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11005 11006 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11007 for (int i = 0; i < N; ++i) { 11008 intentFilters = packageProviders.get(i).intents; 11009 if (intentFilters != null && intentFilters.size() > 0) { 11010 PackageParser.ProviderIntentInfo[] array = 11011 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11012 intentFilters.toArray(array); 11013 listCut.add(array); 11014 } 11015 } 11016 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11017 } 11018 11019 public final void addProvider(PackageParser.Provider p) { 11020 if (mProviders.containsKey(p.getComponentName())) { 11021 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11022 return; 11023 } 11024 11025 mProviders.put(p.getComponentName(), p); 11026 if (DEBUG_SHOW_INFO) { 11027 Log.v(TAG, " " 11028 + (p.info.nonLocalizedLabel != null 11029 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11030 Log.v(TAG, " Class=" + p.info.name); 11031 } 11032 final int NI = p.intents.size(); 11033 int j; 11034 for (j = 0; j < NI; j++) { 11035 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11036 if (DEBUG_SHOW_INFO) { 11037 Log.v(TAG, " IntentFilter:"); 11038 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11039 } 11040 if (!intent.debugCheck()) { 11041 Log.w(TAG, "==> For Provider " + p.info.name); 11042 } 11043 addFilter(intent); 11044 } 11045 } 11046 11047 public final void removeProvider(PackageParser.Provider p) { 11048 mProviders.remove(p.getComponentName()); 11049 if (DEBUG_SHOW_INFO) { 11050 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11051 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11052 Log.v(TAG, " Class=" + p.info.name); 11053 } 11054 final int NI = p.intents.size(); 11055 int j; 11056 for (j = 0; j < NI; j++) { 11057 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11058 if (DEBUG_SHOW_INFO) { 11059 Log.v(TAG, " IntentFilter:"); 11060 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11061 } 11062 removeFilter(intent); 11063 } 11064 } 11065 11066 @Override 11067 protected boolean allowFilterResult( 11068 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11069 ProviderInfo filterPi = filter.provider.info; 11070 for (int i = dest.size() - 1; i >= 0; i--) { 11071 ProviderInfo destPi = dest.get(i).providerInfo; 11072 if (destPi.name == filterPi.name 11073 && destPi.packageName == filterPi.packageName) { 11074 return false; 11075 } 11076 } 11077 return true; 11078 } 11079 11080 @Override 11081 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11082 return new PackageParser.ProviderIntentInfo[size]; 11083 } 11084 11085 @Override 11086 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11087 if (!sUserManager.exists(userId)) 11088 return true; 11089 PackageParser.Package p = filter.provider.owner; 11090 if (p != null) { 11091 PackageSetting ps = (PackageSetting) p.mExtras; 11092 if (ps != null) { 11093 // System apps are never considered stopped for purposes of 11094 // filtering, because there may be no way for the user to 11095 // actually re-launch them. 11096 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11097 && ps.getStopped(userId); 11098 } 11099 } 11100 return false; 11101 } 11102 11103 @Override 11104 protected boolean isPackageForFilter(String packageName, 11105 PackageParser.ProviderIntentInfo info) { 11106 return packageName.equals(info.provider.owner.packageName); 11107 } 11108 11109 @Override 11110 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11111 int match, int userId) { 11112 if (!sUserManager.exists(userId)) 11113 return null; 11114 final PackageParser.ProviderIntentInfo info = filter; 11115 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11116 return null; 11117 } 11118 final PackageParser.Provider provider = info.provider; 11119 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11120 if (ps == null) { 11121 return null; 11122 } 11123 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11124 ps.readUserState(userId), userId); 11125 if (pi == null) { 11126 return null; 11127 } 11128 final ResolveInfo res = new ResolveInfo(); 11129 res.providerInfo = pi; 11130 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11131 res.filter = filter; 11132 } 11133 res.priority = info.getPriority(); 11134 res.preferredOrder = provider.owner.mPreferredOrder; 11135 res.match = match; 11136 res.isDefault = info.hasDefault; 11137 res.labelRes = info.labelRes; 11138 res.nonLocalizedLabel = info.nonLocalizedLabel; 11139 res.icon = info.icon; 11140 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11141 return res; 11142 } 11143 11144 @Override 11145 protected void sortResults(List<ResolveInfo> results) { 11146 Collections.sort(results, mResolvePrioritySorter); 11147 } 11148 11149 @Override 11150 protected void dumpFilter(PrintWriter out, String prefix, 11151 PackageParser.ProviderIntentInfo filter) { 11152 out.print(prefix); 11153 out.print( 11154 Integer.toHexString(System.identityHashCode(filter.provider))); 11155 out.print(' '); 11156 filter.provider.printComponentShortName(out); 11157 out.print(" filter "); 11158 out.println(Integer.toHexString(System.identityHashCode(filter))); 11159 } 11160 11161 @Override 11162 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11163 return filter.provider; 11164 } 11165 11166 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11167 PackageParser.Provider provider = (PackageParser.Provider)label; 11168 out.print(prefix); out.print( 11169 Integer.toHexString(System.identityHashCode(provider))); 11170 out.print(' '); 11171 provider.printComponentShortName(out); 11172 if (count > 1) { 11173 out.print(" ("); out.print(count); out.print(" filters)"); 11174 } 11175 out.println(); 11176 } 11177 11178 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11179 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11180 private int mFlags; 11181 } 11182 11183 private static final class EphemeralIntentResolver 11184 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11185 @Override 11186 protected EphemeralResolveIntentInfo[] newArray(int size) { 11187 return new EphemeralResolveIntentInfo[size]; 11188 } 11189 11190 @Override 11191 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11192 return true; 11193 } 11194 11195 @Override 11196 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11197 int userId) { 11198 if (!sUserManager.exists(userId)) { 11199 return null; 11200 } 11201 return info.getEphemeralResolveInfo(); 11202 } 11203 } 11204 11205 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11206 new Comparator<ResolveInfo>() { 11207 public int compare(ResolveInfo r1, ResolveInfo r2) { 11208 int v1 = r1.priority; 11209 int v2 = r2.priority; 11210 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11211 if (v1 != v2) { 11212 return (v1 > v2) ? -1 : 1; 11213 } 11214 v1 = r1.preferredOrder; 11215 v2 = r2.preferredOrder; 11216 if (v1 != v2) { 11217 return (v1 > v2) ? -1 : 1; 11218 } 11219 if (r1.isDefault != r2.isDefault) { 11220 return r1.isDefault ? -1 : 1; 11221 } 11222 v1 = r1.match; 11223 v2 = r2.match; 11224 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11225 if (v1 != v2) { 11226 return (v1 > v2) ? -1 : 1; 11227 } 11228 if (r1.system != r2.system) { 11229 return r1.system ? -1 : 1; 11230 } 11231 if (r1.activityInfo != null) { 11232 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11233 } 11234 if (r1.serviceInfo != null) { 11235 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11236 } 11237 if (r1.providerInfo != null) { 11238 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11239 } 11240 return 0; 11241 } 11242 }; 11243 11244 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11245 new Comparator<ProviderInfo>() { 11246 public int compare(ProviderInfo p1, ProviderInfo p2) { 11247 final int v1 = p1.initOrder; 11248 final int v2 = p2.initOrder; 11249 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11250 } 11251 }; 11252 11253 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11254 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11255 final int[] userIds) { 11256 mHandler.post(new Runnable() { 11257 @Override 11258 public void run() { 11259 try { 11260 final IActivityManager am = ActivityManagerNative.getDefault(); 11261 if (am == null) return; 11262 final int[] resolvedUserIds; 11263 if (userIds == null) { 11264 resolvedUserIds = am.getRunningUserIds(); 11265 } else { 11266 resolvedUserIds = userIds; 11267 } 11268 for (int id : resolvedUserIds) { 11269 final Intent intent = new Intent(action, 11270 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11271 if (extras != null) { 11272 intent.putExtras(extras); 11273 } 11274 if (targetPkg != null) { 11275 intent.setPackage(targetPkg); 11276 } 11277 // Modify the UID when posting to other users 11278 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11279 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11280 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11281 intent.putExtra(Intent.EXTRA_UID, uid); 11282 } 11283 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11284 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11285 if (DEBUG_BROADCASTS) { 11286 RuntimeException here = new RuntimeException("here"); 11287 here.fillInStackTrace(); 11288 Slog.d(TAG, "Sending to user " + id + ": " 11289 + intent.toShortString(false, true, false, false) 11290 + " " + intent.getExtras(), here); 11291 } 11292 am.broadcastIntent(null, intent, null, finishedReceiver, 11293 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11294 null, finishedReceiver != null, false, id); 11295 } 11296 } catch (RemoteException ex) { 11297 } 11298 } 11299 }); 11300 } 11301 11302 /** 11303 * Check if the external storage media is available. This is true if there 11304 * is a mounted external storage medium or if the external storage is 11305 * emulated. 11306 */ 11307 private boolean isExternalMediaAvailable() { 11308 return mMediaMounted || Environment.isExternalStorageEmulated(); 11309 } 11310 11311 @Override 11312 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11313 // writer 11314 synchronized (mPackages) { 11315 if (!isExternalMediaAvailable()) { 11316 // If the external storage is no longer mounted at this point, 11317 // the caller may not have been able to delete all of this 11318 // packages files and can not delete any more. Bail. 11319 return null; 11320 } 11321 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11322 if (lastPackage != null) { 11323 pkgs.remove(lastPackage); 11324 } 11325 if (pkgs.size() > 0) { 11326 return pkgs.get(0); 11327 } 11328 } 11329 return null; 11330 } 11331 11332 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11333 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11334 userId, andCode ? 1 : 0, packageName); 11335 if (mSystemReady) { 11336 msg.sendToTarget(); 11337 } else { 11338 if (mPostSystemReadyMessages == null) { 11339 mPostSystemReadyMessages = new ArrayList<>(); 11340 } 11341 mPostSystemReadyMessages.add(msg); 11342 } 11343 } 11344 11345 void startCleaningPackages() { 11346 // reader 11347 if (!isExternalMediaAvailable()) { 11348 return; 11349 } 11350 synchronized (mPackages) { 11351 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11352 return; 11353 } 11354 } 11355 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11356 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11357 IActivityManager am = ActivityManagerNative.getDefault(); 11358 if (am != null) { 11359 try { 11360 am.startService(null, intent, null, mContext.getOpPackageName(), 11361 UserHandle.USER_SYSTEM); 11362 } catch (RemoteException e) { 11363 } 11364 } 11365 } 11366 11367 @Override 11368 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11369 int installFlags, String installerPackageName, int userId) { 11370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11371 11372 final int callingUid = Binder.getCallingUid(); 11373 enforceCrossUserPermission(callingUid, userId, 11374 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11375 11376 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11377 try { 11378 if (observer != null) { 11379 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11380 } 11381 } catch (RemoteException re) { 11382 } 11383 return; 11384 } 11385 11386 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11387 installFlags |= PackageManager.INSTALL_FROM_ADB; 11388 11389 } else { 11390 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11391 // about installerPackageName. 11392 11393 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11394 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11395 } 11396 11397 UserHandle user; 11398 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11399 user = UserHandle.ALL; 11400 } else { 11401 user = new UserHandle(userId); 11402 } 11403 11404 // Only system components can circumvent runtime permissions when installing. 11405 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11406 && mContext.checkCallingOrSelfPermission(Manifest.permission 11407 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11408 throw new SecurityException("You need the " 11409 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11410 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11411 } 11412 11413 final File originFile = new File(originPath); 11414 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11415 11416 final Message msg = mHandler.obtainMessage(INIT_COPY); 11417 final VerificationInfo verificationInfo = new VerificationInfo( 11418 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11419 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11420 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11421 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11422 null /*certificates*/); 11423 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11424 msg.obj = params; 11425 11426 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11427 System.identityHashCode(msg.obj)); 11428 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11429 System.identityHashCode(msg.obj)); 11430 11431 mHandler.sendMessage(msg); 11432 } 11433 11434 void installStage(String packageName, File stagedDir, String stagedCid, 11435 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11436 String installerPackageName, int installerUid, UserHandle user, 11437 Certificate[][] certificates) { 11438 if (DEBUG_EPHEMERAL) { 11439 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11440 Slog.d(TAG, "Ephemeral install of " + packageName); 11441 } 11442 } 11443 final VerificationInfo verificationInfo = new VerificationInfo( 11444 sessionParams.originatingUri, sessionParams.referrerUri, 11445 sessionParams.originatingUid, installerUid); 11446 11447 final OriginInfo origin; 11448 if (stagedDir != null) { 11449 origin = OriginInfo.fromStagedFile(stagedDir); 11450 } else { 11451 origin = OriginInfo.fromStagedContainer(stagedCid); 11452 } 11453 11454 final Message msg = mHandler.obtainMessage(INIT_COPY); 11455 final InstallParams params = new InstallParams(origin, null, observer, 11456 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11457 verificationInfo, user, sessionParams.abiOverride, 11458 sessionParams.grantedRuntimePermissions, certificates); 11459 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11460 msg.obj = params; 11461 11462 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11463 System.identityHashCode(msg.obj)); 11464 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11465 System.identityHashCode(msg.obj)); 11466 11467 mHandler.sendMessage(msg); 11468 } 11469 11470 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11471 int userId) { 11472 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11473 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11474 } 11475 11476 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11477 int appId, int userId) { 11478 Bundle extras = new Bundle(1); 11479 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11480 11481 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11482 packageName, extras, 0, null, null, new int[] {userId}); 11483 try { 11484 IActivityManager am = ActivityManagerNative.getDefault(); 11485 if (isSystem && am.isUserRunning(userId, 0)) { 11486 // The just-installed/enabled app is bundled on the system, so presumed 11487 // to be able to run automatically without needing an explicit launch. 11488 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11489 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11490 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11491 .setPackage(packageName); 11492 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11493 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11494 } 11495 } catch (RemoteException e) { 11496 // shouldn't happen 11497 Slog.w(TAG, "Unable to bootstrap installed package", e); 11498 } 11499 } 11500 11501 @Override 11502 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11503 int userId) { 11504 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11505 PackageSetting pkgSetting; 11506 final int uid = Binder.getCallingUid(); 11507 enforceCrossUserPermission(uid, userId, 11508 true /* requireFullPermission */, true /* checkShell */, 11509 "setApplicationHiddenSetting for user " + userId); 11510 11511 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11512 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11513 return false; 11514 } 11515 11516 long callingId = Binder.clearCallingIdentity(); 11517 try { 11518 boolean sendAdded = false; 11519 boolean sendRemoved = false; 11520 // writer 11521 synchronized (mPackages) { 11522 pkgSetting = mSettings.mPackages.get(packageName); 11523 if (pkgSetting == null) { 11524 return false; 11525 } 11526 // Do not allow "android" is being disabled 11527 if ("android".equals(packageName)) { 11528 Slog.w(TAG, "Cannot hide package: android"); 11529 return false; 11530 } 11531 // Only allow protected packages to hide themselves. 11532 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11533 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11534 Slog.w(TAG, "Not hiding protected package: " + packageName); 11535 return false; 11536 } 11537 11538 if (pkgSetting.getHidden(userId) != hidden) { 11539 pkgSetting.setHidden(hidden, userId); 11540 mSettings.writePackageRestrictionsLPr(userId); 11541 if (hidden) { 11542 sendRemoved = true; 11543 } else { 11544 sendAdded = true; 11545 } 11546 } 11547 } 11548 if (sendAdded) { 11549 sendPackageAddedForUser(packageName, pkgSetting, userId); 11550 return true; 11551 } 11552 if (sendRemoved) { 11553 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11554 "hiding pkg"); 11555 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11556 return true; 11557 } 11558 } finally { 11559 Binder.restoreCallingIdentity(callingId); 11560 } 11561 return false; 11562 } 11563 11564 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11565 int userId) { 11566 final PackageRemovedInfo info = new PackageRemovedInfo(); 11567 info.removedPackage = packageName; 11568 info.removedUsers = new int[] {userId}; 11569 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11570 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11571 } 11572 11573 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11574 if (pkgList.length > 0) { 11575 Bundle extras = new Bundle(1); 11576 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11577 11578 sendPackageBroadcast( 11579 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11580 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11581 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11582 new int[] {userId}); 11583 } 11584 } 11585 11586 /** 11587 * Returns true if application is not found or there was an error. Otherwise it returns 11588 * the hidden state of the package for the given user. 11589 */ 11590 @Override 11591 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11592 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11593 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11594 true /* requireFullPermission */, false /* checkShell */, 11595 "getApplicationHidden for user " + userId); 11596 PackageSetting pkgSetting; 11597 long callingId = Binder.clearCallingIdentity(); 11598 try { 11599 // writer 11600 synchronized (mPackages) { 11601 pkgSetting = mSettings.mPackages.get(packageName); 11602 if (pkgSetting == null) { 11603 return true; 11604 } 11605 return pkgSetting.getHidden(userId); 11606 } 11607 } finally { 11608 Binder.restoreCallingIdentity(callingId); 11609 } 11610 } 11611 11612 /** 11613 * @hide 11614 */ 11615 @Override 11616 public int installExistingPackageAsUser(String packageName, int userId) { 11617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11618 null); 11619 PackageSetting pkgSetting; 11620 final int uid = Binder.getCallingUid(); 11621 enforceCrossUserPermission(uid, userId, 11622 true /* requireFullPermission */, true /* checkShell */, 11623 "installExistingPackage for user " + userId); 11624 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11625 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11626 } 11627 11628 long callingId = Binder.clearCallingIdentity(); 11629 try { 11630 boolean installed = false; 11631 11632 // writer 11633 synchronized (mPackages) { 11634 pkgSetting = mSettings.mPackages.get(packageName); 11635 if (pkgSetting == null) { 11636 return PackageManager.INSTALL_FAILED_INVALID_URI; 11637 } 11638 if (!pkgSetting.getInstalled(userId)) { 11639 pkgSetting.setInstalled(true, userId); 11640 pkgSetting.setHidden(false, userId); 11641 mSettings.writePackageRestrictionsLPr(userId); 11642 installed = true; 11643 } 11644 } 11645 11646 if (installed) { 11647 if (pkgSetting.pkg != null) { 11648 synchronized (mInstallLock) { 11649 // We don't need to freeze for a brand new install 11650 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11651 } 11652 } 11653 sendPackageAddedForUser(packageName, pkgSetting, userId); 11654 } 11655 } finally { 11656 Binder.restoreCallingIdentity(callingId); 11657 } 11658 11659 return PackageManager.INSTALL_SUCCEEDED; 11660 } 11661 11662 boolean isUserRestricted(int userId, String restrictionKey) { 11663 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11664 if (restrictions.getBoolean(restrictionKey, false)) { 11665 Log.w(TAG, "User is restricted: " + restrictionKey); 11666 return true; 11667 } 11668 return false; 11669 } 11670 11671 @Override 11672 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11673 int userId) { 11674 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11675 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11676 true /* requireFullPermission */, true /* checkShell */, 11677 "setPackagesSuspended for user " + userId); 11678 11679 if (ArrayUtils.isEmpty(packageNames)) { 11680 return packageNames; 11681 } 11682 11683 // List of package names for whom the suspended state has changed. 11684 List<String> changedPackages = new ArrayList<>(packageNames.length); 11685 // List of package names for whom the suspended state is not set as requested in this 11686 // method. 11687 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11688 long callingId = Binder.clearCallingIdentity(); 11689 try { 11690 for (int i = 0; i < packageNames.length; i++) { 11691 String packageName = packageNames[i]; 11692 boolean changed = false; 11693 final int appId; 11694 synchronized (mPackages) { 11695 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11696 if (pkgSetting == null) { 11697 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11698 + "\". Skipping suspending/un-suspending."); 11699 unactionedPackages.add(packageName); 11700 continue; 11701 } 11702 appId = pkgSetting.appId; 11703 if (pkgSetting.getSuspended(userId) != suspended) { 11704 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11705 unactionedPackages.add(packageName); 11706 continue; 11707 } 11708 pkgSetting.setSuspended(suspended, userId); 11709 mSettings.writePackageRestrictionsLPr(userId); 11710 changed = true; 11711 changedPackages.add(packageName); 11712 } 11713 } 11714 11715 if (changed && suspended) { 11716 killApplication(packageName, UserHandle.getUid(userId, appId), 11717 "suspending package"); 11718 } 11719 } 11720 } finally { 11721 Binder.restoreCallingIdentity(callingId); 11722 } 11723 11724 if (!changedPackages.isEmpty()) { 11725 sendPackagesSuspendedForUser(changedPackages.toArray( 11726 new String[changedPackages.size()]), userId, suspended); 11727 } 11728 11729 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11730 } 11731 11732 @Override 11733 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11734 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11735 true /* requireFullPermission */, false /* checkShell */, 11736 "isPackageSuspendedForUser for user " + userId); 11737 synchronized (mPackages) { 11738 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11739 if (pkgSetting == null) { 11740 throw new IllegalArgumentException("Unknown target package: " + packageName); 11741 } 11742 return pkgSetting.getSuspended(userId); 11743 } 11744 } 11745 11746 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11747 if (isPackageDeviceAdmin(packageName, userId)) { 11748 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11749 + "\": has an active device admin"); 11750 return false; 11751 } 11752 11753 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11754 if (packageName.equals(activeLauncherPackageName)) { 11755 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11756 + "\": contains the active launcher"); 11757 return false; 11758 } 11759 11760 if (packageName.equals(mRequiredInstallerPackage)) { 11761 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11762 + "\": required for package installation"); 11763 return false; 11764 } 11765 11766 if (packageName.equals(mRequiredVerifierPackage)) { 11767 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11768 + "\": required for package verification"); 11769 return false; 11770 } 11771 11772 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11773 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11774 + "\": is the default dialer"); 11775 return false; 11776 } 11777 11778 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11779 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11780 + "\": protected package"); 11781 return false; 11782 } 11783 11784 return true; 11785 } 11786 11787 private String getActiveLauncherPackageName(int userId) { 11788 Intent intent = new Intent(Intent.ACTION_MAIN); 11789 intent.addCategory(Intent.CATEGORY_HOME); 11790 ResolveInfo resolveInfo = resolveIntent( 11791 intent, 11792 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11793 PackageManager.MATCH_DEFAULT_ONLY, 11794 userId); 11795 11796 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11797 } 11798 11799 private String getDefaultDialerPackageName(int userId) { 11800 synchronized (mPackages) { 11801 return mSettings.getDefaultDialerPackageNameLPw(userId); 11802 } 11803 } 11804 11805 @Override 11806 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11807 mContext.enforceCallingOrSelfPermission( 11808 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11809 "Only package verification agents can verify applications"); 11810 11811 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11812 final PackageVerificationResponse response = new PackageVerificationResponse( 11813 verificationCode, Binder.getCallingUid()); 11814 msg.arg1 = id; 11815 msg.obj = response; 11816 mHandler.sendMessage(msg); 11817 } 11818 11819 @Override 11820 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11821 long millisecondsToDelay) { 11822 mContext.enforceCallingOrSelfPermission( 11823 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11824 "Only package verification agents can extend verification timeouts"); 11825 11826 final PackageVerificationState state = mPendingVerification.get(id); 11827 final PackageVerificationResponse response = new PackageVerificationResponse( 11828 verificationCodeAtTimeout, Binder.getCallingUid()); 11829 11830 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11831 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11832 } 11833 if (millisecondsToDelay < 0) { 11834 millisecondsToDelay = 0; 11835 } 11836 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11837 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11838 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11839 } 11840 11841 if ((state != null) && !state.timeoutExtended()) { 11842 state.extendTimeout(); 11843 11844 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11845 msg.arg1 = id; 11846 msg.obj = response; 11847 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11848 } 11849 } 11850 11851 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11852 int verificationCode, UserHandle user) { 11853 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11854 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11855 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11856 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11857 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11858 11859 mContext.sendBroadcastAsUser(intent, user, 11860 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11861 } 11862 11863 private ComponentName matchComponentForVerifier(String packageName, 11864 List<ResolveInfo> receivers) { 11865 ActivityInfo targetReceiver = null; 11866 11867 final int NR = receivers.size(); 11868 for (int i = 0; i < NR; i++) { 11869 final ResolveInfo info = receivers.get(i); 11870 if (info.activityInfo == null) { 11871 continue; 11872 } 11873 11874 if (packageName.equals(info.activityInfo.packageName)) { 11875 targetReceiver = info.activityInfo; 11876 break; 11877 } 11878 } 11879 11880 if (targetReceiver == null) { 11881 return null; 11882 } 11883 11884 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11885 } 11886 11887 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11888 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11889 if (pkgInfo.verifiers.length == 0) { 11890 return null; 11891 } 11892 11893 final int N = pkgInfo.verifiers.length; 11894 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11895 for (int i = 0; i < N; i++) { 11896 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11897 11898 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11899 receivers); 11900 if (comp == null) { 11901 continue; 11902 } 11903 11904 final int verifierUid = getUidForVerifier(verifierInfo); 11905 if (verifierUid == -1) { 11906 continue; 11907 } 11908 11909 if (DEBUG_VERIFY) { 11910 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11911 + " with the correct signature"); 11912 } 11913 sufficientVerifiers.add(comp); 11914 verificationState.addSufficientVerifier(verifierUid); 11915 } 11916 11917 return sufficientVerifiers; 11918 } 11919 11920 private int getUidForVerifier(VerifierInfo verifierInfo) { 11921 synchronized (mPackages) { 11922 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11923 if (pkg == null) { 11924 return -1; 11925 } else if (pkg.mSignatures.length != 1) { 11926 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11927 + " has more than one signature; ignoring"); 11928 return -1; 11929 } 11930 11931 /* 11932 * If the public key of the package's signature does not match 11933 * our expected public key, then this is a different package and 11934 * we should skip. 11935 */ 11936 11937 final byte[] expectedPublicKey; 11938 try { 11939 final Signature verifierSig = pkg.mSignatures[0]; 11940 final PublicKey publicKey = verifierSig.getPublicKey(); 11941 expectedPublicKey = publicKey.getEncoded(); 11942 } catch (CertificateException e) { 11943 return -1; 11944 } 11945 11946 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11947 11948 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11949 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11950 + " does not have the expected public key; ignoring"); 11951 return -1; 11952 } 11953 11954 return pkg.applicationInfo.uid; 11955 } 11956 } 11957 11958 @Override 11959 public void finishPackageInstall(int token, boolean didLaunch) { 11960 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11961 11962 if (DEBUG_INSTALL) { 11963 Slog.v(TAG, "BM finishing package install for " + token); 11964 } 11965 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11966 11967 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11968 mHandler.sendMessage(msg); 11969 } 11970 11971 /** 11972 * Get the verification agent timeout. 11973 * 11974 * @return verification timeout in milliseconds 11975 */ 11976 private long getVerificationTimeout() { 11977 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11978 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11979 DEFAULT_VERIFICATION_TIMEOUT); 11980 } 11981 11982 /** 11983 * Get the default verification agent response code. 11984 * 11985 * @return default verification response code 11986 */ 11987 private int getDefaultVerificationResponse() { 11988 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11989 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11990 DEFAULT_VERIFICATION_RESPONSE); 11991 } 11992 11993 /** 11994 * Check whether or not package verification has been enabled. 11995 * 11996 * @return true if verification should be performed 11997 */ 11998 private boolean isVerificationEnabled(int userId, int installFlags) { 11999 if (!DEFAULT_VERIFY_ENABLE) { 12000 return false; 12001 } 12002 // Ephemeral apps don't get the full verification treatment 12003 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12004 if (DEBUG_EPHEMERAL) { 12005 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12006 } 12007 return false; 12008 } 12009 12010 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12011 12012 // Check if installing from ADB 12013 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12014 // Do not run verification in a test harness environment 12015 if (ActivityManager.isRunningInTestHarness()) { 12016 return false; 12017 } 12018 if (ensureVerifyAppsEnabled) { 12019 return true; 12020 } 12021 // Check if the developer does not want package verification for ADB installs 12022 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12023 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12024 return false; 12025 } 12026 } 12027 12028 if (ensureVerifyAppsEnabled) { 12029 return true; 12030 } 12031 12032 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12033 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12034 } 12035 12036 @Override 12037 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12038 throws RemoteException { 12039 mContext.enforceCallingOrSelfPermission( 12040 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12041 "Only intentfilter verification agents can verify applications"); 12042 12043 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12044 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12045 Binder.getCallingUid(), verificationCode, failedDomains); 12046 msg.arg1 = id; 12047 msg.obj = response; 12048 mHandler.sendMessage(msg); 12049 } 12050 12051 @Override 12052 public int getIntentVerificationStatus(String packageName, int userId) { 12053 synchronized (mPackages) { 12054 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12055 } 12056 } 12057 12058 @Override 12059 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12060 mContext.enforceCallingOrSelfPermission( 12061 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12062 12063 boolean result = false; 12064 synchronized (mPackages) { 12065 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12066 } 12067 if (result) { 12068 scheduleWritePackageRestrictionsLocked(userId); 12069 } 12070 return result; 12071 } 12072 12073 @Override 12074 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12075 String packageName) { 12076 synchronized (mPackages) { 12077 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12078 } 12079 } 12080 12081 @Override 12082 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12083 if (TextUtils.isEmpty(packageName)) { 12084 return ParceledListSlice.emptyList(); 12085 } 12086 synchronized (mPackages) { 12087 PackageParser.Package pkg = mPackages.get(packageName); 12088 if (pkg == null || pkg.activities == null) { 12089 return ParceledListSlice.emptyList(); 12090 } 12091 final int count = pkg.activities.size(); 12092 ArrayList<IntentFilter> result = new ArrayList<>(); 12093 for (int n=0; n<count; n++) { 12094 PackageParser.Activity activity = pkg.activities.get(n); 12095 if (activity.intents != null && activity.intents.size() > 0) { 12096 result.addAll(activity.intents); 12097 } 12098 } 12099 return new ParceledListSlice<>(result); 12100 } 12101 } 12102 12103 @Override 12104 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12105 mContext.enforceCallingOrSelfPermission( 12106 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12107 12108 synchronized (mPackages) { 12109 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12110 if (packageName != null) { 12111 result |= updateIntentVerificationStatus(packageName, 12112 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12113 userId); 12114 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12115 packageName, userId); 12116 } 12117 return result; 12118 } 12119 } 12120 12121 @Override 12122 public String getDefaultBrowserPackageName(int userId) { 12123 synchronized (mPackages) { 12124 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12125 } 12126 } 12127 12128 /** 12129 * Get the "allow unknown sources" setting. 12130 * 12131 * @return the current "allow unknown sources" setting 12132 */ 12133 private int getUnknownSourcesSettings() { 12134 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12135 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12136 -1); 12137 } 12138 12139 @Override 12140 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12141 final int uid = Binder.getCallingUid(); 12142 // writer 12143 synchronized (mPackages) { 12144 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12145 if (targetPackageSetting == null) { 12146 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12147 } 12148 12149 PackageSetting installerPackageSetting; 12150 if (installerPackageName != null) { 12151 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12152 if (installerPackageSetting == null) { 12153 throw new IllegalArgumentException("Unknown installer package: " 12154 + installerPackageName); 12155 } 12156 } else { 12157 installerPackageSetting = null; 12158 } 12159 12160 Signature[] callerSignature; 12161 Object obj = mSettings.getUserIdLPr(uid); 12162 if (obj != null) { 12163 if (obj instanceof SharedUserSetting) { 12164 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12165 } else if (obj instanceof PackageSetting) { 12166 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12167 } else { 12168 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12169 } 12170 } else { 12171 throw new SecurityException("Unknown calling UID: " + uid); 12172 } 12173 12174 // Verify: can't set installerPackageName to a package that is 12175 // not signed with the same cert as the caller. 12176 if (installerPackageSetting != null) { 12177 if (compareSignatures(callerSignature, 12178 installerPackageSetting.signatures.mSignatures) 12179 != PackageManager.SIGNATURE_MATCH) { 12180 throw new SecurityException( 12181 "Caller does not have same cert as new installer package " 12182 + installerPackageName); 12183 } 12184 } 12185 12186 // Verify: if target already has an installer package, it must 12187 // be signed with the same cert as the caller. 12188 if (targetPackageSetting.installerPackageName != null) { 12189 PackageSetting setting = mSettings.mPackages.get( 12190 targetPackageSetting.installerPackageName); 12191 // If the currently set package isn't valid, then it's always 12192 // okay to change it. 12193 if (setting != null) { 12194 if (compareSignatures(callerSignature, 12195 setting.signatures.mSignatures) 12196 != PackageManager.SIGNATURE_MATCH) { 12197 throw new SecurityException( 12198 "Caller does not have same cert as old installer package " 12199 + targetPackageSetting.installerPackageName); 12200 } 12201 } 12202 } 12203 12204 // Okay! 12205 targetPackageSetting.installerPackageName = installerPackageName; 12206 if (installerPackageName != null) { 12207 mSettings.mInstallerPackages.add(installerPackageName); 12208 } 12209 scheduleWriteSettingsLocked(); 12210 } 12211 } 12212 12213 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12214 // Queue up an async operation since the package installation may take a little while. 12215 mHandler.post(new Runnable() { 12216 public void run() { 12217 mHandler.removeCallbacks(this); 12218 // Result object to be returned 12219 PackageInstalledInfo res = new PackageInstalledInfo(); 12220 res.setReturnCode(currentStatus); 12221 res.uid = -1; 12222 res.pkg = null; 12223 res.removedInfo = null; 12224 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12225 args.doPreInstall(res.returnCode); 12226 synchronized (mInstallLock) { 12227 installPackageTracedLI(args, res); 12228 } 12229 args.doPostInstall(res.returnCode, res.uid); 12230 } 12231 12232 // A restore should be performed at this point if (a) the install 12233 // succeeded, (b) the operation is not an update, and (c) the new 12234 // package has not opted out of backup participation. 12235 final boolean update = res.removedInfo != null 12236 && res.removedInfo.removedPackage != null; 12237 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12238 boolean doRestore = !update 12239 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12240 12241 // Set up the post-install work request bookkeeping. This will be used 12242 // and cleaned up by the post-install event handling regardless of whether 12243 // there's a restore pass performed. Token values are >= 1. 12244 int token; 12245 if (mNextInstallToken < 0) mNextInstallToken = 1; 12246 token = mNextInstallToken++; 12247 12248 PostInstallData data = new PostInstallData(args, res); 12249 mRunningInstalls.put(token, data); 12250 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12251 12252 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12253 // Pass responsibility to the Backup Manager. It will perform a 12254 // restore if appropriate, then pass responsibility back to the 12255 // Package Manager to run the post-install observer callbacks 12256 // and broadcasts. 12257 IBackupManager bm = IBackupManager.Stub.asInterface( 12258 ServiceManager.getService(Context.BACKUP_SERVICE)); 12259 if (bm != null) { 12260 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12261 + " to BM for possible restore"); 12262 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12263 try { 12264 // TODO: http://b/22388012 12265 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12266 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12267 } else { 12268 doRestore = false; 12269 } 12270 } catch (RemoteException e) { 12271 // can't happen; the backup manager is local 12272 } catch (Exception e) { 12273 Slog.e(TAG, "Exception trying to enqueue restore", e); 12274 doRestore = false; 12275 } 12276 } else { 12277 Slog.e(TAG, "Backup Manager not found!"); 12278 doRestore = false; 12279 } 12280 } 12281 12282 if (!doRestore) { 12283 // No restore possible, or the Backup Manager was mysteriously not 12284 // available -- just fire the post-install work request directly. 12285 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12286 12287 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12288 12289 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12290 mHandler.sendMessage(msg); 12291 } 12292 } 12293 }); 12294 } 12295 12296 /** 12297 * Callback from PackageSettings whenever an app is first transitioned out of the 12298 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12299 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12300 * here whether the app is the target of an ongoing install, and only send the 12301 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12302 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12303 * handling. 12304 */ 12305 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12306 // Serialize this with the rest of the install-process message chain. In the 12307 // restore-at-install case, this Runnable will necessarily run before the 12308 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12309 // are coherent. In the non-restore case, the app has already completed install 12310 // and been launched through some other means, so it is not in a problematic 12311 // state for observers to see the FIRST_LAUNCH signal. 12312 mHandler.post(new Runnable() { 12313 @Override 12314 public void run() { 12315 for (int i = 0; i < mRunningInstalls.size(); i++) { 12316 final PostInstallData data = mRunningInstalls.valueAt(i); 12317 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12318 continue; 12319 } 12320 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12321 // right package; but is it for the right user? 12322 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12323 if (userId == data.res.newUsers[uIndex]) { 12324 if (DEBUG_BACKUP) { 12325 Slog.i(TAG, "Package " + pkgName 12326 + " being restored so deferring FIRST_LAUNCH"); 12327 } 12328 return; 12329 } 12330 } 12331 } 12332 } 12333 // didn't find it, so not being restored 12334 if (DEBUG_BACKUP) { 12335 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12336 } 12337 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12338 } 12339 }); 12340 } 12341 12342 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12343 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12344 installerPkg, null, userIds); 12345 } 12346 12347 private abstract class HandlerParams { 12348 private static final int MAX_RETRIES = 4; 12349 12350 /** 12351 * Number of times startCopy() has been attempted and had a non-fatal 12352 * error. 12353 */ 12354 private int mRetries = 0; 12355 12356 /** User handle for the user requesting the information or installation. */ 12357 private final UserHandle mUser; 12358 String traceMethod; 12359 int traceCookie; 12360 12361 HandlerParams(UserHandle user) { 12362 mUser = user; 12363 } 12364 12365 UserHandle getUser() { 12366 return mUser; 12367 } 12368 12369 HandlerParams setTraceMethod(String traceMethod) { 12370 this.traceMethod = traceMethod; 12371 return this; 12372 } 12373 12374 HandlerParams setTraceCookie(int traceCookie) { 12375 this.traceCookie = traceCookie; 12376 return this; 12377 } 12378 12379 final boolean startCopy() { 12380 boolean res; 12381 try { 12382 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12383 12384 if (++mRetries > MAX_RETRIES) { 12385 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12386 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12387 handleServiceError(); 12388 return false; 12389 } else { 12390 handleStartCopy(); 12391 res = true; 12392 } 12393 } catch (RemoteException e) { 12394 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12395 mHandler.sendEmptyMessage(MCS_RECONNECT); 12396 res = false; 12397 } 12398 handleReturnCode(); 12399 return res; 12400 } 12401 12402 final void serviceError() { 12403 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12404 handleServiceError(); 12405 handleReturnCode(); 12406 } 12407 12408 abstract void handleStartCopy() throws RemoteException; 12409 abstract void handleServiceError(); 12410 abstract void handleReturnCode(); 12411 } 12412 12413 class MeasureParams extends HandlerParams { 12414 private final PackageStats mStats; 12415 private boolean mSuccess; 12416 12417 private final IPackageStatsObserver mObserver; 12418 12419 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12420 super(new UserHandle(stats.userHandle)); 12421 mObserver = observer; 12422 mStats = stats; 12423 } 12424 12425 @Override 12426 public String toString() { 12427 return "MeasureParams{" 12428 + Integer.toHexString(System.identityHashCode(this)) 12429 + " " + mStats.packageName + "}"; 12430 } 12431 12432 @Override 12433 void handleStartCopy() throws RemoteException { 12434 synchronized (mInstallLock) { 12435 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12436 } 12437 12438 if (mSuccess) { 12439 boolean mounted = false; 12440 try { 12441 final String status = Environment.getExternalStorageState(); 12442 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12443 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12444 } catch (Exception e) { 12445 } 12446 12447 if (mounted) { 12448 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12449 12450 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12451 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12452 12453 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12454 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12455 12456 // Always subtract cache size, since it's a subdirectory 12457 mStats.externalDataSize -= mStats.externalCacheSize; 12458 12459 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12460 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12461 12462 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12463 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12464 } 12465 } 12466 } 12467 12468 @Override 12469 void handleReturnCode() { 12470 if (mObserver != null) { 12471 try { 12472 mObserver.onGetStatsCompleted(mStats, mSuccess); 12473 } catch (RemoteException e) { 12474 Slog.i(TAG, "Observer no longer exists."); 12475 } 12476 } 12477 } 12478 12479 @Override 12480 void handleServiceError() { 12481 Slog.e(TAG, "Could not measure application " + mStats.packageName 12482 + " external storage"); 12483 } 12484 } 12485 12486 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12487 throws RemoteException { 12488 long result = 0; 12489 for (File path : paths) { 12490 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12491 } 12492 return result; 12493 } 12494 12495 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12496 for (File path : paths) { 12497 try { 12498 mcs.clearDirectory(path.getAbsolutePath()); 12499 } catch (RemoteException e) { 12500 } 12501 } 12502 } 12503 12504 static class OriginInfo { 12505 /** 12506 * Location where install is coming from, before it has been 12507 * copied/renamed into place. This could be a single monolithic APK 12508 * file, or a cluster directory. This location may be untrusted. 12509 */ 12510 final File file; 12511 final String cid; 12512 12513 /** 12514 * Flag indicating that {@link #file} or {@link #cid} has already been 12515 * staged, meaning downstream users don't need to defensively copy the 12516 * contents. 12517 */ 12518 final boolean staged; 12519 12520 /** 12521 * Flag indicating that {@link #file} or {@link #cid} is an already 12522 * installed app that is being moved. 12523 */ 12524 final boolean existing; 12525 12526 final String resolvedPath; 12527 final File resolvedFile; 12528 12529 static OriginInfo fromNothing() { 12530 return new OriginInfo(null, null, false, false); 12531 } 12532 12533 static OriginInfo fromUntrustedFile(File file) { 12534 return new OriginInfo(file, null, false, false); 12535 } 12536 12537 static OriginInfo fromExistingFile(File file) { 12538 return new OriginInfo(file, null, false, true); 12539 } 12540 12541 static OriginInfo fromStagedFile(File file) { 12542 return new OriginInfo(file, null, true, false); 12543 } 12544 12545 static OriginInfo fromStagedContainer(String cid) { 12546 return new OriginInfo(null, cid, true, false); 12547 } 12548 12549 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12550 this.file = file; 12551 this.cid = cid; 12552 this.staged = staged; 12553 this.existing = existing; 12554 12555 if (cid != null) { 12556 resolvedPath = PackageHelper.getSdDir(cid); 12557 resolvedFile = new File(resolvedPath); 12558 } else if (file != null) { 12559 resolvedPath = file.getAbsolutePath(); 12560 resolvedFile = file; 12561 } else { 12562 resolvedPath = null; 12563 resolvedFile = null; 12564 } 12565 } 12566 } 12567 12568 static class MoveInfo { 12569 final int moveId; 12570 final String fromUuid; 12571 final String toUuid; 12572 final String packageName; 12573 final String dataAppName; 12574 final int appId; 12575 final String seinfo; 12576 final int targetSdkVersion; 12577 12578 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12579 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12580 this.moveId = moveId; 12581 this.fromUuid = fromUuid; 12582 this.toUuid = toUuid; 12583 this.packageName = packageName; 12584 this.dataAppName = dataAppName; 12585 this.appId = appId; 12586 this.seinfo = seinfo; 12587 this.targetSdkVersion = targetSdkVersion; 12588 } 12589 } 12590 12591 static class VerificationInfo { 12592 /** A constant used to indicate that a uid value is not present. */ 12593 public static final int NO_UID = -1; 12594 12595 /** URI referencing where the package was downloaded from. */ 12596 final Uri originatingUri; 12597 12598 /** HTTP referrer URI associated with the originatingURI. */ 12599 final Uri referrer; 12600 12601 /** UID of the application that the install request originated from. */ 12602 final int originatingUid; 12603 12604 /** UID of application requesting the install */ 12605 final int installerUid; 12606 12607 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12608 this.originatingUri = originatingUri; 12609 this.referrer = referrer; 12610 this.originatingUid = originatingUid; 12611 this.installerUid = installerUid; 12612 } 12613 } 12614 12615 class InstallParams extends HandlerParams { 12616 final OriginInfo origin; 12617 final MoveInfo move; 12618 final IPackageInstallObserver2 observer; 12619 int installFlags; 12620 final String installerPackageName; 12621 final String volumeUuid; 12622 private InstallArgs mArgs; 12623 private int mRet; 12624 final String packageAbiOverride; 12625 final String[] grantedRuntimePermissions; 12626 final VerificationInfo verificationInfo; 12627 final Certificate[][] certificates; 12628 12629 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12630 int installFlags, String installerPackageName, String volumeUuid, 12631 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12632 String[] grantedPermissions, Certificate[][] certificates) { 12633 super(user); 12634 this.origin = origin; 12635 this.move = move; 12636 this.observer = observer; 12637 this.installFlags = installFlags; 12638 this.installerPackageName = installerPackageName; 12639 this.volumeUuid = volumeUuid; 12640 this.verificationInfo = verificationInfo; 12641 this.packageAbiOverride = packageAbiOverride; 12642 this.grantedRuntimePermissions = grantedPermissions; 12643 this.certificates = certificates; 12644 } 12645 12646 @Override 12647 public String toString() { 12648 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12649 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12650 } 12651 12652 private int installLocationPolicy(PackageInfoLite pkgLite) { 12653 String packageName = pkgLite.packageName; 12654 int installLocation = pkgLite.installLocation; 12655 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12656 // reader 12657 synchronized (mPackages) { 12658 // Currently installed package which the new package is attempting to replace or 12659 // null if no such package is installed. 12660 PackageParser.Package installedPkg = mPackages.get(packageName); 12661 // Package which currently owns the data which the new package will own if installed. 12662 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12663 // will be null whereas dataOwnerPkg will contain information about the package 12664 // which was uninstalled while keeping its data. 12665 PackageParser.Package dataOwnerPkg = installedPkg; 12666 if (dataOwnerPkg == null) { 12667 PackageSetting ps = mSettings.mPackages.get(packageName); 12668 if (ps != null) { 12669 dataOwnerPkg = ps.pkg; 12670 } 12671 } 12672 12673 if (dataOwnerPkg != null) { 12674 // If installed, the package will get access to data left on the device by its 12675 // predecessor. As a security measure, this is permited only if this is not a 12676 // version downgrade or if the predecessor package is marked as debuggable and 12677 // a downgrade is explicitly requested. 12678 // 12679 // On debuggable platform builds, downgrades are permitted even for 12680 // non-debuggable packages to make testing easier. Debuggable platform builds do 12681 // not offer security guarantees and thus it's OK to disable some security 12682 // mechanisms to make debugging/testing easier on those builds. However, even on 12683 // debuggable builds downgrades of packages are permitted only if requested via 12684 // installFlags. This is because we aim to keep the behavior of debuggable 12685 // platform builds as close as possible to the behavior of non-debuggable 12686 // platform builds. 12687 final boolean downgradeRequested = 12688 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12689 final boolean packageDebuggable = 12690 (dataOwnerPkg.applicationInfo.flags 12691 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12692 final boolean downgradePermitted = 12693 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12694 if (!downgradePermitted) { 12695 try { 12696 checkDowngrade(dataOwnerPkg, pkgLite); 12697 } catch (PackageManagerException e) { 12698 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12699 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12700 } 12701 } 12702 } 12703 12704 if (installedPkg != null) { 12705 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12706 // Check for updated system application. 12707 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12708 if (onSd) { 12709 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12710 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12711 } 12712 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12713 } else { 12714 if (onSd) { 12715 // Install flag overrides everything. 12716 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12717 } 12718 // If current upgrade specifies particular preference 12719 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12720 // Application explicitly specified internal. 12721 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12722 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12723 // App explictly prefers external. Let policy decide 12724 } else { 12725 // Prefer previous location 12726 if (isExternal(installedPkg)) { 12727 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12728 } 12729 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12730 } 12731 } 12732 } else { 12733 // Invalid install. Return error code 12734 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12735 } 12736 } 12737 } 12738 // All the special cases have been taken care of. 12739 // Return result based on recommended install location. 12740 if (onSd) { 12741 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12742 } 12743 return pkgLite.recommendedInstallLocation; 12744 } 12745 12746 /* 12747 * Invoke remote method to get package information and install 12748 * location values. Override install location based on default 12749 * policy if needed and then create install arguments based 12750 * on the install location. 12751 */ 12752 public void handleStartCopy() throws RemoteException { 12753 int ret = PackageManager.INSTALL_SUCCEEDED; 12754 12755 // If we're already staged, we've firmly committed to an install location 12756 if (origin.staged) { 12757 if (origin.file != null) { 12758 installFlags |= PackageManager.INSTALL_INTERNAL; 12759 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12760 } else if (origin.cid != null) { 12761 installFlags |= PackageManager.INSTALL_EXTERNAL; 12762 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12763 } else { 12764 throw new IllegalStateException("Invalid stage location"); 12765 } 12766 } 12767 12768 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12769 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12770 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12771 PackageInfoLite pkgLite = null; 12772 12773 if (onInt && onSd) { 12774 // Check if both bits are set. 12775 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12776 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12777 } else if (onSd && ephemeral) { 12778 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12779 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12780 } else { 12781 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12782 packageAbiOverride); 12783 12784 if (DEBUG_EPHEMERAL && ephemeral) { 12785 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12786 } 12787 12788 /* 12789 * If we have too little free space, try to free cache 12790 * before giving up. 12791 */ 12792 if (!origin.staged && pkgLite.recommendedInstallLocation 12793 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12794 // TODO: focus freeing disk space on the target device 12795 final StorageManager storage = StorageManager.from(mContext); 12796 final long lowThreshold = storage.getStorageLowBytes( 12797 Environment.getDataDirectory()); 12798 12799 final long sizeBytes = mContainerService.calculateInstalledSize( 12800 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12801 12802 try { 12803 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12804 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12805 installFlags, packageAbiOverride); 12806 } catch (InstallerException e) { 12807 Slog.w(TAG, "Failed to free cache", e); 12808 } 12809 12810 /* 12811 * The cache free must have deleted the file we 12812 * downloaded to install. 12813 * 12814 * TODO: fix the "freeCache" call to not delete 12815 * the file we care about. 12816 */ 12817 if (pkgLite.recommendedInstallLocation 12818 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12819 pkgLite.recommendedInstallLocation 12820 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12821 } 12822 } 12823 } 12824 12825 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12826 int loc = pkgLite.recommendedInstallLocation; 12827 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12828 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12829 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12830 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12831 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12832 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12833 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12834 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12835 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12836 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12837 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12838 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12839 } else { 12840 // Override with defaults if needed. 12841 loc = installLocationPolicy(pkgLite); 12842 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12843 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12844 } else if (!onSd && !onInt) { 12845 // Override install location with flags 12846 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12847 // Set the flag to install on external media. 12848 installFlags |= PackageManager.INSTALL_EXTERNAL; 12849 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12850 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12851 if (DEBUG_EPHEMERAL) { 12852 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12853 } 12854 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12855 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12856 |PackageManager.INSTALL_INTERNAL); 12857 } else { 12858 // Make sure the flag for installing on external 12859 // media is unset 12860 installFlags |= PackageManager.INSTALL_INTERNAL; 12861 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12862 } 12863 } 12864 } 12865 } 12866 12867 final InstallArgs args = createInstallArgs(this); 12868 mArgs = args; 12869 12870 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12871 // TODO: http://b/22976637 12872 // Apps installed for "all" users use the device owner to verify the app 12873 UserHandle verifierUser = getUser(); 12874 if (verifierUser == UserHandle.ALL) { 12875 verifierUser = UserHandle.SYSTEM; 12876 } 12877 12878 /* 12879 * Determine if we have any installed package verifiers. If we 12880 * do, then we'll defer to them to verify the packages. 12881 */ 12882 final int requiredUid = mRequiredVerifierPackage == null ? -1 12883 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12884 verifierUser.getIdentifier()); 12885 if (!origin.existing && requiredUid != -1 12886 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12887 final Intent verification = new Intent( 12888 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12889 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12890 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12891 PACKAGE_MIME_TYPE); 12892 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12893 12894 // Query all live verifiers based on current user state 12895 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12896 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12897 12898 if (DEBUG_VERIFY) { 12899 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12900 + verification.toString() + " with " + pkgLite.verifiers.length 12901 + " optional verifiers"); 12902 } 12903 12904 final int verificationId = mPendingVerificationToken++; 12905 12906 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12907 12908 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12909 installerPackageName); 12910 12911 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12912 installFlags); 12913 12914 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12915 pkgLite.packageName); 12916 12917 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12918 pkgLite.versionCode); 12919 12920 if (verificationInfo != null) { 12921 if (verificationInfo.originatingUri != null) { 12922 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12923 verificationInfo.originatingUri); 12924 } 12925 if (verificationInfo.referrer != null) { 12926 verification.putExtra(Intent.EXTRA_REFERRER, 12927 verificationInfo.referrer); 12928 } 12929 if (verificationInfo.originatingUid >= 0) { 12930 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12931 verificationInfo.originatingUid); 12932 } 12933 if (verificationInfo.installerUid >= 0) { 12934 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12935 verificationInfo.installerUid); 12936 } 12937 } 12938 12939 final PackageVerificationState verificationState = new PackageVerificationState( 12940 requiredUid, args); 12941 12942 mPendingVerification.append(verificationId, verificationState); 12943 12944 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12945 receivers, verificationState); 12946 12947 /* 12948 * If any sufficient verifiers were listed in the package 12949 * manifest, attempt to ask them. 12950 */ 12951 if (sufficientVerifiers != null) { 12952 final int N = sufficientVerifiers.size(); 12953 if (N == 0) { 12954 Slog.i(TAG, "Additional verifiers required, but none installed."); 12955 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12956 } else { 12957 for (int i = 0; i < N; i++) { 12958 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12959 12960 final Intent sufficientIntent = new Intent(verification); 12961 sufficientIntent.setComponent(verifierComponent); 12962 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12963 } 12964 } 12965 } 12966 12967 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12968 mRequiredVerifierPackage, receivers); 12969 if (ret == PackageManager.INSTALL_SUCCEEDED 12970 && mRequiredVerifierPackage != null) { 12971 Trace.asyncTraceBegin( 12972 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12973 /* 12974 * Send the intent to the required verification agent, 12975 * but only start the verification timeout after the 12976 * target BroadcastReceivers have run. 12977 */ 12978 verification.setComponent(requiredVerifierComponent); 12979 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12980 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12981 new BroadcastReceiver() { 12982 @Override 12983 public void onReceive(Context context, Intent intent) { 12984 final Message msg = mHandler 12985 .obtainMessage(CHECK_PENDING_VERIFICATION); 12986 msg.arg1 = verificationId; 12987 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12988 } 12989 }, null, 0, null, null); 12990 12991 /* 12992 * We don't want the copy to proceed until verification 12993 * succeeds, so null out this field. 12994 */ 12995 mArgs = null; 12996 } 12997 } else { 12998 /* 12999 * No package verification is enabled, so immediately start 13000 * the remote call to initiate copy using temporary file. 13001 */ 13002 ret = args.copyApk(mContainerService, true); 13003 } 13004 } 13005 13006 mRet = ret; 13007 } 13008 13009 @Override 13010 void handleReturnCode() { 13011 // If mArgs is null, then MCS couldn't be reached. When it 13012 // reconnects, it will try again to install. At that point, this 13013 // will succeed. 13014 if (mArgs != null) { 13015 processPendingInstall(mArgs, mRet); 13016 } 13017 } 13018 13019 @Override 13020 void handleServiceError() { 13021 mArgs = createInstallArgs(this); 13022 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13023 } 13024 13025 public boolean isForwardLocked() { 13026 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13027 } 13028 } 13029 13030 /** 13031 * Used during creation of InstallArgs 13032 * 13033 * @param installFlags package installation flags 13034 * @return true if should be installed on external storage 13035 */ 13036 private static boolean installOnExternalAsec(int installFlags) { 13037 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13038 return false; 13039 } 13040 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13041 return true; 13042 } 13043 return false; 13044 } 13045 13046 /** 13047 * Used during creation of InstallArgs 13048 * 13049 * @param installFlags package installation flags 13050 * @return true if should be installed as forward locked 13051 */ 13052 private static boolean installForwardLocked(int installFlags) { 13053 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13054 } 13055 13056 private InstallArgs createInstallArgs(InstallParams params) { 13057 if (params.move != null) { 13058 return new MoveInstallArgs(params); 13059 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13060 return new AsecInstallArgs(params); 13061 } else { 13062 return new FileInstallArgs(params); 13063 } 13064 } 13065 13066 /** 13067 * Create args that describe an existing installed package. Typically used 13068 * when cleaning up old installs, or used as a move source. 13069 */ 13070 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13071 String resourcePath, String[] instructionSets) { 13072 final boolean isInAsec; 13073 if (installOnExternalAsec(installFlags)) { 13074 /* Apps on SD card are always in ASEC containers. */ 13075 isInAsec = true; 13076 } else if (installForwardLocked(installFlags) 13077 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13078 /* 13079 * Forward-locked apps are only in ASEC containers if they're the 13080 * new style 13081 */ 13082 isInAsec = true; 13083 } else { 13084 isInAsec = false; 13085 } 13086 13087 if (isInAsec) { 13088 return new AsecInstallArgs(codePath, instructionSets, 13089 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13090 } else { 13091 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13092 } 13093 } 13094 13095 static abstract class InstallArgs { 13096 /** @see InstallParams#origin */ 13097 final OriginInfo origin; 13098 /** @see InstallParams#move */ 13099 final MoveInfo move; 13100 13101 final IPackageInstallObserver2 observer; 13102 // Always refers to PackageManager flags only 13103 final int installFlags; 13104 final String installerPackageName; 13105 final String volumeUuid; 13106 final UserHandle user; 13107 final String abiOverride; 13108 final String[] installGrantPermissions; 13109 /** If non-null, drop an async trace when the install completes */ 13110 final String traceMethod; 13111 final int traceCookie; 13112 final Certificate[][] certificates; 13113 13114 // The list of instruction sets supported by this app. This is currently 13115 // only used during the rmdex() phase to clean up resources. We can get rid of this 13116 // if we move dex files under the common app path. 13117 /* nullable */ String[] instructionSets; 13118 13119 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13120 int installFlags, String installerPackageName, String volumeUuid, 13121 UserHandle user, String[] instructionSets, 13122 String abiOverride, String[] installGrantPermissions, 13123 String traceMethod, int traceCookie, Certificate[][] certificates) { 13124 this.origin = origin; 13125 this.move = move; 13126 this.installFlags = installFlags; 13127 this.observer = observer; 13128 this.installerPackageName = installerPackageName; 13129 this.volumeUuid = volumeUuid; 13130 this.user = user; 13131 this.instructionSets = instructionSets; 13132 this.abiOverride = abiOverride; 13133 this.installGrantPermissions = installGrantPermissions; 13134 this.traceMethod = traceMethod; 13135 this.traceCookie = traceCookie; 13136 this.certificates = certificates; 13137 } 13138 13139 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13140 abstract int doPreInstall(int status); 13141 13142 /** 13143 * Rename package into final resting place. All paths on the given 13144 * scanned package should be updated to reflect the rename. 13145 */ 13146 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13147 abstract int doPostInstall(int status, int uid); 13148 13149 /** @see PackageSettingBase#codePathString */ 13150 abstract String getCodePath(); 13151 /** @see PackageSettingBase#resourcePathString */ 13152 abstract String getResourcePath(); 13153 13154 // Need installer lock especially for dex file removal. 13155 abstract void cleanUpResourcesLI(); 13156 abstract boolean doPostDeleteLI(boolean delete); 13157 13158 /** 13159 * Called before the source arguments are copied. This is used mostly 13160 * for MoveParams when it needs to read the source file to put it in the 13161 * destination. 13162 */ 13163 int doPreCopy() { 13164 return PackageManager.INSTALL_SUCCEEDED; 13165 } 13166 13167 /** 13168 * Called after the source arguments are copied. This is used mostly for 13169 * MoveParams when it needs to read the source file to put it in the 13170 * destination. 13171 */ 13172 int doPostCopy(int uid) { 13173 return PackageManager.INSTALL_SUCCEEDED; 13174 } 13175 13176 protected boolean isFwdLocked() { 13177 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13178 } 13179 13180 protected boolean isExternalAsec() { 13181 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13182 } 13183 13184 protected boolean isEphemeral() { 13185 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13186 } 13187 13188 UserHandle getUser() { 13189 return user; 13190 } 13191 } 13192 13193 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13194 if (!allCodePaths.isEmpty()) { 13195 if (instructionSets == null) { 13196 throw new IllegalStateException("instructionSet == null"); 13197 } 13198 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13199 for (String codePath : allCodePaths) { 13200 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13201 try { 13202 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13203 } catch (InstallerException ignored) { 13204 } 13205 } 13206 } 13207 } 13208 } 13209 13210 /** 13211 * Logic to handle installation of non-ASEC applications, including copying 13212 * and renaming logic. 13213 */ 13214 class FileInstallArgs extends InstallArgs { 13215 private File codeFile; 13216 private File resourceFile; 13217 13218 // Example topology: 13219 // /data/app/com.example/base.apk 13220 // /data/app/com.example/split_foo.apk 13221 // /data/app/com.example/lib/arm/libfoo.so 13222 // /data/app/com.example/lib/arm64/libfoo.so 13223 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13224 13225 /** New install */ 13226 FileInstallArgs(InstallParams params) { 13227 super(params.origin, params.move, params.observer, params.installFlags, 13228 params.installerPackageName, params.volumeUuid, 13229 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13230 params.grantedRuntimePermissions, 13231 params.traceMethod, params.traceCookie, params.certificates); 13232 if (isFwdLocked()) { 13233 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13234 } 13235 } 13236 13237 /** Existing install */ 13238 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13239 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13240 null, null, null, 0, null /*certificates*/); 13241 this.codeFile = (codePath != null) ? new File(codePath) : null; 13242 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13243 } 13244 13245 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13246 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13247 try { 13248 return doCopyApk(imcs, temp); 13249 } finally { 13250 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13251 } 13252 } 13253 13254 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13255 if (origin.staged) { 13256 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13257 codeFile = origin.file; 13258 resourceFile = origin.file; 13259 return PackageManager.INSTALL_SUCCEEDED; 13260 } 13261 13262 try { 13263 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13264 final File tempDir = 13265 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13266 codeFile = tempDir; 13267 resourceFile = tempDir; 13268 } catch (IOException e) { 13269 Slog.w(TAG, "Failed to create copy file: " + e); 13270 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13271 } 13272 13273 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13274 @Override 13275 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13276 if (!FileUtils.isValidExtFilename(name)) { 13277 throw new IllegalArgumentException("Invalid filename: " + name); 13278 } 13279 try { 13280 final File file = new File(codeFile, name); 13281 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13282 O_RDWR | O_CREAT, 0644); 13283 Os.chmod(file.getAbsolutePath(), 0644); 13284 return new ParcelFileDescriptor(fd); 13285 } catch (ErrnoException e) { 13286 throw new RemoteException("Failed to open: " + e.getMessage()); 13287 } 13288 } 13289 }; 13290 13291 int ret = PackageManager.INSTALL_SUCCEEDED; 13292 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13293 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13294 Slog.e(TAG, "Failed to copy package"); 13295 return ret; 13296 } 13297 13298 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13299 NativeLibraryHelper.Handle handle = null; 13300 try { 13301 handle = NativeLibraryHelper.Handle.create(codeFile); 13302 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13303 abiOverride); 13304 } catch (IOException e) { 13305 Slog.e(TAG, "Copying native libraries failed", e); 13306 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13307 } finally { 13308 IoUtils.closeQuietly(handle); 13309 } 13310 13311 return ret; 13312 } 13313 13314 int doPreInstall(int status) { 13315 if (status != PackageManager.INSTALL_SUCCEEDED) { 13316 cleanUp(); 13317 } 13318 return status; 13319 } 13320 13321 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13322 if (status != PackageManager.INSTALL_SUCCEEDED) { 13323 cleanUp(); 13324 return false; 13325 } 13326 13327 final File targetDir = codeFile.getParentFile(); 13328 final File beforeCodeFile = codeFile; 13329 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13330 13331 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13332 try { 13333 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13334 } catch (ErrnoException e) { 13335 Slog.w(TAG, "Failed to rename", e); 13336 return false; 13337 } 13338 13339 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13340 Slog.w(TAG, "Failed to restorecon"); 13341 return false; 13342 } 13343 13344 // Reflect the rename internally 13345 codeFile = afterCodeFile; 13346 resourceFile = afterCodeFile; 13347 13348 // Reflect the rename in scanned details 13349 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13350 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13351 afterCodeFile, pkg.baseCodePath)); 13352 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13353 afterCodeFile, pkg.splitCodePaths)); 13354 13355 // Reflect the rename in app info 13356 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13357 pkg.setApplicationInfoCodePath(pkg.codePath); 13358 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13359 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13360 pkg.setApplicationInfoResourcePath(pkg.codePath); 13361 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13362 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13363 13364 return true; 13365 } 13366 13367 int doPostInstall(int status, int uid) { 13368 if (status != PackageManager.INSTALL_SUCCEEDED) { 13369 cleanUp(); 13370 } 13371 return status; 13372 } 13373 13374 @Override 13375 String getCodePath() { 13376 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13377 } 13378 13379 @Override 13380 String getResourcePath() { 13381 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13382 } 13383 13384 private boolean cleanUp() { 13385 if (codeFile == null || !codeFile.exists()) { 13386 return false; 13387 } 13388 13389 removeCodePathLI(codeFile); 13390 13391 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13392 resourceFile.delete(); 13393 } 13394 13395 return true; 13396 } 13397 13398 void cleanUpResourcesLI() { 13399 // Try enumerating all code paths before deleting 13400 List<String> allCodePaths = Collections.EMPTY_LIST; 13401 if (codeFile != null && codeFile.exists()) { 13402 try { 13403 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13404 allCodePaths = pkg.getAllCodePaths(); 13405 } catch (PackageParserException e) { 13406 // Ignored; we tried our best 13407 } 13408 } 13409 13410 cleanUp(); 13411 removeDexFiles(allCodePaths, instructionSets); 13412 } 13413 13414 boolean doPostDeleteLI(boolean delete) { 13415 // XXX err, shouldn't we respect the delete flag? 13416 cleanUpResourcesLI(); 13417 return true; 13418 } 13419 } 13420 13421 private boolean isAsecExternal(String cid) { 13422 final String asecPath = PackageHelper.getSdFilesystem(cid); 13423 return !asecPath.startsWith(mAsecInternalPath); 13424 } 13425 13426 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13427 PackageManagerException { 13428 if (copyRet < 0) { 13429 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13430 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13431 throw new PackageManagerException(copyRet, message); 13432 } 13433 } 13434 } 13435 13436 /** 13437 * Extract the MountService "container ID" from the full code path of an 13438 * .apk. 13439 */ 13440 static String cidFromCodePath(String fullCodePath) { 13441 int eidx = fullCodePath.lastIndexOf("/"); 13442 String subStr1 = fullCodePath.substring(0, eidx); 13443 int sidx = subStr1.lastIndexOf("/"); 13444 return subStr1.substring(sidx+1, eidx); 13445 } 13446 13447 /** 13448 * Logic to handle installation of ASEC applications, including copying and 13449 * renaming logic. 13450 */ 13451 class AsecInstallArgs extends InstallArgs { 13452 static final String RES_FILE_NAME = "pkg.apk"; 13453 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13454 13455 String cid; 13456 String packagePath; 13457 String resourcePath; 13458 13459 /** New install */ 13460 AsecInstallArgs(InstallParams params) { 13461 super(params.origin, params.move, params.observer, params.installFlags, 13462 params.installerPackageName, params.volumeUuid, 13463 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13464 params.grantedRuntimePermissions, 13465 params.traceMethod, params.traceCookie, params.certificates); 13466 } 13467 13468 /** Existing install */ 13469 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13470 boolean isExternal, boolean isForwardLocked) { 13471 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13472 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13473 instructionSets, null, null, null, 0, null /*certificates*/); 13474 // Hackily pretend we're still looking at a full code path 13475 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13476 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13477 } 13478 13479 // Extract cid from fullCodePath 13480 int eidx = fullCodePath.lastIndexOf("/"); 13481 String subStr1 = fullCodePath.substring(0, eidx); 13482 int sidx = subStr1.lastIndexOf("/"); 13483 cid = subStr1.substring(sidx+1, eidx); 13484 setMountPath(subStr1); 13485 } 13486 13487 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13488 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13489 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13490 instructionSets, null, null, null, 0, null /*certificates*/); 13491 this.cid = cid; 13492 setMountPath(PackageHelper.getSdDir(cid)); 13493 } 13494 13495 void createCopyFile() { 13496 cid = mInstallerService.allocateExternalStageCidLegacy(); 13497 } 13498 13499 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13500 if (origin.staged && origin.cid != null) { 13501 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13502 cid = origin.cid; 13503 setMountPath(PackageHelper.getSdDir(cid)); 13504 return PackageManager.INSTALL_SUCCEEDED; 13505 } 13506 13507 if (temp) { 13508 createCopyFile(); 13509 } else { 13510 /* 13511 * Pre-emptively destroy the container since it's destroyed if 13512 * copying fails due to it existing anyway. 13513 */ 13514 PackageHelper.destroySdDir(cid); 13515 } 13516 13517 final String newMountPath = imcs.copyPackageToContainer( 13518 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13519 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13520 13521 if (newMountPath != null) { 13522 setMountPath(newMountPath); 13523 return PackageManager.INSTALL_SUCCEEDED; 13524 } else { 13525 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13526 } 13527 } 13528 13529 @Override 13530 String getCodePath() { 13531 return packagePath; 13532 } 13533 13534 @Override 13535 String getResourcePath() { 13536 return resourcePath; 13537 } 13538 13539 int doPreInstall(int status) { 13540 if (status != PackageManager.INSTALL_SUCCEEDED) { 13541 // Destroy container 13542 PackageHelper.destroySdDir(cid); 13543 } else { 13544 boolean mounted = PackageHelper.isContainerMounted(cid); 13545 if (!mounted) { 13546 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13547 Process.SYSTEM_UID); 13548 if (newMountPath != null) { 13549 setMountPath(newMountPath); 13550 } else { 13551 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13552 } 13553 } 13554 } 13555 return status; 13556 } 13557 13558 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13559 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13560 String newMountPath = null; 13561 if (PackageHelper.isContainerMounted(cid)) { 13562 // Unmount the container 13563 if (!PackageHelper.unMountSdDir(cid)) { 13564 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13565 return false; 13566 } 13567 } 13568 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13569 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13570 " which might be stale. Will try to clean up."); 13571 // Clean up the stale container and proceed to recreate. 13572 if (!PackageHelper.destroySdDir(newCacheId)) { 13573 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13574 return false; 13575 } 13576 // Successfully cleaned up stale container. Try to rename again. 13577 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13578 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13579 + " inspite of cleaning it up."); 13580 return false; 13581 } 13582 } 13583 if (!PackageHelper.isContainerMounted(newCacheId)) { 13584 Slog.w(TAG, "Mounting container " + newCacheId); 13585 newMountPath = PackageHelper.mountSdDir(newCacheId, 13586 getEncryptKey(), Process.SYSTEM_UID); 13587 } else { 13588 newMountPath = PackageHelper.getSdDir(newCacheId); 13589 } 13590 if (newMountPath == null) { 13591 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13592 return false; 13593 } 13594 Log.i(TAG, "Succesfully renamed " + cid + 13595 " to " + newCacheId + 13596 " at new path: " + newMountPath); 13597 cid = newCacheId; 13598 13599 final File beforeCodeFile = new File(packagePath); 13600 setMountPath(newMountPath); 13601 final File afterCodeFile = new File(packagePath); 13602 13603 // Reflect the rename in scanned details 13604 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13605 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13606 afterCodeFile, pkg.baseCodePath)); 13607 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13608 afterCodeFile, pkg.splitCodePaths)); 13609 13610 // Reflect the rename in app info 13611 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13612 pkg.setApplicationInfoCodePath(pkg.codePath); 13613 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13614 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13615 pkg.setApplicationInfoResourcePath(pkg.codePath); 13616 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13617 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13618 13619 return true; 13620 } 13621 13622 private void setMountPath(String mountPath) { 13623 final File mountFile = new File(mountPath); 13624 13625 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13626 if (monolithicFile.exists()) { 13627 packagePath = monolithicFile.getAbsolutePath(); 13628 if (isFwdLocked()) { 13629 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13630 } else { 13631 resourcePath = packagePath; 13632 } 13633 } else { 13634 packagePath = mountFile.getAbsolutePath(); 13635 resourcePath = packagePath; 13636 } 13637 } 13638 13639 int doPostInstall(int status, int uid) { 13640 if (status != PackageManager.INSTALL_SUCCEEDED) { 13641 cleanUp(); 13642 } else { 13643 final int groupOwner; 13644 final String protectedFile; 13645 if (isFwdLocked()) { 13646 groupOwner = UserHandle.getSharedAppGid(uid); 13647 protectedFile = RES_FILE_NAME; 13648 } else { 13649 groupOwner = -1; 13650 protectedFile = null; 13651 } 13652 13653 if (uid < Process.FIRST_APPLICATION_UID 13654 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13655 Slog.e(TAG, "Failed to finalize " + cid); 13656 PackageHelper.destroySdDir(cid); 13657 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13658 } 13659 13660 boolean mounted = PackageHelper.isContainerMounted(cid); 13661 if (!mounted) { 13662 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13663 } 13664 } 13665 return status; 13666 } 13667 13668 private void cleanUp() { 13669 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13670 13671 // Destroy secure container 13672 PackageHelper.destroySdDir(cid); 13673 } 13674 13675 private List<String> getAllCodePaths() { 13676 final File codeFile = new File(getCodePath()); 13677 if (codeFile != null && codeFile.exists()) { 13678 try { 13679 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13680 return pkg.getAllCodePaths(); 13681 } catch (PackageParserException e) { 13682 // Ignored; we tried our best 13683 } 13684 } 13685 return Collections.EMPTY_LIST; 13686 } 13687 13688 void cleanUpResourcesLI() { 13689 // Enumerate all code paths before deleting 13690 cleanUpResourcesLI(getAllCodePaths()); 13691 } 13692 13693 private void cleanUpResourcesLI(List<String> allCodePaths) { 13694 cleanUp(); 13695 removeDexFiles(allCodePaths, instructionSets); 13696 } 13697 13698 String getPackageName() { 13699 return getAsecPackageName(cid); 13700 } 13701 13702 boolean doPostDeleteLI(boolean delete) { 13703 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13704 final List<String> allCodePaths = getAllCodePaths(); 13705 boolean mounted = PackageHelper.isContainerMounted(cid); 13706 if (mounted) { 13707 // Unmount first 13708 if (PackageHelper.unMountSdDir(cid)) { 13709 mounted = false; 13710 } 13711 } 13712 if (!mounted && delete) { 13713 cleanUpResourcesLI(allCodePaths); 13714 } 13715 return !mounted; 13716 } 13717 13718 @Override 13719 int doPreCopy() { 13720 if (isFwdLocked()) { 13721 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13722 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13723 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13724 } 13725 } 13726 13727 return PackageManager.INSTALL_SUCCEEDED; 13728 } 13729 13730 @Override 13731 int doPostCopy(int uid) { 13732 if (isFwdLocked()) { 13733 if (uid < Process.FIRST_APPLICATION_UID 13734 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13735 RES_FILE_NAME)) { 13736 Slog.e(TAG, "Failed to finalize " + cid); 13737 PackageHelper.destroySdDir(cid); 13738 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13739 } 13740 } 13741 13742 return PackageManager.INSTALL_SUCCEEDED; 13743 } 13744 } 13745 13746 /** 13747 * Logic to handle movement of existing installed applications. 13748 */ 13749 class MoveInstallArgs extends InstallArgs { 13750 private File codeFile; 13751 private File resourceFile; 13752 13753 /** New install */ 13754 MoveInstallArgs(InstallParams params) { 13755 super(params.origin, params.move, params.observer, params.installFlags, 13756 params.installerPackageName, params.volumeUuid, 13757 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13758 params.grantedRuntimePermissions, 13759 params.traceMethod, params.traceCookie, params.certificates); 13760 } 13761 13762 int copyApk(IMediaContainerService imcs, boolean temp) { 13763 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13764 + move.fromUuid + " to " + move.toUuid); 13765 synchronized (mInstaller) { 13766 try { 13767 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13768 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13769 } catch (InstallerException e) { 13770 Slog.w(TAG, "Failed to move app", e); 13771 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13772 } 13773 } 13774 13775 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13776 resourceFile = codeFile; 13777 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13778 13779 return PackageManager.INSTALL_SUCCEEDED; 13780 } 13781 13782 int doPreInstall(int status) { 13783 if (status != PackageManager.INSTALL_SUCCEEDED) { 13784 cleanUp(move.toUuid); 13785 } 13786 return status; 13787 } 13788 13789 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13790 if (status != PackageManager.INSTALL_SUCCEEDED) { 13791 cleanUp(move.toUuid); 13792 return false; 13793 } 13794 13795 // Reflect the move in app info 13796 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13797 pkg.setApplicationInfoCodePath(pkg.codePath); 13798 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13799 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13800 pkg.setApplicationInfoResourcePath(pkg.codePath); 13801 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13802 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13803 13804 return true; 13805 } 13806 13807 int doPostInstall(int status, int uid) { 13808 if (status == PackageManager.INSTALL_SUCCEEDED) { 13809 cleanUp(move.fromUuid); 13810 } else { 13811 cleanUp(move.toUuid); 13812 } 13813 return status; 13814 } 13815 13816 @Override 13817 String getCodePath() { 13818 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13819 } 13820 13821 @Override 13822 String getResourcePath() { 13823 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13824 } 13825 13826 private boolean cleanUp(String volumeUuid) { 13827 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13828 move.dataAppName); 13829 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13830 final int[] userIds = sUserManager.getUserIds(); 13831 synchronized (mInstallLock) { 13832 // Clean up both app data and code 13833 // All package moves are frozen until finished 13834 for (int userId : userIds) { 13835 try { 13836 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13837 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13838 } catch (InstallerException e) { 13839 Slog.w(TAG, String.valueOf(e)); 13840 } 13841 } 13842 removeCodePathLI(codeFile); 13843 } 13844 return true; 13845 } 13846 13847 void cleanUpResourcesLI() { 13848 throw new UnsupportedOperationException(); 13849 } 13850 13851 boolean doPostDeleteLI(boolean delete) { 13852 throw new UnsupportedOperationException(); 13853 } 13854 } 13855 13856 static String getAsecPackageName(String packageCid) { 13857 int idx = packageCid.lastIndexOf("-"); 13858 if (idx == -1) { 13859 return packageCid; 13860 } 13861 return packageCid.substring(0, idx); 13862 } 13863 13864 // Utility method used to create code paths based on package name and available index. 13865 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13866 String idxStr = ""; 13867 int idx = 1; 13868 // Fall back to default value of idx=1 if prefix is not 13869 // part of oldCodePath 13870 if (oldCodePath != null) { 13871 String subStr = oldCodePath; 13872 // Drop the suffix right away 13873 if (suffix != null && subStr.endsWith(suffix)) { 13874 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13875 } 13876 // If oldCodePath already contains prefix find out the 13877 // ending index to either increment or decrement. 13878 int sidx = subStr.lastIndexOf(prefix); 13879 if (sidx != -1) { 13880 subStr = subStr.substring(sidx + prefix.length()); 13881 if (subStr != null) { 13882 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13883 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13884 } 13885 try { 13886 idx = Integer.parseInt(subStr); 13887 if (idx <= 1) { 13888 idx++; 13889 } else { 13890 idx--; 13891 } 13892 } catch(NumberFormatException e) { 13893 } 13894 } 13895 } 13896 } 13897 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13898 return prefix + idxStr; 13899 } 13900 13901 private File getNextCodePath(File targetDir, String packageName) { 13902 int suffix = 1; 13903 File result; 13904 do { 13905 result = new File(targetDir, packageName + "-" + suffix); 13906 suffix++; 13907 } while (result.exists()); 13908 return result; 13909 } 13910 13911 // Utility method that returns the relative package path with respect 13912 // to the installation directory. Like say for /data/data/com.test-1.apk 13913 // string com.test-1 is returned. 13914 static String deriveCodePathName(String codePath) { 13915 if (codePath == null) { 13916 return null; 13917 } 13918 final File codeFile = new File(codePath); 13919 final String name = codeFile.getName(); 13920 if (codeFile.isDirectory()) { 13921 return name; 13922 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13923 final int lastDot = name.lastIndexOf('.'); 13924 return name.substring(0, lastDot); 13925 } else { 13926 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13927 return null; 13928 } 13929 } 13930 13931 static class PackageInstalledInfo { 13932 String name; 13933 int uid; 13934 // The set of users that originally had this package installed. 13935 int[] origUsers; 13936 // The set of users that now have this package installed. 13937 int[] newUsers; 13938 PackageParser.Package pkg; 13939 int returnCode; 13940 String returnMsg; 13941 PackageRemovedInfo removedInfo; 13942 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13943 13944 public void setError(int code, String msg) { 13945 setReturnCode(code); 13946 setReturnMessage(msg); 13947 Slog.w(TAG, msg); 13948 } 13949 13950 public void setError(String msg, PackageParserException e) { 13951 setReturnCode(e.error); 13952 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13953 Slog.w(TAG, msg, e); 13954 } 13955 13956 public void setError(String msg, PackageManagerException e) { 13957 returnCode = e.error; 13958 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13959 Slog.w(TAG, msg, e); 13960 } 13961 13962 public void setReturnCode(int returnCode) { 13963 this.returnCode = returnCode; 13964 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13965 for (int i = 0; i < childCount; i++) { 13966 addedChildPackages.valueAt(i).returnCode = returnCode; 13967 } 13968 } 13969 13970 private void setReturnMessage(String returnMsg) { 13971 this.returnMsg = returnMsg; 13972 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13973 for (int i = 0; i < childCount; i++) { 13974 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13975 } 13976 } 13977 13978 // In some error cases we want to convey more info back to the observer 13979 String origPackage; 13980 String origPermission; 13981 } 13982 13983 /* 13984 * Install a non-existing package. 13985 */ 13986 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13987 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13988 PackageInstalledInfo res) { 13989 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13990 13991 // Remember this for later, in case we need to rollback this install 13992 String pkgName = pkg.packageName; 13993 13994 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13995 13996 synchronized(mPackages) { 13997 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13998 // A package with the same name is already installed, though 13999 // it has been renamed to an older name. The package we 14000 // are trying to install should be installed as an update to 14001 // the existing one, but that has not been requested, so bail. 14002 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14003 + " without first uninstalling package running as " 14004 + mSettings.mRenamedPackages.get(pkgName)); 14005 return; 14006 } 14007 if (mPackages.containsKey(pkgName)) { 14008 // Don't allow installation over an existing package with the same name. 14009 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14010 + " without first uninstalling."); 14011 return; 14012 } 14013 } 14014 14015 try { 14016 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14017 System.currentTimeMillis(), user); 14018 14019 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14020 14021 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14022 prepareAppDataAfterInstallLIF(newPackage); 14023 14024 } else { 14025 // Remove package from internal structures, but keep around any 14026 // data that might have already existed 14027 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14028 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14029 } 14030 } catch (PackageManagerException e) { 14031 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14032 } 14033 14034 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14035 } 14036 14037 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14038 // Can't rotate keys during boot or if sharedUser. 14039 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14040 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14041 return false; 14042 } 14043 // app is using upgradeKeySets; make sure all are valid 14044 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14045 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14046 for (int i = 0; i < upgradeKeySets.length; i++) { 14047 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14048 Slog.wtf(TAG, "Package " 14049 + (oldPs.name != null ? oldPs.name : "<null>") 14050 + " contains upgrade-key-set reference to unknown key-set: " 14051 + upgradeKeySets[i] 14052 + " reverting to signatures check."); 14053 return false; 14054 } 14055 } 14056 return true; 14057 } 14058 14059 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14060 // Upgrade keysets are being used. Determine if new package has a superset of the 14061 // required keys. 14062 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14063 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14064 for (int i = 0; i < upgradeKeySets.length; i++) { 14065 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14066 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14067 return true; 14068 } 14069 } 14070 return false; 14071 } 14072 14073 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14074 try (DigestInputStream digestStream = 14075 new DigestInputStream(new FileInputStream(file), digest)) { 14076 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14077 } 14078 } 14079 14080 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14081 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14082 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14083 14084 final PackageParser.Package oldPackage; 14085 final String pkgName = pkg.packageName; 14086 final int[] allUsers; 14087 final int[] installedUsers; 14088 14089 synchronized(mPackages) { 14090 oldPackage = mPackages.get(pkgName); 14091 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14092 14093 // don't allow upgrade to target a release SDK from a pre-release SDK 14094 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14095 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14096 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14097 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14098 if (oldTargetsPreRelease 14099 && !newTargetsPreRelease 14100 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14101 Slog.w(TAG, "Can't install package targeting released sdk"); 14102 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14103 return; 14104 } 14105 14106 // don't allow an upgrade from full to ephemeral 14107 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14108 if (isEphemeral && !oldIsEphemeral) { 14109 // can't downgrade from full to ephemeral 14110 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14111 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14112 return; 14113 } 14114 14115 // verify signatures are valid 14116 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14117 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14118 if (!checkUpgradeKeySetLP(ps, pkg)) { 14119 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14120 "New package not signed by keys specified by upgrade-keysets: " 14121 + pkgName); 14122 return; 14123 } 14124 } else { 14125 // default to original signature matching 14126 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14127 != PackageManager.SIGNATURE_MATCH) { 14128 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14129 "New package has a different signature: " + pkgName); 14130 return; 14131 } 14132 } 14133 14134 // don't allow a system upgrade unless the upgrade hash matches 14135 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14136 byte[] digestBytes = null; 14137 try { 14138 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14139 updateDigest(digest, new File(pkg.baseCodePath)); 14140 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14141 for (String path : pkg.splitCodePaths) { 14142 updateDigest(digest, new File(path)); 14143 } 14144 } 14145 digestBytes = digest.digest(); 14146 } catch (NoSuchAlgorithmException | IOException e) { 14147 res.setError(INSTALL_FAILED_INVALID_APK, 14148 "Could not compute hash: " + pkgName); 14149 return; 14150 } 14151 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14152 res.setError(INSTALL_FAILED_INVALID_APK, 14153 "New package fails restrict-update check: " + pkgName); 14154 return; 14155 } 14156 // retain upgrade restriction 14157 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14158 } 14159 14160 // Check for shared user id changes 14161 String invalidPackageName = 14162 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14163 if (invalidPackageName != null) { 14164 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14165 "Package " + invalidPackageName + " tried to change user " 14166 + oldPackage.mSharedUserId); 14167 return; 14168 } 14169 14170 // In case of rollback, remember per-user/profile install state 14171 allUsers = sUserManager.getUserIds(); 14172 installedUsers = ps.queryInstalledUsers(allUsers, true); 14173 } 14174 14175 // Update what is removed 14176 res.removedInfo = new PackageRemovedInfo(); 14177 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14178 res.removedInfo.removedPackage = oldPackage.packageName; 14179 res.removedInfo.isUpdate = true; 14180 res.removedInfo.origUsers = installedUsers; 14181 final int childCount = (oldPackage.childPackages != null) 14182 ? oldPackage.childPackages.size() : 0; 14183 for (int i = 0; i < childCount; i++) { 14184 boolean childPackageUpdated = false; 14185 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14186 if (res.addedChildPackages != null) { 14187 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14188 if (childRes != null) { 14189 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14190 childRes.removedInfo.removedPackage = childPkg.packageName; 14191 childRes.removedInfo.isUpdate = true; 14192 childPackageUpdated = true; 14193 } 14194 } 14195 if (!childPackageUpdated) { 14196 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14197 childRemovedRes.removedPackage = childPkg.packageName; 14198 childRemovedRes.isUpdate = false; 14199 childRemovedRes.dataRemoved = true; 14200 synchronized (mPackages) { 14201 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14202 if (childPs != null) { 14203 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14204 } 14205 } 14206 if (res.removedInfo.removedChildPackages == null) { 14207 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14208 } 14209 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14210 } 14211 } 14212 14213 boolean sysPkg = (isSystemApp(oldPackage)); 14214 if (sysPkg) { 14215 // Set the system/privileged flags as needed 14216 final boolean privileged = 14217 (oldPackage.applicationInfo.privateFlags 14218 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14219 final int systemPolicyFlags = policyFlags 14220 | PackageParser.PARSE_IS_SYSTEM 14221 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14222 14223 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14224 user, allUsers, installerPackageName, res); 14225 } else { 14226 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14227 user, allUsers, installerPackageName, res); 14228 } 14229 } 14230 14231 public List<String> getPreviousCodePaths(String packageName) { 14232 final PackageSetting ps = mSettings.mPackages.get(packageName); 14233 final List<String> result = new ArrayList<String>(); 14234 if (ps != null && ps.oldCodePaths != null) { 14235 result.addAll(ps.oldCodePaths); 14236 } 14237 return result; 14238 } 14239 14240 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14241 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14242 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14243 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14244 + deletedPackage); 14245 14246 String pkgName = deletedPackage.packageName; 14247 boolean deletedPkg = true; 14248 boolean addedPkg = false; 14249 boolean updatedSettings = false; 14250 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14251 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14252 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14253 14254 final long origUpdateTime = (pkg.mExtras != null) 14255 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14256 14257 // First delete the existing package while retaining the data directory 14258 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14259 res.removedInfo, true, pkg)) { 14260 // If the existing package wasn't successfully deleted 14261 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14262 deletedPkg = false; 14263 } else { 14264 // Successfully deleted the old package; proceed with replace. 14265 14266 // If deleted package lived in a container, give users a chance to 14267 // relinquish resources before killing. 14268 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14269 if (DEBUG_INSTALL) { 14270 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14271 } 14272 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14273 final ArrayList<String> pkgList = new ArrayList<String>(1); 14274 pkgList.add(deletedPackage.applicationInfo.packageName); 14275 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14276 } 14277 14278 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14279 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14280 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14281 14282 try { 14283 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14284 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14285 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14286 14287 // Update the in-memory copy of the previous code paths. 14288 PackageSetting ps = mSettings.mPackages.get(pkgName); 14289 if (!killApp) { 14290 if (ps.oldCodePaths == null) { 14291 ps.oldCodePaths = new ArraySet<>(); 14292 } 14293 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14294 if (deletedPackage.splitCodePaths != null) { 14295 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14296 } 14297 } else { 14298 ps.oldCodePaths = null; 14299 } 14300 if (ps.childPackageNames != null) { 14301 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14302 final String childPkgName = ps.childPackageNames.get(i); 14303 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14304 childPs.oldCodePaths = ps.oldCodePaths; 14305 } 14306 } 14307 prepareAppDataAfterInstallLIF(newPackage); 14308 addedPkg = true; 14309 } catch (PackageManagerException e) { 14310 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14311 } 14312 } 14313 14314 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14315 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14316 14317 // Revert all internal state mutations and added folders for the failed install 14318 if (addedPkg) { 14319 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14320 res.removedInfo, true, null); 14321 } 14322 14323 // Restore the old package 14324 if (deletedPkg) { 14325 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14326 File restoreFile = new File(deletedPackage.codePath); 14327 // Parse old package 14328 boolean oldExternal = isExternal(deletedPackage); 14329 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14330 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14331 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14332 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14333 try { 14334 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14335 null); 14336 } catch (PackageManagerException e) { 14337 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14338 + e.getMessage()); 14339 return; 14340 } 14341 14342 synchronized (mPackages) { 14343 // Ensure the installer package name up to date 14344 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14345 14346 // Update permissions for restored package 14347 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14348 14349 mSettings.writeLPr(); 14350 } 14351 14352 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14353 } 14354 } else { 14355 synchronized (mPackages) { 14356 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14357 if (ps != null) { 14358 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14359 if (res.removedInfo.removedChildPackages != null) { 14360 final int childCount = res.removedInfo.removedChildPackages.size(); 14361 // Iterate in reverse as we may modify the collection 14362 for (int i = childCount - 1; i >= 0; i--) { 14363 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14364 if (res.addedChildPackages.containsKey(childPackageName)) { 14365 res.removedInfo.removedChildPackages.removeAt(i); 14366 } else { 14367 PackageRemovedInfo childInfo = res.removedInfo 14368 .removedChildPackages.valueAt(i); 14369 childInfo.removedForAllUsers = mPackages.get( 14370 childInfo.removedPackage) == null; 14371 } 14372 } 14373 } 14374 } 14375 } 14376 } 14377 } 14378 14379 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14380 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14381 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14382 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14383 + ", old=" + deletedPackage); 14384 14385 final boolean disabledSystem; 14386 14387 // Remove existing system package 14388 removePackageLI(deletedPackage, true); 14389 14390 synchronized (mPackages) { 14391 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14392 } 14393 if (!disabledSystem) { 14394 // We didn't need to disable the .apk as a current system package, 14395 // which means we are replacing another update that is already 14396 // installed. We need to make sure to delete the older one's .apk. 14397 res.removedInfo.args = createInstallArgsForExisting(0, 14398 deletedPackage.applicationInfo.getCodePath(), 14399 deletedPackage.applicationInfo.getResourcePath(), 14400 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14401 } else { 14402 res.removedInfo.args = null; 14403 } 14404 14405 // Successfully disabled the old package. Now proceed with re-installation 14406 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14407 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14408 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14409 14410 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14411 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14412 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14413 14414 PackageParser.Package newPackage = null; 14415 try { 14416 // Add the package to the internal data structures 14417 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14418 14419 // Set the update and install times 14420 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14421 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14422 System.currentTimeMillis()); 14423 14424 // Update the package dynamic state if succeeded 14425 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14426 // Now that the install succeeded make sure we remove data 14427 // directories for any child package the update removed. 14428 final int deletedChildCount = (deletedPackage.childPackages != null) 14429 ? deletedPackage.childPackages.size() : 0; 14430 final int newChildCount = (newPackage.childPackages != null) 14431 ? newPackage.childPackages.size() : 0; 14432 for (int i = 0; i < deletedChildCount; i++) { 14433 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14434 boolean childPackageDeleted = true; 14435 for (int j = 0; j < newChildCount; j++) { 14436 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14437 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14438 childPackageDeleted = false; 14439 break; 14440 } 14441 } 14442 if (childPackageDeleted) { 14443 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14444 deletedChildPkg.packageName); 14445 if (ps != null && res.removedInfo.removedChildPackages != null) { 14446 PackageRemovedInfo removedChildRes = res.removedInfo 14447 .removedChildPackages.get(deletedChildPkg.packageName); 14448 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14449 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14450 } 14451 } 14452 } 14453 14454 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14455 prepareAppDataAfterInstallLIF(newPackage); 14456 } 14457 } catch (PackageManagerException e) { 14458 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14459 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14460 } 14461 14462 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14463 // Re installation failed. Restore old information 14464 // Remove new pkg information 14465 if (newPackage != null) { 14466 removeInstalledPackageLI(newPackage, true); 14467 } 14468 // Add back the old system package 14469 try { 14470 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14471 } catch (PackageManagerException e) { 14472 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14473 } 14474 14475 synchronized (mPackages) { 14476 if (disabledSystem) { 14477 enableSystemPackageLPw(deletedPackage); 14478 } 14479 14480 // Ensure the installer package name up to date 14481 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14482 14483 // Update permissions for restored package 14484 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14485 14486 mSettings.writeLPr(); 14487 } 14488 14489 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14490 + " after failed upgrade"); 14491 } 14492 } 14493 14494 /** 14495 * Checks whether the parent or any of the child packages have a change shared 14496 * user. For a package to be a valid update the shred users of the parent and 14497 * the children should match. We may later support changing child shared users. 14498 * @param oldPkg The updated package. 14499 * @param newPkg The update package. 14500 * @return The shared user that change between the versions. 14501 */ 14502 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14503 PackageParser.Package newPkg) { 14504 // Check parent shared user 14505 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14506 return newPkg.packageName; 14507 } 14508 // Check child shared users 14509 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14510 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14511 for (int i = 0; i < newChildCount; i++) { 14512 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14513 // If this child was present, did it have the same shared user? 14514 for (int j = 0; j < oldChildCount; j++) { 14515 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14516 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14517 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14518 return newChildPkg.packageName; 14519 } 14520 } 14521 } 14522 return null; 14523 } 14524 14525 private void removeNativeBinariesLI(PackageSetting ps) { 14526 // Remove the lib path for the parent package 14527 if (ps != null) { 14528 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14529 // Remove the lib path for the child packages 14530 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14531 for (int i = 0; i < childCount; i++) { 14532 PackageSetting childPs = null; 14533 synchronized (mPackages) { 14534 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14535 } 14536 if (childPs != null) { 14537 NativeLibraryHelper.removeNativeBinariesLI(childPs 14538 .legacyNativeLibraryPathString); 14539 } 14540 } 14541 } 14542 } 14543 14544 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14545 // Enable the parent package 14546 mSettings.enableSystemPackageLPw(pkg.packageName); 14547 // Enable the child packages 14548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14549 for (int i = 0; i < childCount; i++) { 14550 PackageParser.Package childPkg = pkg.childPackages.get(i); 14551 mSettings.enableSystemPackageLPw(childPkg.packageName); 14552 } 14553 } 14554 14555 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14556 PackageParser.Package newPkg) { 14557 // Disable the parent package (parent always replaced) 14558 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14559 // Disable the child packages 14560 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14561 for (int i = 0; i < childCount; i++) { 14562 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14563 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14564 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14565 } 14566 return disabled; 14567 } 14568 14569 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14570 String installerPackageName) { 14571 // Enable the parent package 14572 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14573 // Enable the child packages 14574 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14575 for (int i = 0; i < childCount; i++) { 14576 PackageParser.Package childPkg = pkg.childPackages.get(i); 14577 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14578 } 14579 } 14580 14581 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14582 // Collect all used permissions in the UID 14583 ArraySet<String> usedPermissions = new ArraySet<>(); 14584 final int packageCount = su.packages.size(); 14585 for (int i = 0; i < packageCount; i++) { 14586 PackageSetting ps = su.packages.valueAt(i); 14587 if (ps.pkg == null) { 14588 continue; 14589 } 14590 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14591 for (int j = 0; j < requestedPermCount; j++) { 14592 String permission = ps.pkg.requestedPermissions.get(j); 14593 BasePermission bp = mSettings.mPermissions.get(permission); 14594 if (bp != null) { 14595 usedPermissions.add(permission); 14596 } 14597 } 14598 } 14599 14600 PermissionsState permissionsState = su.getPermissionsState(); 14601 // Prune install permissions 14602 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14603 final int installPermCount = installPermStates.size(); 14604 for (int i = installPermCount - 1; i >= 0; i--) { 14605 PermissionState permissionState = installPermStates.get(i); 14606 if (!usedPermissions.contains(permissionState.getName())) { 14607 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14608 if (bp != null) { 14609 permissionsState.revokeInstallPermission(bp); 14610 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14611 PackageManager.MASK_PERMISSION_FLAGS, 0); 14612 } 14613 } 14614 } 14615 14616 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14617 14618 // Prune runtime permissions 14619 for (int userId : allUserIds) { 14620 List<PermissionState> runtimePermStates = permissionsState 14621 .getRuntimePermissionStates(userId); 14622 final int runtimePermCount = runtimePermStates.size(); 14623 for (int i = runtimePermCount - 1; i >= 0; i--) { 14624 PermissionState permissionState = runtimePermStates.get(i); 14625 if (!usedPermissions.contains(permissionState.getName())) { 14626 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14627 if (bp != null) { 14628 permissionsState.revokeRuntimePermission(bp, userId); 14629 permissionsState.updatePermissionFlags(bp, userId, 14630 PackageManager.MASK_PERMISSION_FLAGS, 0); 14631 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14632 runtimePermissionChangedUserIds, userId); 14633 } 14634 } 14635 } 14636 } 14637 14638 return runtimePermissionChangedUserIds; 14639 } 14640 14641 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14642 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14643 // Update the parent package setting 14644 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14645 res, user); 14646 // Update the child packages setting 14647 final int childCount = (newPackage.childPackages != null) 14648 ? newPackage.childPackages.size() : 0; 14649 for (int i = 0; i < childCount; i++) { 14650 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14651 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14652 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14653 childRes.origUsers, childRes, user); 14654 } 14655 } 14656 14657 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14658 String installerPackageName, int[] allUsers, int[] installedForUsers, 14659 PackageInstalledInfo res, UserHandle user) { 14660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14661 14662 String pkgName = newPackage.packageName; 14663 synchronized (mPackages) { 14664 //write settings. the installStatus will be incomplete at this stage. 14665 //note that the new package setting would have already been 14666 //added to mPackages. It hasn't been persisted yet. 14667 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14669 mSettings.writeLPr(); 14670 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14671 } 14672 14673 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14674 synchronized (mPackages) { 14675 updatePermissionsLPw(newPackage.packageName, newPackage, 14676 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14677 ? UPDATE_PERMISSIONS_ALL : 0)); 14678 // For system-bundled packages, we assume that installing an upgraded version 14679 // of the package implies that the user actually wants to run that new code, 14680 // so we enable the package. 14681 PackageSetting ps = mSettings.mPackages.get(pkgName); 14682 final int userId = user.getIdentifier(); 14683 if (ps != null) { 14684 if (isSystemApp(newPackage)) { 14685 if (DEBUG_INSTALL) { 14686 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14687 } 14688 // Enable system package for requested users 14689 if (res.origUsers != null) { 14690 for (int origUserId : res.origUsers) { 14691 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14692 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14693 origUserId, installerPackageName); 14694 } 14695 } 14696 } 14697 // Also convey the prior install/uninstall state 14698 if (allUsers != null && installedForUsers != null) { 14699 for (int currentUserId : allUsers) { 14700 final boolean installed = ArrayUtils.contains( 14701 installedForUsers, currentUserId); 14702 if (DEBUG_INSTALL) { 14703 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14704 } 14705 ps.setInstalled(installed, currentUserId); 14706 } 14707 // these install state changes will be persisted in the 14708 // upcoming call to mSettings.writeLPr(). 14709 } 14710 } 14711 // It's implied that when a user requests installation, they want the app to be 14712 // installed and enabled. 14713 if (userId != UserHandle.USER_ALL) { 14714 ps.setInstalled(true, userId); 14715 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14716 } 14717 } 14718 res.name = pkgName; 14719 res.uid = newPackage.applicationInfo.uid; 14720 res.pkg = newPackage; 14721 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14722 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14723 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14724 //to update install status 14725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14726 mSettings.writeLPr(); 14727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14728 } 14729 14730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14731 } 14732 14733 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14734 try { 14735 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14736 installPackageLI(args, res); 14737 } finally { 14738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14739 } 14740 } 14741 14742 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14743 final int installFlags = args.installFlags; 14744 final String installerPackageName = args.installerPackageName; 14745 final String volumeUuid = args.volumeUuid; 14746 final File tmpPackageFile = new File(args.getCodePath()); 14747 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14748 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14749 || (args.volumeUuid != null)); 14750 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14751 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14752 boolean replace = false; 14753 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14754 if (args.move != null) { 14755 // moving a complete application; perform an initial scan on the new install location 14756 scanFlags |= SCAN_INITIAL; 14757 } 14758 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14759 scanFlags |= SCAN_DONT_KILL_APP; 14760 } 14761 14762 // Result object to be returned 14763 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14764 14765 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14766 14767 // Sanity check 14768 if (ephemeral && (forwardLocked || onExternal)) { 14769 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14770 + " external=" + onExternal); 14771 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14772 return; 14773 } 14774 14775 // Retrieve PackageSettings and parse package 14776 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14777 | PackageParser.PARSE_ENFORCE_CODE 14778 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14779 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14780 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14781 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14782 PackageParser pp = new PackageParser(); 14783 pp.setSeparateProcesses(mSeparateProcesses); 14784 pp.setDisplayMetrics(mMetrics); 14785 14786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14787 final PackageParser.Package pkg; 14788 try { 14789 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14790 } catch (PackageParserException e) { 14791 res.setError("Failed parse during installPackageLI", e); 14792 return; 14793 } finally { 14794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14795 } 14796 14797 // If we are installing a clustered package add results for the children 14798 if (pkg.childPackages != null) { 14799 synchronized (mPackages) { 14800 final int childCount = pkg.childPackages.size(); 14801 for (int i = 0; i < childCount; i++) { 14802 PackageParser.Package childPkg = pkg.childPackages.get(i); 14803 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14804 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14805 childRes.pkg = childPkg; 14806 childRes.name = childPkg.packageName; 14807 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14808 if (childPs != null) { 14809 childRes.origUsers = childPs.queryInstalledUsers( 14810 sUserManager.getUserIds(), true); 14811 } 14812 if ((mPackages.containsKey(childPkg.packageName))) { 14813 childRes.removedInfo = new PackageRemovedInfo(); 14814 childRes.removedInfo.removedPackage = childPkg.packageName; 14815 } 14816 if (res.addedChildPackages == null) { 14817 res.addedChildPackages = new ArrayMap<>(); 14818 } 14819 res.addedChildPackages.put(childPkg.packageName, childRes); 14820 } 14821 } 14822 } 14823 14824 // If package doesn't declare API override, mark that we have an install 14825 // time CPU ABI override. 14826 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14827 pkg.cpuAbiOverride = args.abiOverride; 14828 } 14829 14830 String pkgName = res.name = pkg.packageName; 14831 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14832 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14833 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14834 return; 14835 } 14836 } 14837 14838 try { 14839 // either use what we've been given or parse directly from the APK 14840 if (args.certificates != null) { 14841 try { 14842 PackageParser.populateCertificates(pkg, args.certificates); 14843 } catch (PackageParserException e) { 14844 // there was something wrong with the certificates we were given; 14845 // try to pull them from the APK 14846 PackageParser.collectCertificates(pkg, parseFlags); 14847 } 14848 } else { 14849 PackageParser.collectCertificates(pkg, parseFlags); 14850 } 14851 } catch (PackageParserException e) { 14852 res.setError("Failed collect during installPackageLI", e); 14853 return; 14854 } 14855 14856 // Get rid of all references to package scan path via parser. 14857 pp = null; 14858 String oldCodePath = null; 14859 boolean systemApp = false; 14860 synchronized (mPackages) { 14861 // Check if installing already existing package 14862 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14863 String oldName = mSettings.mRenamedPackages.get(pkgName); 14864 if (pkg.mOriginalPackages != null 14865 && pkg.mOriginalPackages.contains(oldName) 14866 && mPackages.containsKey(oldName)) { 14867 // This package is derived from an original package, 14868 // and this device has been updating from that original 14869 // name. We must continue using the original name, so 14870 // rename the new package here. 14871 pkg.setPackageName(oldName); 14872 pkgName = pkg.packageName; 14873 replace = true; 14874 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14875 + oldName + " pkgName=" + pkgName); 14876 } else if (mPackages.containsKey(pkgName)) { 14877 // This package, under its official name, already exists 14878 // on the device; we should replace it. 14879 replace = true; 14880 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14881 } 14882 14883 // Child packages are installed through the parent package 14884 if (pkg.parentPackage != null) { 14885 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14886 "Package " + pkg.packageName + " is child of package " 14887 + pkg.parentPackage.parentPackage + ". Child packages " 14888 + "can be updated only through the parent package."); 14889 return; 14890 } 14891 14892 if (replace) { 14893 // Prevent apps opting out from runtime permissions 14894 PackageParser.Package oldPackage = mPackages.get(pkgName); 14895 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14896 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14897 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14898 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14899 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14900 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14901 + " doesn't support runtime permissions but the old" 14902 + " target SDK " + oldTargetSdk + " does."); 14903 return; 14904 } 14905 14906 // Prevent installing of child packages 14907 if (oldPackage.parentPackage != null) { 14908 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14909 "Package " + pkg.packageName + " is child of package " 14910 + oldPackage.parentPackage + ". Child packages " 14911 + "can be updated only through the parent package."); 14912 return; 14913 } 14914 } 14915 } 14916 14917 PackageSetting ps = mSettings.mPackages.get(pkgName); 14918 if (ps != null) { 14919 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14920 14921 // Quick sanity check that we're signed correctly if updating; 14922 // we'll check this again later when scanning, but we want to 14923 // bail early here before tripping over redefined permissions. 14924 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14925 if (!checkUpgradeKeySetLP(ps, pkg)) { 14926 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14927 + pkg.packageName + " upgrade keys do not match the " 14928 + "previously installed version"); 14929 return; 14930 } 14931 } else { 14932 try { 14933 verifySignaturesLP(ps, pkg); 14934 } catch (PackageManagerException e) { 14935 res.setError(e.error, e.getMessage()); 14936 return; 14937 } 14938 } 14939 14940 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14941 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14942 systemApp = (ps.pkg.applicationInfo.flags & 14943 ApplicationInfo.FLAG_SYSTEM) != 0; 14944 } 14945 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14946 } 14947 14948 // Check whether the newly-scanned package wants to define an already-defined perm 14949 int N = pkg.permissions.size(); 14950 for (int i = N-1; i >= 0; i--) { 14951 PackageParser.Permission perm = pkg.permissions.get(i); 14952 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14953 if (bp != null) { 14954 // If the defining package is signed with our cert, it's okay. This 14955 // also includes the "updating the same package" case, of course. 14956 // "updating same package" could also involve key-rotation. 14957 final boolean sigsOk; 14958 if (bp.sourcePackage.equals(pkg.packageName) 14959 && (bp.packageSetting instanceof PackageSetting) 14960 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14961 scanFlags))) { 14962 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14963 } else { 14964 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14965 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14966 } 14967 if (!sigsOk) { 14968 // If the owning package is the system itself, we log but allow 14969 // install to proceed; we fail the install on all other permission 14970 // redefinitions. 14971 if (!bp.sourcePackage.equals("android")) { 14972 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14973 + pkg.packageName + " attempting to redeclare permission " 14974 + perm.info.name + " already owned by " + bp.sourcePackage); 14975 res.origPermission = perm.info.name; 14976 res.origPackage = bp.sourcePackage; 14977 return; 14978 } else { 14979 Slog.w(TAG, "Package " + pkg.packageName 14980 + " attempting to redeclare system permission " 14981 + perm.info.name + "; ignoring new declaration"); 14982 pkg.permissions.remove(i); 14983 } 14984 } 14985 } 14986 } 14987 } 14988 14989 if (systemApp) { 14990 if (onExternal) { 14991 // Abort update; system app can't be replaced with app on sdcard 14992 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14993 "Cannot install updates to system apps on sdcard"); 14994 return; 14995 } else if (ephemeral) { 14996 // Abort update; system app can't be replaced with an ephemeral app 14997 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14998 "Cannot update a system app with an ephemeral app"); 14999 return; 15000 } 15001 } 15002 15003 if (args.move != null) { 15004 // We did an in-place move, so dex is ready to roll 15005 scanFlags |= SCAN_NO_DEX; 15006 scanFlags |= SCAN_MOVE; 15007 15008 synchronized (mPackages) { 15009 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15010 if (ps == null) { 15011 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15012 "Missing settings for moved package " + pkgName); 15013 } 15014 15015 // We moved the entire application as-is, so bring over the 15016 // previously derived ABI information. 15017 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15018 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15019 } 15020 15021 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15022 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15023 scanFlags |= SCAN_NO_DEX; 15024 15025 try { 15026 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15027 args.abiOverride : pkg.cpuAbiOverride); 15028 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15029 true /* extract libs */); 15030 } catch (PackageManagerException pme) { 15031 Slog.e(TAG, "Error deriving application ABI", pme); 15032 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15033 return; 15034 } 15035 15036 // Shared libraries for the package need to be updated. 15037 synchronized (mPackages) { 15038 try { 15039 updateSharedLibrariesLPw(pkg, null); 15040 } catch (PackageManagerException e) { 15041 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15042 } 15043 } 15044 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15045 // Do not run PackageDexOptimizer through the local performDexOpt 15046 // method because `pkg` may not be in `mPackages` yet. 15047 // 15048 // Also, don't fail application installs if the dexopt step fails. 15049 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15050 null /* instructionSets */, false /* checkProfiles */, 15051 getCompilerFilterForReason(REASON_INSTALL), 15052 getOrCreateCompilerPackageStats(pkg)); 15053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15054 15055 // Notify BackgroundDexOptService that the package has been changed. 15056 // If this is an update of a package which used to fail to compile, 15057 // BDOS will remove it from its blacklist. 15058 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15059 } 15060 15061 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15062 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15063 return; 15064 } 15065 15066 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15067 15068 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15069 "installPackageLI")) { 15070 if (replace) { 15071 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15072 installerPackageName, res); 15073 } else { 15074 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15075 args.user, installerPackageName, volumeUuid, res); 15076 } 15077 } 15078 synchronized (mPackages) { 15079 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15080 if (ps != null) { 15081 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15082 } 15083 15084 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15085 for (int i = 0; i < childCount; i++) { 15086 PackageParser.Package childPkg = pkg.childPackages.get(i); 15087 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15088 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15089 if (childPs != null) { 15090 childRes.newUsers = childPs.queryInstalledUsers( 15091 sUserManager.getUserIds(), true); 15092 } 15093 } 15094 } 15095 } 15096 15097 private void startIntentFilterVerifications(int userId, boolean replacing, 15098 PackageParser.Package pkg) { 15099 if (mIntentFilterVerifierComponent == null) { 15100 Slog.w(TAG, "No IntentFilter verification will not be done as " 15101 + "there is no IntentFilterVerifier available!"); 15102 return; 15103 } 15104 15105 final int verifierUid = getPackageUid( 15106 mIntentFilterVerifierComponent.getPackageName(), 15107 MATCH_DEBUG_TRIAGED_MISSING, 15108 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15109 15110 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15111 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15112 mHandler.sendMessage(msg); 15113 15114 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15115 for (int i = 0; i < childCount; i++) { 15116 PackageParser.Package childPkg = pkg.childPackages.get(i); 15117 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15118 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15119 mHandler.sendMessage(msg); 15120 } 15121 } 15122 15123 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15124 PackageParser.Package pkg) { 15125 int size = pkg.activities.size(); 15126 if (size == 0) { 15127 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15128 "No activity, so no need to verify any IntentFilter!"); 15129 return; 15130 } 15131 15132 final boolean hasDomainURLs = hasDomainURLs(pkg); 15133 if (!hasDomainURLs) { 15134 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15135 "No domain URLs, so no need to verify any IntentFilter!"); 15136 return; 15137 } 15138 15139 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15140 + " if any IntentFilter from the " + size 15141 + " Activities needs verification ..."); 15142 15143 int count = 0; 15144 final String packageName = pkg.packageName; 15145 15146 synchronized (mPackages) { 15147 // If this is a new install and we see that we've already run verification for this 15148 // package, we have nothing to do: it means the state was restored from backup. 15149 if (!replacing) { 15150 IntentFilterVerificationInfo ivi = 15151 mSettings.getIntentFilterVerificationLPr(packageName); 15152 if (ivi != null) { 15153 if (DEBUG_DOMAIN_VERIFICATION) { 15154 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15155 + ivi.getStatusString()); 15156 } 15157 return; 15158 } 15159 } 15160 15161 // If any filters need to be verified, then all need to be. 15162 boolean needToVerify = false; 15163 for (PackageParser.Activity a : pkg.activities) { 15164 for (ActivityIntentInfo filter : a.intents) { 15165 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15166 if (DEBUG_DOMAIN_VERIFICATION) { 15167 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15168 } 15169 needToVerify = true; 15170 break; 15171 } 15172 } 15173 } 15174 15175 if (needToVerify) { 15176 final int verificationId = mIntentFilterVerificationToken++; 15177 for (PackageParser.Activity a : pkg.activities) { 15178 for (ActivityIntentInfo filter : a.intents) { 15179 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15180 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15181 "Verification needed for IntentFilter:" + filter.toString()); 15182 mIntentFilterVerifier.addOneIntentFilterVerification( 15183 verifierUid, userId, verificationId, filter, packageName); 15184 count++; 15185 } 15186 } 15187 } 15188 } 15189 } 15190 15191 if (count > 0) { 15192 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15193 + " IntentFilter verification" + (count > 1 ? "s" : "") 15194 + " for userId:" + userId); 15195 mIntentFilterVerifier.startVerifications(userId); 15196 } else { 15197 if (DEBUG_DOMAIN_VERIFICATION) { 15198 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15199 } 15200 } 15201 } 15202 15203 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15204 final ComponentName cn = filter.activity.getComponentName(); 15205 final String packageName = cn.getPackageName(); 15206 15207 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15208 packageName); 15209 if (ivi == null) { 15210 return true; 15211 } 15212 int status = ivi.getStatus(); 15213 switch (status) { 15214 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15215 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15216 return true; 15217 15218 default: 15219 // Nothing to do 15220 return false; 15221 } 15222 } 15223 15224 private static boolean isMultiArch(ApplicationInfo info) { 15225 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15226 } 15227 15228 private static boolean isExternal(PackageParser.Package pkg) { 15229 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15230 } 15231 15232 private static boolean isExternal(PackageSetting ps) { 15233 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15234 } 15235 15236 private static boolean isEphemeral(PackageParser.Package pkg) { 15237 return pkg.applicationInfo.isEphemeralApp(); 15238 } 15239 15240 private static boolean isEphemeral(PackageSetting ps) { 15241 return ps.pkg != null && isEphemeral(ps.pkg); 15242 } 15243 15244 private static boolean isSystemApp(PackageParser.Package pkg) { 15245 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15246 } 15247 15248 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15249 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15250 } 15251 15252 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15253 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15254 } 15255 15256 private static boolean isSystemApp(PackageSetting ps) { 15257 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15258 } 15259 15260 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15261 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15262 } 15263 15264 private int packageFlagsToInstallFlags(PackageSetting ps) { 15265 int installFlags = 0; 15266 if (isEphemeral(ps)) { 15267 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15268 } 15269 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15270 // This existing package was an external ASEC install when we have 15271 // the external flag without a UUID 15272 installFlags |= PackageManager.INSTALL_EXTERNAL; 15273 } 15274 if (ps.isForwardLocked()) { 15275 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15276 } 15277 return installFlags; 15278 } 15279 15280 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15281 if (isExternal(pkg)) { 15282 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15283 return StorageManager.UUID_PRIMARY_PHYSICAL; 15284 } else { 15285 return pkg.volumeUuid; 15286 } 15287 } else { 15288 return StorageManager.UUID_PRIVATE_INTERNAL; 15289 } 15290 } 15291 15292 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15293 if (isExternal(pkg)) { 15294 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15295 return mSettings.getExternalVersion(); 15296 } else { 15297 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15298 } 15299 } else { 15300 return mSettings.getInternalVersion(); 15301 } 15302 } 15303 15304 private void deleteTempPackageFiles() { 15305 final FilenameFilter filter = new FilenameFilter() { 15306 public boolean accept(File dir, String name) { 15307 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15308 } 15309 }; 15310 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15311 file.delete(); 15312 } 15313 } 15314 15315 @Override 15316 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15317 int flags) { 15318 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15319 flags); 15320 } 15321 15322 @Override 15323 public void deletePackage(final String packageName, 15324 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15325 mContext.enforceCallingOrSelfPermission( 15326 android.Manifest.permission.DELETE_PACKAGES, null); 15327 Preconditions.checkNotNull(packageName); 15328 Preconditions.checkNotNull(observer); 15329 final int uid = Binder.getCallingUid(); 15330 if (uid != Process.SHELL_UID && uid != Process.ROOT_UID && uid != Process.SYSTEM_UID 15331 && uid != getPackageUid(mRequiredInstallerPackage, 0, UserHandle.getUserId(uid)) 15332 && !isOrphaned(packageName) 15333 && !isCallerSameAsInstaller(uid, packageName)) { 15334 try { 15335 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15336 intent.setData(Uri.fromParts("package", packageName, null)); 15337 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15338 observer.onUserActionRequired(intent); 15339 } catch (RemoteException re) { 15340 } 15341 return; 15342 } 15343 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15344 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15345 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15346 mContext.enforceCallingOrSelfPermission( 15347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15348 "deletePackage for user " + userId); 15349 } 15350 15351 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15352 try { 15353 observer.onPackageDeleted(packageName, 15354 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15355 } catch (RemoteException re) { 15356 } 15357 return; 15358 } 15359 15360 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15361 try { 15362 observer.onPackageDeleted(packageName, 15363 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15364 } catch (RemoteException re) { 15365 } 15366 return; 15367 } 15368 15369 if (DEBUG_REMOVE) { 15370 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15371 + " deleteAllUsers: " + deleteAllUsers ); 15372 } 15373 // Queue up an async operation since the package deletion may take a little while. 15374 mHandler.post(new Runnable() { 15375 public void run() { 15376 mHandler.removeCallbacks(this); 15377 int returnCode; 15378 if (!deleteAllUsers) { 15379 returnCode = deletePackageX(packageName, userId, deleteFlags); 15380 } else { 15381 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15382 // If nobody is blocking uninstall, proceed with delete for all users 15383 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15384 returnCode = deletePackageX(packageName, userId, deleteFlags); 15385 } else { 15386 // Otherwise uninstall individually for users with blockUninstalls=false 15387 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15388 for (int userId : users) { 15389 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15390 returnCode = deletePackageX(packageName, userId, userFlags); 15391 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15392 Slog.w(TAG, "Package delete failed for user " + userId 15393 + ", returnCode " + returnCode); 15394 } 15395 } 15396 } 15397 // The app has only been marked uninstalled for certain users. 15398 // We still need to report that delete was blocked 15399 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15400 } 15401 } 15402 try { 15403 observer.onPackageDeleted(packageName, returnCode, null); 15404 } catch (RemoteException e) { 15405 Log.i(TAG, "Observer no longer exists."); 15406 } //end catch 15407 } //end run 15408 }); 15409 } 15410 15411 private boolean isCallerSameAsInstaller(int callingUid, String pkgName) { 15412 final int installerPkgUid = getPackageUid(getInstallerPackageName(pkgName), 15413 0 /* flags */, UserHandle.getUserId(callingUid)); 15414 return installerPkgUid == callingUid; 15415 } 15416 15417 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15418 int[] result = EMPTY_INT_ARRAY; 15419 for (int userId : userIds) { 15420 if (getBlockUninstallForUser(packageName, userId)) { 15421 result = ArrayUtils.appendInt(result, userId); 15422 } 15423 } 15424 return result; 15425 } 15426 15427 @Override 15428 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15429 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15430 } 15431 15432 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15433 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15434 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15435 try { 15436 if (dpm != null) { 15437 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15438 /* callingUserOnly =*/ false); 15439 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15440 : deviceOwnerComponentName.getPackageName(); 15441 // Does the package contains the device owner? 15442 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15443 // this check is probably not needed, since DO should be registered as a device 15444 // admin on some user too. (Original bug for this: b/17657954) 15445 if (packageName.equals(deviceOwnerPackageName)) { 15446 return true; 15447 } 15448 // Does it contain a device admin for any user? 15449 int[] users; 15450 if (userId == UserHandle.USER_ALL) { 15451 users = sUserManager.getUserIds(); 15452 } else { 15453 users = new int[]{userId}; 15454 } 15455 for (int i = 0; i < users.length; ++i) { 15456 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15457 return true; 15458 } 15459 } 15460 } 15461 } catch (RemoteException e) { 15462 } 15463 return false; 15464 } 15465 15466 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15467 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15468 } 15469 15470 /** 15471 * This method is an internal method that could be get invoked either 15472 * to delete an installed package or to clean up a failed installation. 15473 * After deleting an installed package, a broadcast is sent to notify any 15474 * listeners that the package has been removed. For cleaning up a failed 15475 * installation, the broadcast is not necessary since the package's 15476 * installation wouldn't have sent the initial broadcast either 15477 * The key steps in deleting a package are 15478 * deleting the package information in internal structures like mPackages, 15479 * deleting the packages base directories through installd 15480 * updating mSettings to reflect current status 15481 * persisting settings for later use 15482 * sending a broadcast if necessary 15483 */ 15484 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15485 final PackageRemovedInfo info = new PackageRemovedInfo(); 15486 final boolean res; 15487 15488 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15489 ? UserHandle.USER_ALL : userId; 15490 15491 if (isPackageDeviceAdmin(packageName, removeUser)) { 15492 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15493 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15494 } 15495 15496 PackageSetting uninstalledPs = null; 15497 15498 // for the uninstall-updates case and restricted profiles, remember the per- 15499 // user handle installed state 15500 int[] allUsers; 15501 synchronized (mPackages) { 15502 uninstalledPs = mSettings.mPackages.get(packageName); 15503 if (uninstalledPs == null) { 15504 Slog.w(TAG, "Not removing non-existent package " + packageName); 15505 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15506 } 15507 allUsers = sUserManager.getUserIds(); 15508 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15509 } 15510 15511 final int freezeUser; 15512 if (isUpdatedSystemApp(uninstalledPs) 15513 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15514 // We're downgrading a system app, which will apply to all users, so 15515 // freeze them all during the downgrade 15516 freezeUser = UserHandle.USER_ALL; 15517 } else { 15518 freezeUser = removeUser; 15519 } 15520 15521 synchronized (mInstallLock) { 15522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15523 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15524 deleteFlags, "deletePackageX")) { 15525 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15526 deleteFlags | REMOVE_CHATTY, info, true, null); 15527 } 15528 synchronized (mPackages) { 15529 if (res) { 15530 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15531 } 15532 } 15533 } 15534 15535 if (res) { 15536 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15537 info.sendPackageRemovedBroadcasts(killApp); 15538 info.sendSystemPackageUpdatedBroadcasts(); 15539 info.sendSystemPackageAppearedBroadcasts(); 15540 } 15541 // Force a gc here. 15542 Runtime.getRuntime().gc(); 15543 // Delete the resources here after sending the broadcast to let 15544 // other processes clean up before deleting resources. 15545 if (info.args != null) { 15546 synchronized (mInstallLock) { 15547 info.args.doPostDeleteLI(true); 15548 } 15549 } 15550 15551 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15552 } 15553 15554 class PackageRemovedInfo { 15555 String removedPackage; 15556 int uid = -1; 15557 int removedAppId = -1; 15558 int[] origUsers; 15559 int[] removedUsers = null; 15560 boolean isRemovedPackageSystemUpdate = false; 15561 boolean isUpdate; 15562 boolean dataRemoved; 15563 boolean removedForAllUsers; 15564 // Clean up resources deleted packages. 15565 InstallArgs args = null; 15566 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15567 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15568 15569 void sendPackageRemovedBroadcasts(boolean killApp) { 15570 sendPackageRemovedBroadcastInternal(killApp); 15571 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15572 for (int i = 0; i < childCount; i++) { 15573 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15574 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15575 } 15576 } 15577 15578 void sendSystemPackageUpdatedBroadcasts() { 15579 if (isRemovedPackageSystemUpdate) { 15580 sendSystemPackageUpdatedBroadcastsInternal(); 15581 final int childCount = (removedChildPackages != null) 15582 ? removedChildPackages.size() : 0; 15583 for (int i = 0; i < childCount; i++) { 15584 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15585 if (childInfo.isRemovedPackageSystemUpdate) { 15586 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15587 } 15588 } 15589 } 15590 } 15591 15592 void sendSystemPackageAppearedBroadcasts() { 15593 final int packageCount = (appearedChildPackages != null) 15594 ? appearedChildPackages.size() : 0; 15595 for (int i = 0; i < packageCount; i++) { 15596 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15597 for (int userId : installedInfo.newUsers) { 15598 sendPackageAddedForUser(installedInfo.name, true, 15599 UserHandle.getAppId(installedInfo.uid), userId); 15600 } 15601 } 15602 } 15603 15604 private void sendSystemPackageUpdatedBroadcastsInternal() { 15605 Bundle extras = new Bundle(2); 15606 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15607 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15608 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15609 extras, 0, null, null, null); 15610 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15611 extras, 0, null, null, null); 15612 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15613 null, 0, removedPackage, null, null); 15614 } 15615 15616 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15617 Bundle extras = new Bundle(2); 15618 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15619 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15620 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15621 if (isUpdate || isRemovedPackageSystemUpdate) { 15622 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15623 } 15624 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15625 if (removedPackage != null) { 15626 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15627 extras, 0, null, null, removedUsers); 15628 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15629 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15630 removedPackage, extras, 0, null, null, removedUsers); 15631 } 15632 } 15633 if (removedAppId >= 0) { 15634 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15635 removedUsers); 15636 } 15637 } 15638 } 15639 15640 /* 15641 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15642 * flag is not set, the data directory is removed as well. 15643 * make sure this flag is set for partially installed apps. If not its meaningless to 15644 * delete a partially installed application. 15645 */ 15646 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15647 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15648 String packageName = ps.name; 15649 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15650 // Retrieve object to delete permissions for shared user later on 15651 final PackageParser.Package deletedPkg; 15652 final PackageSetting deletedPs; 15653 // reader 15654 synchronized (mPackages) { 15655 deletedPkg = mPackages.get(packageName); 15656 deletedPs = mSettings.mPackages.get(packageName); 15657 if (outInfo != null) { 15658 outInfo.removedPackage = packageName; 15659 outInfo.removedUsers = deletedPs != null 15660 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15661 : null; 15662 } 15663 } 15664 15665 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15666 15667 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15668 final PackageParser.Package resolvedPkg; 15669 if (deletedPkg != null) { 15670 resolvedPkg = deletedPkg; 15671 } else { 15672 // We don't have a parsed package when it lives on an ejected 15673 // adopted storage device, so fake something together 15674 resolvedPkg = new PackageParser.Package(ps.name); 15675 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15676 } 15677 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15678 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15679 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15680 if (outInfo != null) { 15681 outInfo.dataRemoved = true; 15682 } 15683 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15684 } 15685 15686 // writer 15687 synchronized (mPackages) { 15688 if (deletedPs != null) { 15689 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15690 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15691 clearDefaultBrowserIfNeeded(packageName); 15692 if (outInfo != null) { 15693 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15694 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15695 } 15696 updatePermissionsLPw(deletedPs.name, null, 0); 15697 if (deletedPs.sharedUser != null) { 15698 // Remove permissions associated with package. Since runtime 15699 // permissions are per user we have to kill the removed package 15700 // or packages running under the shared user of the removed 15701 // package if revoking the permissions requested only by the removed 15702 // package is successful and this causes a change in gids. 15703 for (int userId : UserManagerService.getInstance().getUserIds()) { 15704 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15705 userId); 15706 if (userIdToKill == UserHandle.USER_ALL 15707 || userIdToKill >= UserHandle.USER_SYSTEM) { 15708 // If gids changed for this user, kill all affected packages. 15709 mHandler.post(new Runnable() { 15710 @Override 15711 public void run() { 15712 // This has to happen with no lock held. 15713 killApplication(deletedPs.name, deletedPs.appId, 15714 KILL_APP_REASON_GIDS_CHANGED); 15715 } 15716 }); 15717 break; 15718 } 15719 } 15720 } 15721 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15722 } 15723 // make sure to preserve per-user disabled state if this removal was just 15724 // a downgrade of a system app to the factory package 15725 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15726 if (DEBUG_REMOVE) { 15727 Slog.d(TAG, "Propagating install state across downgrade"); 15728 } 15729 for (int userId : allUserHandles) { 15730 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15731 if (DEBUG_REMOVE) { 15732 Slog.d(TAG, " user " + userId + " => " + installed); 15733 } 15734 ps.setInstalled(installed, userId); 15735 } 15736 } 15737 } 15738 // can downgrade to reader 15739 if (writeSettings) { 15740 // Save settings now 15741 mSettings.writeLPr(); 15742 } 15743 } 15744 if (outInfo != null) { 15745 // A user ID was deleted here. Go through all users and remove it 15746 // from KeyStore. 15747 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15748 } 15749 } 15750 15751 static boolean locationIsPrivileged(File path) { 15752 try { 15753 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15754 .getCanonicalPath(); 15755 return path.getCanonicalPath().startsWith(privilegedAppDir); 15756 } catch (IOException e) { 15757 Slog.e(TAG, "Unable to access code path " + path); 15758 } 15759 return false; 15760 } 15761 15762 /* 15763 * Tries to delete system package. 15764 */ 15765 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15766 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15767 boolean writeSettings) { 15768 if (deletedPs.parentPackageName != null) { 15769 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15770 return false; 15771 } 15772 15773 final boolean applyUserRestrictions 15774 = (allUserHandles != null) && (outInfo.origUsers != null); 15775 final PackageSetting disabledPs; 15776 // Confirm if the system package has been updated 15777 // An updated system app can be deleted. This will also have to restore 15778 // the system pkg from system partition 15779 // reader 15780 synchronized (mPackages) { 15781 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15782 } 15783 15784 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15785 + " disabledPs=" + disabledPs); 15786 15787 if (disabledPs == null) { 15788 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15789 return false; 15790 } else if (DEBUG_REMOVE) { 15791 Slog.d(TAG, "Deleting system pkg from data partition"); 15792 } 15793 15794 if (DEBUG_REMOVE) { 15795 if (applyUserRestrictions) { 15796 Slog.d(TAG, "Remembering install states:"); 15797 for (int userId : allUserHandles) { 15798 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15799 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15800 } 15801 } 15802 } 15803 15804 // Delete the updated package 15805 outInfo.isRemovedPackageSystemUpdate = true; 15806 if (outInfo.removedChildPackages != null) { 15807 final int childCount = (deletedPs.childPackageNames != null) 15808 ? deletedPs.childPackageNames.size() : 0; 15809 for (int i = 0; i < childCount; i++) { 15810 String childPackageName = deletedPs.childPackageNames.get(i); 15811 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15812 .contains(childPackageName)) { 15813 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15814 childPackageName); 15815 if (childInfo != null) { 15816 childInfo.isRemovedPackageSystemUpdate = true; 15817 } 15818 } 15819 } 15820 } 15821 15822 if (disabledPs.versionCode < deletedPs.versionCode) { 15823 // Delete data for downgrades 15824 flags &= ~PackageManager.DELETE_KEEP_DATA; 15825 } else { 15826 // Preserve data by setting flag 15827 flags |= PackageManager.DELETE_KEEP_DATA; 15828 } 15829 15830 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15831 outInfo, writeSettings, disabledPs.pkg); 15832 if (!ret) { 15833 return false; 15834 } 15835 15836 // writer 15837 synchronized (mPackages) { 15838 // Reinstate the old system package 15839 enableSystemPackageLPw(disabledPs.pkg); 15840 // Remove any native libraries from the upgraded package. 15841 removeNativeBinariesLI(deletedPs); 15842 } 15843 15844 // Install the system package 15845 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15846 int parseFlags = mDefParseFlags 15847 | PackageParser.PARSE_MUST_BE_APK 15848 | PackageParser.PARSE_IS_SYSTEM 15849 | PackageParser.PARSE_IS_SYSTEM_DIR; 15850 if (locationIsPrivileged(disabledPs.codePath)) { 15851 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15852 } 15853 15854 final PackageParser.Package newPkg; 15855 try { 15856 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15857 } catch (PackageManagerException e) { 15858 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15859 + e.getMessage()); 15860 return false; 15861 } 15862 try { 15863 // update shared libraries for the newly re-installed system package 15864 updateSharedLibrariesLPw(newPkg, null); 15865 } catch (PackageManagerException e) { 15866 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 15867 } 15868 15869 prepareAppDataAfterInstallLIF(newPkg); 15870 15871 // writer 15872 synchronized (mPackages) { 15873 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15874 15875 // Propagate the permissions state as we do not want to drop on the floor 15876 // runtime permissions. The update permissions method below will take 15877 // care of removing obsolete permissions and grant install permissions. 15878 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15879 updatePermissionsLPw(newPkg.packageName, newPkg, 15880 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15881 15882 if (applyUserRestrictions) { 15883 if (DEBUG_REMOVE) { 15884 Slog.d(TAG, "Propagating install state across reinstall"); 15885 } 15886 for (int userId : allUserHandles) { 15887 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15888 if (DEBUG_REMOVE) { 15889 Slog.d(TAG, " user " + userId + " => " + installed); 15890 } 15891 ps.setInstalled(installed, userId); 15892 15893 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15894 } 15895 // Regardless of writeSettings we need to ensure that this restriction 15896 // state propagation is persisted 15897 mSettings.writeAllUsersPackageRestrictionsLPr(); 15898 } 15899 // can downgrade to reader here 15900 if (writeSettings) { 15901 mSettings.writeLPr(); 15902 } 15903 } 15904 return true; 15905 } 15906 15907 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15908 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15909 PackageRemovedInfo outInfo, boolean writeSettings, 15910 PackageParser.Package replacingPackage) { 15911 synchronized (mPackages) { 15912 if (outInfo != null) { 15913 outInfo.uid = ps.appId; 15914 } 15915 15916 if (outInfo != null && outInfo.removedChildPackages != null) { 15917 final int childCount = (ps.childPackageNames != null) 15918 ? ps.childPackageNames.size() : 0; 15919 for (int i = 0; i < childCount; i++) { 15920 String childPackageName = ps.childPackageNames.get(i); 15921 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15922 if (childPs == null) { 15923 return false; 15924 } 15925 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15926 childPackageName); 15927 if (childInfo != null) { 15928 childInfo.uid = childPs.appId; 15929 } 15930 } 15931 } 15932 } 15933 15934 // Delete package data from internal structures and also remove data if flag is set 15935 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15936 15937 // Delete the child packages data 15938 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15939 for (int i = 0; i < childCount; i++) { 15940 PackageSetting childPs; 15941 synchronized (mPackages) { 15942 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15943 } 15944 if (childPs != null) { 15945 PackageRemovedInfo childOutInfo = (outInfo != null 15946 && outInfo.removedChildPackages != null) 15947 ? outInfo.removedChildPackages.get(childPs.name) : null; 15948 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15949 && (replacingPackage != null 15950 && !replacingPackage.hasChildPackage(childPs.name)) 15951 ? flags & ~DELETE_KEEP_DATA : flags; 15952 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15953 deleteFlags, writeSettings); 15954 } 15955 } 15956 15957 // Delete application code and resources only for parent packages 15958 if (ps.parentPackageName == null) { 15959 if (deleteCodeAndResources && (outInfo != null)) { 15960 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15961 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15962 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15963 } 15964 } 15965 15966 return true; 15967 } 15968 15969 @Override 15970 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15971 int userId) { 15972 mContext.enforceCallingOrSelfPermission( 15973 android.Manifest.permission.DELETE_PACKAGES, null); 15974 synchronized (mPackages) { 15975 PackageSetting ps = mSettings.mPackages.get(packageName); 15976 if (ps == null) { 15977 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15978 return false; 15979 } 15980 if (!ps.getInstalled(userId)) { 15981 // Can't block uninstall for an app that is not installed or enabled. 15982 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15983 return false; 15984 } 15985 ps.setBlockUninstall(blockUninstall, userId); 15986 mSettings.writePackageRestrictionsLPr(userId); 15987 } 15988 return true; 15989 } 15990 15991 @Override 15992 public boolean getBlockUninstallForUser(String packageName, int userId) { 15993 synchronized (mPackages) { 15994 PackageSetting ps = mSettings.mPackages.get(packageName); 15995 if (ps == null) { 15996 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15997 return false; 15998 } 15999 return ps.getBlockUninstall(userId); 16000 } 16001 } 16002 16003 @Override 16004 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16005 int callingUid = Binder.getCallingUid(); 16006 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16007 throw new SecurityException( 16008 "setRequiredForSystemUser can only be run by the system or root"); 16009 } 16010 synchronized (mPackages) { 16011 PackageSetting ps = mSettings.mPackages.get(packageName); 16012 if (ps == null) { 16013 Log.w(TAG, "Package doesn't exist: " + packageName); 16014 return false; 16015 } 16016 if (systemUserApp) { 16017 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16018 } else { 16019 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16020 } 16021 mSettings.writeLPr(); 16022 } 16023 return true; 16024 } 16025 16026 /* 16027 * This method handles package deletion in general 16028 */ 16029 private boolean deletePackageLIF(String packageName, UserHandle user, 16030 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16031 PackageRemovedInfo outInfo, boolean writeSettings, 16032 PackageParser.Package replacingPackage) { 16033 if (packageName == null) { 16034 Slog.w(TAG, "Attempt to delete null packageName."); 16035 return false; 16036 } 16037 16038 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16039 16040 PackageSetting ps; 16041 16042 synchronized (mPackages) { 16043 ps = mSettings.mPackages.get(packageName); 16044 if (ps == null) { 16045 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16046 return false; 16047 } 16048 16049 if (ps.parentPackageName != null && (!isSystemApp(ps) 16050 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16051 if (DEBUG_REMOVE) { 16052 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16053 + ((user == null) ? UserHandle.USER_ALL : user)); 16054 } 16055 final int removedUserId = (user != null) ? user.getIdentifier() 16056 : UserHandle.USER_ALL; 16057 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16058 return false; 16059 } 16060 markPackageUninstalledForUserLPw(ps, user); 16061 scheduleWritePackageRestrictionsLocked(user); 16062 return true; 16063 } 16064 } 16065 16066 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16067 && user.getIdentifier() != UserHandle.USER_ALL)) { 16068 // The caller is asking that the package only be deleted for a single 16069 // user. To do this, we just mark its uninstalled state and delete 16070 // its data. If this is a system app, we only allow this to happen if 16071 // they have set the special DELETE_SYSTEM_APP which requests different 16072 // semantics than normal for uninstalling system apps. 16073 markPackageUninstalledForUserLPw(ps, user); 16074 16075 if (!isSystemApp(ps)) { 16076 // Do not uninstall the APK if an app should be cached 16077 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16078 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16079 // Other user still have this package installed, so all 16080 // we need to do is clear this user's data and save that 16081 // it is uninstalled. 16082 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16083 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16084 return false; 16085 } 16086 scheduleWritePackageRestrictionsLocked(user); 16087 return true; 16088 } else { 16089 // We need to set it back to 'installed' so the uninstall 16090 // broadcasts will be sent correctly. 16091 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16092 ps.setInstalled(true, user.getIdentifier()); 16093 } 16094 } else { 16095 // This is a system app, so we assume that the 16096 // other users still have this package installed, so all 16097 // we need to do is clear this user's data and save that 16098 // it is uninstalled. 16099 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16100 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16101 return false; 16102 } 16103 scheduleWritePackageRestrictionsLocked(user); 16104 return true; 16105 } 16106 } 16107 16108 // If we are deleting a composite package for all users, keep track 16109 // of result for each child. 16110 if (ps.childPackageNames != null && outInfo != null) { 16111 synchronized (mPackages) { 16112 final int childCount = ps.childPackageNames.size(); 16113 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16114 for (int i = 0; i < childCount; i++) { 16115 String childPackageName = ps.childPackageNames.get(i); 16116 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16117 childInfo.removedPackage = childPackageName; 16118 outInfo.removedChildPackages.put(childPackageName, childInfo); 16119 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16120 if (childPs != null) { 16121 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16122 } 16123 } 16124 } 16125 } 16126 16127 boolean ret = false; 16128 if (isSystemApp(ps)) { 16129 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16130 // When an updated system application is deleted we delete the existing resources 16131 // as well and fall back to existing code in system partition 16132 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16133 } else { 16134 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16135 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16136 outInfo, writeSettings, replacingPackage); 16137 } 16138 16139 // Take a note whether we deleted the package for all users 16140 if (outInfo != null) { 16141 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16142 if (outInfo.removedChildPackages != null) { 16143 synchronized (mPackages) { 16144 final int childCount = outInfo.removedChildPackages.size(); 16145 for (int i = 0; i < childCount; i++) { 16146 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16147 if (childInfo != null) { 16148 childInfo.removedForAllUsers = mPackages.get( 16149 childInfo.removedPackage) == null; 16150 } 16151 } 16152 } 16153 } 16154 // If we uninstalled an update to a system app there may be some 16155 // child packages that appeared as they are declared in the system 16156 // app but were not declared in the update. 16157 if (isSystemApp(ps)) { 16158 synchronized (mPackages) { 16159 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16160 final int childCount = (updatedPs.childPackageNames != null) 16161 ? updatedPs.childPackageNames.size() : 0; 16162 for (int i = 0; i < childCount; i++) { 16163 String childPackageName = updatedPs.childPackageNames.get(i); 16164 if (outInfo.removedChildPackages == null 16165 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16166 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16167 if (childPs == null) { 16168 continue; 16169 } 16170 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16171 installRes.name = childPackageName; 16172 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16173 installRes.pkg = mPackages.get(childPackageName); 16174 installRes.uid = childPs.pkg.applicationInfo.uid; 16175 if (outInfo.appearedChildPackages == null) { 16176 outInfo.appearedChildPackages = new ArrayMap<>(); 16177 } 16178 outInfo.appearedChildPackages.put(childPackageName, installRes); 16179 } 16180 } 16181 } 16182 } 16183 } 16184 16185 return ret; 16186 } 16187 16188 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16189 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16190 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16191 for (int nextUserId : userIds) { 16192 if (DEBUG_REMOVE) { 16193 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16194 } 16195 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16196 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16197 false /*hidden*/, false /*suspended*/, null, null, null, 16198 false /*blockUninstall*/, 16199 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16200 } 16201 } 16202 16203 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16204 PackageRemovedInfo outInfo) { 16205 final PackageParser.Package pkg; 16206 synchronized (mPackages) { 16207 pkg = mPackages.get(ps.name); 16208 } 16209 16210 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16211 : new int[] {userId}; 16212 for (int nextUserId : userIds) { 16213 if (DEBUG_REMOVE) { 16214 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16215 + nextUserId); 16216 } 16217 16218 destroyAppDataLIF(pkg, userId, 16219 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16220 destroyAppProfilesLIF(pkg, userId); 16221 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16222 schedulePackageCleaning(ps.name, nextUserId, false); 16223 synchronized (mPackages) { 16224 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16225 scheduleWritePackageRestrictionsLocked(nextUserId); 16226 } 16227 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16228 } 16229 } 16230 16231 if (outInfo != null) { 16232 outInfo.removedPackage = ps.name; 16233 outInfo.removedAppId = ps.appId; 16234 outInfo.removedUsers = userIds; 16235 } 16236 16237 return true; 16238 } 16239 16240 private final class ClearStorageConnection implements ServiceConnection { 16241 IMediaContainerService mContainerService; 16242 16243 @Override 16244 public void onServiceConnected(ComponentName name, IBinder service) { 16245 synchronized (this) { 16246 mContainerService = IMediaContainerService.Stub.asInterface(service); 16247 notifyAll(); 16248 } 16249 } 16250 16251 @Override 16252 public void onServiceDisconnected(ComponentName name) { 16253 } 16254 } 16255 16256 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16257 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16258 16259 final boolean mounted; 16260 if (Environment.isExternalStorageEmulated()) { 16261 mounted = true; 16262 } else { 16263 final String status = Environment.getExternalStorageState(); 16264 16265 mounted = status.equals(Environment.MEDIA_MOUNTED) 16266 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16267 } 16268 16269 if (!mounted) { 16270 return; 16271 } 16272 16273 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16274 int[] users; 16275 if (userId == UserHandle.USER_ALL) { 16276 users = sUserManager.getUserIds(); 16277 } else { 16278 users = new int[] { userId }; 16279 } 16280 final ClearStorageConnection conn = new ClearStorageConnection(); 16281 if (mContext.bindServiceAsUser( 16282 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16283 try { 16284 for (int curUser : users) { 16285 long timeout = SystemClock.uptimeMillis() + 5000; 16286 synchronized (conn) { 16287 long now; 16288 while (conn.mContainerService == null && 16289 (now = SystemClock.uptimeMillis()) < timeout) { 16290 try { 16291 conn.wait(timeout - now); 16292 } catch (InterruptedException e) { 16293 } 16294 } 16295 } 16296 if (conn.mContainerService == null) { 16297 return; 16298 } 16299 16300 final UserEnvironment userEnv = new UserEnvironment(curUser); 16301 clearDirectory(conn.mContainerService, 16302 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16303 if (allData) { 16304 clearDirectory(conn.mContainerService, 16305 userEnv.buildExternalStorageAppDataDirs(packageName)); 16306 clearDirectory(conn.mContainerService, 16307 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16308 } 16309 } 16310 } finally { 16311 mContext.unbindService(conn); 16312 } 16313 } 16314 } 16315 16316 @Override 16317 public void clearApplicationProfileData(String packageName) { 16318 enforceSystemOrRoot("Only the system can clear all profile data"); 16319 16320 final PackageParser.Package pkg; 16321 synchronized (mPackages) { 16322 pkg = mPackages.get(packageName); 16323 } 16324 16325 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16326 synchronized (mInstallLock) { 16327 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16328 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16329 true /* removeBaseMarker */); 16330 } 16331 } 16332 } 16333 16334 @Override 16335 public void clearApplicationUserData(final String packageName, 16336 final IPackageDataObserver observer, final int userId) { 16337 mContext.enforceCallingOrSelfPermission( 16338 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16339 16340 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16341 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16342 16343 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16344 throw new SecurityException("Cannot clear data for a protected package: " 16345 + packageName); 16346 } 16347 // Queue up an async operation since the package deletion may take a little while. 16348 mHandler.post(new Runnable() { 16349 public void run() { 16350 mHandler.removeCallbacks(this); 16351 final boolean succeeded; 16352 try (PackageFreezer freezer = freezePackage(packageName, 16353 "clearApplicationUserData")) { 16354 synchronized (mInstallLock) { 16355 succeeded = clearApplicationUserDataLIF(packageName, userId); 16356 } 16357 clearExternalStorageDataSync(packageName, userId, true); 16358 } 16359 if (succeeded) { 16360 // invoke DeviceStorageMonitor's update method to clear any notifications 16361 DeviceStorageMonitorInternal dsm = LocalServices 16362 .getService(DeviceStorageMonitorInternal.class); 16363 if (dsm != null) { 16364 dsm.checkMemory(); 16365 } 16366 } 16367 if(observer != null) { 16368 try { 16369 observer.onRemoveCompleted(packageName, succeeded); 16370 } catch (RemoteException e) { 16371 Log.i(TAG, "Observer no longer exists."); 16372 } 16373 } //end if observer 16374 } //end run 16375 }); 16376 } 16377 16378 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16379 if (packageName == null) { 16380 Slog.w(TAG, "Attempt to delete null packageName."); 16381 return false; 16382 } 16383 16384 // Try finding details about the requested package 16385 PackageParser.Package pkg; 16386 synchronized (mPackages) { 16387 pkg = mPackages.get(packageName); 16388 if (pkg == null) { 16389 final PackageSetting ps = mSettings.mPackages.get(packageName); 16390 if (ps != null) { 16391 pkg = ps.pkg; 16392 } 16393 } 16394 16395 if (pkg == null) { 16396 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16397 return false; 16398 } 16399 16400 PackageSetting ps = (PackageSetting) pkg.mExtras; 16401 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16402 } 16403 16404 clearAppDataLIF(pkg, userId, 16405 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16406 16407 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16408 removeKeystoreDataIfNeeded(userId, appId); 16409 16410 UserManagerInternal umInternal = getUserManagerInternal(); 16411 final int flags; 16412 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16413 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16414 } else if (umInternal.isUserRunning(userId)) { 16415 flags = StorageManager.FLAG_STORAGE_DE; 16416 } else { 16417 flags = 0; 16418 } 16419 prepareAppDataContentsLIF(pkg, userId, flags); 16420 16421 return true; 16422 } 16423 16424 /** 16425 * Reverts user permission state changes (permissions and flags) in 16426 * all packages for a given user. 16427 * 16428 * @param userId The device user for which to do a reset. 16429 */ 16430 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16431 final int packageCount = mPackages.size(); 16432 for (int i = 0; i < packageCount; i++) { 16433 PackageParser.Package pkg = mPackages.valueAt(i); 16434 PackageSetting ps = (PackageSetting) pkg.mExtras; 16435 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16436 } 16437 } 16438 16439 private void resetNetworkPolicies(int userId) { 16440 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16441 } 16442 16443 /** 16444 * Reverts user permission state changes (permissions and flags). 16445 * 16446 * @param ps The package for which to reset. 16447 * @param userId The device user for which to do a reset. 16448 */ 16449 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16450 final PackageSetting ps, final int userId) { 16451 if (ps.pkg == null) { 16452 return; 16453 } 16454 16455 // These are flags that can change base on user actions. 16456 final int userSettableMask = FLAG_PERMISSION_USER_SET 16457 | FLAG_PERMISSION_USER_FIXED 16458 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16459 | FLAG_PERMISSION_REVIEW_REQUIRED; 16460 16461 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16462 | FLAG_PERMISSION_POLICY_FIXED; 16463 16464 boolean writeInstallPermissions = false; 16465 boolean writeRuntimePermissions = false; 16466 16467 final int permissionCount = ps.pkg.requestedPermissions.size(); 16468 for (int i = 0; i < permissionCount; i++) { 16469 String permission = ps.pkg.requestedPermissions.get(i); 16470 16471 BasePermission bp = mSettings.mPermissions.get(permission); 16472 if (bp == null) { 16473 continue; 16474 } 16475 16476 // If shared user we just reset the state to which only this app contributed. 16477 if (ps.sharedUser != null) { 16478 boolean used = false; 16479 final int packageCount = ps.sharedUser.packages.size(); 16480 for (int j = 0; j < packageCount; j++) { 16481 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16482 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16483 && pkg.pkg.requestedPermissions.contains(permission)) { 16484 used = true; 16485 break; 16486 } 16487 } 16488 if (used) { 16489 continue; 16490 } 16491 } 16492 16493 PermissionsState permissionsState = ps.getPermissionsState(); 16494 16495 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16496 16497 // Always clear the user settable flags. 16498 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16499 bp.name) != null; 16500 // If permission review is enabled and this is a legacy app, mark the 16501 // permission as requiring a review as this is the initial state. 16502 int flags = 0; 16503 if (Build.PERMISSIONS_REVIEW_REQUIRED 16504 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16505 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16506 } 16507 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16508 if (hasInstallState) { 16509 writeInstallPermissions = true; 16510 } else { 16511 writeRuntimePermissions = true; 16512 } 16513 } 16514 16515 // Below is only runtime permission handling. 16516 if (!bp.isRuntime()) { 16517 continue; 16518 } 16519 16520 // Never clobber system or policy. 16521 if ((oldFlags & policyOrSystemFlags) != 0) { 16522 continue; 16523 } 16524 16525 // If this permission was granted by default, make sure it is. 16526 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16527 if (permissionsState.grantRuntimePermission(bp, userId) 16528 != PERMISSION_OPERATION_FAILURE) { 16529 writeRuntimePermissions = true; 16530 } 16531 // If permission review is enabled the permissions for a legacy apps 16532 // are represented as constantly granted runtime ones, so don't revoke. 16533 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16534 // Otherwise, reset the permission. 16535 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16536 switch (revokeResult) { 16537 case PERMISSION_OPERATION_SUCCESS: 16538 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16539 writeRuntimePermissions = true; 16540 final int appId = ps.appId; 16541 mHandler.post(new Runnable() { 16542 @Override 16543 public void run() { 16544 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16545 } 16546 }); 16547 } break; 16548 } 16549 } 16550 } 16551 16552 // Synchronously write as we are taking permissions away. 16553 if (writeRuntimePermissions) { 16554 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16555 } 16556 16557 // Synchronously write as we are taking permissions away. 16558 if (writeInstallPermissions) { 16559 mSettings.writeLPr(); 16560 } 16561 } 16562 16563 /** 16564 * Remove entries from the keystore daemon. Will only remove it if the 16565 * {@code appId} is valid. 16566 */ 16567 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16568 if (appId < 0) { 16569 return; 16570 } 16571 16572 final KeyStore keyStore = KeyStore.getInstance(); 16573 if (keyStore != null) { 16574 if (userId == UserHandle.USER_ALL) { 16575 for (final int individual : sUserManager.getUserIds()) { 16576 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16577 } 16578 } else { 16579 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16580 } 16581 } else { 16582 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16583 } 16584 } 16585 16586 @Override 16587 public void deleteApplicationCacheFiles(final String packageName, 16588 final IPackageDataObserver observer) { 16589 final int userId = UserHandle.getCallingUserId(); 16590 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16591 } 16592 16593 @Override 16594 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16595 final IPackageDataObserver observer) { 16596 mContext.enforceCallingOrSelfPermission( 16597 android.Manifest.permission.DELETE_CACHE_FILES, null); 16598 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16599 /* requireFullPermission= */ true, /* checkShell= */ false, 16600 "delete application cache files"); 16601 16602 final PackageParser.Package pkg; 16603 synchronized (mPackages) { 16604 pkg = mPackages.get(packageName); 16605 } 16606 16607 // Queue up an async operation since the package deletion may take a little while. 16608 mHandler.post(new Runnable() { 16609 public void run() { 16610 synchronized (mInstallLock) { 16611 final int flags = StorageManager.FLAG_STORAGE_DE 16612 | StorageManager.FLAG_STORAGE_CE; 16613 // We're only clearing cache files, so we don't care if the 16614 // app is unfrozen and still able to run 16615 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16616 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16617 } 16618 clearExternalStorageDataSync(packageName, userId, false); 16619 if (observer != null) { 16620 try { 16621 observer.onRemoveCompleted(packageName, true); 16622 } catch (RemoteException e) { 16623 Log.i(TAG, "Observer no longer exists."); 16624 } 16625 } 16626 } 16627 }); 16628 } 16629 16630 @Override 16631 public void getPackageSizeInfo(final String packageName, int userHandle, 16632 final IPackageStatsObserver observer) { 16633 mContext.enforceCallingOrSelfPermission( 16634 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16635 if (packageName == null) { 16636 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16637 } 16638 16639 PackageStats stats = new PackageStats(packageName, userHandle); 16640 16641 /* 16642 * Queue up an async operation since the package measurement may take a 16643 * little while. 16644 */ 16645 Message msg = mHandler.obtainMessage(INIT_COPY); 16646 msg.obj = new MeasureParams(stats, observer); 16647 mHandler.sendMessage(msg); 16648 } 16649 16650 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16651 final PackageSetting ps; 16652 synchronized (mPackages) { 16653 ps = mSettings.mPackages.get(packageName); 16654 if (ps == null) { 16655 Slog.w(TAG, "Failed to find settings for " + packageName); 16656 return false; 16657 } 16658 } 16659 try { 16660 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16661 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16662 ps.getCeDataInode(userId), ps.codePathString, stats); 16663 } catch (InstallerException e) { 16664 Slog.w(TAG, String.valueOf(e)); 16665 return false; 16666 } 16667 16668 // For now, ignore code size of packages on system partition 16669 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16670 stats.codeSize = 0; 16671 } 16672 16673 return true; 16674 } 16675 16676 private int getUidTargetSdkVersionLockedLPr(int uid) { 16677 Object obj = mSettings.getUserIdLPr(uid); 16678 if (obj instanceof SharedUserSetting) { 16679 final SharedUserSetting sus = (SharedUserSetting) obj; 16680 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16681 final Iterator<PackageSetting> it = sus.packages.iterator(); 16682 while (it.hasNext()) { 16683 final PackageSetting ps = it.next(); 16684 if (ps.pkg != null) { 16685 int v = ps.pkg.applicationInfo.targetSdkVersion; 16686 if (v < vers) vers = v; 16687 } 16688 } 16689 return vers; 16690 } else if (obj instanceof PackageSetting) { 16691 final PackageSetting ps = (PackageSetting) obj; 16692 if (ps.pkg != null) { 16693 return ps.pkg.applicationInfo.targetSdkVersion; 16694 } 16695 } 16696 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16697 } 16698 16699 @Override 16700 public void addPreferredActivity(IntentFilter filter, int match, 16701 ComponentName[] set, ComponentName activity, int userId) { 16702 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16703 "Adding preferred"); 16704 } 16705 16706 private void addPreferredActivityInternal(IntentFilter filter, int match, 16707 ComponentName[] set, ComponentName activity, boolean always, int userId, 16708 String opname) { 16709 // writer 16710 int callingUid = Binder.getCallingUid(); 16711 enforceCrossUserPermission(callingUid, userId, 16712 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16713 if (filter.countActions() == 0) { 16714 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16715 return; 16716 } 16717 synchronized (mPackages) { 16718 if (mContext.checkCallingOrSelfPermission( 16719 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16720 != PackageManager.PERMISSION_GRANTED) { 16721 if (getUidTargetSdkVersionLockedLPr(callingUid) 16722 < Build.VERSION_CODES.FROYO) { 16723 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16724 + callingUid); 16725 return; 16726 } 16727 mContext.enforceCallingOrSelfPermission( 16728 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16729 } 16730 16731 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16732 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16733 + userId + ":"); 16734 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16735 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16736 scheduleWritePackageRestrictionsLocked(userId); 16737 postPreferredActivityChangedBroadcast(userId); 16738 } 16739 } 16740 16741 private void postPreferredActivityChangedBroadcast(int userId) { 16742 mHandler.post(() -> { 16743 final IActivityManager am = ActivityManagerNative.getDefault(); 16744 if (am == null) { 16745 return; 16746 } 16747 16748 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16749 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16750 try { 16751 am.broadcastIntent(null, intent, null, null, 16752 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16753 null, false, false, userId); 16754 } catch (RemoteException e) { 16755 } 16756 }); 16757 } 16758 16759 @Override 16760 public void replacePreferredActivity(IntentFilter filter, int match, 16761 ComponentName[] set, ComponentName activity, int userId) { 16762 if (filter.countActions() != 1) { 16763 throw new IllegalArgumentException( 16764 "replacePreferredActivity expects filter to have only 1 action."); 16765 } 16766 if (filter.countDataAuthorities() != 0 16767 || filter.countDataPaths() != 0 16768 || filter.countDataSchemes() > 1 16769 || filter.countDataTypes() != 0) { 16770 throw new IllegalArgumentException( 16771 "replacePreferredActivity expects filter to have no data authorities, " + 16772 "paths, or types; and at most one scheme."); 16773 } 16774 16775 final int callingUid = Binder.getCallingUid(); 16776 enforceCrossUserPermission(callingUid, userId, 16777 true /* requireFullPermission */, false /* checkShell */, 16778 "replace preferred activity"); 16779 synchronized (mPackages) { 16780 if (mContext.checkCallingOrSelfPermission( 16781 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16782 != PackageManager.PERMISSION_GRANTED) { 16783 if (getUidTargetSdkVersionLockedLPr(callingUid) 16784 < Build.VERSION_CODES.FROYO) { 16785 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16786 + Binder.getCallingUid()); 16787 return; 16788 } 16789 mContext.enforceCallingOrSelfPermission( 16790 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16791 } 16792 16793 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16794 if (pir != null) { 16795 // Get all of the existing entries that exactly match this filter. 16796 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16797 if (existing != null && existing.size() == 1) { 16798 PreferredActivity cur = existing.get(0); 16799 if (DEBUG_PREFERRED) { 16800 Slog.i(TAG, "Checking replace of preferred:"); 16801 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16802 if (!cur.mPref.mAlways) { 16803 Slog.i(TAG, " -- CUR; not mAlways!"); 16804 } else { 16805 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16806 Slog.i(TAG, " -- CUR: mSet=" 16807 + Arrays.toString(cur.mPref.mSetComponents)); 16808 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16809 Slog.i(TAG, " -- NEW: mMatch=" 16810 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16811 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16812 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16813 } 16814 } 16815 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16816 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16817 && cur.mPref.sameSet(set)) { 16818 // Setting the preferred activity to what it happens to be already 16819 if (DEBUG_PREFERRED) { 16820 Slog.i(TAG, "Replacing with same preferred activity " 16821 + cur.mPref.mShortComponent + " for user " 16822 + userId + ":"); 16823 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16824 } 16825 return; 16826 } 16827 } 16828 16829 if (existing != null) { 16830 if (DEBUG_PREFERRED) { 16831 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16832 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16833 } 16834 for (int i = 0; i < existing.size(); i++) { 16835 PreferredActivity pa = existing.get(i); 16836 if (DEBUG_PREFERRED) { 16837 Slog.i(TAG, "Removing existing preferred activity " 16838 + pa.mPref.mComponent + ":"); 16839 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16840 } 16841 pir.removeFilter(pa); 16842 } 16843 } 16844 } 16845 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16846 "Replacing preferred"); 16847 } 16848 } 16849 16850 @Override 16851 public void clearPackagePreferredActivities(String packageName) { 16852 final int uid = Binder.getCallingUid(); 16853 // writer 16854 synchronized (mPackages) { 16855 PackageParser.Package pkg = mPackages.get(packageName); 16856 if (pkg == null || pkg.applicationInfo.uid != uid) { 16857 if (mContext.checkCallingOrSelfPermission( 16858 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16859 != PackageManager.PERMISSION_GRANTED) { 16860 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16861 < Build.VERSION_CODES.FROYO) { 16862 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16863 + Binder.getCallingUid()); 16864 return; 16865 } 16866 mContext.enforceCallingOrSelfPermission( 16867 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16868 } 16869 } 16870 16871 int user = UserHandle.getCallingUserId(); 16872 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16873 scheduleWritePackageRestrictionsLocked(user); 16874 } 16875 } 16876 } 16877 16878 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16879 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16880 ArrayList<PreferredActivity> removed = null; 16881 boolean changed = false; 16882 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16883 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16884 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16885 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16886 continue; 16887 } 16888 Iterator<PreferredActivity> it = pir.filterIterator(); 16889 while (it.hasNext()) { 16890 PreferredActivity pa = it.next(); 16891 // Mark entry for removal only if it matches the package name 16892 // and the entry is of type "always". 16893 if (packageName == null || 16894 (pa.mPref.mComponent.getPackageName().equals(packageName) 16895 && pa.mPref.mAlways)) { 16896 if (removed == null) { 16897 removed = new ArrayList<PreferredActivity>(); 16898 } 16899 removed.add(pa); 16900 } 16901 } 16902 if (removed != null) { 16903 for (int j=0; j<removed.size(); j++) { 16904 PreferredActivity pa = removed.get(j); 16905 pir.removeFilter(pa); 16906 } 16907 changed = true; 16908 } 16909 } 16910 if (changed) { 16911 postPreferredActivityChangedBroadcast(userId); 16912 } 16913 return changed; 16914 } 16915 16916 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16917 private void clearIntentFilterVerificationsLPw(int userId) { 16918 final int packageCount = mPackages.size(); 16919 for (int i = 0; i < packageCount; i++) { 16920 PackageParser.Package pkg = mPackages.valueAt(i); 16921 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16922 } 16923 } 16924 16925 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16926 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16927 if (userId == UserHandle.USER_ALL) { 16928 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16929 sUserManager.getUserIds())) { 16930 for (int oneUserId : sUserManager.getUserIds()) { 16931 scheduleWritePackageRestrictionsLocked(oneUserId); 16932 } 16933 } 16934 } else { 16935 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16936 scheduleWritePackageRestrictionsLocked(userId); 16937 } 16938 } 16939 } 16940 16941 void clearDefaultBrowserIfNeeded(String packageName) { 16942 for (int oneUserId : sUserManager.getUserIds()) { 16943 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16944 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16945 if (packageName.equals(defaultBrowserPackageName)) { 16946 setDefaultBrowserPackageName(null, oneUserId); 16947 } 16948 } 16949 } 16950 16951 @Override 16952 public void resetApplicationPreferences(int userId) { 16953 mContext.enforceCallingOrSelfPermission( 16954 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16955 final long identity = Binder.clearCallingIdentity(); 16956 // writer 16957 try { 16958 synchronized (mPackages) { 16959 clearPackagePreferredActivitiesLPw(null, userId); 16960 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16961 // TODO: We have to reset the default SMS and Phone. This requires 16962 // significant refactoring to keep all default apps in the package 16963 // manager (cleaner but more work) or have the services provide 16964 // callbacks to the package manager to request a default app reset. 16965 applyFactoryDefaultBrowserLPw(userId); 16966 clearIntentFilterVerificationsLPw(userId); 16967 primeDomainVerificationsLPw(userId); 16968 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16969 scheduleWritePackageRestrictionsLocked(userId); 16970 } 16971 resetNetworkPolicies(userId); 16972 } finally { 16973 Binder.restoreCallingIdentity(identity); 16974 } 16975 } 16976 16977 @Override 16978 public int getPreferredActivities(List<IntentFilter> outFilters, 16979 List<ComponentName> outActivities, String packageName) { 16980 16981 int num = 0; 16982 final int userId = UserHandle.getCallingUserId(); 16983 // reader 16984 synchronized (mPackages) { 16985 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16986 if (pir != null) { 16987 final Iterator<PreferredActivity> it = pir.filterIterator(); 16988 while (it.hasNext()) { 16989 final PreferredActivity pa = it.next(); 16990 if (packageName == null 16991 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16992 && pa.mPref.mAlways)) { 16993 if (outFilters != null) { 16994 outFilters.add(new IntentFilter(pa)); 16995 } 16996 if (outActivities != null) { 16997 outActivities.add(pa.mPref.mComponent); 16998 } 16999 } 17000 } 17001 } 17002 } 17003 17004 return num; 17005 } 17006 17007 @Override 17008 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17009 int userId) { 17010 int callingUid = Binder.getCallingUid(); 17011 if (callingUid != Process.SYSTEM_UID) { 17012 throw new SecurityException( 17013 "addPersistentPreferredActivity can only be run by the system"); 17014 } 17015 if (filter.countActions() == 0) { 17016 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17017 return; 17018 } 17019 synchronized (mPackages) { 17020 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17021 ":"); 17022 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17023 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17024 new PersistentPreferredActivity(filter, activity)); 17025 scheduleWritePackageRestrictionsLocked(userId); 17026 postPreferredActivityChangedBroadcast(userId); 17027 } 17028 } 17029 17030 @Override 17031 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17032 int callingUid = Binder.getCallingUid(); 17033 if (callingUid != Process.SYSTEM_UID) { 17034 throw new SecurityException( 17035 "clearPackagePersistentPreferredActivities can only be run by the system"); 17036 } 17037 ArrayList<PersistentPreferredActivity> removed = null; 17038 boolean changed = false; 17039 synchronized (mPackages) { 17040 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17041 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17042 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17043 .valueAt(i); 17044 if (userId != thisUserId) { 17045 continue; 17046 } 17047 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17048 while (it.hasNext()) { 17049 PersistentPreferredActivity ppa = it.next(); 17050 // Mark entry for removal only if it matches the package name. 17051 if (ppa.mComponent.getPackageName().equals(packageName)) { 17052 if (removed == null) { 17053 removed = new ArrayList<PersistentPreferredActivity>(); 17054 } 17055 removed.add(ppa); 17056 } 17057 } 17058 if (removed != null) { 17059 for (int j=0; j<removed.size(); j++) { 17060 PersistentPreferredActivity ppa = removed.get(j); 17061 ppir.removeFilter(ppa); 17062 } 17063 changed = true; 17064 } 17065 } 17066 17067 if (changed) { 17068 scheduleWritePackageRestrictionsLocked(userId); 17069 postPreferredActivityChangedBroadcast(userId); 17070 } 17071 } 17072 } 17073 17074 /** 17075 * Common machinery for picking apart a restored XML blob and passing 17076 * it to a caller-supplied functor to be applied to the running system. 17077 */ 17078 private void restoreFromXml(XmlPullParser parser, int userId, 17079 String expectedStartTag, BlobXmlRestorer functor) 17080 throws IOException, XmlPullParserException { 17081 int type; 17082 while ((type = parser.next()) != XmlPullParser.START_TAG 17083 && type != XmlPullParser.END_DOCUMENT) { 17084 } 17085 if (type != XmlPullParser.START_TAG) { 17086 // oops didn't find a start tag?! 17087 if (DEBUG_BACKUP) { 17088 Slog.e(TAG, "Didn't find start tag during restore"); 17089 } 17090 return; 17091 } 17092Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17093 // this is supposed to be TAG_PREFERRED_BACKUP 17094 if (!expectedStartTag.equals(parser.getName())) { 17095 if (DEBUG_BACKUP) { 17096 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17097 } 17098 return; 17099 } 17100 17101 // skip interfering stuff, then we're aligned with the backing implementation 17102 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17103Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17104 functor.apply(parser, userId); 17105 } 17106 17107 private interface BlobXmlRestorer { 17108 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17109 } 17110 17111 /** 17112 * Non-Binder method, support for the backup/restore mechanism: write the 17113 * full set of preferred activities in its canonical XML format. Returns the 17114 * XML output as a byte array, or null if there is none. 17115 */ 17116 @Override 17117 public byte[] getPreferredActivityBackup(int userId) { 17118 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17119 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17120 } 17121 17122 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17123 try { 17124 final XmlSerializer serializer = new FastXmlSerializer(); 17125 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17126 serializer.startDocument(null, true); 17127 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17128 17129 synchronized (mPackages) { 17130 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17131 } 17132 17133 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17134 serializer.endDocument(); 17135 serializer.flush(); 17136 } catch (Exception e) { 17137 if (DEBUG_BACKUP) { 17138 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17139 } 17140 return null; 17141 } 17142 17143 return dataStream.toByteArray(); 17144 } 17145 17146 @Override 17147 public void restorePreferredActivities(byte[] backup, int userId) { 17148 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17149 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17150 } 17151 17152 try { 17153 final XmlPullParser parser = Xml.newPullParser(); 17154 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17155 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17156 new BlobXmlRestorer() { 17157 @Override 17158 public void apply(XmlPullParser parser, int userId) 17159 throws XmlPullParserException, IOException { 17160 synchronized (mPackages) { 17161 mSettings.readPreferredActivitiesLPw(parser, userId); 17162 } 17163 } 17164 } ); 17165 } catch (Exception e) { 17166 if (DEBUG_BACKUP) { 17167 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17168 } 17169 } 17170 } 17171 17172 /** 17173 * Non-Binder method, support for the backup/restore mechanism: write the 17174 * default browser (etc) settings in its canonical XML format. Returns the default 17175 * browser XML representation as a byte array, or null if there is none. 17176 */ 17177 @Override 17178 public byte[] getDefaultAppsBackup(int userId) { 17179 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17180 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17181 } 17182 17183 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17184 try { 17185 final XmlSerializer serializer = new FastXmlSerializer(); 17186 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17187 serializer.startDocument(null, true); 17188 serializer.startTag(null, TAG_DEFAULT_APPS); 17189 17190 synchronized (mPackages) { 17191 mSettings.writeDefaultAppsLPr(serializer, userId); 17192 } 17193 17194 serializer.endTag(null, TAG_DEFAULT_APPS); 17195 serializer.endDocument(); 17196 serializer.flush(); 17197 } catch (Exception e) { 17198 if (DEBUG_BACKUP) { 17199 Slog.e(TAG, "Unable to write default apps for backup", e); 17200 } 17201 return null; 17202 } 17203 17204 return dataStream.toByteArray(); 17205 } 17206 17207 @Override 17208 public void restoreDefaultApps(byte[] backup, int userId) { 17209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17210 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17211 } 17212 17213 try { 17214 final XmlPullParser parser = Xml.newPullParser(); 17215 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17216 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17217 new BlobXmlRestorer() { 17218 @Override 17219 public void apply(XmlPullParser parser, int userId) 17220 throws XmlPullParserException, IOException { 17221 synchronized (mPackages) { 17222 mSettings.readDefaultAppsLPw(parser, userId); 17223 } 17224 } 17225 } ); 17226 } catch (Exception e) { 17227 if (DEBUG_BACKUP) { 17228 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17229 } 17230 } 17231 } 17232 17233 @Override 17234 public byte[] getIntentFilterVerificationBackup(int userId) { 17235 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17236 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17237 } 17238 17239 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17240 try { 17241 final XmlSerializer serializer = new FastXmlSerializer(); 17242 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17243 serializer.startDocument(null, true); 17244 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17245 17246 synchronized (mPackages) { 17247 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17248 } 17249 17250 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17251 serializer.endDocument(); 17252 serializer.flush(); 17253 } catch (Exception e) { 17254 if (DEBUG_BACKUP) { 17255 Slog.e(TAG, "Unable to write default apps for backup", e); 17256 } 17257 return null; 17258 } 17259 17260 return dataStream.toByteArray(); 17261 } 17262 17263 @Override 17264 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17265 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17266 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17267 } 17268 17269 try { 17270 final XmlPullParser parser = Xml.newPullParser(); 17271 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17272 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17273 new BlobXmlRestorer() { 17274 @Override 17275 public void apply(XmlPullParser parser, int userId) 17276 throws XmlPullParserException, IOException { 17277 synchronized (mPackages) { 17278 mSettings.readAllDomainVerificationsLPr(parser, userId); 17279 mSettings.writeLPr(); 17280 } 17281 } 17282 } ); 17283 } catch (Exception e) { 17284 if (DEBUG_BACKUP) { 17285 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17286 } 17287 } 17288 } 17289 17290 @Override 17291 public byte[] getPermissionGrantBackup(int userId) { 17292 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17293 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17294 } 17295 17296 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17297 try { 17298 final XmlSerializer serializer = new FastXmlSerializer(); 17299 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17300 serializer.startDocument(null, true); 17301 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17302 17303 synchronized (mPackages) { 17304 serializeRuntimePermissionGrantsLPr(serializer, userId); 17305 } 17306 17307 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17308 serializer.endDocument(); 17309 serializer.flush(); 17310 } catch (Exception e) { 17311 if (DEBUG_BACKUP) { 17312 Slog.e(TAG, "Unable to write default apps for backup", e); 17313 } 17314 return null; 17315 } 17316 17317 return dataStream.toByteArray(); 17318 } 17319 17320 @Override 17321 public void restorePermissionGrants(byte[] backup, int userId) { 17322 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17323 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17324 } 17325 17326 try { 17327 final XmlPullParser parser = Xml.newPullParser(); 17328 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17329 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17330 new BlobXmlRestorer() { 17331 @Override 17332 public void apply(XmlPullParser parser, int userId) 17333 throws XmlPullParserException, IOException { 17334 synchronized (mPackages) { 17335 processRestoredPermissionGrantsLPr(parser, userId); 17336 } 17337 } 17338 } ); 17339 } catch (Exception e) { 17340 if (DEBUG_BACKUP) { 17341 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17342 } 17343 } 17344 } 17345 17346 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17347 throws IOException { 17348 serializer.startTag(null, TAG_ALL_GRANTS); 17349 17350 final int N = mSettings.mPackages.size(); 17351 for (int i = 0; i < N; i++) { 17352 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17353 boolean pkgGrantsKnown = false; 17354 17355 PermissionsState packagePerms = ps.getPermissionsState(); 17356 17357 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17358 final int grantFlags = state.getFlags(); 17359 // only look at grants that are not system/policy fixed 17360 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17361 final boolean isGranted = state.isGranted(); 17362 // And only back up the user-twiddled state bits 17363 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17364 final String packageName = mSettings.mPackages.keyAt(i); 17365 if (!pkgGrantsKnown) { 17366 serializer.startTag(null, TAG_GRANT); 17367 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17368 pkgGrantsKnown = true; 17369 } 17370 17371 final boolean userSet = 17372 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17373 final boolean userFixed = 17374 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17375 final boolean revoke = 17376 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17377 17378 serializer.startTag(null, TAG_PERMISSION); 17379 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17380 if (isGranted) { 17381 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17382 } 17383 if (userSet) { 17384 serializer.attribute(null, ATTR_USER_SET, "true"); 17385 } 17386 if (userFixed) { 17387 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17388 } 17389 if (revoke) { 17390 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17391 } 17392 serializer.endTag(null, TAG_PERMISSION); 17393 } 17394 } 17395 } 17396 17397 if (pkgGrantsKnown) { 17398 serializer.endTag(null, TAG_GRANT); 17399 } 17400 } 17401 17402 serializer.endTag(null, TAG_ALL_GRANTS); 17403 } 17404 17405 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17406 throws XmlPullParserException, IOException { 17407 String pkgName = null; 17408 int outerDepth = parser.getDepth(); 17409 int type; 17410 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17411 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17412 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17413 continue; 17414 } 17415 17416 final String tagName = parser.getName(); 17417 if (tagName.equals(TAG_GRANT)) { 17418 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17419 if (DEBUG_BACKUP) { 17420 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17421 } 17422 } else if (tagName.equals(TAG_PERMISSION)) { 17423 17424 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17425 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17426 17427 int newFlagSet = 0; 17428 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17429 newFlagSet |= FLAG_PERMISSION_USER_SET; 17430 } 17431 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17432 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17433 } 17434 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17435 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17436 } 17437 if (DEBUG_BACKUP) { 17438 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17439 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17440 } 17441 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17442 if (ps != null) { 17443 // Already installed so we apply the grant immediately 17444 if (DEBUG_BACKUP) { 17445 Slog.v(TAG, " + already installed; applying"); 17446 } 17447 PermissionsState perms = ps.getPermissionsState(); 17448 BasePermission bp = mSettings.mPermissions.get(permName); 17449 if (bp != null) { 17450 if (isGranted) { 17451 perms.grantRuntimePermission(bp, userId); 17452 } 17453 if (newFlagSet != 0) { 17454 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17455 } 17456 } 17457 } else { 17458 // Need to wait for post-restore install to apply the grant 17459 if (DEBUG_BACKUP) { 17460 Slog.v(TAG, " - not yet installed; saving for later"); 17461 } 17462 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17463 isGranted, newFlagSet, userId); 17464 } 17465 } else { 17466 PackageManagerService.reportSettingsProblem(Log.WARN, 17467 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17468 XmlUtils.skipCurrentTag(parser); 17469 } 17470 } 17471 17472 scheduleWriteSettingsLocked(); 17473 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17474 } 17475 17476 @Override 17477 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17478 int sourceUserId, int targetUserId, int flags) { 17479 mContext.enforceCallingOrSelfPermission( 17480 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17481 int callingUid = Binder.getCallingUid(); 17482 enforceOwnerRights(ownerPackage, callingUid); 17483 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17484 if (intentFilter.countActions() == 0) { 17485 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17486 return; 17487 } 17488 synchronized (mPackages) { 17489 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17490 ownerPackage, targetUserId, flags); 17491 CrossProfileIntentResolver resolver = 17492 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17493 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17494 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17495 if (existing != null) { 17496 int size = existing.size(); 17497 for (int i = 0; i < size; i++) { 17498 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17499 return; 17500 } 17501 } 17502 } 17503 resolver.addFilter(newFilter); 17504 scheduleWritePackageRestrictionsLocked(sourceUserId); 17505 } 17506 } 17507 17508 @Override 17509 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17510 mContext.enforceCallingOrSelfPermission( 17511 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17512 int callingUid = Binder.getCallingUid(); 17513 enforceOwnerRights(ownerPackage, callingUid); 17514 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17515 synchronized (mPackages) { 17516 CrossProfileIntentResolver resolver = 17517 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17518 ArraySet<CrossProfileIntentFilter> set = 17519 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17520 for (CrossProfileIntentFilter filter : set) { 17521 if (filter.getOwnerPackage().equals(ownerPackage)) { 17522 resolver.removeFilter(filter); 17523 } 17524 } 17525 scheduleWritePackageRestrictionsLocked(sourceUserId); 17526 } 17527 } 17528 17529 // Enforcing that callingUid is owning pkg on userId 17530 private void enforceOwnerRights(String pkg, int callingUid) { 17531 // The system owns everything. 17532 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17533 return; 17534 } 17535 int callingUserId = UserHandle.getUserId(callingUid); 17536 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17537 if (pi == null) { 17538 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17539 + callingUserId); 17540 } 17541 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17542 throw new SecurityException("Calling uid " + callingUid 17543 + " does not own package " + pkg); 17544 } 17545 } 17546 17547 @Override 17548 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17549 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17550 } 17551 17552 private Intent getHomeIntent() { 17553 Intent intent = new Intent(Intent.ACTION_MAIN); 17554 intent.addCategory(Intent.CATEGORY_HOME); 17555 intent.addCategory(Intent.CATEGORY_DEFAULT); 17556 return intent; 17557 } 17558 17559 private IntentFilter getHomeFilter() { 17560 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17561 filter.addCategory(Intent.CATEGORY_HOME); 17562 filter.addCategory(Intent.CATEGORY_DEFAULT); 17563 return filter; 17564 } 17565 17566 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17567 int userId) { 17568 Intent intent = getHomeIntent(); 17569 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17570 PackageManager.GET_META_DATA, userId); 17571 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17572 true, false, false, userId); 17573 17574 allHomeCandidates.clear(); 17575 if (list != null) { 17576 for (ResolveInfo ri : list) { 17577 allHomeCandidates.add(ri); 17578 } 17579 } 17580 return (preferred == null || preferred.activityInfo == null) 17581 ? null 17582 : new ComponentName(preferred.activityInfo.packageName, 17583 preferred.activityInfo.name); 17584 } 17585 17586 @Override 17587 public void setHomeActivity(ComponentName comp, int userId) { 17588 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17589 getHomeActivitiesAsUser(homeActivities, userId); 17590 17591 boolean found = false; 17592 17593 final int size = homeActivities.size(); 17594 final ComponentName[] set = new ComponentName[size]; 17595 for (int i = 0; i < size; i++) { 17596 final ResolveInfo candidate = homeActivities.get(i); 17597 final ActivityInfo info = candidate.activityInfo; 17598 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17599 set[i] = activityName; 17600 if (!found && activityName.equals(comp)) { 17601 found = true; 17602 } 17603 } 17604 if (!found) { 17605 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17606 + userId); 17607 } 17608 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17609 set, comp, userId); 17610 } 17611 17612 private @Nullable String getSetupWizardPackageName() { 17613 final Intent intent = new Intent(Intent.ACTION_MAIN); 17614 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17615 17616 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17617 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17618 | MATCH_DISABLED_COMPONENTS, 17619 UserHandle.myUserId()); 17620 if (matches.size() == 1) { 17621 return matches.get(0).getComponentInfo().packageName; 17622 } else { 17623 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17624 + ": matches=" + matches); 17625 return null; 17626 } 17627 } 17628 17629 @Override 17630 public void setApplicationEnabledSetting(String appPackageName, 17631 int newState, int flags, int userId, String callingPackage) { 17632 if (!sUserManager.exists(userId)) return; 17633 if (callingPackage == null) { 17634 callingPackage = Integer.toString(Binder.getCallingUid()); 17635 } 17636 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17637 } 17638 17639 @Override 17640 public void setComponentEnabledSetting(ComponentName componentName, 17641 int newState, int flags, int userId) { 17642 if (!sUserManager.exists(userId)) return; 17643 setEnabledSetting(componentName.getPackageName(), 17644 componentName.getClassName(), newState, flags, userId, null); 17645 } 17646 17647 private void setEnabledSetting(final String packageName, String className, int newState, 17648 final int flags, int userId, String callingPackage) { 17649 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17650 || newState == COMPONENT_ENABLED_STATE_ENABLED 17651 || newState == COMPONENT_ENABLED_STATE_DISABLED 17652 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17653 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17654 throw new IllegalArgumentException("Invalid new component state: " 17655 + newState); 17656 } 17657 PackageSetting pkgSetting; 17658 final int uid = Binder.getCallingUid(); 17659 final int permission; 17660 if (uid == Process.SYSTEM_UID) { 17661 permission = PackageManager.PERMISSION_GRANTED; 17662 } else { 17663 permission = mContext.checkCallingOrSelfPermission( 17664 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17665 } 17666 enforceCrossUserPermission(uid, userId, 17667 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17668 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17669 boolean sendNow = false; 17670 boolean isApp = (className == null); 17671 String componentName = isApp ? packageName : className; 17672 int packageUid = -1; 17673 ArrayList<String> components; 17674 17675 // writer 17676 synchronized (mPackages) { 17677 pkgSetting = mSettings.mPackages.get(packageName); 17678 if (pkgSetting == null) { 17679 if (className == null) { 17680 throw new IllegalArgumentException("Unknown package: " + packageName); 17681 } 17682 throw new IllegalArgumentException( 17683 "Unknown component: " + packageName + "/" + className); 17684 } 17685 } 17686 17687 // Limit who can change which apps 17688 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17689 // Don't allow apps that don't have permission to modify other apps 17690 if (!allowedByPermission) { 17691 throw new SecurityException( 17692 "Permission Denial: attempt to change component state from pid=" 17693 + Binder.getCallingPid() 17694 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17695 } 17696 // Don't allow changing protected packages. 17697 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17698 throw new SecurityException("Cannot disable a protected package: " + packageName); 17699 } 17700 } 17701 17702 synchronized (mPackages) { 17703 if (uid == Process.SHELL_UID) { 17704 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17705 int oldState = pkgSetting.getEnabled(userId); 17706 if (className == null 17707 && 17708 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17709 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17710 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17711 && 17712 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17713 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17714 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17715 // ok 17716 } else { 17717 throw new SecurityException( 17718 "Shell cannot change component state for " + packageName + "/" 17719 + className + " to " + newState); 17720 } 17721 } 17722 if (className == null) { 17723 // We're dealing with an application/package level state change 17724 if (pkgSetting.getEnabled(userId) == newState) { 17725 // Nothing to do 17726 return; 17727 } 17728 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17729 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17730 // Don't care about who enables an app. 17731 callingPackage = null; 17732 } 17733 pkgSetting.setEnabled(newState, userId, callingPackage); 17734 // pkgSetting.pkg.mSetEnabled = newState; 17735 } else { 17736 // We're dealing with a component level state change 17737 // First, verify that this is a valid class name. 17738 PackageParser.Package pkg = pkgSetting.pkg; 17739 if (pkg == null || !pkg.hasComponentClassName(className)) { 17740 if (pkg != null && 17741 pkg.applicationInfo.targetSdkVersion >= 17742 Build.VERSION_CODES.JELLY_BEAN) { 17743 throw new IllegalArgumentException("Component class " + className 17744 + " does not exist in " + packageName); 17745 } else { 17746 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17747 + className + " does not exist in " + packageName); 17748 } 17749 } 17750 switch (newState) { 17751 case COMPONENT_ENABLED_STATE_ENABLED: 17752 if (!pkgSetting.enableComponentLPw(className, userId)) { 17753 return; 17754 } 17755 break; 17756 case COMPONENT_ENABLED_STATE_DISABLED: 17757 if (!pkgSetting.disableComponentLPw(className, userId)) { 17758 return; 17759 } 17760 break; 17761 case COMPONENT_ENABLED_STATE_DEFAULT: 17762 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17763 return; 17764 } 17765 break; 17766 default: 17767 Slog.e(TAG, "Invalid new component state: " + newState); 17768 return; 17769 } 17770 } 17771 scheduleWritePackageRestrictionsLocked(userId); 17772 components = mPendingBroadcasts.get(userId, packageName); 17773 final boolean newPackage = components == null; 17774 if (newPackage) { 17775 components = new ArrayList<String>(); 17776 } 17777 if (!components.contains(componentName)) { 17778 components.add(componentName); 17779 } 17780 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17781 sendNow = true; 17782 // Purge entry from pending broadcast list if another one exists already 17783 // since we are sending one right away. 17784 mPendingBroadcasts.remove(userId, packageName); 17785 } else { 17786 if (newPackage) { 17787 mPendingBroadcasts.put(userId, packageName, components); 17788 } 17789 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17790 // Schedule a message 17791 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17792 } 17793 } 17794 } 17795 17796 long callingId = Binder.clearCallingIdentity(); 17797 try { 17798 if (sendNow) { 17799 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17800 sendPackageChangedBroadcast(packageName, 17801 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17802 } 17803 } finally { 17804 Binder.restoreCallingIdentity(callingId); 17805 } 17806 } 17807 17808 @Override 17809 public void flushPackageRestrictionsAsUser(int userId) { 17810 if (!sUserManager.exists(userId)) { 17811 return; 17812 } 17813 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17814 false /* checkShell */, "flushPackageRestrictions"); 17815 synchronized (mPackages) { 17816 mSettings.writePackageRestrictionsLPr(userId); 17817 mDirtyUsers.remove(userId); 17818 if (mDirtyUsers.isEmpty()) { 17819 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17820 } 17821 } 17822 } 17823 17824 private void sendPackageChangedBroadcast(String packageName, 17825 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17826 if (DEBUG_INSTALL) 17827 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17828 + componentNames); 17829 Bundle extras = new Bundle(4); 17830 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17831 String nameList[] = new String[componentNames.size()]; 17832 componentNames.toArray(nameList); 17833 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17834 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17835 extras.putInt(Intent.EXTRA_UID, packageUid); 17836 // If this is not reporting a change of the overall package, then only send it 17837 // to registered receivers. We don't want to launch a swath of apps for every 17838 // little component state change. 17839 final int flags = !componentNames.contains(packageName) 17840 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17841 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17842 new int[] {UserHandle.getUserId(packageUid)}); 17843 } 17844 17845 @Override 17846 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17847 if (!sUserManager.exists(userId)) return; 17848 final int uid = Binder.getCallingUid(); 17849 final int permission = mContext.checkCallingOrSelfPermission( 17850 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17851 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17852 enforceCrossUserPermission(uid, userId, 17853 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17854 // writer 17855 synchronized (mPackages) { 17856 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17857 allowedByPermission, uid, userId)) { 17858 scheduleWritePackageRestrictionsLocked(userId); 17859 } 17860 } 17861 } 17862 17863 @Override 17864 public String getInstallerPackageName(String packageName) { 17865 // reader 17866 synchronized (mPackages) { 17867 return mSettings.getInstallerPackageNameLPr(packageName); 17868 } 17869 } 17870 17871 public boolean isOrphaned(String packageName) { 17872 // reader 17873 synchronized (mPackages) { 17874 return mSettings.isOrphaned(packageName); 17875 } 17876 } 17877 17878 @Override 17879 public int getApplicationEnabledSetting(String packageName, int userId) { 17880 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17881 int uid = Binder.getCallingUid(); 17882 enforceCrossUserPermission(uid, userId, 17883 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17884 // reader 17885 synchronized (mPackages) { 17886 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17887 } 17888 } 17889 17890 @Override 17891 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17892 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17893 int uid = Binder.getCallingUid(); 17894 enforceCrossUserPermission(uid, userId, 17895 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17896 // reader 17897 synchronized (mPackages) { 17898 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17899 } 17900 } 17901 17902 @Override 17903 public void enterSafeMode() { 17904 enforceSystemOrRoot("Only the system can request entering safe mode"); 17905 17906 if (!mSystemReady) { 17907 mSafeMode = true; 17908 } 17909 } 17910 17911 @Override 17912 public void systemReady() { 17913 mSystemReady = true; 17914 17915 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 17916 // disabled after already being started. 17917 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 17918 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 17919 17920 // Read the compatibilty setting when the system is ready. 17921 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17922 mContext.getContentResolver(), 17923 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17924 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17925 if (DEBUG_SETTINGS) { 17926 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17927 } 17928 17929 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17930 17931 synchronized (mPackages) { 17932 // Verify that all of the preferred activity components actually 17933 // exist. It is possible for applications to be updated and at 17934 // that point remove a previously declared activity component that 17935 // had been set as a preferred activity. We try to clean this up 17936 // the next time we encounter that preferred activity, but it is 17937 // possible for the user flow to never be able to return to that 17938 // situation so here we do a sanity check to make sure we haven't 17939 // left any junk around. 17940 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17941 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17942 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17943 removed.clear(); 17944 for (PreferredActivity pa : pir.filterSet()) { 17945 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17946 removed.add(pa); 17947 } 17948 } 17949 if (removed.size() > 0) { 17950 for (int r=0; r<removed.size(); r++) { 17951 PreferredActivity pa = removed.get(r); 17952 Slog.w(TAG, "Removing dangling preferred activity: " 17953 + pa.mPref.mComponent); 17954 pir.removeFilter(pa); 17955 } 17956 mSettings.writePackageRestrictionsLPr( 17957 mSettings.mPreferredActivities.keyAt(i)); 17958 } 17959 } 17960 17961 for (int userId : UserManagerService.getInstance().getUserIds()) { 17962 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17963 grantPermissionsUserIds = ArrayUtils.appendInt( 17964 grantPermissionsUserIds, userId); 17965 } 17966 } 17967 } 17968 sUserManager.systemReady(); 17969 17970 // If we upgraded grant all default permissions before kicking off. 17971 for (int userId : grantPermissionsUserIds) { 17972 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17973 } 17974 17975 // If we did not grant default permissions, we preload from this the 17976 // default permission exceptions lazily to ensure we don't hit the 17977 // disk on a new user creation. 17978 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 17979 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 17980 } 17981 17982 // Kick off any messages waiting for system ready 17983 if (mPostSystemReadyMessages != null) { 17984 for (Message msg : mPostSystemReadyMessages) { 17985 msg.sendToTarget(); 17986 } 17987 mPostSystemReadyMessages = null; 17988 } 17989 17990 // Watch for external volumes that come and go over time 17991 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17992 storage.registerListener(mStorageListener); 17993 17994 mInstallerService.systemReady(); 17995 mPackageDexOptimizer.systemReady(); 17996 17997 MountServiceInternal mountServiceInternal = LocalServices.getService( 17998 MountServiceInternal.class); 17999 mountServiceInternal.addExternalStoragePolicy( 18000 new MountServiceInternal.ExternalStorageMountPolicy() { 18001 @Override 18002 public int getMountMode(int uid, String packageName) { 18003 if (Process.isIsolated(uid)) { 18004 return Zygote.MOUNT_EXTERNAL_NONE; 18005 } 18006 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18007 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18008 } 18009 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18010 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18011 } 18012 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18013 return Zygote.MOUNT_EXTERNAL_READ; 18014 } 18015 return Zygote.MOUNT_EXTERNAL_WRITE; 18016 } 18017 18018 @Override 18019 public boolean hasExternalStorage(int uid, String packageName) { 18020 return true; 18021 } 18022 }); 18023 18024 // Now that we're mostly running, clean up stale users and apps 18025 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18026 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18027 } 18028 18029 @Override 18030 public boolean isSafeMode() { 18031 return mSafeMode; 18032 } 18033 18034 @Override 18035 public boolean hasSystemUidErrors() { 18036 return mHasSystemUidErrors; 18037 } 18038 18039 static String arrayToString(int[] array) { 18040 StringBuffer buf = new StringBuffer(128); 18041 buf.append('['); 18042 if (array != null) { 18043 for (int i=0; i<array.length; i++) { 18044 if (i > 0) buf.append(", "); 18045 buf.append(array[i]); 18046 } 18047 } 18048 buf.append(']'); 18049 return buf.toString(); 18050 } 18051 18052 static class DumpState { 18053 public static final int DUMP_LIBS = 1 << 0; 18054 public static final int DUMP_FEATURES = 1 << 1; 18055 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18056 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18057 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18058 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18059 public static final int DUMP_PERMISSIONS = 1 << 6; 18060 public static final int DUMP_PACKAGES = 1 << 7; 18061 public static final int DUMP_SHARED_USERS = 1 << 8; 18062 public static final int DUMP_MESSAGES = 1 << 9; 18063 public static final int DUMP_PROVIDERS = 1 << 10; 18064 public static final int DUMP_VERIFIERS = 1 << 11; 18065 public static final int DUMP_PREFERRED = 1 << 12; 18066 public static final int DUMP_PREFERRED_XML = 1 << 13; 18067 public static final int DUMP_KEYSETS = 1 << 14; 18068 public static final int DUMP_VERSION = 1 << 15; 18069 public static final int DUMP_INSTALLS = 1 << 16; 18070 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18071 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18072 public static final int DUMP_FROZEN = 1 << 19; 18073 public static final int DUMP_DEXOPT = 1 << 20; 18074 public static final int DUMP_COMPILER_STATS = 1 << 21; 18075 18076 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18077 18078 private int mTypes; 18079 18080 private int mOptions; 18081 18082 private boolean mTitlePrinted; 18083 18084 private SharedUserSetting mSharedUser; 18085 18086 public boolean isDumping(int type) { 18087 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18088 return true; 18089 } 18090 18091 return (mTypes & type) != 0; 18092 } 18093 18094 public void setDump(int type) { 18095 mTypes |= type; 18096 } 18097 18098 public boolean isOptionEnabled(int option) { 18099 return (mOptions & option) != 0; 18100 } 18101 18102 public void setOptionEnabled(int option) { 18103 mOptions |= option; 18104 } 18105 18106 public boolean onTitlePrinted() { 18107 final boolean printed = mTitlePrinted; 18108 mTitlePrinted = true; 18109 return printed; 18110 } 18111 18112 public boolean getTitlePrinted() { 18113 return mTitlePrinted; 18114 } 18115 18116 public void setTitlePrinted(boolean enabled) { 18117 mTitlePrinted = enabled; 18118 } 18119 18120 public SharedUserSetting getSharedUser() { 18121 return mSharedUser; 18122 } 18123 18124 public void setSharedUser(SharedUserSetting user) { 18125 mSharedUser = user; 18126 } 18127 } 18128 18129 @Override 18130 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18131 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18132 (new PackageManagerShellCommand(this)).exec( 18133 this, in, out, err, args, resultReceiver); 18134 } 18135 18136 @Override 18137 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18138 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18139 != PackageManager.PERMISSION_GRANTED) { 18140 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18141 + Binder.getCallingPid() 18142 + ", uid=" + Binder.getCallingUid() 18143 + " without permission " 18144 + android.Manifest.permission.DUMP); 18145 return; 18146 } 18147 18148 DumpState dumpState = new DumpState(); 18149 boolean fullPreferred = false; 18150 boolean checkin = false; 18151 18152 String packageName = null; 18153 ArraySet<String> permissionNames = null; 18154 18155 int opti = 0; 18156 while (opti < args.length) { 18157 String opt = args[opti]; 18158 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18159 break; 18160 } 18161 opti++; 18162 18163 if ("-a".equals(opt)) { 18164 // Right now we only know how to print all. 18165 } else if ("-h".equals(opt)) { 18166 pw.println("Package manager dump options:"); 18167 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18168 pw.println(" --checkin: dump for a checkin"); 18169 pw.println(" -f: print details of intent filters"); 18170 pw.println(" -h: print this help"); 18171 pw.println(" cmd may be one of:"); 18172 pw.println(" l[ibraries]: list known shared libraries"); 18173 pw.println(" f[eatures]: list device features"); 18174 pw.println(" k[eysets]: print known keysets"); 18175 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18176 pw.println(" perm[issions]: dump permissions"); 18177 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18178 pw.println(" pref[erred]: print preferred package settings"); 18179 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18180 pw.println(" prov[iders]: dump content providers"); 18181 pw.println(" p[ackages]: dump installed packages"); 18182 pw.println(" s[hared-users]: dump shared user IDs"); 18183 pw.println(" m[essages]: print collected runtime messages"); 18184 pw.println(" v[erifiers]: print package verifier info"); 18185 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18186 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18187 pw.println(" version: print database version info"); 18188 pw.println(" write: write current settings now"); 18189 pw.println(" installs: details about install sessions"); 18190 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18191 pw.println(" dexopt: dump dexopt state"); 18192 pw.println(" compiler-stats: dump compiler statistics"); 18193 pw.println(" <package.name>: info about given package"); 18194 return; 18195 } else if ("--checkin".equals(opt)) { 18196 checkin = true; 18197 } else if ("-f".equals(opt)) { 18198 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18199 } else { 18200 pw.println("Unknown argument: " + opt + "; use -h for help"); 18201 } 18202 } 18203 18204 // Is the caller requesting to dump a particular piece of data? 18205 if (opti < args.length) { 18206 String cmd = args[opti]; 18207 opti++; 18208 // Is this a package name? 18209 if ("android".equals(cmd) || cmd.contains(".")) { 18210 packageName = cmd; 18211 // When dumping a single package, we always dump all of its 18212 // filter information since the amount of data will be reasonable. 18213 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18214 } else if ("check-permission".equals(cmd)) { 18215 if (opti >= args.length) { 18216 pw.println("Error: check-permission missing permission argument"); 18217 return; 18218 } 18219 String perm = args[opti]; 18220 opti++; 18221 if (opti >= args.length) { 18222 pw.println("Error: check-permission missing package argument"); 18223 return; 18224 } 18225 String pkg = args[opti]; 18226 opti++; 18227 int user = UserHandle.getUserId(Binder.getCallingUid()); 18228 if (opti < args.length) { 18229 try { 18230 user = Integer.parseInt(args[opti]); 18231 } catch (NumberFormatException e) { 18232 pw.println("Error: check-permission user argument is not a number: " 18233 + args[opti]); 18234 return; 18235 } 18236 } 18237 pw.println(checkPermission(perm, pkg, user)); 18238 return; 18239 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18240 dumpState.setDump(DumpState.DUMP_LIBS); 18241 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18242 dumpState.setDump(DumpState.DUMP_FEATURES); 18243 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18244 if (opti >= args.length) { 18245 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18246 | DumpState.DUMP_SERVICE_RESOLVERS 18247 | DumpState.DUMP_RECEIVER_RESOLVERS 18248 | DumpState.DUMP_CONTENT_RESOLVERS); 18249 } else { 18250 while (opti < args.length) { 18251 String name = args[opti]; 18252 if ("a".equals(name) || "activity".equals(name)) { 18253 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18254 } else if ("s".equals(name) || "service".equals(name)) { 18255 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18256 } else if ("r".equals(name) || "receiver".equals(name)) { 18257 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18258 } else if ("c".equals(name) || "content".equals(name)) { 18259 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18260 } else { 18261 pw.println("Error: unknown resolver table type: " + name); 18262 return; 18263 } 18264 opti++; 18265 } 18266 } 18267 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18268 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18269 } else if ("permission".equals(cmd)) { 18270 if (opti >= args.length) { 18271 pw.println("Error: permission requires permission name"); 18272 return; 18273 } 18274 permissionNames = new ArraySet<>(); 18275 while (opti < args.length) { 18276 permissionNames.add(args[opti]); 18277 opti++; 18278 } 18279 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18280 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18281 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18282 dumpState.setDump(DumpState.DUMP_PREFERRED); 18283 } else if ("preferred-xml".equals(cmd)) { 18284 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18285 if (opti < args.length && "--full".equals(args[opti])) { 18286 fullPreferred = true; 18287 opti++; 18288 } 18289 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18290 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18291 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18292 dumpState.setDump(DumpState.DUMP_PACKAGES); 18293 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18294 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18295 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18296 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18297 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18298 dumpState.setDump(DumpState.DUMP_MESSAGES); 18299 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18300 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18301 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18302 || "intent-filter-verifiers".equals(cmd)) { 18303 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18304 } else if ("version".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_VERSION); 18306 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_KEYSETS); 18308 } else if ("installs".equals(cmd)) { 18309 dumpState.setDump(DumpState.DUMP_INSTALLS); 18310 } else if ("frozen".equals(cmd)) { 18311 dumpState.setDump(DumpState.DUMP_FROZEN); 18312 } else if ("dexopt".equals(cmd)) { 18313 dumpState.setDump(DumpState.DUMP_DEXOPT); 18314 } else if ("compiler-stats".equals(cmd)) { 18315 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18316 } else if ("write".equals(cmd)) { 18317 synchronized (mPackages) { 18318 mSettings.writeLPr(); 18319 pw.println("Settings written."); 18320 return; 18321 } 18322 } 18323 } 18324 18325 if (checkin) { 18326 pw.println("vers,1"); 18327 } 18328 18329 // reader 18330 synchronized (mPackages) { 18331 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18332 if (!checkin) { 18333 if (dumpState.onTitlePrinted()) 18334 pw.println(); 18335 pw.println("Database versions:"); 18336 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18337 } 18338 } 18339 18340 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18341 if (!checkin) { 18342 if (dumpState.onTitlePrinted()) 18343 pw.println(); 18344 pw.println("Verifiers:"); 18345 pw.print(" Required: "); 18346 pw.print(mRequiredVerifierPackage); 18347 pw.print(" (uid="); 18348 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18349 UserHandle.USER_SYSTEM)); 18350 pw.println(")"); 18351 } else if (mRequiredVerifierPackage != null) { 18352 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18353 pw.print(","); 18354 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18355 UserHandle.USER_SYSTEM)); 18356 } 18357 } 18358 18359 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18360 packageName == null) { 18361 if (mIntentFilterVerifierComponent != null) { 18362 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18363 if (!checkin) { 18364 if (dumpState.onTitlePrinted()) 18365 pw.println(); 18366 pw.println("Intent Filter Verifier:"); 18367 pw.print(" Using: "); 18368 pw.print(verifierPackageName); 18369 pw.print(" (uid="); 18370 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18371 UserHandle.USER_SYSTEM)); 18372 pw.println(")"); 18373 } else if (verifierPackageName != null) { 18374 pw.print("ifv,"); pw.print(verifierPackageName); 18375 pw.print(","); 18376 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18377 UserHandle.USER_SYSTEM)); 18378 } 18379 } else { 18380 pw.println(); 18381 pw.println("No Intent Filter Verifier available!"); 18382 } 18383 } 18384 18385 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18386 boolean printedHeader = false; 18387 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18388 while (it.hasNext()) { 18389 String name = it.next(); 18390 SharedLibraryEntry ent = mSharedLibraries.get(name); 18391 if (!checkin) { 18392 if (!printedHeader) { 18393 if (dumpState.onTitlePrinted()) 18394 pw.println(); 18395 pw.println("Libraries:"); 18396 printedHeader = true; 18397 } 18398 pw.print(" "); 18399 } else { 18400 pw.print("lib,"); 18401 } 18402 pw.print(name); 18403 if (!checkin) { 18404 pw.print(" -> "); 18405 } 18406 if (ent.path != null) { 18407 if (!checkin) { 18408 pw.print("(jar) "); 18409 pw.print(ent.path); 18410 } else { 18411 pw.print(",jar,"); 18412 pw.print(ent.path); 18413 } 18414 } else { 18415 if (!checkin) { 18416 pw.print("(apk) "); 18417 pw.print(ent.apk); 18418 } else { 18419 pw.print(",apk,"); 18420 pw.print(ent.apk); 18421 } 18422 } 18423 pw.println(); 18424 } 18425 } 18426 18427 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18428 if (dumpState.onTitlePrinted()) 18429 pw.println(); 18430 if (!checkin) { 18431 pw.println("Features:"); 18432 } 18433 18434 for (FeatureInfo feat : mAvailableFeatures.values()) { 18435 if (checkin) { 18436 pw.print("feat,"); 18437 pw.print(feat.name); 18438 pw.print(","); 18439 pw.println(feat.version); 18440 } else { 18441 pw.print(" "); 18442 pw.print(feat.name); 18443 if (feat.version > 0) { 18444 pw.print(" version="); 18445 pw.print(feat.version); 18446 } 18447 pw.println(); 18448 } 18449 } 18450 } 18451 18452 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18453 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18454 : "Activity Resolver Table:", " ", packageName, 18455 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18456 dumpState.setTitlePrinted(true); 18457 } 18458 } 18459 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18460 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18461 : "Receiver Resolver Table:", " ", packageName, 18462 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18463 dumpState.setTitlePrinted(true); 18464 } 18465 } 18466 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18467 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18468 : "Service Resolver Table:", " ", packageName, 18469 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18470 dumpState.setTitlePrinted(true); 18471 } 18472 } 18473 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18474 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18475 : "Provider Resolver Table:", " ", packageName, 18476 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18477 dumpState.setTitlePrinted(true); 18478 } 18479 } 18480 18481 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18482 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18483 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18484 int user = mSettings.mPreferredActivities.keyAt(i); 18485 if (pir.dump(pw, 18486 dumpState.getTitlePrinted() 18487 ? "\nPreferred Activities User " + user + ":" 18488 : "Preferred Activities User " + user + ":", " ", 18489 packageName, true, false)) { 18490 dumpState.setTitlePrinted(true); 18491 } 18492 } 18493 } 18494 18495 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18496 pw.flush(); 18497 FileOutputStream fout = new FileOutputStream(fd); 18498 BufferedOutputStream str = new BufferedOutputStream(fout); 18499 XmlSerializer serializer = new FastXmlSerializer(); 18500 try { 18501 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18502 serializer.startDocument(null, true); 18503 serializer.setFeature( 18504 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18505 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18506 serializer.endDocument(); 18507 serializer.flush(); 18508 } catch (IllegalArgumentException e) { 18509 pw.println("Failed writing: " + e); 18510 } catch (IllegalStateException e) { 18511 pw.println("Failed writing: " + e); 18512 } catch (IOException e) { 18513 pw.println("Failed writing: " + e); 18514 } 18515 } 18516 18517 if (!checkin 18518 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18519 && packageName == null) { 18520 pw.println(); 18521 int count = mSettings.mPackages.size(); 18522 if (count == 0) { 18523 pw.println("No applications!"); 18524 pw.println(); 18525 } else { 18526 final String prefix = " "; 18527 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18528 if (allPackageSettings.size() == 0) { 18529 pw.println("No domain preferred apps!"); 18530 pw.println(); 18531 } else { 18532 pw.println("App verification status:"); 18533 pw.println(); 18534 count = 0; 18535 for (PackageSetting ps : allPackageSettings) { 18536 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18537 if (ivi == null || ivi.getPackageName() == null) continue; 18538 pw.println(prefix + "Package: " + ivi.getPackageName()); 18539 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18540 pw.println(prefix + "Status: " + ivi.getStatusString()); 18541 pw.println(); 18542 count++; 18543 } 18544 if (count == 0) { 18545 pw.println(prefix + "No app verification established."); 18546 pw.println(); 18547 } 18548 for (int userId : sUserManager.getUserIds()) { 18549 pw.println("App linkages for user " + userId + ":"); 18550 pw.println(); 18551 count = 0; 18552 for (PackageSetting ps : allPackageSettings) { 18553 final long status = ps.getDomainVerificationStatusForUser(userId); 18554 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18555 continue; 18556 } 18557 pw.println(prefix + "Package: " + ps.name); 18558 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18559 String statusStr = IntentFilterVerificationInfo. 18560 getStatusStringFromValue(status); 18561 pw.println(prefix + "Status: " + statusStr); 18562 pw.println(); 18563 count++; 18564 } 18565 if (count == 0) { 18566 pw.println(prefix + "No configured app linkages."); 18567 pw.println(); 18568 } 18569 } 18570 } 18571 } 18572 } 18573 18574 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18575 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18576 if (packageName == null && permissionNames == null) { 18577 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18578 if (iperm == 0) { 18579 if (dumpState.onTitlePrinted()) 18580 pw.println(); 18581 pw.println("AppOp Permissions:"); 18582 } 18583 pw.print(" AppOp Permission "); 18584 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18585 pw.println(":"); 18586 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18587 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18588 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18589 } 18590 } 18591 } 18592 } 18593 18594 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18595 boolean printedSomething = false; 18596 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18597 if (packageName != null && !packageName.equals(p.info.packageName)) { 18598 continue; 18599 } 18600 if (!printedSomething) { 18601 if (dumpState.onTitlePrinted()) 18602 pw.println(); 18603 pw.println("Registered ContentProviders:"); 18604 printedSomething = true; 18605 } 18606 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18607 pw.print(" "); pw.println(p.toString()); 18608 } 18609 printedSomething = false; 18610 for (Map.Entry<String, PackageParser.Provider> entry : 18611 mProvidersByAuthority.entrySet()) { 18612 PackageParser.Provider p = entry.getValue(); 18613 if (packageName != null && !packageName.equals(p.info.packageName)) { 18614 continue; 18615 } 18616 if (!printedSomething) { 18617 if (dumpState.onTitlePrinted()) 18618 pw.println(); 18619 pw.println("ContentProvider Authorities:"); 18620 printedSomething = true; 18621 } 18622 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18623 pw.print(" "); pw.println(p.toString()); 18624 if (p.info != null && p.info.applicationInfo != null) { 18625 final String appInfo = p.info.applicationInfo.toString(); 18626 pw.print(" applicationInfo="); pw.println(appInfo); 18627 } 18628 } 18629 } 18630 18631 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18632 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18633 } 18634 18635 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18636 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18637 } 18638 18639 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18640 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18641 } 18642 18643 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18644 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18645 } 18646 18647 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18648 // XXX should handle packageName != null by dumping only install data that 18649 // the given package is involved with. 18650 if (dumpState.onTitlePrinted()) pw.println(); 18651 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18652 } 18653 18654 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18655 // XXX should handle packageName != null by dumping only install data that 18656 // the given package is involved with. 18657 if (dumpState.onTitlePrinted()) pw.println(); 18658 18659 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18660 ipw.println(); 18661 ipw.println("Frozen packages:"); 18662 ipw.increaseIndent(); 18663 if (mFrozenPackages.size() == 0) { 18664 ipw.println("(none)"); 18665 } else { 18666 for (int i = 0; i < mFrozenPackages.size(); i++) { 18667 ipw.println(mFrozenPackages.valueAt(i)); 18668 } 18669 } 18670 ipw.decreaseIndent(); 18671 } 18672 18673 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18674 if (dumpState.onTitlePrinted()) pw.println(); 18675 dumpDexoptStateLPr(pw, packageName); 18676 } 18677 18678 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18679 if (dumpState.onTitlePrinted()) pw.println(); 18680 dumpCompilerStatsLPr(pw, packageName); 18681 } 18682 18683 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18684 if (dumpState.onTitlePrinted()) pw.println(); 18685 mSettings.dumpReadMessagesLPr(pw, dumpState); 18686 18687 pw.println(); 18688 pw.println("Package warning messages:"); 18689 BufferedReader in = null; 18690 String line = null; 18691 try { 18692 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18693 while ((line = in.readLine()) != null) { 18694 if (line.contains("ignored: updated version")) continue; 18695 pw.println(line); 18696 } 18697 } catch (IOException ignored) { 18698 } finally { 18699 IoUtils.closeQuietly(in); 18700 } 18701 } 18702 18703 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18704 BufferedReader in = null; 18705 String line = null; 18706 try { 18707 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18708 while ((line = in.readLine()) != null) { 18709 if (line.contains("ignored: updated version")) continue; 18710 pw.print("msg,"); 18711 pw.println(line); 18712 } 18713 } catch (IOException ignored) { 18714 } finally { 18715 IoUtils.closeQuietly(in); 18716 } 18717 } 18718 } 18719 } 18720 18721 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18722 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18723 ipw.println(); 18724 ipw.println("Dexopt state:"); 18725 ipw.increaseIndent(); 18726 Collection<PackageParser.Package> packages = null; 18727 if (packageName != null) { 18728 PackageParser.Package targetPackage = mPackages.get(packageName); 18729 if (targetPackage != null) { 18730 packages = Collections.singletonList(targetPackage); 18731 } else { 18732 ipw.println("Unable to find package: " + packageName); 18733 return; 18734 } 18735 } else { 18736 packages = mPackages.values(); 18737 } 18738 18739 for (PackageParser.Package pkg : packages) { 18740 ipw.println("[" + pkg.packageName + "]"); 18741 ipw.increaseIndent(); 18742 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18743 ipw.decreaseIndent(); 18744 } 18745 } 18746 18747 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18748 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18749 ipw.println(); 18750 ipw.println("Compiler stats:"); 18751 ipw.increaseIndent(); 18752 Collection<PackageParser.Package> packages = null; 18753 if (packageName != null) { 18754 PackageParser.Package targetPackage = mPackages.get(packageName); 18755 if (targetPackage != null) { 18756 packages = Collections.singletonList(targetPackage); 18757 } else { 18758 ipw.println("Unable to find package: " + packageName); 18759 return; 18760 } 18761 } else { 18762 packages = mPackages.values(); 18763 } 18764 18765 for (PackageParser.Package pkg : packages) { 18766 ipw.println("[" + pkg.packageName + "]"); 18767 ipw.increaseIndent(); 18768 18769 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18770 if (stats == null) { 18771 ipw.println("(No recorded stats)"); 18772 } else { 18773 stats.dump(ipw); 18774 } 18775 ipw.decreaseIndent(); 18776 } 18777 } 18778 18779 private String dumpDomainString(String packageName) { 18780 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18781 .getList(); 18782 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18783 18784 ArraySet<String> result = new ArraySet<>(); 18785 if (iviList.size() > 0) { 18786 for (IntentFilterVerificationInfo ivi : iviList) { 18787 for (String host : ivi.getDomains()) { 18788 result.add(host); 18789 } 18790 } 18791 } 18792 if (filters != null && filters.size() > 0) { 18793 for (IntentFilter filter : filters) { 18794 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18795 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18796 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18797 result.addAll(filter.getHostsList()); 18798 } 18799 } 18800 } 18801 18802 StringBuilder sb = new StringBuilder(result.size() * 16); 18803 for (String domain : result) { 18804 if (sb.length() > 0) sb.append(" "); 18805 sb.append(domain); 18806 } 18807 return sb.toString(); 18808 } 18809 18810 // ------- apps on sdcard specific code ------- 18811 static final boolean DEBUG_SD_INSTALL = false; 18812 18813 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18814 18815 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18816 18817 private boolean mMediaMounted = false; 18818 18819 static String getEncryptKey() { 18820 try { 18821 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18822 SD_ENCRYPTION_KEYSTORE_NAME); 18823 if (sdEncKey == null) { 18824 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18825 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18826 if (sdEncKey == null) { 18827 Slog.e(TAG, "Failed to create encryption keys"); 18828 return null; 18829 } 18830 } 18831 return sdEncKey; 18832 } catch (NoSuchAlgorithmException nsae) { 18833 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18834 return null; 18835 } catch (IOException ioe) { 18836 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18837 return null; 18838 } 18839 } 18840 18841 /* 18842 * Update media status on PackageManager. 18843 */ 18844 @Override 18845 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18846 int callingUid = Binder.getCallingUid(); 18847 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18848 throw new SecurityException("Media status can only be updated by the system"); 18849 } 18850 // reader; this apparently protects mMediaMounted, but should probably 18851 // be a different lock in that case. 18852 synchronized (mPackages) { 18853 Log.i(TAG, "Updating external media status from " 18854 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18855 + (mediaStatus ? "mounted" : "unmounted")); 18856 if (DEBUG_SD_INSTALL) 18857 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18858 + ", mMediaMounted=" + mMediaMounted); 18859 if (mediaStatus == mMediaMounted) { 18860 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18861 : 0, -1); 18862 mHandler.sendMessage(msg); 18863 return; 18864 } 18865 mMediaMounted = mediaStatus; 18866 } 18867 // Queue up an async operation since the package installation may take a 18868 // little while. 18869 mHandler.post(new Runnable() { 18870 public void run() { 18871 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18872 } 18873 }); 18874 } 18875 18876 /** 18877 * Called by MountService when the initial ASECs to scan are available. 18878 * Should block until all the ASEC containers are finished being scanned. 18879 */ 18880 public void scanAvailableAsecs() { 18881 updateExternalMediaStatusInner(true, false, false); 18882 } 18883 18884 /* 18885 * Collect information of applications on external media, map them against 18886 * existing containers and update information based on current mount status. 18887 * Please note that we always have to report status if reportStatus has been 18888 * set to true especially when unloading packages. 18889 */ 18890 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18891 boolean externalStorage) { 18892 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18893 int[] uidArr = EmptyArray.INT; 18894 18895 final String[] list = PackageHelper.getSecureContainerList(); 18896 if (ArrayUtils.isEmpty(list)) { 18897 Log.i(TAG, "No secure containers found"); 18898 } else { 18899 // Process list of secure containers and categorize them 18900 // as active or stale based on their package internal state. 18901 18902 // reader 18903 synchronized (mPackages) { 18904 for (String cid : list) { 18905 // Leave stages untouched for now; installer service owns them 18906 if (PackageInstallerService.isStageName(cid)) continue; 18907 18908 if (DEBUG_SD_INSTALL) 18909 Log.i(TAG, "Processing container " + cid); 18910 String pkgName = getAsecPackageName(cid); 18911 if (pkgName == null) { 18912 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18913 continue; 18914 } 18915 if (DEBUG_SD_INSTALL) 18916 Log.i(TAG, "Looking for pkg : " + pkgName); 18917 18918 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18919 if (ps == null) { 18920 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18921 continue; 18922 } 18923 18924 /* 18925 * Skip packages that are not external if we're unmounting 18926 * external storage. 18927 */ 18928 if (externalStorage && !isMounted && !isExternal(ps)) { 18929 continue; 18930 } 18931 18932 final AsecInstallArgs args = new AsecInstallArgs(cid, 18933 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18934 // The package status is changed only if the code path 18935 // matches between settings and the container id. 18936 if (ps.codePathString != null 18937 && ps.codePathString.startsWith(args.getCodePath())) { 18938 if (DEBUG_SD_INSTALL) { 18939 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18940 + " at code path: " + ps.codePathString); 18941 } 18942 18943 // We do have a valid package installed on sdcard 18944 processCids.put(args, ps.codePathString); 18945 final int uid = ps.appId; 18946 if (uid != -1) { 18947 uidArr = ArrayUtils.appendInt(uidArr, uid); 18948 } 18949 } else { 18950 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18951 + ps.codePathString); 18952 } 18953 } 18954 } 18955 18956 Arrays.sort(uidArr); 18957 } 18958 18959 // Process packages with valid entries. 18960 if (isMounted) { 18961 if (DEBUG_SD_INSTALL) 18962 Log.i(TAG, "Loading packages"); 18963 loadMediaPackages(processCids, uidArr, externalStorage); 18964 startCleaningPackages(); 18965 mInstallerService.onSecureContainersAvailable(); 18966 } else { 18967 if (DEBUG_SD_INSTALL) 18968 Log.i(TAG, "Unloading packages"); 18969 unloadMediaPackages(processCids, uidArr, reportStatus); 18970 } 18971 } 18972 18973 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18974 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18975 final int size = infos.size(); 18976 final String[] packageNames = new String[size]; 18977 final int[] packageUids = new int[size]; 18978 for (int i = 0; i < size; i++) { 18979 final ApplicationInfo info = infos.get(i); 18980 packageNames[i] = info.packageName; 18981 packageUids[i] = info.uid; 18982 } 18983 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18984 finishedReceiver); 18985 } 18986 18987 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18988 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18989 sendResourcesChangedBroadcast(mediaStatus, replacing, 18990 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18991 } 18992 18993 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18994 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18995 int size = pkgList.length; 18996 if (size > 0) { 18997 // Send broadcasts here 18998 Bundle extras = new Bundle(); 18999 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19000 if (uidArr != null) { 19001 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19002 } 19003 if (replacing) { 19004 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19005 } 19006 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19007 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19008 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19009 } 19010 } 19011 19012 /* 19013 * Look at potentially valid container ids from processCids If package 19014 * information doesn't match the one on record or package scanning fails, 19015 * the cid is added to list of removeCids. We currently don't delete stale 19016 * containers. 19017 */ 19018 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19019 boolean externalStorage) { 19020 ArrayList<String> pkgList = new ArrayList<String>(); 19021 Set<AsecInstallArgs> keys = processCids.keySet(); 19022 19023 for (AsecInstallArgs args : keys) { 19024 String codePath = processCids.get(args); 19025 if (DEBUG_SD_INSTALL) 19026 Log.i(TAG, "Loading container : " + args.cid); 19027 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19028 try { 19029 // Make sure there are no container errors first. 19030 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19031 Slog.e(TAG, "Failed to mount cid : " + args.cid 19032 + " when installing from sdcard"); 19033 continue; 19034 } 19035 // Check code path here. 19036 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19037 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19038 + " does not match one in settings " + codePath); 19039 continue; 19040 } 19041 // Parse package 19042 int parseFlags = mDefParseFlags; 19043 if (args.isExternalAsec()) { 19044 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19045 } 19046 if (args.isFwdLocked()) { 19047 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19048 } 19049 19050 synchronized (mInstallLock) { 19051 PackageParser.Package pkg = null; 19052 try { 19053 // Sadly we don't know the package name yet to freeze it 19054 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19055 SCAN_IGNORE_FROZEN, 0, null); 19056 } catch (PackageManagerException e) { 19057 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19058 } 19059 // Scan the package 19060 if (pkg != null) { 19061 /* 19062 * TODO why is the lock being held? doPostInstall is 19063 * called in other places without the lock. This needs 19064 * to be straightened out. 19065 */ 19066 // writer 19067 synchronized (mPackages) { 19068 retCode = PackageManager.INSTALL_SUCCEEDED; 19069 pkgList.add(pkg.packageName); 19070 // Post process args 19071 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19072 pkg.applicationInfo.uid); 19073 } 19074 } else { 19075 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19076 } 19077 } 19078 19079 } finally { 19080 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19081 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19082 } 19083 } 19084 } 19085 // writer 19086 synchronized (mPackages) { 19087 // If the platform SDK has changed since the last time we booted, 19088 // we need to re-grant app permission to catch any new ones that 19089 // appear. This is really a hack, and means that apps can in some 19090 // cases get permissions that the user didn't initially explicitly 19091 // allow... it would be nice to have some better way to handle 19092 // this situation. 19093 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19094 : mSettings.getInternalVersion(); 19095 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19096 : StorageManager.UUID_PRIVATE_INTERNAL; 19097 19098 int updateFlags = UPDATE_PERMISSIONS_ALL; 19099 if (ver.sdkVersion != mSdkVersion) { 19100 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19101 + mSdkVersion + "; regranting permissions for external"); 19102 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19103 } 19104 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19105 19106 // Yay, everything is now upgraded 19107 ver.forceCurrent(); 19108 19109 // can downgrade to reader 19110 // Persist settings 19111 mSettings.writeLPr(); 19112 } 19113 // Send a broadcast to let everyone know we are done processing 19114 if (pkgList.size() > 0) { 19115 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19116 } 19117 } 19118 19119 /* 19120 * Utility method to unload a list of specified containers 19121 */ 19122 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19123 // Just unmount all valid containers. 19124 for (AsecInstallArgs arg : cidArgs) { 19125 synchronized (mInstallLock) { 19126 arg.doPostDeleteLI(false); 19127 } 19128 } 19129 } 19130 19131 /* 19132 * Unload packages mounted on external media. This involves deleting package 19133 * data from internal structures, sending broadcasts about disabled packages, 19134 * gc'ing to free up references, unmounting all secure containers 19135 * corresponding to packages on external media, and posting a 19136 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19137 * that we always have to post this message if status has been requested no 19138 * matter what. 19139 */ 19140 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19141 final boolean reportStatus) { 19142 if (DEBUG_SD_INSTALL) 19143 Log.i(TAG, "unloading media packages"); 19144 ArrayList<String> pkgList = new ArrayList<String>(); 19145 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19146 final Set<AsecInstallArgs> keys = processCids.keySet(); 19147 for (AsecInstallArgs args : keys) { 19148 String pkgName = args.getPackageName(); 19149 if (DEBUG_SD_INSTALL) 19150 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19151 // Delete package internally 19152 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19153 synchronized (mInstallLock) { 19154 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19155 final boolean res; 19156 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19157 "unloadMediaPackages")) { 19158 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19159 null); 19160 } 19161 if (res) { 19162 pkgList.add(pkgName); 19163 } else { 19164 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19165 failedList.add(args); 19166 } 19167 } 19168 } 19169 19170 // reader 19171 synchronized (mPackages) { 19172 // We didn't update the settings after removing each package; 19173 // write them now for all packages. 19174 mSettings.writeLPr(); 19175 } 19176 19177 // We have to absolutely send UPDATED_MEDIA_STATUS only 19178 // after confirming that all the receivers processed the ordered 19179 // broadcast when packages get disabled, force a gc to clean things up. 19180 // and unload all the containers. 19181 if (pkgList.size() > 0) { 19182 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19183 new IIntentReceiver.Stub() { 19184 public void performReceive(Intent intent, int resultCode, String data, 19185 Bundle extras, boolean ordered, boolean sticky, 19186 int sendingUser) throws RemoteException { 19187 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19188 reportStatus ? 1 : 0, 1, keys); 19189 mHandler.sendMessage(msg); 19190 } 19191 }); 19192 } else { 19193 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19194 keys); 19195 mHandler.sendMessage(msg); 19196 } 19197 } 19198 19199 private void loadPrivatePackages(final VolumeInfo vol) { 19200 mHandler.post(new Runnable() { 19201 @Override 19202 public void run() { 19203 loadPrivatePackagesInner(vol); 19204 } 19205 }); 19206 } 19207 19208 private void loadPrivatePackagesInner(VolumeInfo vol) { 19209 final String volumeUuid = vol.fsUuid; 19210 if (TextUtils.isEmpty(volumeUuid)) { 19211 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19212 return; 19213 } 19214 19215 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19216 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19217 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19218 19219 final VersionInfo ver; 19220 final List<PackageSetting> packages; 19221 synchronized (mPackages) { 19222 ver = mSettings.findOrCreateVersion(volumeUuid); 19223 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19224 } 19225 19226 for (PackageSetting ps : packages) { 19227 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19228 synchronized (mInstallLock) { 19229 final PackageParser.Package pkg; 19230 try { 19231 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19232 loaded.add(pkg.applicationInfo); 19233 19234 } catch (PackageManagerException e) { 19235 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19236 } 19237 19238 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19239 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19240 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19241 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19242 } 19243 } 19244 } 19245 19246 // Reconcile app data for all started/unlocked users 19247 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19248 final UserManager um = mContext.getSystemService(UserManager.class); 19249 UserManagerInternal umInternal = getUserManagerInternal(); 19250 for (UserInfo user : um.getUsers()) { 19251 final int flags; 19252 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19253 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19254 } else if (umInternal.isUserRunning(user.id)) { 19255 flags = StorageManager.FLAG_STORAGE_DE; 19256 } else { 19257 continue; 19258 } 19259 19260 try { 19261 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19262 synchronized (mInstallLock) { 19263 reconcileAppsDataLI(volumeUuid, user.id, flags); 19264 } 19265 } catch (IllegalStateException e) { 19266 // Device was probably ejected, and we'll process that event momentarily 19267 Slog.w(TAG, "Failed to prepare storage: " + e); 19268 } 19269 } 19270 19271 synchronized (mPackages) { 19272 int updateFlags = UPDATE_PERMISSIONS_ALL; 19273 if (ver.sdkVersion != mSdkVersion) { 19274 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19275 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19276 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19277 } 19278 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19279 19280 // Yay, everything is now upgraded 19281 ver.forceCurrent(); 19282 19283 mSettings.writeLPr(); 19284 } 19285 19286 for (PackageFreezer freezer : freezers) { 19287 freezer.close(); 19288 } 19289 19290 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19291 sendResourcesChangedBroadcast(true, false, loaded, null); 19292 } 19293 19294 private void unloadPrivatePackages(final VolumeInfo vol) { 19295 mHandler.post(new Runnable() { 19296 @Override 19297 public void run() { 19298 unloadPrivatePackagesInner(vol); 19299 } 19300 }); 19301 } 19302 19303 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19304 final String volumeUuid = vol.fsUuid; 19305 if (TextUtils.isEmpty(volumeUuid)) { 19306 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19307 return; 19308 } 19309 19310 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19311 synchronized (mInstallLock) { 19312 synchronized (mPackages) { 19313 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19314 for (PackageSetting ps : packages) { 19315 if (ps.pkg == null) continue; 19316 19317 final ApplicationInfo info = ps.pkg.applicationInfo; 19318 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19319 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19320 19321 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19322 "unloadPrivatePackagesInner")) { 19323 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19324 false, null)) { 19325 unloaded.add(info); 19326 } else { 19327 Slog.w(TAG, "Failed to unload " + ps.codePath); 19328 } 19329 } 19330 19331 // Try very hard to release any references to this package 19332 // so we don't risk the system server being killed due to 19333 // open FDs 19334 AttributeCache.instance().removePackage(ps.name); 19335 } 19336 19337 mSettings.writeLPr(); 19338 } 19339 } 19340 19341 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19342 sendResourcesChangedBroadcast(false, false, unloaded, null); 19343 19344 // Try very hard to release any references to this path so we don't risk 19345 // the system server being killed due to open FDs 19346 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19347 19348 for (int i = 0; i < 3; i++) { 19349 System.gc(); 19350 System.runFinalization(); 19351 } 19352 } 19353 19354 /** 19355 * Prepare storage areas for given user on all mounted devices. 19356 */ 19357 void prepareUserData(int userId, int userSerial, int flags) { 19358 synchronized (mInstallLock) { 19359 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19360 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19361 final String volumeUuid = vol.getFsUuid(); 19362 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19363 } 19364 } 19365 } 19366 19367 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19368 boolean allowRecover) { 19369 // Prepare storage and verify that serial numbers are consistent; if 19370 // there's a mismatch we need to destroy to avoid leaking data 19371 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19372 try { 19373 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19374 19375 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19376 UserManagerService.enforceSerialNumber( 19377 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19378 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19379 UserManagerService.enforceSerialNumber( 19380 Environment.getDataSystemDeDirectory(userId), userSerial); 19381 } 19382 } 19383 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19384 UserManagerService.enforceSerialNumber( 19385 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19386 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19387 UserManagerService.enforceSerialNumber( 19388 Environment.getDataSystemCeDirectory(userId), userSerial); 19389 } 19390 } 19391 19392 synchronized (mInstallLock) { 19393 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19394 } 19395 } catch (Exception e) { 19396 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19397 + " because we failed to prepare: " + e); 19398 destroyUserDataLI(volumeUuid, userId, 19399 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19400 19401 if (allowRecover) { 19402 // Try one last time; if we fail again we're really in trouble 19403 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19404 } 19405 } 19406 } 19407 19408 /** 19409 * Destroy storage areas for given user on all mounted devices. 19410 */ 19411 void destroyUserData(int userId, int flags) { 19412 synchronized (mInstallLock) { 19413 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19414 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19415 final String volumeUuid = vol.getFsUuid(); 19416 destroyUserDataLI(volumeUuid, userId, flags); 19417 } 19418 } 19419 } 19420 19421 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19422 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19423 try { 19424 // Clean up app data, profile data, and media data 19425 mInstaller.destroyUserData(volumeUuid, userId, flags); 19426 19427 // Clean up system data 19428 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19429 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19430 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19431 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19432 } 19433 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19434 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19435 } 19436 } 19437 19438 // Data with special labels is now gone, so finish the job 19439 storage.destroyUserStorage(volumeUuid, userId, flags); 19440 19441 } catch (Exception e) { 19442 logCriticalInfo(Log.WARN, 19443 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19444 } 19445 } 19446 19447 /** 19448 * Examine all users present on given mounted volume, and destroy data 19449 * belonging to users that are no longer valid, or whose user ID has been 19450 * recycled. 19451 */ 19452 private void reconcileUsers(String volumeUuid) { 19453 final List<File> files = new ArrayList<>(); 19454 Collections.addAll(files, FileUtils 19455 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19456 Collections.addAll(files, FileUtils 19457 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19458 Collections.addAll(files, FileUtils 19459 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19460 Collections.addAll(files, FileUtils 19461 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19462 for (File file : files) { 19463 if (!file.isDirectory()) continue; 19464 19465 final int userId; 19466 final UserInfo info; 19467 try { 19468 userId = Integer.parseInt(file.getName()); 19469 info = sUserManager.getUserInfo(userId); 19470 } catch (NumberFormatException e) { 19471 Slog.w(TAG, "Invalid user directory " + file); 19472 continue; 19473 } 19474 19475 boolean destroyUser = false; 19476 if (info == null) { 19477 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19478 + " because no matching user was found"); 19479 destroyUser = true; 19480 } else if (!mOnlyCore) { 19481 try { 19482 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19483 } catch (IOException e) { 19484 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19485 + " because we failed to enforce serial number: " + e); 19486 destroyUser = true; 19487 } 19488 } 19489 19490 if (destroyUser) { 19491 synchronized (mInstallLock) { 19492 destroyUserDataLI(volumeUuid, userId, 19493 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19494 } 19495 } 19496 } 19497 } 19498 19499 private void assertPackageKnown(String volumeUuid, String packageName) 19500 throws PackageManagerException { 19501 synchronized (mPackages) { 19502 final PackageSetting ps = mSettings.mPackages.get(packageName); 19503 if (ps == null) { 19504 throw new PackageManagerException("Package " + packageName + " is unknown"); 19505 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19506 throw new PackageManagerException( 19507 "Package " + packageName + " found on unknown volume " + volumeUuid 19508 + "; expected volume " + ps.volumeUuid); 19509 } 19510 } 19511 } 19512 19513 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19514 throws PackageManagerException { 19515 synchronized (mPackages) { 19516 final PackageSetting ps = mSettings.mPackages.get(packageName); 19517 if (ps == null) { 19518 throw new PackageManagerException("Package " + packageName + " is unknown"); 19519 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19520 throw new PackageManagerException( 19521 "Package " + packageName + " found on unknown volume " + volumeUuid 19522 + "; expected volume " + ps.volumeUuid); 19523 } else if (!ps.getInstalled(userId)) { 19524 throw new PackageManagerException( 19525 "Package " + packageName + " not installed for user " + userId); 19526 } 19527 } 19528 } 19529 19530 /** 19531 * Examine all apps present on given mounted volume, and destroy apps that 19532 * aren't expected, either due to uninstallation or reinstallation on 19533 * another volume. 19534 */ 19535 private void reconcileApps(String volumeUuid) { 19536 final File[] files = FileUtils 19537 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19538 for (File file : files) { 19539 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19540 && !PackageInstallerService.isStageName(file.getName()); 19541 if (!isPackage) { 19542 // Ignore entries which are not packages 19543 continue; 19544 } 19545 19546 try { 19547 final PackageLite pkg = PackageParser.parsePackageLite(file, 19548 PackageParser.PARSE_MUST_BE_APK); 19549 assertPackageKnown(volumeUuid, pkg.packageName); 19550 19551 } catch (PackageParserException | PackageManagerException e) { 19552 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19553 synchronized (mInstallLock) { 19554 removeCodePathLI(file); 19555 } 19556 } 19557 } 19558 } 19559 19560 /** 19561 * Reconcile all app data for the given user. 19562 * <p> 19563 * Verifies that directories exist and that ownership and labeling is 19564 * correct for all installed apps on all mounted volumes. 19565 */ 19566 void reconcileAppsData(int userId, int flags) { 19567 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19568 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19569 final String volumeUuid = vol.getFsUuid(); 19570 synchronized (mInstallLock) { 19571 reconcileAppsDataLI(volumeUuid, userId, flags); 19572 } 19573 } 19574 } 19575 19576 /** 19577 * Reconcile all app data on given mounted volume. 19578 * <p> 19579 * Destroys app data that isn't expected, either due to uninstallation or 19580 * reinstallation on another volume. 19581 * <p> 19582 * Verifies that directories exist and that ownership and labeling is 19583 * correct for all installed apps. 19584 */ 19585 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19586 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19587 + Integer.toHexString(flags)); 19588 19589 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19590 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19591 19592 boolean restoreconNeeded = false; 19593 19594 // First look for stale data that doesn't belong, and check if things 19595 // have changed since we did our last restorecon 19596 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19597 if (StorageManager.isFileEncryptedNativeOrEmulated() 19598 && !StorageManager.isUserKeyUnlocked(userId)) { 19599 throw new RuntimeException( 19600 "Yikes, someone asked us to reconcile CE storage while " + userId 19601 + " was still locked; this would have caused massive data loss!"); 19602 } 19603 19604 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19605 19606 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19607 for (File file : files) { 19608 final String packageName = file.getName(); 19609 try { 19610 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19611 } catch (PackageManagerException e) { 19612 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19613 try { 19614 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19615 StorageManager.FLAG_STORAGE_CE, 0); 19616 } catch (InstallerException e2) { 19617 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19618 } 19619 } 19620 } 19621 } 19622 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19623 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19624 19625 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19626 for (File file : files) { 19627 final String packageName = file.getName(); 19628 try { 19629 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19630 } catch (PackageManagerException e) { 19631 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19632 try { 19633 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19634 StorageManager.FLAG_STORAGE_DE, 0); 19635 } catch (InstallerException e2) { 19636 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19637 } 19638 } 19639 } 19640 } 19641 19642 // Ensure that data directories are ready to roll for all packages 19643 // installed for this volume and user 19644 final List<PackageSetting> packages; 19645 synchronized (mPackages) { 19646 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19647 } 19648 int preparedCount = 0; 19649 for (PackageSetting ps : packages) { 19650 final String packageName = ps.name; 19651 if (ps.pkg == null) { 19652 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19653 // TODO: might be due to legacy ASEC apps; we should circle back 19654 // and reconcile again once they're scanned 19655 continue; 19656 } 19657 19658 if (ps.getInstalled(userId)) { 19659 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19660 19661 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19662 // We may have just shuffled around app data directories, so 19663 // prepare them one more time 19664 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19665 } 19666 19667 preparedCount++; 19668 } 19669 } 19670 19671 if (restoreconNeeded) { 19672 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19673 SELinuxMMAC.setRestoreconDone(ceDir); 19674 } 19675 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19676 SELinuxMMAC.setRestoreconDone(deDir); 19677 } 19678 } 19679 19680 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19681 + " packages; restoreconNeeded was " + restoreconNeeded); 19682 } 19683 19684 /** 19685 * Prepare app data for the given app just after it was installed or 19686 * upgraded. This method carefully only touches users that it's installed 19687 * for, and it forces a restorecon to handle any seinfo changes. 19688 * <p> 19689 * Verifies that directories exist and that ownership and labeling is 19690 * correct for all installed apps. If there is an ownership mismatch, it 19691 * will try recovering system apps by wiping data; third-party app data is 19692 * left intact. 19693 * <p> 19694 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19695 */ 19696 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19697 final PackageSetting ps; 19698 synchronized (mPackages) { 19699 ps = mSettings.mPackages.get(pkg.packageName); 19700 mSettings.writeKernelMappingLPr(ps); 19701 } 19702 19703 final UserManager um = mContext.getSystemService(UserManager.class); 19704 UserManagerInternal umInternal = getUserManagerInternal(); 19705 for (UserInfo user : um.getUsers()) { 19706 final int flags; 19707 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19708 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19709 } else if (umInternal.isUserRunning(user.id)) { 19710 flags = StorageManager.FLAG_STORAGE_DE; 19711 } else { 19712 continue; 19713 } 19714 19715 if (ps.getInstalled(user.id)) { 19716 // Whenever an app changes, force a restorecon of its data 19717 // TODO: when user data is locked, mark that we're still dirty 19718 prepareAppDataLIF(pkg, user.id, flags, true); 19719 } 19720 } 19721 } 19722 19723 /** 19724 * Prepare app data for the given app. 19725 * <p> 19726 * Verifies that directories exist and that ownership and labeling is 19727 * correct for all installed apps. If there is an ownership mismatch, this 19728 * will try recovering system apps by wiping data; third-party app data is 19729 * left intact. 19730 */ 19731 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19732 boolean restoreconNeeded) { 19733 if (pkg == null) { 19734 Slog.wtf(TAG, "Package was null!", new Throwable()); 19735 return; 19736 } 19737 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19739 for (int i = 0; i < childCount; i++) { 19740 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19741 } 19742 } 19743 19744 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19745 boolean restoreconNeeded) { 19746 if (DEBUG_APP_DATA) { 19747 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19748 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19749 } 19750 19751 final String volumeUuid = pkg.volumeUuid; 19752 final String packageName = pkg.packageName; 19753 final ApplicationInfo app = pkg.applicationInfo; 19754 final int appId = UserHandle.getAppId(app.uid); 19755 19756 Preconditions.checkNotNull(app.seinfo); 19757 19758 try { 19759 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19760 appId, app.seinfo, app.targetSdkVersion); 19761 } catch (InstallerException e) { 19762 if (app.isSystemApp()) { 19763 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19764 + ", but trying to recover: " + e); 19765 destroyAppDataLeafLIF(pkg, userId, flags); 19766 try { 19767 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19768 appId, app.seinfo, app.targetSdkVersion); 19769 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19770 } catch (InstallerException e2) { 19771 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19772 } 19773 } else { 19774 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19775 } 19776 } 19777 19778 if (restoreconNeeded) { 19779 try { 19780 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19781 app.seinfo); 19782 } catch (InstallerException e) { 19783 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19784 } 19785 } 19786 19787 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19788 try { 19789 // CE storage is unlocked right now, so read out the inode and 19790 // remember for use later when it's locked 19791 // TODO: mark this structure as dirty so we persist it! 19792 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19793 StorageManager.FLAG_STORAGE_CE); 19794 synchronized (mPackages) { 19795 final PackageSetting ps = mSettings.mPackages.get(packageName); 19796 if (ps != null) { 19797 ps.setCeDataInode(ceDataInode, userId); 19798 } 19799 } 19800 } catch (InstallerException e) { 19801 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19802 } 19803 } 19804 19805 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19806 } 19807 19808 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19809 if (pkg == null) { 19810 Slog.wtf(TAG, "Package was null!", new Throwable()); 19811 return; 19812 } 19813 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19814 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19815 for (int i = 0; i < childCount; i++) { 19816 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19817 } 19818 } 19819 19820 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19821 final String volumeUuid = pkg.volumeUuid; 19822 final String packageName = pkg.packageName; 19823 final ApplicationInfo app = pkg.applicationInfo; 19824 19825 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19826 // Create a native library symlink only if we have native libraries 19827 // and if the native libraries are 32 bit libraries. We do not provide 19828 // this symlink for 64 bit libraries. 19829 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19830 final String nativeLibPath = app.nativeLibraryDir; 19831 try { 19832 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19833 nativeLibPath, userId); 19834 } catch (InstallerException e) { 19835 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19836 } 19837 } 19838 } 19839 } 19840 19841 /** 19842 * For system apps on non-FBE devices, this method migrates any existing 19843 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19844 * requested by the app. 19845 */ 19846 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19847 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19848 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19849 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19850 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19851 try { 19852 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19853 storageTarget); 19854 } catch (InstallerException e) { 19855 logCriticalInfo(Log.WARN, 19856 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19857 } 19858 return true; 19859 } else { 19860 return false; 19861 } 19862 } 19863 19864 public PackageFreezer freezePackage(String packageName, String killReason) { 19865 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19866 } 19867 19868 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19869 return new PackageFreezer(packageName, userId, killReason); 19870 } 19871 19872 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19873 String killReason) { 19874 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19875 } 19876 19877 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19878 String killReason) { 19879 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19880 return new PackageFreezer(); 19881 } else { 19882 return freezePackage(packageName, userId, killReason); 19883 } 19884 } 19885 19886 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19887 String killReason) { 19888 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19889 } 19890 19891 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19892 String killReason) { 19893 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19894 return new PackageFreezer(); 19895 } else { 19896 return freezePackage(packageName, userId, killReason); 19897 } 19898 } 19899 19900 /** 19901 * Class that freezes and kills the given package upon creation, and 19902 * unfreezes it upon closing. This is typically used when doing surgery on 19903 * app code/data to prevent the app from running while you're working. 19904 */ 19905 private class PackageFreezer implements AutoCloseable { 19906 private final String mPackageName; 19907 private final PackageFreezer[] mChildren; 19908 19909 private final boolean mWeFroze; 19910 19911 private final AtomicBoolean mClosed = new AtomicBoolean(); 19912 private final CloseGuard mCloseGuard = CloseGuard.get(); 19913 19914 /** 19915 * Create and return a stub freezer that doesn't actually do anything, 19916 * typically used when someone requested 19917 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19918 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19919 */ 19920 public PackageFreezer() { 19921 mPackageName = null; 19922 mChildren = null; 19923 mWeFroze = false; 19924 mCloseGuard.open("close"); 19925 } 19926 19927 public PackageFreezer(String packageName, int userId, String killReason) { 19928 synchronized (mPackages) { 19929 mPackageName = packageName; 19930 mWeFroze = mFrozenPackages.add(mPackageName); 19931 19932 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19933 if (ps != null) { 19934 killApplication(ps.name, ps.appId, userId, killReason); 19935 } 19936 19937 final PackageParser.Package p = mPackages.get(packageName); 19938 if (p != null && p.childPackages != null) { 19939 final int N = p.childPackages.size(); 19940 mChildren = new PackageFreezer[N]; 19941 for (int i = 0; i < N; i++) { 19942 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19943 userId, killReason); 19944 } 19945 } else { 19946 mChildren = null; 19947 } 19948 } 19949 mCloseGuard.open("close"); 19950 } 19951 19952 @Override 19953 protected void finalize() throws Throwable { 19954 try { 19955 mCloseGuard.warnIfOpen(); 19956 close(); 19957 } finally { 19958 super.finalize(); 19959 } 19960 } 19961 19962 @Override 19963 public void close() { 19964 mCloseGuard.close(); 19965 if (mClosed.compareAndSet(false, true)) { 19966 synchronized (mPackages) { 19967 if (mWeFroze) { 19968 mFrozenPackages.remove(mPackageName); 19969 } 19970 19971 if (mChildren != null) { 19972 for (PackageFreezer freezer : mChildren) { 19973 freezer.close(); 19974 } 19975 } 19976 } 19977 } 19978 } 19979 } 19980 19981 /** 19982 * Verify that given package is currently frozen. 19983 */ 19984 private void checkPackageFrozen(String packageName) { 19985 synchronized (mPackages) { 19986 if (!mFrozenPackages.contains(packageName)) { 19987 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19988 } 19989 } 19990 } 19991 19992 @Override 19993 public int movePackage(final String packageName, final String volumeUuid) { 19994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19995 19996 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19997 final int moveId = mNextMoveId.getAndIncrement(); 19998 mHandler.post(new Runnable() { 19999 @Override 20000 public void run() { 20001 try { 20002 movePackageInternal(packageName, volumeUuid, moveId, user); 20003 } catch (PackageManagerException e) { 20004 Slog.w(TAG, "Failed to move " + packageName, e); 20005 mMoveCallbacks.notifyStatusChanged(moveId, 20006 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20007 } 20008 } 20009 }); 20010 return moveId; 20011 } 20012 20013 private void movePackageInternal(final String packageName, final String volumeUuid, 20014 final int moveId, UserHandle user) throws PackageManagerException { 20015 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20016 final PackageManager pm = mContext.getPackageManager(); 20017 20018 final boolean currentAsec; 20019 final String currentVolumeUuid; 20020 final File codeFile; 20021 final String installerPackageName; 20022 final String packageAbiOverride; 20023 final int appId; 20024 final String seinfo; 20025 final String label; 20026 final int targetSdkVersion; 20027 final PackageFreezer freezer; 20028 final int[] installedUserIds; 20029 20030 // reader 20031 synchronized (mPackages) { 20032 final PackageParser.Package pkg = mPackages.get(packageName); 20033 final PackageSetting ps = mSettings.mPackages.get(packageName); 20034 if (pkg == null || ps == null) { 20035 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20036 } 20037 20038 if (pkg.applicationInfo.isSystemApp()) { 20039 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20040 "Cannot move system application"); 20041 } 20042 20043 if (pkg.applicationInfo.isExternalAsec()) { 20044 currentAsec = true; 20045 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20046 } else if (pkg.applicationInfo.isForwardLocked()) { 20047 currentAsec = true; 20048 currentVolumeUuid = "forward_locked"; 20049 } else { 20050 currentAsec = false; 20051 currentVolumeUuid = ps.volumeUuid; 20052 20053 final File probe = new File(pkg.codePath); 20054 final File probeOat = new File(probe, "oat"); 20055 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20056 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20057 "Move only supported for modern cluster style installs"); 20058 } 20059 } 20060 20061 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20062 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20063 "Package already moved to " + volumeUuid); 20064 } 20065 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20066 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20067 "Device admin cannot be moved"); 20068 } 20069 20070 if (mFrozenPackages.contains(packageName)) { 20071 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20072 "Failed to move already frozen package"); 20073 } 20074 20075 codeFile = new File(pkg.codePath); 20076 installerPackageName = ps.installerPackageName; 20077 packageAbiOverride = ps.cpuAbiOverrideString; 20078 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20079 seinfo = pkg.applicationInfo.seinfo; 20080 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20081 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20082 freezer = freezePackage(packageName, "movePackageInternal"); 20083 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20084 } 20085 20086 final Bundle extras = new Bundle(); 20087 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20088 extras.putString(Intent.EXTRA_TITLE, label); 20089 mMoveCallbacks.notifyCreated(moveId, extras); 20090 20091 int installFlags; 20092 final boolean moveCompleteApp; 20093 final File measurePath; 20094 20095 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20096 installFlags = INSTALL_INTERNAL; 20097 moveCompleteApp = !currentAsec; 20098 measurePath = Environment.getDataAppDirectory(volumeUuid); 20099 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20100 installFlags = INSTALL_EXTERNAL; 20101 moveCompleteApp = false; 20102 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20103 } else { 20104 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20105 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20106 || !volume.isMountedWritable()) { 20107 freezer.close(); 20108 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20109 "Move location not mounted private volume"); 20110 } 20111 20112 Preconditions.checkState(!currentAsec); 20113 20114 installFlags = INSTALL_INTERNAL; 20115 moveCompleteApp = true; 20116 measurePath = Environment.getDataAppDirectory(volumeUuid); 20117 } 20118 20119 final PackageStats stats = new PackageStats(null, -1); 20120 synchronized (mInstaller) { 20121 for (int userId : installedUserIds) { 20122 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20123 freezer.close(); 20124 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20125 "Failed to measure package size"); 20126 } 20127 } 20128 } 20129 20130 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20131 + stats.dataSize); 20132 20133 final long startFreeBytes = measurePath.getFreeSpace(); 20134 final long sizeBytes; 20135 if (moveCompleteApp) { 20136 sizeBytes = stats.codeSize + stats.dataSize; 20137 } else { 20138 sizeBytes = stats.codeSize; 20139 } 20140 20141 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20142 freezer.close(); 20143 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20144 "Not enough free space to move"); 20145 } 20146 20147 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20148 20149 final CountDownLatch installedLatch = new CountDownLatch(1); 20150 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20151 @Override 20152 public void onUserActionRequired(Intent intent) throws RemoteException { 20153 throw new IllegalStateException(); 20154 } 20155 20156 @Override 20157 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20158 Bundle extras) throws RemoteException { 20159 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20160 + PackageManager.installStatusToString(returnCode, msg)); 20161 20162 installedLatch.countDown(); 20163 freezer.close(); 20164 20165 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20166 switch (status) { 20167 case PackageInstaller.STATUS_SUCCESS: 20168 mMoveCallbacks.notifyStatusChanged(moveId, 20169 PackageManager.MOVE_SUCCEEDED); 20170 break; 20171 case PackageInstaller.STATUS_FAILURE_STORAGE: 20172 mMoveCallbacks.notifyStatusChanged(moveId, 20173 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20174 break; 20175 default: 20176 mMoveCallbacks.notifyStatusChanged(moveId, 20177 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20178 break; 20179 } 20180 } 20181 }; 20182 20183 final MoveInfo move; 20184 if (moveCompleteApp) { 20185 // Kick off a thread to report progress estimates 20186 new Thread() { 20187 @Override 20188 public void run() { 20189 while (true) { 20190 try { 20191 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20192 break; 20193 } 20194 } catch (InterruptedException ignored) { 20195 } 20196 20197 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20198 final int progress = 10 + (int) MathUtils.constrain( 20199 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20200 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20201 } 20202 } 20203 }.start(); 20204 20205 final String dataAppName = codeFile.getName(); 20206 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20207 dataAppName, appId, seinfo, targetSdkVersion); 20208 } else { 20209 move = null; 20210 } 20211 20212 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20213 20214 final Message msg = mHandler.obtainMessage(INIT_COPY); 20215 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20216 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20217 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20218 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20219 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20220 msg.obj = params; 20221 20222 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20223 System.identityHashCode(msg.obj)); 20224 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20225 System.identityHashCode(msg.obj)); 20226 20227 mHandler.sendMessage(msg); 20228 } 20229 20230 @Override 20231 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20233 20234 final int realMoveId = mNextMoveId.getAndIncrement(); 20235 final Bundle extras = new Bundle(); 20236 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20237 mMoveCallbacks.notifyCreated(realMoveId, extras); 20238 20239 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20240 @Override 20241 public void onCreated(int moveId, Bundle extras) { 20242 // Ignored 20243 } 20244 20245 @Override 20246 public void onStatusChanged(int moveId, int status, long estMillis) { 20247 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20248 } 20249 }; 20250 20251 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20252 storage.setPrimaryStorageUuid(volumeUuid, callback); 20253 return realMoveId; 20254 } 20255 20256 @Override 20257 public int getMoveStatus(int moveId) { 20258 mContext.enforceCallingOrSelfPermission( 20259 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20260 return mMoveCallbacks.mLastStatus.get(moveId); 20261 } 20262 20263 @Override 20264 public void registerMoveCallback(IPackageMoveObserver callback) { 20265 mContext.enforceCallingOrSelfPermission( 20266 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20267 mMoveCallbacks.register(callback); 20268 } 20269 20270 @Override 20271 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20272 mContext.enforceCallingOrSelfPermission( 20273 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20274 mMoveCallbacks.unregister(callback); 20275 } 20276 20277 @Override 20278 public boolean setInstallLocation(int loc) { 20279 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20280 null); 20281 if (getInstallLocation() == loc) { 20282 return true; 20283 } 20284 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20285 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20286 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20287 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20288 return true; 20289 } 20290 return false; 20291 } 20292 20293 @Override 20294 public int getInstallLocation() { 20295 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20296 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20297 PackageHelper.APP_INSTALL_AUTO); 20298 } 20299 20300 /** Called by UserManagerService */ 20301 void cleanUpUser(UserManagerService userManager, int userHandle) { 20302 synchronized (mPackages) { 20303 mDirtyUsers.remove(userHandle); 20304 mUserNeedsBadging.delete(userHandle); 20305 mSettings.removeUserLPw(userHandle); 20306 mPendingBroadcasts.remove(userHandle); 20307 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20308 removeUnusedPackagesLPw(userManager, userHandle); 20309 } 20310 } 20311 20312 /** 20313 * We're removing userHandle and would like to remove any downloaded packages 20314 * that are no longer in use by any other user. 20315 * @param userHandle the user being removed 20316 */ 20317 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20318 final boolean DEBUG_CLEAN_APKS = false; 20319 int [] users = userManager.getUserIds(); 20320 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20321 while (psit.hasNext()) { 20322 PackageSetting ps = psit.next(); 20323 if (ps.pkg == null) { 20324 continue; 20325 } 20326 final String packageName = ps.pkg.packageName; 20327 // Skip over if system app 20328 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20329 continue; 20330 } 20331 if (DEBUG_CLEAN_APKS) { 20332 Slog.i(TAG, "Checking package " + packageName); 20333 } 20334 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20335 if (keep) { 20336 if (DEBUG_CLEAN_APKS) { 20337 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20338 } 20339 } else { 20340 for (int i = 0; i < users.length; i++) { 20341 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20342 keep = true; 20343 if (DEBUG_CLEAN_APKS) { 20344 Slog.i(TAG, " Keeping package " + packageName + " for user " 20345 + users[i]); 20346 } 20347 break; 20348 } 20349 } 20350 } 20351 if (!keep) { 20352 if (DEBUG_CLEAN_APKS) { 20353 Slog.i(TAG, " Removing package " + packageName); 20354 } 20355 mHandler.post(new Runnable() { 20356 public void run() { 20357 deletePackageX(packageName, userHandle, 0); 20358 } //end run 20359 }); 20360 } 20361 } 20362 } 20363 20364 /** Called by UserManagerService */ 20365 void createNewUser(int userId) { 20366 synchronized (mInstallLock) { 20367 mSettings.createNewUserLI(this, mInstaller, userId); 20368 } 20369 synchronized (mPackages) { 20370 scheduleWritePackageRestrictionsLocked(userId); 20371 scheduleWritePackageListLocked(userId); 20372 applyFactoryDefaultBrowserLPw(userId); 20373 primeDomainVerificationsLPw(userId); 20374 } 20375 } 20376 20377 void onNewUserCreated(final int userId) { 20378 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20379 // If permission review for legacy apps is required, we represent 20380 // dagerous permissions for such apps as always granted runtime 20381 // permissions to keep per user flag state whether review is needed. 20382 // Hence, if a new user is added we have to propagate dangerous 20383 // permission grants for these legacy apps. 20384 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20385 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20386 | UPDATE_PERMISSIONS_REPLACE_ALL); 20387 } 20388 } 20389 20390 @Override 20391 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20392 mContext.enforceCallingOrSelfPermission( 20393 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20394 "Only package verification agents can read the verifier device identity"); 20395 20396 synchronized (mPackages) { 20397 return mSettings.getVerifierDeviceIdentityLPw(); 20398 } 20399 } 20400 20401 @Override 20402 public void setPermissionEnforced(String permission, boolean enforced) { 20403 // TODO: Now that we no longer change GID for storage, this should to away. 20404 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20405 "setPermissionEnforced"); 20406 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20407 synchronized (mPackages) { 20408 if (mSettings.mReadExternalStorageEnforced == null 20409 || mSettings.mReadExternalStorageEnforced != enforced) { 20410 mSettings.mReadExternalStorageEnforced = enforced; 20411 mSettings.writeLPr(); 20412 } 20413 } 20414 // kill any non-foreground processes so we restart them and 20415 // grant/revoke the GID. 20416 final IActivityManager am = ActivityManagerNative.getDefault(); 20417 if (am != null) { 20418 final long token = Binder.clearCallingIdentity(); 20419 try { 20420 am.killProcessesBelowForeground("setPermissionEnforcement"); 20421 } catch (RemoteException e) { 20422 } finally { 20423 Binder.restoreCallingIdentity(token); 20424 } 20425 } 20426 } else { 20427 throw new IllegalArgumentException("No selective enforcement for " + permission); 20428 } 20429 } 20430 20431 @Override 20432 @Deprecated 20433 public boolean isPermissionEnforced(String permission) { 20434 return true; 20435 } 20436 20437 @Override 20438 public boolean isStorageLow() { 20439 final long token = Binder.clearCallingIdentity(); 20440 try { 20441 final DeviceStorageMonitorInternal 20442 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20443 if (dsm != null) { 20444 return dsm.isMemoryLow(); 20445 } else { 20446 return false; 20447 } 20448 } finally { 20449 Binder.restoreCallingIdentity(token); 20450 } 20451 } 20452 20453 @Override 20454 public IPackageInstaller getPackageInstaller() { 20455 return mInstallerService; 20456 } 20457 20458 private boolean userNeedsBadging(int userId) { 20459 int index = mUserNeedsBadging.indexOfKey(userId); 20460 if (index < 0) { 20461 final UserInfo userInfo; 20462 final long token = Binder.clearCallingIdentity(); 20463 try { 20464 userInfo = sUserManager.getUserInfo(userId); 20465 } finally { 20466 Binder.restoreCallingIdentity(token); 20467 } 20468 final boolean b; 20469 if (userInfo != null && userInfo.isManagedProfile()) { 20470 b = true; 20471 } else { 20472 b = false; 20473 } 20474 mUserNeedsBadging.put(userId, b); 20475 return b; 20476 } 20477 return mUserNeedsBadging.valueAt(index); 20478 } 20479 20480 @Override 20481 public KeySet getKeySetByAlias(String packageName, String alias) { 20482 if (packageName == null || alias == null) { 20483 return null; 20484 } 20485 synchronized(mPackages) { 20486 final PackageParser.Package pkg = mPackages.get(packageName); 20487 if (pkg == null) { 20488 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20489 throw new IllegalArgumentException("Unknown package: " + packageName); 20490 } 20491 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20492 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20493 } 20494 } 20495 20496 @Override 20497 public KeySet getSigningKeySet(String packageName) { 20498 if (packageName == null) { 20499 return null; 20500 } 20501 synchronized(mPackages) { 20502 final PackageParser.Package pkg = mPackages.get(packageName); 20503 if (pkg == null) { 20504 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20505 throw new IllegalArgumentException("Unknown package: " + packageName); 20506 } 20507 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20508 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20509 throw new SecurityException("May not access signing KeySet of other apps."); 20510 } 20511 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20512 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20513 } 20514 } 20515 20516 @Override 20517 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20518 if (packageName == null || ks == null) { 20519 return false; 20520 } 20521 synchronized(mPackages) { 20522 final PackageParser.Package pkg = mPackages.get(packageName); 20523 if (pkg == null) { 20524 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20525 throw new IllegalArgumentException("Unknown package: " + packageName); 20526 } 20527 IBinder ksh = ks.getToken(); 20528 if (ksh instanceof KeySetHandle) { 20529 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20530 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20531 } 20532 return false; 20533 } 20534 } 20535 20536 @Override 20537 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20538 if (packageName == null || ks == null) { 20539 return false; 20540 } 20541 synchronized(mPackages) { 20542 final PackageParser.Package pkg = mPackages.get(packageName); 20543 if (pkg == null) { 20544 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20545 throw new IllegalArgumentException("Unknown package: " + packageName); 20546 } 20547 IBinder ksh = ks.getToken(); 20548 if (ksh instanceof KeySetHandle) { 20549 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20550 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20551 } 20552 return false; 20553 } 20554 } 20555 20556 private void deletePackageIfUnusedLPr(final String packageName) { 20557 PackageSetting ps = mSettings.mPackages.get(packageName); 20558 if (ps == null) { 20559 return; 20560 } 20561 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20562 // TODO Implement atomic delete if package is unused 20563 // It is currently possible that the package will be deleted even if it is installed 20564 // after this method returns. 20565 mHandler.post(new Runnable() { 20566 public void run() { 20567 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20568 } 20569 }); 20570 } 20571 } 20572 20573 /** 20574 * Check and throw if the given before/after packages would be considered a 20575 * downgrade. 20576 */ 20577 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20578 throws PackageManagerException { 20579 if (after.versionCode < before.mVersionCode) { 20580 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20581 "Update version code " + after.versionCode + " is older than current " 20582 + before.mVersionCode); 20583 } else if (after.versionCode == before.mVersionCode) { 20584 if (after.baseRevisionCode < before.baseRevisionCode) { 20585 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20586 "Update base revision code " + after.baseRevisionCode 20587 + " is older than current " + before.baseRevisionCode); 20588 } 20589 20590 if (!ArrayUtils.isEmpty(after.splitNames)) { 20591 for (int i = 0; i < after.splitNames.length; i++) { 20592 final String splitName = after.splitNames[i]; 20593 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20594 if (j != -1) { 20595 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20596 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20597 "Update split " + splitName + " revision code " 20598 + after.splitRevisionCodes[i] + " is older than current " 20599 + before.splitRevisionCodes[j]); 20600 } 20601 } 20602 } 20603 } 20604 } 20605 } 20606 20607 private static class MoveCallbacks extends Handler { 20608 private static final int MSG_CREATED = 1; 20609 private static final int MSG_STATUS_CHANGED = 2; 20610 20611 private final RemoteCallbackList<IPackageMoveObserver> 20612 mCallbacks = new RemoteCallbackList<>(); 20613 20614 private final SparseIntArray mLastStatus = new SparseIntArray(); 20615 20616 public MoveCallbacks(Looper looper) { 20617 super(looper); 20618 } 20619 20620 public void register(IPackageMoveObserver callback) { 20621 mCallbacks.register(callback); 20622 } 20623 20624 public void unregister(IPackageMoveObserver callback) { 20625 mCallbacks.unregister(callback); 20626 } 20627 20628 @Override 20629 public void handleMessage(Message msg) { 20630 final SomeArgs args = (SomeArgs) msg.obj; 20631 final int n = mCallbacks.beginBroadcast(); 20632 for (int i = 0; i < n; i++) { 20633 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20634 try { 20635 invokeCallback(callback, msg.what, args); 20636 } catch (RemoteException ignored) { 20637 } 20638 } 20639 mCallbacks.finishBroadcast(); 20640 args.recycle(); 20641 } 20642 20643 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20644 throws RemoteException { 20645 switch (what) { 20646 case MSG_CREATED: { 20647 callback.onCreated(args.argi1, (Bundle) args.arg2); 20648 break; 20649 } 20650 case MSG_STATUS_CHANGED: { 20651 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20652 break; 20653 } 20654 } 20655 } 20656 20657 private void notifyCreated(int moveId, Bundle extras) { 20658 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20659 20660 final SomeArgs args = SomeArgs.obtain(); 20661 args.argi1 = moveId; 20662 args.arg2 = extras; 20663 obtainMessage(MSG_CREATED, args).sendToTarget(); 20664 } 20665 20666 private void notifyStatusChanged(int moveId, int status) { 20667 notifyStatusChanged(moveId, status, -1); 20668 } 20669 20670 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20671 Slog.v(TAG, "Move " + moveId + " status " + status); 20672 20673 final SomeArgs args = SomeArgs.obtain(); 20674 args.argi1 = moveId; 20675 args.argi2 = status; 20676 args.arg3 = estMillis; 20677 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20678 20679 synchronized (mLastStatus) { 20680 mLastStatus.put(moveId, status); 20681 } 20682 } 20683 } 20684 20685 private final static class OnPermissionChangeListeners extends Handler { 20686 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20687 20688 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20689 new RemoteCallbackList<>(); 20690 20691 public OnPermissionChangeListeners(Looper looper) { 20692 super(looper); 20693 } 20694 20695 @Override 20696 public void handleMessage(Message msg) { 20697 switch (msg.what) { 20698 case MSG_ON_PERMISSIONS_CHANGED: { 20699 final int uid = msg.arg1; 20700 handleOnPermissionsChanged(uid); 20701 } break; 20702 } 20703 } 20704 20705 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20706 mPermissionListeners.register(listener); 20707 20708 } 20709 20710 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20711 mPermissionListeners.unregister(listener); 20712 } 20713 20714 public void onPermissionsChanged(int uid) { 20715 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20716 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20717 } 20718 } 20719 20720 private void handleOnPermissionsChanged(int uid) { 20721 final int count = mPermissionListeners.beginBroadcast(); 20722 try { 20723 for (int i = 0; i < count; i++) { 20724 IOnPermissionsChangeListener callback = mPermissionListeners 20725 .getBroadcastItem(i); 20726 try { 20727 callback.onPermissionsChanged(uid); 20728 } catch (RemoteException e) { 20729 Log.e(TAG, "Permission listener is dead", e); 20730 } 20731 } 20732 } finally { 20733 mPermissionListeners.finishBroadcast(); 20734 } 20735 } 20736 } 20737 20738 private class PackageManagerInternalImpl extends PackageManagerInternal { 20739 @Override 20740 public void setLocationPackagesProvider(PackagesProvider provider) { 20741 synchronized (mPackages) { 20742 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20743 } 20744 } 20745 20746 @Override 20747 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20748 synchronized (mPackages) { 20749 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20750 } 20751 } 20752 20753 @Override 20754 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20755 synchronized (mPackages) { 20756 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20757 } 20758 } 20759 20760 @Override 20761 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20762 synchronized (mPackages) { 20763 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20764 } 20765 } 20766 20767 @Override 20768 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20769 synchronized (mPackages) { 20770 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20771 } 20772 } 20773 20774 @Override 20775 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20776 synchronized (mPackages) { 20777 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20778 } 20779 } 20780 20781 @Override 20782 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20783 synchronized (mPackages) { 20784 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20785 packageName, userId); 20786 } 20787 } 20788 20789 @Override 20790 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20791 synchronized (mPackages) { 20792 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20793 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20794 packageName, userId); 20795 } 20796 } 20797 20798 @Override 20799 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20800 synchronized (mPackages) { 20801 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20802 packageName, userId); 20803 } 20804 } 20805 20806 @Override 20807 public void setKeepUninstalledPackages(final List<String> packageList) { 20808 Preconditions.checkNotNull(packageList); 20809 List<String> removedFromList = null; 20810 synchronized (mPackages) { 20811 if (mKeepUninstalledPackages != null) { 20812 final int packagesCount = mKeepUninstalledPackages.size(); 20813 for (int i = 0; i < packagesCount; i++) { 20814 String oldPackage = mKeepUninstalledPackages.get(i); 20815 if (packageList != null && packageList.contains(oldPackage)) { 20816 continue; 20817 } 20818 if (removedFromList == null) { 20819 removedFromList = new ArrayList<>(); 20820 } 20821 removedFromList.add(oldPackage); 20822 } 20823 } 20824 mKeepUninstalledPackages = new ArrayList<>(packageList); 20825 if (removedFromList != null) { 20826 final int removedCount = removedFromList.size(); 20827 for (int i = 0; i < removedCount; i++) { 20828 deletePackageIfUnusedLPr(removedFromList.get(i)); 20829 } 20830 } 20831 } 20832 } 20833 20834 @Override 20835 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20836 synchronized (mPackages) { 20837 // If we do not support permission review, done. 20838 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20839 return false; 20840 } 20841 20842 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20843 if (packageSetting == null) { 20844 return false; 20845 } 20846 20847 // Permission review applies only to apps not supporting the new permission model. 20848 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20849 return false; 20850 } 20851 20852 // Legacy apps have the permission and get user consent on launch. 20853 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20854 return permissionsState.isPermissionReviewRequired(userId); 20855 } 20856 } 20857 20858 @Override 20859 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20860 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20861 } 20862 20863 @Override 20864 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20865 int userId) { 20866 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20867 } 20868 20869 @Override 20870 public void setDeviceAndProfileOwnerPackages( 20871 int deviceOwnerUserId, String deviceOwnerPackage, 20872 SparseArray<String> profileOwnerPackages) { 20873 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20874 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20875 } 20876 20877 @Override 20878 public boolean isPackageDataProtected(int userId, String packageName) { 20879 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20880 } 20881 } 20882 20883 @Override 20884 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20885 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20886 synchronized (mPackages) { 20887 final long identity = Binder.clearCallingIdentity(); 20888 try { 20889 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20890 packageNames, userId); 20891 } finally { 20892 Binder.restoreCallingIdentity(identity); 20893 } 20894 } 20895 } 20896 20897 private static void enforceSystemOrPhoneCaller(String tag) { 20898 int callingUid = Binder.getCallingUid(); 20899 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20900 throw new SecurityException( 20901 "Cannot call " + tag + " from UID " + callingUid); 20902 } 20903 } 20904 20905 boolean isHistoricalPackageUsageAvailable() { 20906 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20907 } 20908 20909 /** 20910 * Return a <b>copy</b> of the collection of packages known to the package manager. 20911 * @return A copy of the values of mPackages. 20912 */ 20913 Collection<PackageParser.Package> getPackages() { 20914 synchronized (mPackages) { 20915 return new ArrayList<>(mPackages.values()); 20916 } 20917 } 20918 20919 /** 20920 * Logs process start information (including base APK hash) to the security log. 20921 * @hide 20922 */ 20923 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20924 String apkFile, int pid) { 20925 if (!SecurityLog.isLoggingEnabled()) { 20926 return; 20927 } 20928 Bundle data = new Bundle(); 20929 data.putLong("startTimestamp", System.currentTimeMillis()); 20930 data.putString("processName", processName); 20931 data.putInt("uid", uid); 20932 data.putString("seinfo", seinfo); 20933 data.putString("apkFile", apkFile); 20934 data.putInt("pid", pid); 20935 Message msg = mProcessLoggingHandler.obtainMessage( 20936 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20937 msg.setData(data); 20938 mProcessLoggingHandler.sendMessage(msg); 20939 } 20940 20941 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20942 return mCompilerStats.getPackageStats(pkgName); 20943 } 20944 20945 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20946 return getOrCreateCompilerPackageStats(pkg.packageName); 20947 } 20948 20949 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20950 return mCompilerStats.getOrCreatePackageStats(pkgName); 20951 } 20952 20953 public void deleteCompilerPackageStats(String pkgName) { 20954 mCompilerStats.deletePackageStats(pkgName); 20955 } 20956} 20957