PackageManagerService.java revision d69c9e7efbb4983527acf5c4feca9d1fde7b611d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.FIRST_APPLICATION_UID; 80import static android.os.Process.PACKAGE_INFO_GID; 81import static android.os.Process.SYSTEM_UID; 82import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 83import static android.system.OsConstants.O_CREAT; 84import static android.system.OsConstants.O_RDWR; 85 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 88import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 89import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 90import static com.android.internal.util.ArrayUtils.appendInt; 91import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102 103import android.Manifest; 104import android.annotation.NonNull; 105import android.annotation.Nullable; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentFilter.AuthorityEntry; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralResolveInfo; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.IntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.Process; 185import android.os.RemoteCallbackList; 186import android.os.RemoteException; 187import android.os.ResultReceiver; 188import android.os.SELinux; 189import android.os.ServiceManager; 190import android.os.SystemClock; 191import android.os.SystemProperties; 192import android.os.Trace; 193import android.os.UserHandle; 194import android.os.UserManager; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.AtomicFile; 210import android.util.DisplayMetrics; 211import android.util.EventLog; 212import android.util.ExceptionUtils; 213import android.util.Log; 214import android.util.LogPrinter; 215import android.util.MathUtils; 216import android.util.PrintStreamPrinter; 217import android.util.Slog; 218import android.util.SparseArray; 219import android.util.SparseBooleanArray; 220import android.util.SparseIntArray; 221import android.util.Xml; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 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.EventLogTags; 241import com.android.server.FgThread; 242import com.android.server.IntentResolver; 243import com.android.server.LocalServices; 244import com.android.server.ServiceThread; 245import com.android.server.SystemConfig; 246import com.android.server.Watchdog; 247import com.android.server.pm.PermissionsState.PermissionState; 248import com.android.server.pm.Settings.DatabaseVersion; 249import com.android.server.pm.Settings.VersionInfo; 250import com.android.server.storage.DeviceStorageMonitorInternal; 251 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those .apks everywhere. 303 * 304 * This is very central to the platform's security; please run the unit 305 * tests whenever making modifications here: 306 * 307runtest -c android.content.pm.PackageManagerTests frameworks-core 308 * 309 * {@hide} 310 */ 311public class PackageManagerService extends IPackageManager.Stub { 312 static final String TAG = "PackageManager"; 313 static final boolean DEBUG_SETTINGS = false; 314 static final boolean DEBUG_PREFERRED = false; 315 static final boolean DEBUG_UPGRADE = false; 316 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 317 private static final boolean DEBUG_BACKUP = false; 318 private static final boolean DEBUG_INSTALL = false; 319 private static final boolean DEBUG_REMOVE = false; 320 private static final boolean DEBUG_BROADCASTS = false; 321 private static final boolean DEBUG_SHOW_INFO = false; 322 private static final boolean DEBUG_PACKAGE_INFO = false; 323 private static final boolean DEBUG_INTENT_MATCHING = false; 324 private static final boolean DEBUG_PACKAGE_SCANNING = false; 325 private static final boolean DEBUG_VERIFY = false; 326 private static final boolean DEBUG_FILTERS = false; 327 328 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 329 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 330 // user, but by default initialize to this. 331 static final boolean DEBUG_DEXOPT = false; 332 333 private static final boolean DEBUG_ABI_SELECTION = false; 334 private static final boolean DEBUG_EPHEMERAL = false; 335 private static final boolean DEBUG_TRIAGED_MISSING = false; 336 private static final boolean DEBUG_APP_DATA = false; 337 338 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 339 340 private static final boolean DISABLE_EPHEMERAL_APPS = true; 341 342 private static final int RADIO_UID = Process.PHONE_UID; 343 private static final int LOG_UID = Process.LOG_UID; 344 private static final int NFC_UID = Process.NFC_UID; 345 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 346 private static final int SHELL_UID = Process.SHELL_UID; 347 348 // Cap the size of permission trees that 3rd party apps can define 349 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 350 351 // Suffix used during package installation when copying/moving 352 // package apks to install directory. 353 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 354 355 static final int SCAN_NO_DEX = 1<<1; 356 static final int SCAN_FORCE_DEX = 1<<2; 357 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 358 static final int SCAN_NEW_INSTALL = 1<<4; 359 static final int SCAN_NO_PATHS = 1<<5; 360 static final int SCAN_UPDATE_TIME = 1<<6; 361 static final int SCAN_DEFER_DEX = 1<<7; 362 static final int SCAN_BOOTING = 1<<8; 363 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 364 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 365 static final int SCAN_REPLACING = 1<<11; 366 static final int SCAN_REQUIRE_KNOWN = 1<<12; 367 static final int SCAN_MOVE = 1<<13; 368 static final int SCAN_INITIAL = 1<<14; 369 static final int SCAN_CHECK_ONLY = 1<<15; 370 static final int SCAN_DONT_KILL_APP = 1<<17; 371 372 static final int REMOVE_CHATTY = 1<<16; 373 374 private static final int[] EMPTY_INT_ARRAY = new int[0]; 375 376 /** 377 * Timeout (in milliseconds) after which the watchdog should declare that 378 * our handler thread is wedged. The usual default for such things is one 379 * minute but we sometimes do very lengthy I/O operations on this thread, 380 * such as installing multi-gigabyte applications, so ours needs to be longer. 381 */ 382 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 383 384 /** 385 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 386 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 387 * settings entry if available, otherwise we use the hardcoded default. If it's been 388 * more than this long since the last fstrim, we force one during the boot sequence. 389 * 390 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 391 * one gets run at the next available charging+idle time. This final mandatory 392 * no-fstrim check kicks in only of the other scheduling criteria is never met. 393 */ 394 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 395 396 /** 397 * Whether verification is enabled by default. 398 */ 399 private static final boolean DEFAULT_VERIFY_ENABLE = true; 400 401 /** 402 * The default maximum time to wait for the verification agent to return in 403 * milliseconds. 404 */ 405 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 406 407 /** 408 * The default response for package verification timeout. 409 * 410 * This can be either PackageManager.VERIFICATION_ALLOW or 411 * PackageManager.VERIFICATION_REJECT. 412 */ 413 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 414 415 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 416 417 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 418 DEFAULT_CONTAINER_PACKAGE, 419 "com.android.defcontainer.DefaultContainerService"); 420 421 private static final String KILL_APP_REASON_GIDS_CHANGED = 422 "permission grant or revoke changed gids"; 423 424 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 425 "permissions revoked"; 426 427 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 428 429 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 430 431 /** Permission grant: not grant the permission. */ 432 private static final int GRANT_DENIED = 1; 433 434 /** Permission grant: grant the permission as an install permission. */ 435 private static final int GRANT_INSTALL = 2; 436 437 /** Permission grant: grant the permission as a runtime one. */ 438 private static final int GRANT_RUNTIME = 3; 439 440 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 441 private static final int GRANT_UPGRADE = 4; 442 443 /** Canonical intent used to identify what counts as a "web browser" app */ 444 private static final Intent sBrowserIntent; 445 static { 446 sBrowserIntent = new Intent(); 447 sBrowserIntent.setAction(Intent.ACTION_VIEW); 448 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 449 sBrowserIntent.setData(Uri.parse("http:")); 450 } 451 452 /** 453 * The set of all protected actions [i.e. those actions for which a high priority 454 * intent filter is disallowed]. 455 */ 456 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 457 static { 458 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 459 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 460 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 461 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 462 } 463 464 // Compilation reasons. 465 public static final int REASON_FIRST_BOOT = 0; 466 public static final int REASON_BOOT = 1; 467 public static final int REASON_INSTALL = 2; 468 public static final int REASON_BACKGROUND_DEXOPT = 3; 469 public static final int REASON_AB_OTA = 4; 470 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 471 public static final int REASON_SHARED_APK = 6; 472 public static final int REASON_FORCED_DEXOPT = 7; 473 474 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 475 476 final ServiceThread mHandlerThread; 477 478 final PackageHandler mHandler; 479 480 private final ProcessLoggingHandler mProcessLoggingHandler; 481 482 /** 483 * Messages for {@link #mHandler} that need to wait for system ready before 484 * being dispatched. 485 */ 486 private ArrayList<Message> mPostSystemReadyMessages; 487 488 final int mSdkVersion = Build.VERSION.SDK_INT; 489 490 final Context mContext; 491 final boolean mFactoryTest; 492 final boolean mOnlyCore; 493 final DisplayMetrics mMetrics; 494 final int mDefParseFlags; 495 final String[] mSeparateProcesses; 496 final boolean mIsUpgrade; 497 final boolean mIsPreNUpgrade; 498 499 /** The location for ASEC container files on internal storage. */ 500 final String mAsecInternalPath; 501 502 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 503 // LOCK HELD. Can be called with mInstallLock held. 504 @GuardedBy("mInstallLock") 505 final Installer mInstaller; 506 507 /** Directory where installed third-party apps stored */ 508 final File mAppInstallDir; 509 final File mEphemeralInstallDir; 510 511 /** 512 * Directory to which applications installed internally have their 513 * 32 bit native libraries copied. 514 */ 515 private File mAppLib32InstallDir; 516 517 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 518 // apps. 519 final File mDrmAppPrivateInstallDir; 520 521 // ---------------------------------------------------------------- 522 523 // Lock for state used when installing and doing other long running 524 // operations. Methods that must be called with this lock held have 525 // the suffix "LI". 526 final Object mInstallLock = new Object(); 527 528 // ---------------------------------------------------------------- 529 530 // Keys are String (package name), values are Package. This also serves 531 // as the lock for the global state. Methods that must be called with 532 // this lock held have the prefix "LP". 533 @GuardedBy("mPackages") 534 final ArrayMap<String, PackageParser.Package> mPackages = 535 new ArrayMap<String, PackageParser.Package>(); 536 537 final ArrayMap<String, Set<String>> mKnownCodebase = 538 new ArrayMap<String, Set<String>>(); 539 540 // Tracks available target package names -> overlay package paths. 541 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 542 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 543 544 /** 545 * Tracks new system packages [received in an OTA] that we expect to 546 * find updated user-installed versions. Keys are package name, values 547 * are package location. 548 */ 549 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 550 /** 551 * Tracks high priority intent filters for protected actions. During boot, certain 552 * filter actions are protected and should never be allowed to have a high priority 553 * intent filter for them. However, there is one, and only one exception -- the 554 * setup wizard. It must be able to define a high priority intent filter for these 555 * actions to ensure there are no escapes from the wizard. We need to delay processing 556 * of these during boot as we need to look at all of the system packages in order 557 * to know which component is the setup wizard. 558 */ 559 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 560 /** 561 * Whether or not processing protected filters should be deferred. 562 */ 563 private boolean mDeferProtectedFilters = true; 564 565 /** 566 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 567 */ 568 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 569 /** 570 * Whether or not system app permissions should be promoted from install to runtime. 571 */ 572 boolean mPromoteSystemApps; 573 574 final Settings mSettings; 575 boolean mRestoredSettings; 576 577 // System configuration read by SystemConfig. 578 final int[] mGlobalGids; 579 final SparseArray<ArraySet<String>> mSystemPermissions; 580 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 581 582 // If mac_permissions.xml was found for seinfo labeling. 583 boolean mFoundPolicyFile; 584 585 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 586 587 public static final class SharedLibraryEntry { 588 public final String path; 589 public final String apk; 590 591 SharedLibraryEntry(String _path, String _apk) { 592 path = _path; 593 apk = _apk; 594 } 595 } 596 597 // Currently known shared libraries. 598 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 599 new ArrayMap<String, SharedLibraryEntry>(); 600 601 // All available activities, for your resolving pleasure. 602 final ActivityIntentResolver mActivities = 603 new ActivityIntentResolver(); 604 605 // All available receivers, for your resolving pleasure. 606 final ActivityIntentResolver mReceivers = 607 new ActivityIntentResolver(); 608 609 // All available services, for your resolving pleasure. 610 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 611 612 // All available providers, for your resolving pleasure. 613 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 614 615 // Mapping from provider base names (first directory in content URI codePath) 616 // to the provider information. 617 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 618 new ArrayMap<String, PackageParser.Provider>(); 619 620 // Mapping from instrumentation class names to info about them. 621 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 622 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 623 624 // Mapping from permission names to info about them. 625 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 626 new ArrayMap<String, PackageParser.PermissionGroup>(); 627 628 // Packages whose data we have transfered into another package, thus 629 // should no longer exist. 630 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 631 632 // Broadcast actions that are only available to the system. 633 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 634 635 /** List of packages waiting for verification. */ 636 final SparseArray<PackageVerificationState> mPendingVerification 637 = new SparseArray<PackageVerificationState>(); 638 639 /** Set of packages associated with each app op permission. */ 640 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 641 642 final PackageInstallerService mInstallerService; 643 644 private final PackageDexOptimizer mPackageDexOptimizer; 645 646 private AtomicInteger mNextMoveId = new AtomicInteger(); 647 private final MoveCallbacks mMoveCallbacks; 648 649 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 650 651 // Cache of users who need badging. 652 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 653 654 /** Token for keys in mPendingVerification. */ 655 private int mPendingVerificationToken = 0; 656 657 volatile boolean mSystemReady; 658 volatile boolean mSafeMode; 659 volatile boolean mHasSystemUidErrors; 660 661 ApplicationInfo mAndroidApplication; 662 final ActivityInfo mResolveActivity = new ActivityInfo(); 663 final ResolveInfo mResolveInfo = new ResolveInfo(); 664 ComponentName mResolveComponentName; 665 PackageParser.Package mPlatformPackage; 666 ComponentName mCustomResolverComponentName; 667 668 boolean mResolverReplaced = false; 669 670 private final @Nullable ComponentName mIntentFilterVerifierComponent; 671 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 672 673 private int mIntentFilterVerificationToken = 0; 674 675 /** Component that knows whether or not an ephemeral application exists */ 676 final ComponentName mEphemeralResolverComponent; 677 /** The service connection to the ephemeral resolver */ 678 final EphemeralResolverConnection mEphemeralResolverConnection; 679 680 /** Component used to install ephemeral applications */ 681 final ComponentName mEphemeralInstallerComponent; 682 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 683 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 684 685 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 686 = new SparseArray<IntentFilterVerificationState>(); 687 688 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 689 new DefaultPermissionGrantPolicy(this); 690 691 // List of packages names to keep cached, even if they are uninstalled for all users 692 private List<String> mKeepUninstalledPackages; 693 694 private static class IFVerificationParams { 695 PackageParser.Package pkg; 696 boolean replacing; 697 int userId; 698 int verifierUid; 699 700 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 701 int _userId, int _verifierUid) { 702 pkg = _pkg; 703 replacing = _replacing; 704 userId = _userId; 705 replacing = _replacing; 706 verifierUid = _verifierUid; 707 } 708 } 709 710 private interface IntentFilterVerifier<T extends IntentFilter> { 711 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 712 T filter, String packageName); 713 void startVerifications(int userId); 714 void receiveVerificationResponse(int verificationId); 715 } 716 717 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 718 private Context mContext; 719 private ComponentName mIntentFilterVerifierComponent; 720 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 721 722 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 723 mContext = context; 724 mIntentFilterVerifierComponent = verifierComponent; 725 } 726 727 private String getDefaultScheme() { 728 return IntentFilter.SCHEME_HTTPS; 729 } 730 731 @Override 732 public void startVerifications(int userId) { 733 // Launch verifications requests 734 int count = mCurrentIntentFilterVerifications.size(); 735 for (int n=0; n<count; n++) { 736 int verificationId = mCurrentIntentFilterVerifications.get(n); 737 final IntentFilterVerificationState ivs = 738 mIntentFilterVerificationStates.get(verificationId); 739 740 String packageName = ivs.getPackageName(); 741 742 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 743 final int filterCount = filters.size(); 744 ArraySet<String> domainsSet = new ArraySet<>(); 745 for (int m=0; m<filterCount; m++) { 746 PackageParser.ActivityIntentInfo filter = filters.get(m); 747 domainsSet.addAll(filter.getHostsList()); 748 } 749 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 750 synchronized (mPackages) { 751 if (mSettings.createIntentFilterVerificationIfNeededLPw( 752 packageName, domainsList) != null) { 753 scheduleWriteSettingsLocked(); 754 } 755 } 756 sendVerificationRequest(userId, verificationId, ivs); 757 } 758 mCurrentIntentFilterVerifications.clear(); 759 } 760 761 private void sendVerificationRequest(int userId, int verificationId, 762 IntentFilterVerificationState ivs) { 763 764 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 765 verificationIntent.putExtra( 766 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 767 verificationId); 768 verificationIntent.putExtra( 769 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 770 getDefaultScheme()); 771 verificationIntent.putExtra( 772 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 773 ivs.getHostsString()); 774 verificationIntent.putExtra( 775 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 776 ivs.getPackageName()); 777 verificationIntent.setComponent(mIntentFilterVerifierComponent); 778 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 779 780 UserHandle user = new UserHandle(userId); 781 mContext.sendBroadcastAsUser(verificationIntent, user); 782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 783 "Sending IntentFilter verification broadcast"); 784 } 785 786 public void receiveVerificationResponse(int verificationId) { 787 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 788 789 final boolean verified = ivs.isVerified(); 790 791 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 792 final int count = filters.size(); 793 if (DEBUG_DOMAIN_VERIFICATION) { 794 Slog.i(TAG, "Received verification response " + verificationId 795 + " for " + count + " filters, verified=" + verified); 796 } 797 for (int n=0; n<count; n++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(n); 799 filter.setVerified(verified); 800 801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 802 + " verified with result:" + verified + " and hosts:" 803 + ivs.getHostsString()); 804 } 805 806 mIntentFilterVerificationStates.remove(verificationId); 807 808 final String packageName = ivs.getPackageName(); 809 IntentFilterVerificationInfo ivi = null; 810 811 synchronized (mPackages) { 812 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 813 } 814 if (ivi == null) { 815 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 816 + verificationId + " packageName:" + packageName); 817 return; 818 } 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Updating IntentFilterVerificationInfo for package " + packageName 821 +" verificationId:" + verificationId); 822 823 synchronized (mPackages) { 824 if (verified) { 825 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 826 } else { 827 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 828 } 829 scheduleWriteSettingsLocked(); 830 831 final int userId = ivs.getUserId(); 832 if (userId != UserHandle.USER_ALL) { 833 final int userStatus = 834 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 835 836 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 837 boolean needUpdate = false; 838 839 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 840 // already been set by the User thru the Disambiguation dialog 841 switch (userStatus) { 842 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 843 if (verified) { 844 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 845 } else { 846 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 847 } 848 needUpdate = true; 849 break; 850 851 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 852 if (verified) { 853 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 854 needUpdate = true; 855 } 856 break; 857 858 default: 859 // Nothing to do 860 } 861 862 if (needUpdate) { 863 mSettings.updateIntentFilterVerificationStatusLPw( 864 packageName, updatedStatus, userId); 865 scheduleWritePackageRestrictionsLocked(userId); 866 } 867 } 868 } 869 } 870 871 @Override 872 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 873 ActivityIntentInfo filter, String packageName) { 874 if (!hasValidDomains(filter)) { 875 return false; 876 } 877 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 878 if (ivs == null) { 879 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 880 packageName); 881 } 882 if (DEBUG_DOMAIN_VERIFICATION) { 883 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 884 } 885 ivs.addFilter(filter); 886 return true; 887 } 888 889 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 890 int userId, int verificationId, String packageName) { 891 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 892 verifierUid, userId, packageName); 893 ivs.setPendingState(); 894 synchronized (mPackages) { 895 mIntentFilterVerificationStates.append(verificationId, ivs); 896 mCurrentIntentFilterVerifications.add(verificationId); 897 } 898 return ivs; 899 } 900 } 901 902 private static boolean hasValidDomains(ActivityIntentInfo filter) { 903 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 904 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 905 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 906 } 907 908 // Set of pending broadcasts for aggregating enable/disable of components. 909 static class PendingPackageBroadcasts { 910 // for each user id, a map of <package name -> components within that package> 911 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 912 913 public PendingPackageBroadcasts() { 914 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 915 } 916 917 public ArrayList<String> get(int userId, String packageName) { 918 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 919 return packages.get(packageName); 920 } 921 922 public void put(int userId, String packageName, ArrayList<String> components) { 923 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 924 packages.put(packageName, components); 925 } 926 927 public void remove(int userId, String packageName) { 928 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 929 if (packages != null) { 930 packages.remove(packageName); 931 } 932 } 933 934 public void remove(int userId) { 935 mUidMap.remove(userId); 936 } 937 938 public int userIdCount() { 939 return mUidMap.size(); 940 } 941 942 public int userIdAt(int n) { 943 return mUidMap.keyAt(n); 944 } 945 946 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 947 return mUidMap.get(userId); 948 } 949 950 public int size() { 951 // total number of pending broadcast entries across all userIds 952 int num = 0; 953 for (int i = 0; i< mUidMap.size(); i++) { 954 num += mUidMap.valueAt(i).size(); 955 } 956 return num; 957 } 958 959 public void clear() { 960 mUidMap.clear(); 961 } 962 963 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 964 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 965 if (map == null) { 966 map = new ArrayMap<String, ArrayList<String>>(); 967 mUidMap.put(userId, map); 968 } 969 return map; 970 } 971 } 972 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 973 974 // Service Connection to remote media container service to copy 975 // package uri's from external media onto secure containers 976 // or internal storage. 977 private IMediaContainerService mContainerService = null; 978 979 static final int SEND_PENDING_BROADCAST = 1; 980 static final int MCS_BOUND = 3; 981 static final int END_COPY = 4; 982 static final int INIT_COPY = 5; 983 static final int MCS_UNBIND = 6; 984 static final int START_CLEANING_PACKAGE = 7; 985 static final int FIND_INSTALL_LOC = 8; 986 static final int POST_INSTALL = 9; 987 static final int MCS_RECONNECT = 10; 988 static final int MCS_GIVE_UP = 11; 989 static final int UPDATED_MEDIA_STATUS = 12; 990 static final int WRITE_SETTINGS = 13; 991 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 992 static final int PACKAGE_VERIFIED = 15; 993 static final int CHECK_PENDING_VERIFICATION = 16; 994 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 995 static final int INTENT_FILTER_VERIFIED = 18; 996 997 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 998 999 // Delay time in millisecs 1000 static final int BROADCAST_DELAY = 10 * 1000; 1001 1002 static UserManagerService sUserManager; 1003 1004 // Stores a list of users whose package restrictions file needs to be updated 1005 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1006 1007 final private DefaultContainerConnection mDefContainerConn = 1008 new DefaultContainerConnection(); 1009 class DefaultContainerConnection implements ServiceConnection { 1010 public void onServiceConnected(ComponentName name, IBinder service) { 1011 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1012 IMediaContainerService imcs = 1013 IMediaContainerService.Stub.asInterface(service); 1014 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1015 } 1016 1017 public void onServiceDisconnected(ComponentName name) { 1018 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1019 } 1020 } 1021 1022 // Recordkeeping of restore-after-install operations that are currently in flight 1023 // between the Package Manager and the Backup Manager 1024 static class PostInstallData { 1025 public InstallArgs args; 1026 public PackageInstalledInfo res; 1027 1028 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1029 args = _a; 1030 res = _r; 1031 } 1032 } 1033 1034 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1035 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1036 1037 // XML tags for backup/restore of various bits of state 1038 private static final String TAG_PREFERRED_BACKUP = "pa"; 1039 private static final String TAG_DEFAULT_APPS = "da"; 1040 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1041 1042 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1043 private static final String TAG_ALL_GRANTS = "rt-grants"; 1044 private static final String TAG_GRANT = "grant"; 1045 private static final String ATTR_PACKAGE_NAME = "pkg"; 1046 1047 private static final String TAG_PERMISSION = "perm"; 1048 private static final String ATTR_PERMISSION_NAME = "name"; 1049 private static final String ATTR_IS_GRANTED = "g"; 1050 private static final String ATTR_USER_SET = "set"; 1051 private static final String ATTR_USER_FIXED = "fixed"; 1052 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1053 1054 // System/policy permission grants are not backed up 1055 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1056 FLAG_PERMISSION_POLICY_FIXED 1057 | FLAG_PERMISSION_SYSTEM_FIXED 1058 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1059 1060 // And we back up these user-adjusted states 1061 private static final int USER_RUNTIME_GRANT_MASK = 1062 FLAG_PERMISSION_USER_SET 1063 | FLAG_PERMISSION_USER_FIXED 1064 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1065 1066 final @Nullable String mRequiredVerifierPackage; 1067 final @Nullable String mRequiredInstallerPackage; 1068 final @Nullable String mSetupWizardPackage; 1069 1070 private final PackageUsage mPackageUsage = new PackageUsage(); 1071 1072 private class PackageUsage { 1073 private static final int WRITE_INTERVAL 1074 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1075 1076 private final Object mFileLock = new Object(); 1077 private final AtomicLong mLastWritten = new AtomicLong(0); 1078 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1079 1080 private boolean mIsHistoricalPackageUsageAvailable = true; 1081 1082 boolean isHistoricalPackageUsageAvailable() { 1083 return mIsHistoricalPackageUsageAvailable; 1084 } 1085 1086 void write(boolean force) { 1087 if (force) { 1088 writeInternal(); 1089 return; 1090 } 1091 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1092 && !DEBUG_DEXOPT) { 1093 return; 1094 } 1095 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1096 new Thread("PackageUsage_DiskWriter") { 1097 @Override 1098 public void run() { 1099 try { 1100 writeInternal(); 1101 } finally { 1102 mBackgroundWriteRunning.set(false); 1103 } 1104 } 1105 }.start(); 1106 } 1107 } 1108 1109 private void writeInternal() { 1110 synchronized (mPackages) { 1111 synchronized (mFileLock) { 1112 AtomicFile file = getFile(); 1113 FileOutputStream f = null; 1114 try { 1115 f = file.startWrite(); 1116 BufferedOutputStream out = new BufferedOutputStream(f); 1117 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1118 StringBuilder sb = new StringBuilder(); 1119 for (PackageParser.Package pkg : mPackages.values()) { 1120 if (pkg.mLastPackageUsageTimeInMills == 0) { 1121 continue; 1122 } 1123 sb.setLength(0); 1124 sb.append(pkg.packageName); 1125 sb.append(' '); 1126 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1127 sb.append('\n'); 1128 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1129 } 1130 out.flush(); 1131 file.finishWrite(f); 1132 } catch (IOException e) { 1133 if (f != null) { 1134 file.failWrite(f); 1135 } 1136 Log.e(TAG, "Failed to write package usage times", e); 1137 } 1138 } 1139 } 1140 mLastWritten.set(SystemClock.elapsedRealtime()); 1141 } 1142 1143 void readLP() { 1144 synchronized (mFileLock) { 1145 AtomicFile file = getFile(); 1146 BufferedInputStream in = null; 1147 try { 1148 in = new BufferedInputStream(file.openRead()); 1149 StringBuffer sb = new StringBuffer(); 1150 while (true) { 1151 String packageName = readToken(in, sb, ' '); 1152 if (packageName == null) { 1153 break; 1154 } 1155 String timeInMillisString = readToken(in, sb, '\n'); 1156 if (timeInMillisString == null) { 1157 throw new IOException("Failed to find last usage time for package " 1158 + packageName); 1159 } 1160 PackageParser.Package pkg = mPackages.get(packageName); 1161 if (pkg == null) { 1162 continue; 1163 } 1164 long timeInMillis; 1165 try { 1166 timeInMillis = Long.parseLong(timeInMillisString); 1167 } catch (NumberFormatException e) { 1168 throw new IOException("Failed to parse " + timeInMillisString 1169 + " as a long.", e); 1170 } 1171 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1172 } 1173 } catch (FileNotFoundException expected) { 1174 mIsHistoricalPackageUsageAvailable = false; 1175 } catch (IOException e) { 1176 Log.w(TAG, "Failed to read package usage times", e); 1177 } finally { 1178 IoUtils.closeQuietly(in); 1179 } 1180 } 1181 mLastWritten.set(SystemClock.elapsedRealtime()); 1182 } 1183 1184 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1185 throws IOException { 1186 sb.setLength(0); 1187 while (true) { 1188 int ch = in.read(); 1189 if (ch == -1) { 1190 if (sb.length() == 0) { 1191 return null; 1192 } 1193 throw new IOException("Unexpected EOF"); 1194 } 1195 if (ch == endOfToken) { 1196 return sb.toString(); 1197 } 1198 sb.append((char)ch); 1199 } 1200 } 1201 1202 private AtomicFile getFile() { 1203 File dataDir = Environment.getDataDirectory(); 1204 File systemDir = new File(dataDir, "system"); 1205 File fname = new File(systemDir, "package-usage.list"); 1206 return new AtomicFile(fname); 1207 } 1208 } 1209 1210 class PackageHandler extends Handler { 1211 private boolean mBound = false; 1212 final ArrayList<HandlerParams> mPendingInstalls = 1213 new ArrayList<HandlerParams>(); 1214 1215 private boolean connectToService() { 1216 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1217 " DefaultContainerService"); 1218 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1219 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1220 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1221 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1222 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1223 mBound = true; 1224 return true; 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 return false; 1228 } 1229 1230 private void disconnectService() { 1231 mContainerService = null; 1232 mBound = false; 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 mContext.unbindService(mDefContainerConn); 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1236 } 1237 1238 PackageHandler(Looper looper) { 1239 super(looper); 1240 } 1241 1242 public void handleMessage(Message msg) { 1243 try { 1244 doHandleMessage(msg); 1245 } finally { 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 } 1248 } 1249 1250 void doHandleMessage(Message msg) { 1251 switch (msg.what) { 1252 case INIT_COPY: { 1253 HandlerParams params = (HandlerParams) msg.obj; 1254 int idx = mPendingInstalls.size(); 1255 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1256 // If a bind was already initiated we dont really 1257 // need to do anything. The pending install 1258 // will be processed later on. 1259 if (!mBound) { 1260 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1261 System.identityHashCode(mHandler)); 1262 // If this is the only one pending we might 1263 // have to bind to the service again. 1264 if (!connectToService()) { 1265 Slog.e(TAG, "Failed to bind to media container service"); 1266 params.serviceError(); 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1268 System.identityHashCode(mHandler)); 1269 if (params.traceMethod != null) { 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1271 params.traceCookie); 1272 } 1273 return; 1274 } else { 1275 // Once we bind to the service, the first 1276 // pending request will be processed. 1277 mPendingInstalls.add(idx, params); 1278 } 1279 } else { 1280 mPendingInstalls.add(idx, params); 1281 // Already bound to the service. Just make 1282 // sure we trigger off processing the first request. 1283 if (idx == 0) { 1284 mHandler.sendEmptyMessage(MCS_BOUND); 1285 } 1286 } 1287 break; 1288 } 1289 case MCS_BOUND: { 1290 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1291 if (msg.obj != null) { 1292 mContainerService = (IMediaContainerService) msg.obj; 1293 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1294 System.identityHashCode(mHandler)); 1295 } 1296 if (mContainerService == null) { 1297 if (!mBound) { 1298 // Something seriously wrong since we are not bound and we are not 1299 // waiting for connection. Bail out. 1300 Slog.e(TAG, "Cannot bind to media container service"); 1301 for (HandlerParams params : mPendingInstalls) { 1302 // Indicate service bind error 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1305 System.identityHashCode(params)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1308 params.traceMethod, params.traceCookie); 1309 } 1310 return; 1311 } 1312 mPendingInstalls.clear(); 1313 } else { 1314 Slog.w(TAG, "Waiting to connect to media container service"); 1315 } 1316 } else if (mPendingInstalls.size() > 0) { 1317 HandlerParams params = mPendingInstalls.get(0); 1318 if (params != null) { 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1322 if (params.startCopy()) { 1323 // We are done... look for more work or to 1324 // go idle. 1325 if (DEBUG_SD_INSTALL) Log.i(TAG, 1326 "Checking for more work or unbind..."); 1327 // Delete pending install 1328 if (mPendingInstalls.size() > 0) { 1329 mPendingInstalls.remove(0); 1330 } 1331 if (mPendingInstalls.size() == 0) { 1332 if (mBound) { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, 1334 "Posting delayed MCS_UNBIND"); 1335 removeMessages(MCS_UNBIND); 1336 Message ubmsg = obtainMessage(MCS_UNBIND); 1337 // Unbind after a little delay, to avoid 1338 // continual thrashing. 1339 sendMessageDelayed(ubmsg, 10000); 1340 } 1341 } else { 1342 // There are more pending requests in queue. 1343 // Just post MCS_BOUND message to trigger processing 1344 // of next pending install. 1345 if (DEBUG_SD_INSTALL) Log.i(TAG, 1346 "Posting MCS_BOUND for next work"); 1347 mHandler.sendEmptyMessage(MCS_BOUND); 1348 } 1349 } 1350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1351 } 1352 } else { 1353 // Should never happen ideally. 1354 Slog.w(TAG, "Empty queue"); 1355 } 1356 break; 1357 } 1358 case MCS_RECONNECT: { 1359 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1360 if (mPendingInstalls.size() > 0) { 1361 if (mBound) { 1362 disconnectService(); 1363 } 1364 if (!connectToService()) { 1365 Slog.e(TAG, "Failed to bind to media container service"); 1366 for (HandlerParams params : mPendingInstalls) { 1367 // Indicate service bind error 1368 params.serviceError(); 1369 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1370 System.identityHashCode(params)); 1371 } 1372 mPendingInstalls.clear(); 1373 } 1374 } 1375 break; 1376 } 1377 case MCS_UNBIND: { 1378 // If there is no actual work left, then time to unbind. 1379 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1380 1381 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1382 if (mBound) { 1383 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1384 1385 disconnectService(); 1386 } 1387 } else if (mPendingInstalls.size() > 0) { 1388 // There are more pending requests in queue. 1389 // Just post MCS_BOUND message to trigger processing 1390 // of next pending install. 1391 mHandler.sendEmptyMessage(MCS_BOUND); 1392 } 1393 1394 break; 1395 } 1396 case MCS_GIVE_UP: { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1398 HandlerParams params = mPendingInstalls.remove(0); 1399 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1400 System.identityHashCode(params)); 1401 break; 1402 } 1403 case SEND_PENDING_BROADCAST: { 1404 String packages[]; 1405 ArrayList<String> components[]; 1406 int size = 0; 1407 int uids[]; 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1409 synchronized (mPackages) { 1410 if (mPendingBroadcasts == null) { 1411 return; 1412 } 1413 size = mPendingBroadcasts.size(); 1414 if (size <= 0) { 1415 // Nothing to be done. Just return 1416 return; 1417 } 1418 packages = new String[size]; 1419 components = new ArrayList[size]; 1420 uids = new int[size]; 1421 int i = 0; // filling out the above arrays 1422 1423 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1424 int packageUserId = mPendingBroadcasts.userIdAt(n); 1425 Iterator<Map.Entry<String, ArrayList<String>>> it 1426 = mPendingBroadcasts.packagesForUserId(packageUserId) 1427 .entrySet().iterator(); 1428 while (it.hasNext() && i < size) { 1429 Map.Entry<String, ArrayList<String>> ent = it.next(); 1430 packages[i] = ent.getKey(); 1431 components[i] = ent.getValue(); 1432 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1433 uids[i] = (ps != null) 1434 ? UserHandle.getUid(packageUserId, ps.appId) 1435 : -1; 1436 i++; 1437 } 1438 } 1439 size = i; 1440 mPendingBroadcasts.clear(); 1441 } 1442 // Send broadcasts 1443 for (int i = 0; i < size; i++) { 1444 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1445 } 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1447 break; 1448 } 1449 case START_CLEANING_PACKAGE: { 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1451 final String packageName = (String)msg.obj; 1452 final int userId = msg.arg1; 1453 final boolean andCode = msg.arg2 != 0; 1454 synchronized (mPackages) { 1455 if (userId == UserHandle.USER_ALL) { 1456 int[] users = sUserManager.getUserIds(); 1457 for (int user : users) { 1458 mSettings.addPackageToCleanLPw( 1459 new PackageCleanItem(user, packageName, andCode)); 1460 } 1461 } else { 1462 mSettings.addPackageToCleanLPw( 1463 new PackageCleanItem(userId, packageName, andCode)); 1464 } 1465 } 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1467 startCleaningPackages(); 1468 } break; 1469 case POST_INSTALL: { 1470 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1471 1472 PostInstallData data = mRunningInstalls.get(msg.arg1); 1473 mRunningInstalls.delete(msg.arg1); 1474 1475 if (data != null) { 1476 InstallArgs args = data.args; 1477 PackageInstalledInfo parentRes = data.res; 1478 1479 final boolean grantPermissions = (args.installFlags 1480 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1481 final boolean killApp = (args.installFlags 1482 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1483 final String[] grantedPermissions = args.installGrantPermissions; 1484 1485 // Handle the parent package 1486 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1487 grantedPermissions, args.observer); 1488 1489 // Handle the child packages 1490 final int childCount = (parentRes.addedChildPackages != null) 1491 ? parentRes.addedChildPackages.size() : 0; 1492 for (int i = 0; i < childCount; i++) { 1493 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1494 handlePackagePostInstall(childRes, grantPermissions, killApp, 1495 grantedPermissions, args.observer); 1496 } 1497 1498 // Log tracing if needed 1499 if (args.traceMethod != null) { 1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1501 args.traceCookie); 1502 } 1503 } else { 1504 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1505 } 1506 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1508 } break; 1509 case UPDATED_MEDIA_STATUS: { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1511 boolean reportStatus = msg.arg1 == 1; 1512 boolean doGc = msg.arg2 == 1; 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1514 if (doGc) { 1515 // Force a gc to clear up stale containers. 1516 Runtime.getRuntime().gc(); 1517 } 1518 if (msg.obj != null) { 1519 @SuppressWarnings("unchecked") 1520 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1521 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1522 // Unload containers 1523 unloadAllContainers(args); 1524 } 1525 if (reportStatus) { 1526 try { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1528 PackageHelper.getMountService().finishMediaUpdate(); 1529 } catch (RemoteException e) { 1530 Log.e(TAG, "MountService not running?"); 1531 } 1532 } 1533 } break; 1534 case WRITE_SETTINGS: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_SETTINGS); 1538 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1539 mSettings.writeLPr(); 1540 mDirtyUsers.clear(); 1541 } 1542 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1543 } break; 1544 case WRITE_PACKAGE_RESTRICTIONS: { 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1546 synchronized (mPackages) { 1547 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1548 for (int userId : mDirtyUsers) { 1549 mSettings.writePackageRestrictionsLPr(userId); 1550 } 1551 mDirtyUsers.clear(); 1552 } 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1554 } break; 1555 case CHECK_PENDING_VERIFICATION: { 1556 final int verificationId = msg.arg1; 1557 final PackageVerificationState state = mPendingVerification.get(verificationId); 1558 1559 if ((state != null) && !state.timeoutExtended()) { 1560 final InstallArgs args = state.getInstallArgs(); 1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1562 1563 Slog.i(TAG, "Verification timed out for " + originUri); 1564 mPendingVerification.remove(verificationId); 1565 1566 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1567 1568 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1569 Slog.i(TAG, "Continuing with installation of " + originUri); 1570 state.setVerifierResponse(Binder.getCallingUid(), 1571 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1572 broadcastPackageVerified(verificationId, originUri, 1573 PackageManager.VERIFICATION_ALLOW, 1574 state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 broadcastPackageVerified(verificationId, originUri, 1582 PackageManager.VERIFICATION_REJECT, 1583 state.getInstallArgs().getUser()); 1584 } 1585 1586 Trace.asyncTraceEnd( 1587 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1588 1589 processPendingInstall(args, ret); 1590 mHandler.sendEmptyMessage(MCS_UNBIND); 1591 } 1592 break; 1593 } 1594 case PACKAGE_VERIFIED: { 1595 final int verificationId = msg.arg1; 1596 1597 final PackageVerificationState state = mPendingVerification.get(verificationId); 1598 if (state == null) { 1599 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1600 break; 1601 } 1602 1603 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1604 1605 state.setVerifierResponse(response.callerUid, response.code); 1606 1607 if (state.isVerificationComplete()) { 1608 mPendingVerification.remove(verificationId); 1609 1610 final InstallArgs args = state.getInstallArgs(); 1611 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1612 1613 int ret; 1614 if (state.isInstallAllowed()) { 1615 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1616 broadcastPackageVerified(verificationId, originUri, 1617 response.code, state.getInstallArgs().getUser()); 1618 try { 1619 ret = args.copyApk(mContainerService, true); 1620 } catch (RemoteException e) { 1621 Slog.e(TAG, "Could not contact the ContainerService"); 1622 } 1623 } else { 1624 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1625 } 1626 1627 Trace.asyncTraceEnd( 1628 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1629 1630 processPendingInstall(args, ret); 1631 mHandler.sendEmptyMessage(MCS_UNBIND); 1632 } 1633 1634 break; 1635 } 1636 case START_INTENT_FILTER_VERIFICATIONS: { 1637 IFVerificationParams params = (IFVerificationParams) msg.obj; 1638 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1639 params.replacing, params.pkg); 1640 break; 1641 } 1642 case INTENT_FILTER_VERIFIED: { 1643 final int verificationId = msg.arg1; 1644 1645 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1646 verificationId); 1647 if (state == null) { 1648 Slog.w(TAG, "Invalid IntentFilter verification token " 1649 + verificationId + " received"); 1650 break; 1651 } 1652 1653 final int userId = state.getUserId(); 1654 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1656 "Processing IntentFilter verification with token:" 1657 + verificationId + " and userId:" + userId); 1658 1659 final IntentFilterVerificationResponse response = 1660 (IntentFilterVerificationResponse) msg.obj; 1661 1662 state.setVerifierResponse(response.callerUid, response.code); 1663 1664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1665 "IntentFilter verification with token:" + verificationId 1666 + " and userId:" + userId 1667 + " is settings verifier response with response code:" 1668 + response.code); 1669 1670 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1671 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1672 + response.getFailedDomainsString()); 1673 } 1674 1675 if (state.isVerificationComplete()) { 1676 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1677 } else { 1678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1679 "IntentFilter verification with token:" + verificationId 1680 + " was not said to be complete"); 1681 } 1682 1683 break; 1684 } 1685 } 1686 } 1687 } 1688 1689 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1690 boolean killApp, String[] grantedPermissions, 1691 IPackageInstallObserver2 installObserver) { 1692 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1693 // Send the removed broadcasts 1694 if (res.removedInfo != null) { 1695 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1696 } 1697 1698 // Now that we successfully installed the package, grant runtime 1699 // permissions if requested before broadcasting the install. 1700 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1701 >= Build.VERSION_CODES.M) { 1702 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1703 } 1704 1705 final boolean update = res.removedInfo != null 1706 && res.removedInfo.removedPackage != null; 1707 1708 // If this is the first time we have child packages for a disabled privileged 1709 // app that had no children, we grant requested runtime permissions to the new 1710 // children if the parent on the system image had them already granted. 1711 if (res.pkg.parentPackage != null) { 1712 synchronized (mPackages) { 1713 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1714 } 1715 } 1716 1717 synchronized (mPackages) { 1718 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1719 } 1720 1721 final String packageName = res.pkg.applicationInfo.packageName; 1722 Bundle extras = new Bundle(1); 1723 extras.putInt(Intent.EXTRA_UID, res.uid); 1724 1725 // Determine the set of users who are adding this package for 1726 // the first time vs. those who are seeing an update. 1727 int[] firstUsers = EMPTY_INT_ARRAY; 1728 int[] updateUsers = EMPTY_INT_ARRAY; 1729 if (res.origUsers == null || res.origUsers.length == 0) { 1730 firstUsers = res.newUsers; 1731 } else { 1732 for (int newUser : res.newUsers) { 1733 boolean isNew = true; 1734 for (int origUser : res.origUsers) { 1735 if (origUser == newUser) { 1736 isNew = false; 1737 break; 1738 } 1739 } 1740 if (isNew) { 1741 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1742 } else { 1743 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1744 } 1745 } 1746 } 1747 1748 // Send installed broadcasts if the install/update is not ephemeral 1749 if (!isEphemeral(res.pkg)) { 1750 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1751 1752 // Send added for users that see the package for the first time 1753 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1754 extras, 0 /*flags*/, null /*targetPackage*/, 1755 null /*finishedReceiver*/, firstUsers); 1756 1757 // Send added for users that don't see the package for the first time 1758 if (update) { 1759 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1760 } 1761 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1762 extras, 0 /*flags*/, null /*targetPackage*/, 1763 null /*finishedReceiver*/, updateUsers); 1764 1765 // Send replaced for users that don't see the package for the first time 1766 if (update) { 1767 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1768 packageName, extras, 0 /*flags*/, 1769 null /*targetPackage*/, null /*finishedReceiver*/, 1770 updateUsers); 1771 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1772 null /*package*/, null /*extras*/, 0 /*flags*/, 1773 packageName /*targetPackage*/, 1774 null /*finishedReceiver*/, updateUsers); 1775 } 1776 1777 // Send broadcast package appeared if forward locked/external for all users 1778 // treat asec-hosted packages like removable media on upgrade 1779 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1780 if (DEBUG_INSTALL) { 1781 Slog.i(TAG, "upgrading pkg " + res.pkg 1782 + " is ASEC-hosted -> AVAILABLE"); 1783 } 1784 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1785 ArrayList<String> pkgList = new ArrayList<>(1); 1786 pkgList.add(packageName); 1787 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1788 } 1789 } 1790 1791 // Work that needs to happen on first install within each user 1792 if (firstUsers != null && firstUsers.length > 0) { 1793 synchronized (mPackages) { 1794 for (int userId : firstUsers) { 1795 // If this app is a browser and it's newly-installed for some 1796 // users, clear any default-browser state in those users. The 1797 // app's nature doesn't depend on the user, so we can just check 1798 // its browser nature in any user and generalize. 1799 if (packageIsBrowser(packageName, userId)) { 1800 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1801 } 1802 1803 // We may also need to apply pending (restored) runtime 1804 // permission grants within these users. 1805 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1806 } 1807 } 1808 } 1809 1810 // Log current value of "unknown sources" setting 1811 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1812 getUnknownSourcesSettings()); 1813 1814 // Force a gc to clear up things 1815 Runtime.getRuntime().gc(); 1816 1817 // Remove the replaced package's older resources safely now 1818 // We delete after a gc for applications on sdcard. 1819 if (res.removedInfo != null && res.removedInfo.args != null) { 1820 synchronized (mInstallLock) { 1821 res.removedInfo.args.doPostDeleteLI(true); 1822 } 1823 } 1824 } 1825 1826 // If someone is watching installs - notify them 1827 if (installObserver != null) { 1828 try { 1829 Bundle extras = extrasForInstallResult(res); 1830 installObserver.onPackageInstalled(res.name, res.returnCode, 1831 res.returnMsg, extras); 1832 } catch (RemoteException e) { 1833 Slog.i(TAG, "Observer no longer exists."); 1834 } 1835 } 1836 } 1837 1838 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1839 PackageParser.Package pkg) { 1840 if (pkg.parentPackage == null) { 1841 return; 1842 } 1843 if (pkg.requestedPermissions == null) { 1844 return; 1845 } 1846 final PackageSetting disabledSysParentPs = mSettings 1847 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1848 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1849 || !disabledSysParentPs.isPrivileged() 1850 || (disabledSysParentPs.childPackageNames != null 1851 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1852 return; 1853 } 1854 final int[] allUserIds = sUserManager.getUserIds(); 1855 final int permCount = pkg.requestedPermissions.size(); 1856 for (int i = 0; i < permCount; i++) { 1857 String permission = pkg.requestedPermissions.get(i); 1858 BasePermission bp = mSettings.mPermissions.get(permission); 1859 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1860 continue; 1861 } 1862 for (int userId : allUserIds) { 1863 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1864 permission, userId)) { 1865 grantRuntimePermission(pkg.packageName, permission, userId); 1866 } 1867 } 1868 } 1869 } 1870 1871 private StorageEventListener mStorageListener = new StorageEventListener() { 1872 @Override 1873 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1874 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1875 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1876 final String volumeUuid = vol.getFsUuid(); 1877 1878 // Clean up any users or apps that were removed or recreated 1879 // while this volume was missing 1880 reconcileUsers(volumeUuid); 1881 reconcileApps(volumeUuid); 1882 1883 // Clean up any install sessions that expired or were 1884 // cancelled while this volume was missing 1885 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1886 1887 loadPrivatePackages(vol); 1888 1889 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1890 unloadPrivatePackages(vol); 1891 } 1892 } 1893 1894 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1895 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1896 updateExternalMediaStatus(true, false); 1897 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1898 updateExternalMediaStatus(false, false); 1899 } 1900 } 1901 } 1902 1903 @Override 1904 public void onVolumeForgotten(String fsUuid) { 1905 if (TextUtils.isEmpty(fsUuid)) { 1906 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1907 return; 1908 } 1909 1910 // Remove any apps installed on the forgotten volume 1911 synchronized (mPackages) { 1912 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1913 for (PackageSetting ps : packages) { 1914 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1915 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1916 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1917 } 1918 1919 mSettings.onVolumeForgotten(fsUuid); 1920 mSettings.writeLPr(); 1921 } 1922 } 1923 }; 1924 1925 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1926 String[] grantedPermissions) { 1927 for (int userId : userIds) { 1928 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1929 } 1930 1931 // We could have touched GID membership, so flush out packages.list 1932 synchronized (mPackages) { 1933 mSettings.writePackageListLPr(); 1934 } 1935 } 1936 1937 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1938 String[] grantedPermissions) { 1939 SettingBase sb = (SettingBase) pkg.mExtras; 1940 if (sb == null) { 1941 return; 1942 } 1943 1944 PermissionsState permissionsState = sb.getPermissionsState(); 1945 1946 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1947 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1948 1949 synchronized (mPackages) { 1950 for (String permission : pkg.requestedPermissions) { 1951 BasePermission bp = mSettings.mPermissions.get(permission); 1952 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1953 && (grantedPermissions == null 1954 || ArrayUtils.contains(grantedPermissions, permission))) { 1955 final int flags = permissionsState.getPermissionFlags(permission, userId); 1956 // Installer cannot change immutable permissions. 1957 if ((flags & immutableFlags) == 0) { 1958 grantRuntimePermission(pkg.packageName, permission, userId); 1959 } 1960 } 1961 } 1962 } 1963 } 1964 1965 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1966 Bundle extras = null; 1967 switch (res.returnCode) { 1968 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1969 extras = new Bundle(); 1970 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1971 res.origPermission); 1972 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1973 res.origPackage); 1974 break; 1975 } 1976 case PackageManager.INSTALL_SUCCEEDED: { 1977 extras = new Bundle(); 1978 extras.putBoolean(Intent.EXTRA_REPLACING, 1979 res.removedInfo != null && res.removedInfo.removedPackage != null); 1980 break; 1981 } 1982 } 1983 return extras; 1984 } 1985 1986 void scheduleWriteSettingsLocked() { 1987 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1988 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1989 } 1990 } 1991 1992 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1993 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1994 scheduleWritePackageRestrictionsLocked(userId); 1995 } 1996 1997 void scheduleWritePackageRestrictionsLocked(int userId) { 1998 final int[] userIds = (userId == UserHandle.USER_ALL) 1999 ? sUserManager.getUserIds() : new int[]{userId}; 2000 for (int nextUserId : userIds) { 2001 if (!sUserManager.exists(nextUserId)) return; 2002 mDirtyUsers.add(nextUserId); 2003 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2004 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2005 } 2006 } 2007 } 2008 2009 public static PackageManagerService main(Context context, Installer installer, 2010 boolean factoryTest, boolean onlyCore) { 2011 // Self-check for initial settings. 2012 PackageManagerServiceCompilerMapping.checkProperties(); 2013 2014 PackageManagerService m = new PackageManagerService(context, installer, 2015 factoryTest, onlyCore); 2016 m.enableSystemUserPackages(); 2017 ServiceManager.addService("package", m); 2018 return m; 2019 } 2020 2021 private void enableSystemUserPackages() { 2022 if (!UserManager.isSplitSystemUser()) { 2023 return; 2024 } 2025 // For system user, enable apps based on the following conditions: 2026 // - app is whitelisted or belong to one of these groups: 2027 // -- system app which has no launcher icons 2028 // -- system app which has INTERACT_ACROSS_USERS permission 2029 // -- system IME app 2030 // - app is not in the blacklist 2031 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2032 Set<String> enableApps = new ArraySet<>(); 2033 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2034 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2035 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2036 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2037 enableApps.addAll(wlApps); 2038 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2039 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2040 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2041 enableApps.removeAll(blApps); 2042 Log.i(TAG, "Applications installed for system user: " + enableApps); 2043 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2044 UserHandle.SYSTEM); 2045 final int allAppsSize = allAps.size(); 2046 synchronized (mPackages) { 2047 for (int i = 0; i < allAppsSize; i++) { 2048 String pName = allAps.get(i); 2049 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2050 // Should not happen, but we shouldn't be failing if it does 2051 if (pkgSetting == null) { 2052 continue; 2053 } 2054 boolean install = enableApps.contains(pName); 2055 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2056 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2057 + " for system user"); 2058 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2059 } 2060 } 2061 } 2062 } 2063 2064 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2065 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2066 Context.DISPLAY_SERVICE); 2067 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2068 } 2069 2070 public PackageManagerService(Context context, Installer installer, 2071 boolean factoryTest, boolean onlyCore) { 2072 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2073 SystemClock.uptimeMillis()); 2074 2075 if (mSdkVersion <= 0) { 2076 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2077 } 2078 2079 mContext = context; 2080 mFactoryTest = factoryTest; 2081 mOnlyCore = onlyCore; 2082 mMetrics = new DisplayMetrics(); 2083 mSettings = new Settings(mPackages); 2084 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2085 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2086 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2087 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2088 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2089 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2090 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2091 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2092 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2094 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2096 2097 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2098 if (separateProcesses != null && separateProcesses.length() > 0) { 2099 if ("*".equals(separateProcesses)) { 2100 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2101 mSeparateProcesses = null; 2102 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2103 } else { 2104 mDefParseFlags = 0; 2105 mSeparateProcesses = separateProcesses.split(","); 2106 Slog.w(TAG, "Running with debug.separate_processes: " 2107 + separateProcesses); 2108 } 2109 } else { 2110 mDefParseFlags = 0; 2111 mSeparateProcesses = null; 2112 } 2113 2114 mInstaller = installer; 2115 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2116 "*dexopt*"); 2117 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2118 2119 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2120 FgThread.get().getLooper()); 2121 2122 getDefaultDisplayMetrics(context, mMetrics); 2123 2124 SystemConfig systemConfig = SystemConfig.getInstance(); 2125 mGlobalGids = systemConfig.getGlobalGids(); 2126 mSystemPermissions = systemConfig.getSystemPermissions(); 2127 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2128 2129 synchronized (mInstallLock) { 2130 // writer 2131 synchronized (mPackages) { 2132 mHandlerThread = new ServiceThread(TAG, 2133 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2134 mHandlerThread.start(); 2135 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2136 mProcessLoggingHandler = new ProcessLoggingHandler(); 2137 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2138 2139 File dataDir = Environment.getDataDirectory(); 2140 mAppInstallDir = new File(dataDir, "app"); 2141 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2142 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2143 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2144 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2145 2146 sUserManager = new UserManagerService(context, this, mPackages); 2147 2148 // Propagate permission configuration in to package manager. 2149 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2150 = systemConfig.getPermissions(); 2151 for (int i=0; i<permConfig.size(); i++) { 2152 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2153 BasePermission bp = mSettings.mPermissions.get(perm.name); 2154 if (bp == null) { 2155 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2156 mSettings.mPermissions.put(perm.name, bp); 2157 } 2158 if (perm.gids != null) { 2159 bp.setGids(perm.gids, perm.perUser); 2160 } 2161 } 2162 2163 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2164 for (int i=0; i<libConfig.size(); i++) { 2165 mSharedLibraries.put(libConfig.keyAt(i), 2166 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2167 } 2168 2169 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2170 2171 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2172 2173 String customResolverActivity = Resources.getSystem().getString( 2174 R.string.config_customResolverActivity); 2175 if (TextUtils.isEmpty(customResolverActivity)) { 2176 customResolverActivity = null; 2177 } else { 2178 mCustomResolverComponentName = ComponentName.unflattenFromString( 2179 customResolverActivity); 2180 } 2181 2182 long startTime = SystemClock.uptimeMillis(); 2183 2184 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2185 startTime); 2186 2187 // Set flag to monitor and not change apk file paths when 2188 // scanning install directories. 2189 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2190 2191 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2192 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2193 2194 if (bootClassPath == null) { 2195 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2196 } 2197 2198 if (systemServerClassPath == null) { 2199 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2200 } 2201 2202 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2203 final String[] dexCodeInstructionSets = 2204 getDexCodeInstructionSets( 2205 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2206 2207 /** 2208 * Ensure all external libraries have had dexopt run on them. 2209 */ 2210 if (mSharedLibraries.size() > 0) { 2211 // NOTE: For now, we're compiling these system "shared libraries" 2212 // (and framework jars) into all available architectures. It's possible 2213 // to compile them only when we come across an app that uses them (there's 2214 // already logic for that in scanPackageLI) but that adds some complexity. 2215 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2216 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2217 final String lib = libEntry.path; 2218 if (lib == null) { 2219 continue; 2220 } 2221 2222 try { 2223 // Shared libraries do not have profiles so we perform a full 2224 // AOT compilation (if needed). 2225 int dexoptNeeded = DexFile.getDexOptNeeded( 2226 lib, dexCodeInstructionSet, 2227 getCompilerFilterForReason(REASON_SHARED_APK), 2228 false /* newProfile */); 2229 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2230 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2231 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2232 getCompilerFilterForReason(REASON_SHARED_APK), 2233 StorageManager.UUID_PRIVATE_INTERNAL); 2234 } 2235 } catch (FileNotFoundException e) { 2236 Slog.w(TAG, "Library not found: " + lib); 2237 } catch (IOException | InstallerException e) { 2238 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2239 + e.getMessage()); 2240 } 2241 } 2242 } 2243 } 2244 2245 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2246 2247 final VersionInfo ver = mSettings.getInternalVersion(); 2248 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2249 2250 // when upgrading from pre-M, promote system app permissions from install to runtime 2251 mPromoteSystemApps = 2252 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2253 2254 // save off the names of pre-existing system packages prior to scanning; we don't 2255 // want to automatically grant runtime permissions for new system apps 2256 if (mPromoteSystemApps) { 2257 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2258 while (pkgSettingIter.hasNext()) { 2259 PackageSetting ps = pkgSettingIter.next(); 2260 if (isSystemApp(ps)) { 2261 mExistingSystemPackages.add(ps.name); 2262 } 2263 } 2264 } 2265 2266 // When upgrading from pre-N, we need to handle package extraction like first boot, 2267 // as there is no profiling data available. 2268 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2269 mSettings.setNWorkDone(); 2270 2271 // Collect vendor overlay packages. 2272 // (Do this before scanning any apps.) 2273 // For security and version matching reason, only consider 2274 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2275 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2276 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2278 2279 // Find base frameworks (resource packages without code). 2280 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR 2282 | PackageParser.PARSE_IS_PRIVILEGED, 2283 scanFlags | SCAN_NO_DEX, 0); 2284 2285 // Collected privileged system packages. 2286 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2287 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2288 | PackageParser.PARSE_IS_SYSTEM_DIR 2289 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2290 2291 // Collect ordinary system packages. 2292 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2293 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2294 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2295 2296 // Collect all vendor packages. 2297 File vendorAppDir = new File("/vendor/app"); 2298 try { 2299 vendorAppDir = vendorAppDir.getCanonicalFile(); 2300 } catch (IOException e) { 2301 // failed to look up canonical path, continue with original one 2302 } 2303 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2305 2306 // Collect all OEM packages. 2307 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2308 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2309 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2310 2311 // Prune any system packages that no longer exist. 2312 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2313 if (!mOnlyCore) { 2314 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2315 while (psit.hasNext()) { 2316 PackageSetting ps = psit.next(); 2317 2318 /* 2319 * If this is not a system app, it can't be a 2320 * disable system app. 2321 */ 2322 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2323 continue; 2324 } 2325 2326 /* 2327 * If the package is scanned, it's not erased. 2328 */ 2329 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2330 if (scannedPkg != null) { 2331 /* 2332 * If the system app is both scanned and in the 2333 * disabled packages list, then it must have been 2334 * added via OTA. Remove it from the currently 2335 * scanned package so the previously user-installed 2336 * application can be scanned. 2337 */ 2338 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2339 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2340 + ps.name + "; removing system app. Last known codePath=" 2341 + ps.codePathString + ", installStatus=" + ps.installStatus 2342 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2343 + scannedPkg.mVersionCode); 2344 removePackageLI(scannedPkg, true); 2345 mExpectingBetter.put(ps.name, ps.codePath); 2346 } 2347 2348 continue; 2349 } 2350 2351 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2352 psit.remove(); 2353 logCriticalInfo(Log.WARN, "System package " + ps.name 2354 + " no longer exists; wiping its data"); 2355 removeDataDirsLI(null, ps.name); 2356 } else { 2357 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2358 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2359 possiblyDeletedUpdatedSystemApps.add(ps.name); 2360 } 2361 } 2362 } 2363 } 2364 2365 //look for any incomplete package installations 2366 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2367 //clean up list 2368 for(int i = 0; i < deletePkgsList.size(); i++) { 2369 //clean up here 2370 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2371 } 2372 //delete tmp files 2373 deleteTempPackageFiles(); 2374 2375 // Remove any shared userIDs that have no associated packages 2376 mSettings.pruneSharedUsersLPw(); 2377 2378 if (!mOnlyCore) { 2379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2380 SystemClock.uptimeMillis()); 2381 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2382 2383 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2384 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2385 2386 scanDirLI(mEphemeralInstallDir, 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; wiping its data"; 2403 removeDataDirsLI(null, deletedAppName); 2404 } else { 2405 msg = "Updated system app + " + deletedAppName 2406 + " no longer present; removing system privileges for " 2407 + deletedAppName; 2408 2409 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2410 2411 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2412 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2413 } 2414 logCriticalInfo(Log.WARN, msg); 2415 } 2416 2417 /** 2418 * Make sure all system apps that we expected to appear on 2419 * the userdata partition actually showed up. If they never 2420 * appeared, crawl back and revive the system version. 2421 */ 2422 for (int i = 0; i < mExpectingBetter.size(); i++) { 2423 final String packageName = mExpectingBetter.keyAt(i); 2424 if (!mPackages.containsKey(packageName)) { 2425 final File scanFile = mExpectingBetter.valueAt(i); 2426 2427 logCriticalInfo(Log.WARN, "Expected better " + packageName 2428 + " but never showed up; reverting to system"); 2429 2430 final int reparseFlags; 2431 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2432 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2433 | PackageParser.PARSE_IS_SYSTEM_DIR 2434 | PackageParser.PARSE_IS_PRIVILEGED; 2435 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2436 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR; 2438 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2439 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR; 2441 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2442 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR; 2444 } else { 2445 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2446 continue; 2447 } 2448 2449 mSettings.enableSystemPackageLPw(packageName); 2450 2451 try { 2452 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2453 } catch (PackageManagerException e) { 2454 Slog.e(TAG, "Failed to parse original system package: " 2455 + e.getMessage()); 2456 } 2457 } 2458 } 2459 } 2460 mExpectingBetter.clear(); 2461 2462 // Resolve protected action filters. Only the setup wizard is allowed to 2463 // have a high priority filter for these actions. 2464 mSetupWizardPackage = getSetupWizardPackageName(); 2465 if (mProtectedFilters.size() > 0) { 2466 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2467 Slog.i(TAG, "No setup wizard;" 2468 + " All protected intents capped to priority 0"); 2469 } 2470 for (ActivityIntentInfo filter : mProtectedFilters) { 2471 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2472 if (DEBUG_FILTERS) { 2473 Slog.i(TAG, "Found setup wizard;" 2474 + " allow priority " + filter.getPriority() + ";" 2475 + " package: " + filter.activity.info.packageName 2476 + " activity: " + filter.activity.className 2477 + " priority: " + filter.getPriority()); 2478 } 2479 // skip setup wizard; allow it to keep the high priority filter 2480 continue; 2481 } 2482 Slog.w(TAG, "Protected action; cap priority to 0;" 2483 + " package: " + filter.activity.info.packageName 2484 + " activity: " + filter.activity.className 2485 + " origPrio: " + filter.getPriority()); 2486 filter.setPriority(0); 2487 } 2488 } 2489 mDeferProtectedFilters = false; 2490 mProtectedFilters.clear(); 2491 2492 // Now that we know all of the shared libraries, update all clients to have 2493 // the correct library paths. 2494 updateAllSharedLibrariesLPw(); 2495 2496 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2497 // NOTE: We ignore potential failures here during a system scan (like 2498 // the rest of the commands above) because there's precious little we 2499 // can do about it. A settings error is reported, though. 2500 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2501 false /* boot complete */); 2502 } 2503 2504 // Now that we know all the packages we are keeping, 2505 // read and update their last usage times. 2506 mPackageUsage.readLP(); 2507 2508 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2509 SystemClock.uptimeMillis()); 2510 Slog.i(TAG, "Time to scan packages: " 2511 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2512 + " seconds"); 2513 2514 // If the platform SDK has changed since the last time we booted, 2515 // we need to re-grant app permission to catch any new ones that 2516 // appear. This is really a hack, and means that apps can in some 2517 // cases get permissions that the user didn't initially explicitly 2518 // allow... it would be nice to have some better way to handle 2519 // this situation. 2520 int updateFlags = UPDATE_PERMISSIONS_ALL; 2521 if (ver.sdkVersion != mSdkVersion) { 2522 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2523 + mSdkVersion + "; regranting permissions for internal storage"); 2524 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2525 } 2526 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2527 ver.sdkVersion = mSdkVersion; 2528 2529 // If this is the first boot or an update from pre-M, and it is a normal 2530 // boot, then we need to initialize the default preferred apps across 2531 // all defined users. 2532 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2533 for (UserInfo user : sUserManager.getUsers(true)) { 2534 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2535 applyFactoryDefaultBrowserLPw(user.id); 2536 primeDomainVerificationsLPw(user.id); 2537 } 2538 } 2539 2540 // Prepare storage for system user really early during boot, 2541 // since core system apps like SettingsProvider and SystemUI 2542 // can't wait for user to start 2543 final int storageFlags; 2544 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2545 storageFlags = StorageManager.FLAG_STORAGE_DE; 2546 } else { 2547 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2548 } 2549 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2550 storageFlags); 2551 2552 // If this is first boot after an OTA, and a normal boot, then 2553 // we need to clear code cache directories. 2554 if (mIsUpgrade && !onlyCore) { 2555 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2556 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2557 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2558 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2559 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2560 } 2561 } 2562 ver.fingerprint = Build.FINGERPRINT; 2563 } 2564 2565 checkDefaultBrowser(); 2566 2567 // clear only after permissions and other defaults have been updated 2568 mExistingSystemPackages.clear(); 2569 mPromoteSystemApps = false; 2570 2571 // All the changes are done during package scanning. 2572 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2573 2574 // can downgrade to reader 2575 mSettings.writeLPr(); 2576 2577 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2578 SystemClock.uptimeMillis()); 2579 2580 if (!mOnlyCore) { 2581 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2582 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2583 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2584 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2585 mIntentFilterVerifierComponent); 2586 } else { 2587 mRequiredVerifierPackage = null; 2588 mRequiredInstallerPackage = null; 2589 mIntentFilterVerifierComponent = null; 2590 mIntentFilterVerifier = null; 2591 } 2592 2593 mInstallerService = new PackageInstallerService(context, this); 2594 2595 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2596 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2597 // both the installer and resolver must be present to enable ephemeral 2598 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2599 if (DEBUG_EPHEMERAL) { 2600 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2601 + " installer:" + ephemeralInstallerComponent); 2602 } 2603 mEphemeralResolverComponent = ephemeralResolverComponent; 2604 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2605 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2606 mEphemeralResolverConnection = 2607 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2608 } else { 2609 if (DEBUG_EPHEMERAL) { 2610 final String missingComponent = 2611 (ephemeralResolverComponent == null) 2612 ? (ephemeralInstallerComponent == null) 2613 ? "resolver and installer" 2614 : "resolver" 2615 : "installer"; 2616 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2617 } 2618 mEphemeralResolverComponent = null; 2619 mEphemeralInstallerComponent = null; 2620 mEphemeralResolverConnection = null; 2621 } 2622 2623 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2624 } // synchronized (mPackages) 2625 } // synchronized (mInstallLock) 2626 2627 // Now after opening every single application zip, make sure they 2628 // are all flushed. Not really needed, but keeps things nice and 2629 // tidy. 2630 Runtime.getRuntime().gc(); 2631 2632 // The initial scanning above does many calls into installd while 2633 // holding the mPackages lock, but we're mostly interested in yelling 2634 // once we have a booted system. 2635 mInstaller.setWarnIfHeld(mPackages); 2636 2637 // Expose private service for system components to use. 2638 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2639 } 2640 2641 @Override 2642 public boolean isFirstBoot() { 2643 return !mRestoredSettings; 2644 } 2645 2646 @Override 2647 public boolean isOnlyCoreApps() { 2648 return mOnlyCore; 2649 } 2650 2651 @Override 2652 public boolean isUpgrade() { 2653 return mIsUpgrade; 2654 } 2655 2656 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2657 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2658 2659 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2660 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2661 UserHandle.USER_SYSTEM); 2662 if (matches.size() == 1) { 2663 return matches.get(0).getComponentInfo().packageName; 2664 } else { 2665 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2666 return null; 2667 } 2668 } 2669 2670 private @NonNull String getRequiredInstallerLPr() { 2671 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2672 intent.addCategory(Intent.CATEGORY_DEFAULT); 2673 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2674 2675 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2676 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2677 UserHandle.USER_SYSTEM); 2678 if (matches.size() == 1) { 2679 return matches.get(0).getComponentInfo().packageName; 2680 } else { 2681 throw new RuntimeException("There must be exactly one installer; found " + matches); 2682 } 2683 } 2684 2685 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2686 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2687 2688 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2689 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2690 UserHandle.USER_SYSTEM); 2691 ResolveInfo best = null; 2692 final int N = matches.size(); 2693 for (int i = 0; i < N; i++) { 2694 final ResolveInfo cur = matches.get(i); 2695 final String packageName = cur.getComponentInfo().packageName; 2696 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2697 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2698 continue; 2699 } 2700 2701 if (best == null || cur.priority > best.priority) { 2702 best = cur; 2703 } 2704 } 2705 2706 if (best != null) { 2707 return best.getComponentInfo().getComponentName(); 2708 } else { 2709 throw new RuntimeException("There must be at least one intent filter verifier"); 2710 } 2711 } 2712 2713 private @Nullable ComponentName getEphemeralResolverLPr() { 2714 final String[] packageArray = 2715 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2716 if (packageArray.length == 0) { 2717 if (DEBUG_EPHEMERAL) { 2718 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2719 } 2720 return null; 2721 } 2722 2723 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2724 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2725 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2726 UserHandle.USER_SYSTEM); 2727 2728 final int N = resolvers.size(); 2729 if (N == 0) { 2730 if (DEBUG_EPHEMERAL) { 2731 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2732 } 2733 return null; 2734 } 2735 2736 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2737 for (int i = 0; i < N; i++) { 2738 final ResolveInfo info = resolvers.get(i); 2739 2740 if (info.serviceInfo == null) { 2741 continue; 2742 } 2743 2744 final String packageName = info.serviceInfo.packageName; 2745 if (!possiblePackages.contains(packageName)) { 2746 if (DEBUG_EPHEMERAL) { 2747 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2748 + " pkg: " + packageName + ", info:" + info); 2749 } 2750 continue; 2751 } 2752 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.v(TAG, "Ephemeral resolver found;" 2755 + " pkg: " + packageName + ", info:" + info); 2756 } 2757 return new ComponentName(packageName, info.serviceInfo.name); 2758 } 2759 if (DEBUG_EPHEMERAL) { 2760 Slog.v(TAG, "Ephemeral resolver NOT found"); 2761 } 2762 return null; 2763 } 2764 2765 private @Nullable ComponentName getEphemeralInstallerLPr() { 2766 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2767 intent.addCategory(Intent.CATEGORY_DEFAULT); 2768 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2769 2770 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2771 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2772 UserHandle.USER_SYSTEM); 2773 if (matches.size() == 0) { 2774 return null; 2775 } else if (matches.size() == 1) { 2776 return matches.get(0).getComponentInfo().getComponentName(); 2777 } else { 2778 throw new RuntimeException( 2779 "There must be at most one ephemeral installer; found " + matches); 2780 } 2781 } 2782 2783 private void primeDomainVerificationsLPw(int userId) { 2784 if (DEBUG_DOMAIN_VERIFICATION) { 2785 Slog.d(TAG, "Priming domain verifications in user " + userId); 2786 } 2787 2788 SystemConfig systemConfig = SystemConfig.getInstance(); 2789 ArraySet<String> packages = systemConfig.getLinkedApps(); 2790 ArraySet<String> domains = new ArraySet<String>(); 2791 2792 for (String packageName : packages) { 2793 PackageParser.Package pkg = mPackages.get(packageName); 2794 if (pkg != null) { 2795 if (!pkg.isSystemApp()) { 2796 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2797 continue; 2798 } 2799 2800 domains.clear(); 2801 for (PackageParser.Activity a : pkg.activities) { 2802 for (ActivityIntentInfo filter : a.intents) { 2803 if (hasValidDomains(filter)) { 2804 domains.addAll(filter.getHostsList()); 2805 } 2806 } 2807 } 2808 2809 if (domains.size() > 0) { 2810 if (DEBUG_DOMAIN_VERIFICATION) { 2811 Slog.v(TAG, " + " + packageName); 2812 } 2813 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2814 // state w.r.t. the formal app-linkage "no verification attempted" state; 2815 // and then 'always' in the per-user state actually used for intent resolution. 2816 final IntentFilterVerificationInfo ivi; 2817 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2818 new ArrayList<String>(domains)); 2819 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2820 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2821 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2822 } else { 2823 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2824 + "' does not handle web links"); 2825 } 2826 } else { 2827 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2828 } 2829 } 2830 2831 scheduleWritePackageRestrictionsLocked(userId); 2832 scheduleWriteSettingsLocked(); 2833 } 2834 2835 private void applyFactoryDefaultBrowserLPw(int userId) { 2836 // The default browser app's package name is stored in a string resource, 2837 // with a product-specific overlay used for vendor customization. 2838 String browserPkg = mContext.getResources().getString( 2839 com.android.internal.R.string.default_browser); 2840 if (!TextUtils.isEmpty(browserPkg)) { 2841 // non-empty string => required to be a known package 2842 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2843 if (ps == null) { 2844 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2845 browserPkg = null; 2846 } else { 2847 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2848 } 2849 } 2850 2851 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2852 // default. If there's more than one, just leave everything alone. 2853 if (browserPkg == null) { 2854 calculateDefaultBrowserLPw(userId); 2855 } 2856 } 2857 2858 private void calculateDefaultBrowserLPw(int userId) { 2859 List<String> allBrowsers = resolveAllBrowserApps(userId); 2860 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2861 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2862 } 2863 2864 private List<String> resolveAllBrowserApps(int userId) { 2865 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2866 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2867 PackageManager.MATCH_ALL, userId); 2868 2869 final int count = list.size(); 2870 List<String> result = new ArrayList<String>(count); 2871 for (int i=0; i<count; i++) { 2872 ResolveInfo info = list.get(i); 2873 if (info.activityInfo == null 2874 || !info.handleAllWebDataURI 2875 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2876 || result.contains(info.activityInfo.packageName)) { 2877 continue; 2878 } 2879 result.add(info.activityInfo.packageName); 2880 } 2881 2882 return result; 2883 } 2884 2885 private boolean packageIsBrowser(String packageName, int userId) { 2886 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2887 PackageManager.MATCH_ALL, userId); 2888 final int N = list.size(); 2889 for (int i = 0; i < N; i++) { 2890 ResolveInfo info = list.get(i); 2891 if (packageName.equals(info.activityInfo.packageName)) { 2892 return true; 2893 } 2894 } 2895 return false; 2896 } 2897 2898 private void checkDefaultBrowser() { 2899 final int myUserId = UserHandle.myUserId(); 2900 final String packageName = getDefaultBrowserPackageName(myUserId); 2901 if (packageName != null) { 2902 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2903 if (info == null) { 2904 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2905 synchronized (mPackages) { 2906 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2907 } 2908 } 2909 } 2910 } 2911 2912 @Override 2913 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2914 throws RemoteException { 2915 try { 2916 return super.onTransact(code, data, reply, flags); 2917 } catch (RuntimeException e) { 2918 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2919 Slog.wtf(TAG, "Package Manager Crash", e); 2920 } 2921 throw e; 2922 } 2923 } 2924 2925 void cleanupInstallFailedPackage(PackageSetting ps) { 2926 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2927 2928 removeDataDirsLI(ps.volumeUuid, ps.name); 2929 if (ps.codePath != null) { 2930 removeCodePathLI(ps.codePath); 2931 } 2932 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2933 if (ps.resourcePath.isDirectory()) { 2934 FileUtils.deleteContents(ps.resourcePath); 2935 } 2936 ps.resourcePath.delete(); 2937 } 2938 mSettings.removePackageLPw(ps.name); 2939 } 2940 2941 static int[] appendInts(int[] cur, int[] add) { 2942 if (add == null) return cur; 2943 if (cur == null) return add; 2944 final int N = add.length; 2945 for (int i=0; i<N; i++) { 2946 cur = appendInt(cur, add[i]); 2947 } 2948 return cur; 2949 } 2950 2951 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 2952 if (!sUserManager.exists(userId)) return null; 2953 if (ps == null) { 2954 return null; 2955 } 2956 final PackageParser.Package p = ps.pkg; 2957 if (p == null) { 2958 return null; 2959 } 2960 2961 final PermissionsState permissionsState = ps.getPermissionsState(); 2962 2963 final int[] gids = permissionsState.computeGids(userId); 2964 final Set<String> permissions = permissionsState.getPermissions(userId); 2965 final PackageUserState state = ps.readUserState(userId); 2966 2967 return PackageParser.generatePackageInfo(p, gids, flags, 2968 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2969 } 2970 2971 @Override 2972 public void checkPackageStartable(String packageName, int userId) { 2973 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2974 2975 synchronized (mPackages) { 2976 final PackageSetting ps = mSettings.mPackages.get(packageName); 2977 if (ps == null) { 2978 throw new SecurityException("Package " + packageName + " was not found!"); 2979 } 2980 2981 if (!ps.getInstalled(userId)) { 2982 throw new SecurityException( 2983 "Package " + packageName + " was not installed for user " + userId + "!"); 2984 } 2985 2986 if (mSafeMode && !ps.isSystem()) { 2987 throw new SecurityException("Package " + packageName + " not a system app!"); 2988 } 2989 2990 if (ps.frozen) { 2991 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2992 } 2993 2994 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2995 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2996 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2997 } 2998 } 2999 } 3000 3001 @Override 3002 public boolean isPackageAvailable(String packageName, int userId) { 3003 if (!sUserManager.exists(userId)) return false; 3004 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3005 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3006 synchronized (mPackages) { 3007 PackageParser.Package p = mPackages.get(packageName); 3008 if (p != null) { 3009 final PackageSetting ps = (PackageSetting) p.mExtras; 3010 if (ps != null) { 3011 final PackageUserState state = ps.readUserState(userId); 3012 if (state != null) { 3013 return PackageParser.isAvailable(state); 3014 } 3015 } 3016 } 3017 } 3018 return false; 3019 } 3020 3021 @Override 3022 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 flags = updateFlagsForPackage(flags, userId, packageName); 3025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3026 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3027 // reader 3028 synchronized (mPackages) { 3029 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3030 PackageParser.Package p = null; 3031 if (matchFactoryOnly) { 3032 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3033 if (ps != null) { 3034 return generatePackageInfo(ps, flags, userId); 3035 } 3036 } 3037 if (p == null) { 3038 p = mPackages.get(packageName); 3039 if (matchFactoryOnly && !isSystemApp(p)) { 3040 return null; 3041 } 3042 } 3043 if (DEBUG_PACKAGE_INFO) 3044 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3045 if (p != null) { 3046 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3047 } 3048 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3049 final PackageSetting ps = mSettings.mPackages.get(packageName); 3050 return generatePackageInfo(ps, flags, userId); 3051 } 3052 } 3053 return null; 3054 } 3055 3056 @Override 3057 public String[] currentToCanonicalPackageNames(String[] names) { 3058 String[] out = new String[names.length]; 3059 // reader 3060 synchronized (mPackages) { 3061 for (int i=names.length-1; i>=0; i--) { 3062 PackageSetting ps = mSettings.mPackages.get(names[i]); 3063 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3064 } 3065 } 3066 return out; 3067 } 3068 3069 @Override 3070 public String[] canonicalToCurrentPackageNames(String[] names) { 3071 String[] out = new String[names.length]; 3072 // reader 3073 synchronized (mPackages) { 3074 for (int i=names.length-1; i>=0; i--) { 3075 String cur = mSettings.mRenamedPackages.get(names[i]); 3076 out[i] = cur != null ? cur : names[i]; 3077 } 3078 } 3079 return out; 3080 } 3081 3082 @Override 3083 public int getPackageUid(String packageName, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return -1; 3085 flags = updateFlagsForPackage(flags, userId, packageName); 3086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3087 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3088 3089 // reader 3090 synchronized (mPackages) { 3091 final PackageParser.Package p = mPackages.get(packageName); 3092 if (p != null && p.isMatch(flags)) { 3093 return UserHandle.getUid(userId, p.applicationInfo.uid); 3094 } 3095 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3096 final PackageSetting ps = mSettings.mPackages.get(packageName); 3097 if (ps != null && ps.isMatch(flags)) { 3098 return UserHandle.getUid(userId, ps.appId); 3099 } 3100 } 3101 } 3102 3103 return -1; 3104 } 3105 3106 @Override 3107 public int[] getPackageGids(String packageName, int flags, int userId) { 3108 if (!sUserManager.exists(userId)) return null; 3109 flags = updateFlagsForPackage(flags, userId, packageName); 3110 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3111 false /* requireFullPermission */, false /* checkShell */, 3112 "getPackageGids"); 3113 3114 // reader 3115 synchronized (mPackages) { 3116 final PackageParser.Package p = mPackages.get(packageName); 3117 if (p != null && p.isMatch(flags)) { 3118 PackageSetting ps = (PackageSetting) p.mExtras; 3119 return ps.getPermissionsState().computeGids(userId); 3120 } 3121 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps != null && ps.isMatch(flags)) { 3124 return ps.getPermissionsState().computeGids(userId); 3125 } 3126 } 3127 } 3128 3129 return null; 3130 } 3131 3132 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3133 if (bp.perm != null) { 3134 return PackageParser.generatePermissionInfo(bp.perm, flags); 3135 } 3136 PermissionInfo pi = new PermissionInfo(); 3137 pi.name = bp.name; 3138 pi.packageName = bp.sourcePackage; 3139 pi.nonLocalizedLabel = bp.name; 3140 pi.protectionLevel = bp.protectionLevel; 3141 return pi; 3142 } 3143 3144 @Override 3145 public PermissionInfo getPermissionInfo(String name, int flags) { 3146 // reader 3147 synchronized (mPackages) { 3148 final BasePermission p = mSettings.mPermissions.get(name); 3149 if (p != null) { 3150 return generatePermissionInfo(p, flags); 3151 } 3152 return null; 3153 } 3154 } 3155 3156 @Override 3157 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3158 int flags) { 3159 // reader 3160 synchronized (mPackages) { 3161 if (group != null && !mPermissionGroups.containsKey(group)) { 3162 // This is thrown as NameNotFoundException 3163 return null; 3164 } 3165 3166 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3167 for (BasePermission p : mSettings.mPermissions.values()) { 3168 if (group == null) { 3169 if (p.perm == null || p.perm.info.group == null) { 3170 out.add(generatePermissionInfo(p, flags)); 3171 } 3172 } else { 3173 if (p.perm != null && group.equals(p.perm.info.group)) { 3174 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3175 } 3176 } 3177 } 3178 return new ParceledListSlice<>(out); 3179 } 3180 } 3181 3182 @Override 3183 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3184 // reader 3185 synchronized (mPackages) { 3186 return PackageParser.generatePermissionGroupInfo( 3187 mPermissionGroups.get(name), flags); 3188 } 3189 } 3190 3191 @Override 3192 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3193 // reader 3194 synchronized (mPackages) { 3195 final int N = mPermissionGroups.size(); 3196 ArrayList<PermissionGroupInfo> out 3197 = new ArrayList<PermissionGroupInfo>(N); 3198 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3199 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3200 } 3201 return new ParceledListSlice<>(out); 3202 } 3203 } 3204 3205 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3206 int userId) { 3207 if (!sUserManager.exists(userId)) return null; 3208 PackageSetting ps = mSettings.mPackages.get(packageName); 3209 if (ps != null) { 3210 if (ps.pkg == null) { 3211 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3212 if (pInfo != null) { 3213 return pInfo.applicationInfo; 3214 } 3215 return null; 3216 } 3217 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3218 ps.readUserState(userId), userId); 3219 } 3220 return null; 3221 } 3222 3223 @Override 3224 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3225 if (!sUserManager.exists(userId)) return null; 3226 flags = updateFlagsForApplication(flags, userId, packageName); 3227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3228 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3229 // writer 3230 synchronized (mPackages) { 3231 PackageParser.Package p = mPackages.get(packageName); 3232 if (DEBUG_PACKAGE_INFO) Log.v( 3233 TAG, "getApplicationInfo " + packageName 3234 + ": " + p); 3235 if (p != null) { 3236 PackageSetting ps = mSettings.mPackages.get(packageName); 3237 if (ps == null) return null; 3238 // Note: isEnabledLP() does not apply here - always return info 3239 return PackageParser.generateApplicationInfo( 3240 p, flags, ps.readUserState(userId), userId); 3241 } 3242 if ("android".equals(packageName)||"system".equals(packageName)) { 3243 return mAndroidApplication; 3244 } 3245 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3246 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3247 } 3248 } 3249 return null; 3250 } 3251 3252 @Override 3253 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3254 final IPackageDataObserver observer) { 3255 mContext.enforceCallingOrSelfPermission( 3256 android.Manifest.permission.CLEAR_APP_CACHE, null); 3257 // Queue up an async operation since clearing cache may take a little while. 3258 mHandler.post(new Runnable() { 3259 public void run() { 3260 mHandler.removeCallbacks(this); 3261 boolean success = true; 3262 synchronized (mInstallLock) { 3263 try { 3264 mInstaller.freeCache(volumeUuid, freeStorageSize); 3265 } catch (InstallerException e) { 3266 Slog.w(TAG, "Couldn't clear application caches: " + e); 3267 success = false; 3268 } 3269 } 3270 if (observer != null) { 3271 try { 3272 observer.onRemoveCompleted(null, success); 3273 } catch (RemoteException e) { 3274 Slog.w(TAG, "RemoveException when invoking call back"); 3275 } 3276 } 3277 } 3278 }); 3279 } 3280 3281 @Override 3282 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3283 final IntentSender pi) { 3284 mContext.enforceCallingOrSelfPermission( 3285 android.Manifest.permission.CLEAR_APP_CACHE, null); 3286 // Queue up an async operation since clearing cache may take a little while. 3287 mHandler.post(new Runnable() { 3288 public void run() { 3289 mHandler.removeCallbacks(this); 3290 boolean success = true; 3291 synchronized (mInstallLock) { 3292 try { 3293 mInstaller.freeCache(volumeUuid, freeStorageSize); 3294 } catch (InstallerException e) { 3295 Slog.w(TAG, "Couldn't clear application caches: " + e); 3296 success = false; 3297 } 3298 } 3299 if(pi != null) { 3300 try { 3301 // Callback via pending intent 3302 int code = success ? 1 : 0; 3303 pi.sendIntent(null, code, null, 3304 null, null); 3305 } catch (SendIntentException e1) { 3306 Slog.i(TAG, "Failed to send pending intent"); 3307 } 3308 } 3309 } 3310 }); 3311 } 3312 3313 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3314 synchronized (mInstallLock) { 3315 try { 3316 mInstaller.freeCache(volumeUuid, freeStorageSize); 3317 } catch (InstallerException e) { 3318 throw new IOException("Failed to free enough space", e); 3319 } 3320 } 3321 } 3322 3323 /** 3324 * Return if the user key is currently unlocked. 3325 */ 3326 private boolean isUserKeyUnlocked(int userId) { 3327 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3328 final IMountService mount = IMountService.Stub 3329 .asInterface(ServiceManager.getService("mount")); 3330 if (mount == null) { 3331 Slog.w(TAG, "Early during boot, assuming locked"); 3332 return false; 3333 } 3334 final long token = Binder.clearCallingIdentity(); 3335 try { 3336 return mount.isUserKeyUnlocked(userId); 3337 } catch (RemoteException e) { 3338 throw e.rethrowAsRuntimeException(); 3339 } finally { 3340 Binder.restoreCallingIdentity(token); 3341 } 3342 } else { 3343 return true; 3344 } 3345 } 3346 3347 /** 3348 * Update given flags based on encryption status of current user. 3349 */ 3350 private int updateFlags(int flags, int userId) { 3351 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3352 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3353 // Caller expressed an explicit opinion about what encryption 3354 // aware/unaware components they want to see, so fall through and 3355 // give them what they want 3356 } else { 3357 // Caller expressed no opinion, so match based on user state 3358 if (isUserKeyUnlocked(userId)) { 3359 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3360 } else { 3361 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3362 } 3363 } 3364 return flags; 3365 } 3366 3367 /** 3368 * Update given flags when being used to request {@link PackageInfo}. 3369 */ 3370 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3371 boolean triaged = true; 3372 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3373 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3374 // Caller is asking for component details, so they'd better be 3375 // asking for specific encryption matching behavior, or be triaged 3376 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3377 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3378 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3379 triaged = false; 3380 } 3381 } 3382 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3383 | PackageManager.MATCH_SYSTEM_ONLY 3384 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3385 triaged = false; 3386 } 3387 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3388 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3389 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3390 } 3391 return updateFlags(flags, userId); 3392 } 3393 3394 /** 3395 * Update given flags when being used to request {@link ApplicationInfo}. 3396 */ 3397 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3398 return updateFlagsForPackage(flags, userId, cookie); 3399 } 3400 3401 /** 3402 * Update given flags when being used to request {@link ComponentInfo}. 3403 */ 3404 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3405 if (cookie instanceof Intent) { 3406 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3407 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3408 } 3409 } 3410 3411 boolean triaged = true; 3412 // Caller is asking for component details, so they'd better be 3413 // asking for specific encryption matching behavior, or be triaged 3414 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3415 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3416 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3417 triaged = false; 3418 } 3419 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3420 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3421 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3422 } 3423 3424 return updateFlags(flags, userId); 3425 } 3426 3427 /** 3428 * Update given flags when being used to request {@link ResolveInfo}. 3429 */ 3430 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3431 // Safe mode means we shouldn't match any third-party components 3432 if (mSafeMode) { 3433 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3434 } 3435 3436 return updateFlagsForComponent(flags, userId, cookie); 3437 } 3438 3439 @Override 3440 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3441 if (!sUserManager.exists(userId)) return null; 3442 flags = updateFlagsForComponent(flags, userId, component); 3443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3444 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3445 synchronized (mPackages) { 3446 PackageParser.Activity a = mActivities.mActivities.get(component); 3447 3448 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3449 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3450 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3451 if (ps == null) return null; 3452 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3453 userId); 3454 } 3455 if (mResolveComponentName.equals(component)) { 3456 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3457 new PackageUserState(), userId); 3458 } 3459 } 3460 return null; 3461 } 3462 3463 @Override 3464 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3465 String resolvedType) { 3466 synchronized (mPackages) { 3467 if (component.equals(mResolveComponentName)) { 3468 // The resolver supports EVERYTHING! 3469 return true; 3470 } 3471 PackageParser.Activity a = mActivities.mActivities.get(component); 3472 if (a == null) { 3473 return false; 3474 } 3475 for (int i=0; i<a.intents.size(); i++) { 3476 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3477 intent.getData(), intent.getCategories(), TAG) >= 0) { 3478 return true; 3479 } 3480 } 3481 return false; 3482 } 3483 } 3484 3485 @Override 3486 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3487 if (!sUserManager.exists(userId)) return null; 3488 flags = updateFlagsForComponent(flags, userId, component); 3489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3490 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3491 synchronized (mPackages) { 3492 PackageParser.Activity a = mReceivers.mActivities.get(component); 3493 if (DEBUG_PACKAGE_INFO) Log.v( 3494 TAG, "getReceiverInfo " + component + ": " + a); 3495 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3496 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3497 if (ps == null) return null; 3498 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3499 userId); 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3507 if (!sUserManager.exists(userId)) return null; 3508 flags = updateFlagsForComponent(flags, userId, component); 3509 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3510 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3511 synchronized (mPackages) { 3512 PackageParser.Service s = mServices.mServices.get(component); 3513 if (DEBUG_PACKAGE_INFO) Log.v( 3514 TAG, "getServiceInfo " + component + ": " + s); 3515 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3516 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3517 if (ps == null) return null; 3518 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3519 userId); 3520 } 3521 } 3522 return null; 3523 } 3524 3525 @Override 3526 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3527 if (!sUserManager.exists(userId)) return null; 3528 flags = updateFlagsForComponent(flags, userId, component); 3529 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3530 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3531 synchronized (mPackages) { 3532 PackageParser.Provider p = mProviders.mProviders.get(component); 3533 if (DEBUG_PACKAGE_INFO) Log.v( 3534 TAG, "getProviderInfo " + component + ": " + p); 3535 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3536 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3537 if (ps == null) return null; 3538 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3539 userId); 3540 } 3541 } 3542 return null; 3543 } 3544 3545 @Override 3546 public String[] getSystemSharedLibraryNames() { 3547 Set<String> libSet; 3548 synchronized (mPackages) { 3549 libSet = mSharedLibraries.keySet(); 3550 int size = libSet.size(); 3551 if (size > 0) { 3552 String[] libs = new String[size]; 3553 libSet.toArray(libs); 3554 return libs; 3555 } 3556 } 3557 return null; 3558 } 3559 3560 @Override 3561 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3562 synchronized (mPackages) { 3563 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3564 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3565 if (libraryEntry != null) { 3566 return libraryEntry.apk; 3567 } 3568 } 3569 return null; 3570 } 3571 3572 @Override 3573 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3574 synchronized (mPackages) { 3575 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3576 3577 final FeatureInfo fi = new FeatureInfo(); 3578 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3579 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3580 res.add(fi); 3581 3582 return new ParceledListSlice<>(res); 3583 } 3584 } 3585 3586 @Override 3587 public boolean hasSystemFeature(String name, int version) { 3588 synchronized (mPackages) { 3589 final FeatureInfo feat = mAvailableFeatures.get(name); 3590 if (feat == null) { 3591 return false; 3592 } else { 3593 return feat.version >= version; 3594 } 3595 } 3596 } 3597 3598 @Override 3599 public int checkPermission(String permName, String pkgName, int userId) { 3600 if (!sUserManager.exists(userId)) { 3601 return PackageManager.PERMISSION_DENIED; 3602 } 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package p = mPackages.get(pkgName); 3606 if (p != null && p.mExtras != null) { 3607 final PackageSetting ps = (PackageSetting) p.mExtras; 3608 final PermissionsState permissionsState = ps.getPermissionsState(); 3609 if (permissionsState.hasPermission(permName, userId)) { 3610 return PackageManager.PERMISSION_GRANTED; 3611 } 3612 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3613 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3614 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3615 return PackageManager.PERMISSION_GRANTED; 3616 } 3617 } 3618 } 3619 3620 return PackageManager.PERMISSION_DENIED; 3621 } 3622 3623 @Override 3624 public int checkUidPermission(String permName, int uid) { 3625 final int userId = UserHandle.getUserId(uid); 3626 3627 if (!sUserManager.exists(userId)) { 3628 return PackageManager.PERMISSION_DENIED; 3629 } 3630 3631 synchronized (mPackages) { 3632 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3633 if (obj != null) { 3634 final SettingBase ps = (SettingBase) obj; 3635 final PermissionsState permissionsState = ps.getPermissionsState(); 3636 if (permissionsState.hasPermission(permName, userId)) { 3637 return PackageManager.PERMISSION_GRANTED; 3638 } 3639 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3640 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3641 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3642 return PackageManager.PERMISSION_GRANTED; 3643 } 3644 } else { 3645 ArraySet<String> perms = mSystemPermissions.get(uid); 3646 if (perms != null) { 3647 if (perms.contains(permName)) { 3648 return PackageManager.PERMISSION_GRANTED; 3649 } 3650 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3651 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3652 return PackageManager.PERMISSION_GRANTED; 3653 } 3654 } 3655 } 3656 } 3657 3658 return PackageManager.PERMISSION_DENIED; 3659 } 3660 3661 @Override 3662 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3663 if (UserHandle.getCallingUserId() != userId) { 3664 mContext.enforceCallingPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "isPermissionRevokedByPolicy for user " + userId); 3667 } 3668 3669 if (checkPermission(permission, packageName, userId) 3670 == PackageManager.PERMISSION_GRANTED) { 3671 return false; 3672 } 3673 3674 final long identity = Binder.clearCallingIdentity(); 3675 try { 3676 final int flags = getPermissionFlags(permission, packageName, userId); 3677 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3678 } finally { 3679 Binder.restoreCallingIdentity(identity); 3680 } 3681 } 3682 3683 @Override 3684 public String getPermissionControllerPackageName() { 3685 synchronized (mPackages) { 3686 return mRequiredInstallerPackage; 3687 } 3688 } 3689 3690 /** 3691 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3692 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3693 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3694 * @param message the message to log on security exception 3695 */ 3696 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3697 boolean checkShell, String message) { 3698 if (userId < 0) { 3699 throw new IllegalArgumentException("Invalid userId " + userId); 3700 } 3701 if (checkShell) { 3702 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3703 } 3704 if (userId == UserHandle.getUserId(callingUid)) return; 3705 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3706 if (requireFullPermission) { 3707 mContext.enforceCallingOrSelfPermission( 3708 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3709 } else { 3710 try { 3711 mContext.enforceCallingOrSelfPermission( 3712 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3713 } catch (SecurityException se) { 3714 mContext.enforceCallingOrSelfPermission( 3715 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3716 } 3717 } 3718 } 3719 } 3720 3721 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3722 if (callingUid == Process.SHELL_UID) { 3723 if (userHandle >= 0 3724 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3725 throw new SecurityException("Shell does not have permission to access user " 3726 + userHandle); 3727 } else if (userHandle < 0) { 3728 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3729 + Debug.getCallers(3)); 3730 } 3731 } 3732 } 3733 3734 private BasePermission findPermissionTreeLP(String permName) { 3735 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3736 if (permName.startsWith(bp.name) && 3737 permName.length() > bp.name.length() && 3738 permName.charAt(bp.name.length()) == '.') { 3739 return bp; 3740 } 3741 } 3742 return null; 3743 } 3744 3745 private BasePermission checkPermissionTreeLP(String permName) { 3746 if (permName != null) { 3747 BasePermission bp = findPermissionTreeLP(permName); 3748 if (bp != null) { 3749 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3750 return bp; 3751 } 3752 throw new SecurityException("Calling uid " 3753 + Binder.getCallingUid() 3754 + " is not allowed to add to permission tree " 3755 + bp.name + " owned by uid " + bp.uid); 3756 } 3757 } 3758 throw new SecurityException("No permission tree found for " + permName); 3759 } 3760 3761 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3762 if (s1 == null) { 3763 return s2 == null; 3764 } 3765 if (s2 == null) { 3766 return false; 3767 } 3768 if (s1.getClass() != s2.getClass()) { 3769 return false; 3770 } 3771 return s1.equals(s2); 3772 } 3773 3774 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3775 if (pi1.icon != pi2.icon) return false; 3776 if (pi1.logo != pi2.logo) return false; 3777 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3778 if (!compareStrings(pi1.name, pi2.name)) return false; 3779 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3780 // We'll take care of setting this one. 3781 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3782 // These are not currently stored in settings. 3783 //if (!compareStrings(pi1.group, pi2.group)) return false; 3784 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3785 //if (pi1.labelRes != pi2.labelRes) return false; 3786 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3787 return true; 3788 } 3789 3790 int permissionInfoFootprint(PermissionInfo info) { 3791 int size = info.name.length(); 3792 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3793 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3794 return size; 3795 } 3796 3797 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3798 int size = 0; 3799 for (BasePermission perm : mSettings.mPermissions.values()) { 3800 if (perm.uid == tree.uid) { 3801 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3802 } 3803 } 3804 return size; 3805 } 3806 3807 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3808 // We calculate the max size of permissions defined by this uid and throw 3809 // if that plus the size of 'info' would exceed our stated maximum. 3810 if (tree.uid != Process.SYSTEM_UID) { 3811 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3812 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3813 throw new SecurityException("Permission tree size cap exceeded"); 3814 } 3815 } 3816 } 3817 3818 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3819 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3820 throw new SecurityException("Label must be specified in permission"); 3821 } 3822 BasePermission tree = checkPermissionTreeLP(info.name); 3823 BasePermission bp = mSettings.mPermissions.get(info.name); 3824 boolean added = bp == null; 3825 boolean changed = true; 3826 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3827 if (added) { 3828 enforcePermissionCapLocked(info, tree); 3829 bp = new BasePermission(info.name, tree.sourcePackage, 3830 BasePermission.TYPE_DYNAMIC); 3831 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3832 throw new SecurityException( 3833 "Not allowed to modify non-dynamic permission " 3834 + info.name); 3835 } else { 3836 if (bp.protectionLevel == fixedLevel 3837 && bp.perm.owner.equals(tree.perm.owner) 3838 && bp.uid == tree.uid 3839 && comparePermissionInfos(bp.perm.info, info)) { 3840 changed = false; 3841 } 3842 } 3843 bp.protectionLevel = fixedLevel; 3844 info = new PermissionInfo(info); 3845 info.protectionLevel = fixedLevel; 3846 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3847 bp.perm.info.packageName = tree.perm.info.packageName; 3848 bp.uid = tree.uid; 3849 if (added) { 3850 mSettings.mPermissions.put(info.name, bp); 3851 } 3852 if (changed) { 3853 if (!async) { 3854 mSettings.writeLPr(); 3855 } else { 3856 scheduleWriteSettingsLocked(); 3857 } 3858 } 3859 return added; 3860 } 3861 3862 @Override 3863 public boolean addPermission(PermissionInfo info) { 3864 synchronized (mPackages) { 3865 return addPermissionLocked(info, false); 3866 } 3867 } 3868 3869 @Override 3870 public boolean addPermissionAsync(PermissionInfo info) { 3871 synchronized (mPackages) { 3872 return addPermissionLocked(info, true); 3873 } 3874 } 3875 3876 @Override 3877 public void removePermission(String name) { 3878 synchronized (mPackages) { 3879 checkPermissionTreeLP(name); 3880 BasePermission bp = mSettings.mPermissions.get(name); 3881 if (bp != null) { 3882 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3883 throw new SecurityException( 3884 "Not allowed to modify non-dynamic permission " 3885 + name); 3886 } 3887 mSettings.mPermissions.remove(name); 3888 mSettings.writeLPr(); 3889 } 3890 } 3891 } 3892 3893 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3894 BasePermission bp) { 3895 int index = pkg.requestedPermissions.indexOf(bp.name); 3896 if (index == -1) { 3897 throw new SecurityException("Package " + pkg.packageName 3898 + " has not requested permission " + bp.name); 3899 } 3900 if (!bp.isRuntime() && !bp.isDevelopment()) { 3901 throw new SecurityException("Permission " + bp.name 3902 + " is not a changeable permission type"); 3903 } 3904 } 3905 3906 @Override 3907 public void grantRuntimePermission(String packageName, String name, final int userId) { 3908 if (!sUserManager.exists(userId)) { 3909 Log.e(TAG, "No such user:" + userId); 3910 return; 3911 } 3912 3913 mContext.enforceCallingOrSelfPermission( 3914 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3915 "grantRuntimePermission"); 3916 3917 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3918 true /* requireFullPermission */, true /* checkShell */, 3919 "grantRuntimePermission"); 3920 3921 final int uid; 3922 final SettingBase sb; 3923 3924 synchronized (mPackages) { 3925 final PackageParser.Package pkg = mPackages.get(packageName); 3926 if (pkg == null) { 3927 throw new IllegalArgumentException("Unknown package: " + packageName); 3928 } 3929 3930 final BasePermission bp = mSettings.mPermissions.get(name); 3931 if (bp == null) { 3932 throw new IllegalArgumentException("Unknown permission: " + name); 3933 } 3934 3935 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3936 3937 // If a permission review is required for legacy apps we represent 3938 // their permissions as always granted runtime ones since we need 3939 // to keep the review required permission flag per user while an 3940 // install permission's state is shared across all users. 3941 if (Build.PERMISSIONS_REVIEW_REQUIRED 3942 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3943 && bp.isRuntime()) { 3944 return; 3945 } 3946 3947 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3948 sb = (SettingBase) pkg.mExtras; 3949 if (sb == null) { 3950 throw new IllegalArgumentException("Unknown package: " + packageName); 3951 } 3952 3953 final PermissionsState permissionsState = sb.getPermissionsState(); 3954 3955 final int flags = permissionsState.getPermissionFlags(name, userId); 3956 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3957 throw new SecurityException("Cannot grant system fixed permission " 3958 + name + " for package " + packageName); 3959 } 3960 3961 if (bp.isDevelopment()) { 3962 // Development permissions must be handled specially, since they are not 3963 // normal runtime permissions. For now they apply to all users. 3964 if (permissionsState.grantInstallPermission(bp) != 3965 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3966 scheduleWriteSettingsLocked(); 3967 } 3968 return; 3969 } 3970 3971 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3972 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3973 return; 3974 } 3975 3976 final int result = permissionsState.grantRuntimePermission(bp, userId); 3977 switch (result) { 3978 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3979 return; 3980 } 3981 3982 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3983 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3984 mHandler.post(new Runnable() { 3985 @Override 3986 public void run() { 3987 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3988 } 3989 }); 3990 } 3991 break; 3992 } 3993 3994 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3995 3996 // Not critical if that is lost - app has to request again. 3997 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3998 } 3999 4000 // Only need to do this if user is initialized. Otherwise it's a new user 4001 // and there are no processes running as the user yet and there's no need 4002 // to make an expensive call to remount processes for the changed permissions. 4003 if (READ_EXTERNAL_STORAGE.equals(name) 4004 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4005 final long token = Binder.clearCallingIdentity(); 4006 try { 4007 if (sUserManager.isInitialized(userId)) { 4008 MountServiceInternal mountServiceInternal = LocalServices.getService( 4009 MountServiceInternal.class); 4010 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4011 } 4012 } finally { 4013 Binder.restoreCallingIdentity(token); 4014 } 4015 } 4016 } 4017 4018 @Override 4019 public void revokeRuntimePermission(String packageName, String name, int userId) { 4020 if (!sUserManager.exists(userId)) { 4021 Log.e(TAG, "No such user:" + userId); 4022 return; 4023 } 4024 4025 mContext.enforceCallingOrSelfPermission( 4026 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4027 "revokeRuntimePermission"); 4028 4029 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4030 true /* requireFullPermission */, true /* checkShell */, 4031 "revokeRuntimePermission"); 4032 4033 final int appId; 4034 4035 synchronized (mPackages) { 4036 final PackageParser.Package pkg = mPackages.get(packageName); 4037 if (pkg == null) { 4038 throw new IllegalArgumentException("Unknown package: " + packageName); 4039 } 4040 4041 final BasePermission bp = mSettings.mPermissions.get(name); 4042 if (bp == null) { 4043 throw new IllegalArgumentException("Unknown permission: " + name); 4044 } 4045 4046 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4047 4048 // If a permission review is required for legacy apps we represent 4049 // their permissions as always granted runtime ones since we need 4050 // to keep the review required permission flag per user while an 4051 // install permission's state is shared across all users. 4052 if (Build.PERMISSIONS_REVIEW_REQUIRED 4053 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4054 && bp.isRuntime()) { 4055 return; 4056 } 4057 4058 SettingBase sb = (SettingBase) pkg.mExtras; 4059 if (sb == null) { 4060 throw new IllegalArgumentException("Unknown package: " + packageName); 4061 } 4062 4063 final PermissionsState permissionsState = sb.getPermissionsState(); 4064 4065 final int flags = permissionsState.getPermissionFlags(name, userId); 4066 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4067 throw new SecurityException("Cannot revoke system fixed permission " 4068 + name + " for package " + packageName); 4069 } 4070 4071 if (bp.isDevelopment()) { 4072 // Development permissions must be handled specially, since they are not 4073 // normal runtime permissions. For now they apply to all users. 4074 if (permissionsState.revokeInstallPermission(bp) != 4075 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4076 scheduleWriteSettingsLocked(); 4077 } 4078 return; 4079 } 4080 4081 if (permissionsState.revokeRuntimePermission(bp, userId) == 4082 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4083 return; 4084 } 4085 4086 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4087 4088 // Critical, after this call app should never have the permission. 4089 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4090 4091 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4092 } 4093 4094 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4095 } 4096 4097 @Override 4098 public void resetRuntimePermissions() { 4099 mContext.enforceCallingOrSelfPermission( 4100 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4101 "revokeRuntimePermission"); 4102 4103 int callingUid = Binder.getCallingUid(); 4104 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4105 mContext.enforceCallingOrSelfPermission( 4106 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4107 "resetRuntimePermissions"); 4108 } 4109 4110 synchronized (mPackages) { 4111 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4112 for (int userId : UserManagerService.getInstance().getUserIds()) { 4113 final int packageCount = mPackages.size(); 4114 for (int i = 0; i < packageCount; i++) { 4115 PackageParser.Package pkg = mPackages.valueAt(i); 4116 if (!(pkg.mExtras instanceof PackageSetting)) { 4117 continue; 4118 } 4119 PackageSetting ps = (PackageSetting) pkg.mExtras; 4120 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4121 } 4122 } 4123 } 4124 } 4125 4126 @Override 4127 public int getPermissionFlags(String name, String packageName, int userId) { 4128 if (!sUserManager.exists(userId)) { 4129 return 0; 4130 } 4131 4132 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4133 4134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4135 true /* requireFullPermission */, false /* checkShell */, 4136 "getPermissionFlags"); 4137 4138 synchronized (mPackages) { 4139 final PackageParser.Package pkg = mPackages.get(packageName); 4140 if (pkg == null) { 4141 throw new IllegalArgumentException("Unknown package: " + packageName); 4142 } 4143 4144 final BasePermission bp = mSettings.mPermissions.get(name); 4145 if (bp == null) { 4146 throw new IllegalArgumentException("Unknown permission: " + name); 4147 } 4148 4149 SettingBase sb = (SettingBase) pkg.mExtras; 4150 if (sb == null) { 4151 throw new IllegalArgumentException("Unknown package: " + packageName); 4152 } 4153 4154 PermissionsState permissionsState = sb.getPermissionsState(); 4155 return permissionsState.getPermissionFlags(name, userId); 4156 } 4157 } 4158 4159 @Override 4160 public void updatePermissionFlags(String name, String packageName, int flagMask, 4161 int flagValues, int userId) { 4162 if (!sUserManager.exists(userId)) { 4163 return; 4164 } 4165 4166 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4167 4168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4169 true /* requireFullPermission */, true /* checkShell */, 4170 "updatePermissionFlags"); 4171 4172 // Only the system can change these flags and nothing else. 4173 if (getCallingUid() != Process.SYSTEM_UID) { 4174 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4175 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4176 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4177 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4178 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4179 } 4180 4181 synchronized (mPackages) { 4182 final PackageParser.Package pkg = mPackages.get(packageName); 4183 if (pkg == null) { 4184 throw new IllegalArgumentException("Unknown package: " + packageName); 4185 } 4186 4187 final BasePermission bp = mSettings.mPermissions.get(name); 4188 if (bp == null) { 4189 throw new IllegalArgumentException("Unknown permission: " + name); 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4200 4201 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4202 // Install and runtime permissions are stored in different places, 4203 // so figure out what permission changed and persist the change. 4204 if (permissionsState.getInstallPermissionState(name) != null) { 4205 scheduleWriteSettingsLocked(); 4206 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4207 || hadState) { 4208 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4209 } 4210 } 4211 } 4212 } 4213 4214 /** 4215 * Update the permission flags for all packages and runtime permissions of a user in order 4216 * to allow device or profile owner to remove POLICY_FIXED. 4217 */ 4218 @Override 4219 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4220 if (!sUserManager.exists(userId)) { 4221 return; 4222 } 4223 4224 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4225 4226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4227 true /* requireFullPermission */, true /* checkShell */, 4228 "updatePermissionFlagsForAllApps"); 4229 4230 // Only the system can change system fixed flags. 4231 if (getCallingUid() != Process.SYSTEM_UID) { 4232 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4233 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4234 } 4235 4236 synchronized (mPackages) { 4237 boolean changed = false; 4238 final int packageCount = mPackages.size(); 4239 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4240 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4241 SettingBase sb = (SettingBase) pkg.mExtras; 4242 if (sb == null) { 4243 continue; 4244 } 4245 PermissionsState permissionsState = sb.getPermissionsState(); 4246 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4247 userId, flagMask, flagValues); 4248 } 4249 if (changed) { 4250 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4251 } 4252 } 4253 } 4254 4255 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4256 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4257 != PackageManager.PERMISSION_GRANTED 4258 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4259 != PackageManager.PERMISSION_GRANTED) { 4260 throw new SecurityException(message + " requires " 4261 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4262 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4263 } 4264 } 4265 4266 @Override 4267 public boolean shouldShowRequestPermissionRationale(String permissionName, 4268 String packageName, int userId) { 4269 if (UserHandle.getCallingUserId() != userId) { 4270 mContext.enforceCallingPermission( 4271 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4272 "canShowRequestPermissionRationale for user " + userId); 4273 } 4274 4275 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4276 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4277 return false; 4278 } 4279 4280 if (checkPermission(permissionName, packageName, userId) 4281 == PackageManager.PERMISSION_GRANTED) { 4282 return false; 4283 } 4284 4285 final int flags; 4286 4287 final long identity = Binder.clearCallingIdentity(); 4288 try { 4289 flags = getPermissionFlags(permissionName, 4290 packageName, userId); 4291 } finally { 4292 Binder.restoreCallingIdentity(identity); 4293 } 4294 4295 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4296 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4297 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4298 4299 if ((flags & fixedFlags) != 0) { 4300 return false; 4301 } 4302 4303 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4304 } 4305 4306 @Override 4307 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4308 mContext.enforceCallingOrSelfPermission( 4309 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4310 "addOnPermissionsChangeListener"); 4311 4312 synchronized (mPackages) { 4313 mOnPermissionChangeListeners.addListenerLocked(listener); 4314 } 4315 } 4316 4317 @Override 4318 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4319 synchronized (mPackages) { 4320 mOnPermissionChangeListeners.removeListenerLocked(listener); 4321 } 4322 } 4323 4324 @Override 4325 public boolean isProtectedBroadcast(String actionName) { 4326 synchronized (mPackages) { 4327 if (mProtectedBroadcasts.contains(actionName)) { 4328 return true; 4329 } else if (actionName != null) { 4330 // TODO: remove these terrible hacks 4331 if (actionName.startsWith("android.net.netmon.lingerExpired") 4332 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4333 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4334 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4335 return true; 4336 } 4337 } 4338 } 4339 return false; 4340 } 4341 4342 @Override 4343 public int checkSignatures(String pkg1, String pkg2) { 4344 synchronized (mPackages) { 4345 final PackageParser.Package p1 = mPackages.get(pkg1); 4346 final PackageParser.Package p2 = mPackages.get(pkg2); 4347 if (p1 == null || p1.mExtras == null 4348 || p2 == null || p2.mExtras == null) { 4349 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4350 } 4351 return compareSignatures(p1.mSignatures, p2.mSignatures); 4352 } 4353 } 4354 4355 @Override 4356 public int checkUidSignatures(int uid1, int uid2) { 4357 // Map to base uids. 4358 uid1 = UserHandle.getAppId(uid1); 4359 uid2 = UserHandle.getAppId(uid2); 4360 // reader 4361 synchronized (mPackages) { 4362 Signature[] s1; 4363 Signature[] s2; 4364 Object obj = mSettings.getUserIdLPr(uid1); 4365 if (obj != null) { 4366 if (obj instanceof SharedUserSetting) { 4367 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4368 } else if (obj instanceof PackageSetting) { 4369 s1 = ((PackageSetting)obj).signatures.mSignatures; 4370 } else { 4371 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4372 } 4373 } else { 4374 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4375 } 4376 obj = mSettings.getUserIdLPr(uid2); 4377 if (obj != null) { 4378 if (obj instanceof SharedUserSetting) { 4379 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4380 } else if (obj instanceof PackageSetting) { 4381 s2 = ((PackageSetting)obj).signatures.mSignatures; 4382 } else { 4383 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4384 } 4385 } else { 4386 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4387 } 4388 return compareSignatures(s1, s2); 4389 } 4390 } 4391 4392 private void killUid(int appId, int userId, String reason) { 4393 final long identity = Binder.clearCallingIdentity(); 4394 try { 4395 IActivityManager am = ActivityManagerNative.getDefault(); 4396 if (am != null) { 4397 try { 4398 am.killUid(appId, userId, reason); 4399 } catch (RemoteException e) { 4400 /* ignore - same process */ 4401 } 4402 } 4403 } finally { 4404 Binder.restoreCallingIdentity(identity); 4405 } 4406 } 4407 4408 /** 4409 * Compares two sets of signatures. Returns: 4410 * <br /> 4411 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4412 * <br /> 4413 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4414 * <br /> 4415 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4416 * <br /> 4417 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4418 * <br /> 4419 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4420 */ 4421 static int compareSignatures(Signature[] s1, Signature[] s2) { 4422 if (s1 == null) { 4423 return s2 == null 4424 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4425 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4426 } 4427 4428 if (s2 == null) { 4429 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4430 } 4431 4432 if (s1.length != s2.length) { 4433 return PackageManager.SIGNATURE_NO_MATCH; 4434 } 4435 4436 // Since both signature sets are of size 1, we can compare without HashSets. 4437 if (s1.length == 1) { 4438 return s1[0].equals(s2[0]) ? 4439 PackageManager.SIGNATURE_MATCH : 4440 PackageManager.SIGNATURE_NO_MATCH; 4441 } 4442 4443 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4444 for (Signature sig : s1) { 4445 set1.add(sig); 4446 } 4447 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4448 for (Signature sig : s2) { 4449 set2.add(sig); 4450 } 4451 // Make sure s2 contains all signatures in s1. 4452 if (set1.equals(set2)) { 4453 return PackageManager.SIGNATURE_MATCH; 4454 } 4455 return PackageManager.SIGNATURE_NO_MATCH; 4456 } 4457 4458 /** 4459 * If the database version for this type of package (internal storage or 4460 * external storage) is less than the version where package signatures 4461 * were updated, return true. 4462 */ 4463 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4464 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4465 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4466 } 4467 4468 /** 4469 * Used for backward compatibility to make sure any packages with 4470 * certificate chains get upgraded to the new style. {@code existingSigs} 4471 * will be in the old format (since they were stored on disk from before the 4472 * system upgrade) and {@code scannedSigs} will be in the newer format. 4473 */ 4474 private int compareSignaturesCompat(PackageSignatures existingSigs, 4475 PackageParser.Package scannedPkg) { 4476 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4477 return PackageManager.SIGNATURE_NO_MATCH; 4478 } 4479 4480 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4481 for (Signature sig : existingSigs.mSignatures) { 4482 existingSet.add(sig); 4483 } 4484 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4485 for (Signature sig : scannedPkg.mSignatures) { 4486 try { 4487 Signature[] chainSignatures = sig.getChainSignatures(); 4488 for (Signature chainSig : chainSignatures) { 4489 scannedCompatSet.add(chainSig); 4490 } 4491 } catch (CertificateEncodingException e) { 4492 scannedCompatSet.add(sig); 4493 } 4494 } 4495 /* 4496 * Make sure the expanded scanned set contains all signatures in the 4497 * existing one. 4498 */ 4499 if (scannedCompatSet.equals(existingSet)) { 4500 // Migrate the old signatures to the new scheme. 4501 existingSigs.assignSignatures(scannedPkg.mSignatures); 4502 // The new KeySets will be re-added later in the scanning process. 4503 synchronized (mPackages) { 4504 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4505 } 4506 return PackageManager.SIGNATURE_MATCH; 4507 } 4508 return PackageManager.SIGNATURE_NO_MATCH; 4509 } 4510 4511 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4512 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4513 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4514 } 4515 4516 private int compareSignaturesRecover(PackageSignatures existingSigs, 4517 PackageParser.Package scannedPkg) { 4518 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4519 return PackageManager.SIGNATURE_NO_MATCH; 4520 } 4521 4522 String msg = null; 4523 try { 4524 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4525 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4526 + scannedPkg.packageName); 4527 return PackageManager.SIGNATURE_MATCH; 4528 } 4529 } catch (CertificateException e) { 4530 msg = e.getMessage(); 4531 } 4532 4533 logCriticalInfo(Log.INFO, 4534 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4535 return PackageManager.SIGNATURE_NO_MATCH; 4536 } 4537 4538 @Override 4539 public List<String> getAllPackages() { 4540 synchronized (mPackages) { 4541 return new ArrayList<String>(mPackages.keySet()); 4542 } 4543 } 4544 4545 @Override 4546 public String[] getPackagesForUid(int uid) { 4547 uid = UserHandle.getAppId(uid); 4548 // reader 4549 synchronized (mPackages) { 4550 Object obj = mSettings.getUserIdLPr(uid); 4551 if (obj instanceof SharedUserSetting) { 4552 final SharedUserSetting sus = (SharedUserSetting) obj; 4553 final int N = sus.packages.size(); 4554 final String[] res = new String[N]; 4555 final Iterator<PackageSetting> it = sus.packages.iterator(); 4556 int i = 0; 4557 while (it.hasNext()) { 4558 res[i++] = it.next().name; 4559 } 4560 return res; 4561 } else if (obj instanceof PackageSetting) { 4562 final PackageSetting ps = (PackageSetting) obj; 4563 return new String[] { ps.name }; 4564 } 4565 } 4566 return null; 4567 } 4568 4569 @Override 4570 public String getNameForUid(int uid) { 4571 // reader 4572 synchronized (mPackages) { 4573 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4574 if (obj instanceof SharedUserSetting) { 4575 final SharedUserSetting sus = (SharedUserSetting) obj; 4576 return sus.name + ":" + sus.userId; 4577 } else if (obj instanceof PackageSetting) { 4578 final PackageSetting ps = (PackageSetting) obj; 4579 return ps.name; 4580 } 4581 } 4582 return null; 4583 } 4584 4585 @Override 4586 public int getUidForSharedUser(String sharedUserName) { 4587 if(sharedUserName == null) { 4588 return -1; 4589 } 4590 // reader 4591 synchronized (mPackages) { 4592 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4593 if (suid == null) { 4594 return -1; 4595 } 4596 return suid.userId; 4597 } 4598 } 4599 4600 @Override 4601 public int getFlagsForUid(int uid) { 4602 synchronized (mPackages) { 4603 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4604 if (obj instanceof SharedUserSetting) { 4605 final SharedUserSetting sus = (SharedUserSetting) obj; 4606 return sus.pkgFlags; 4607 } else if (obj instanceof PackageSetting) { 4608 final PackageSetting ps = (PackageSetting) obj; 4609 return ps.pkgFlags; 4610 } 4611 } 4612 return 0; 4613 } 4614 4615 @Override 4616 public int getPrivateFlagsForUid(int uid) { 4617 synchronized (mPackages) { 4618 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4619 if (obj instanceof SharedUserSetting) { 4620 final SharedUserSetting sus = (SharedUserSetting) obj; 4621 return sus.pkgPrivateFlags; 4622 } else if (obj instanceof PackageSetting) { 4623 final PackageSetting ps = (PackageSetting) obj; 4624 return ps.pkgPrivateFlags; 4625 } 4626 } 4627 return 0; 4628 } 4629 4630 @Override 4631 public boolean isUidPrivileged(int uid) { 4632 uid = UserHandle.getAppId(uid); 4633 // reader 4634 synchronized (mPackages) { 4635 Object obj = mSettings.getUserIdLPr(uid); 4636 if (obj instanceof SharedUserSetting) { 4637 final SharedUserSetting sus = (SharedUserSetting) obj; 4638 final Iterator<PackageSetting> it = sus.packages.iterator(); 4639 while (it.hasNext()) { 4640 if (it.next().isPrivileged()) { 4641 return true; 4642 } 4643 } 4644 } else if (obj instanceof PackageSetting) { 4645 final PackageSetting ps = (PackageSetting) obj; 4646 return ps.isPrivileged(); 4647 } 4648 } 4649 return false; 4650 } 4651 4652 @Override 4653 public String[] getAppOpPermissionPackages(String permissionName) { 4654 synchronized (mPackages) { 4655 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4656 if (pkgs == null) { 4657 return null; 4658 } 4659 return pkgs.toArray(new String[pkgs.size()]); 4660 } 4661 } 4662 4663 @Override 4664 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4665 int flags, int userId) { 4666 if (!sUserManager.exists(userId)) return null; 4667 flags = updateFlagsForResolve(flags, userId, intent); 4668 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4669 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4670 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4671 userId); 4672 final ResolveInfo bestChoice = 4673 chooseBestActivity(intent, resolvedType, flags, query, userId); 4674 4675 if (isEphemeralAllowed(intent, query, userId)) { 4676 final EphemeralResolveInfo ai = 4677 getEphemeralResolveInfo(intent, resolvedType, userId); 4678 if (ai != null) { 4679 if (DEBUG_EPHEMERAL) { 4680 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4681 } 4682 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4683 bestChoice.ephemeralResolveInfo = ai; 4684 } 4685 } 4686 return bestChoice; 4687 } 4688 4689 @Override 4690 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4691 IntentFilter filter, int match, ComponentName activity) { 4692 final int userId = UserHandle.getCallingUserId(); 4693 if (DEBUG_PREFERRED) { 4694 Log.v(TAG, "setLastChosenActivity intent=" + intent 4695 + " resolvedType=" + resolvedType 4696 + " flags=" + flags 4697 + " filter=" + filter 4698 + " match=" + match 4699 + " activity=" + activity); 4700 filter.dump(new PrintStreamPrinter(System.out), " "); 4701 } 4702 intent.setComponent(null); 4703 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4704 userId); 4705 // Find any earlier preferred or last chosen entries and nuke them 4706 findPreferredActivity(intent, resolvedType, 4707 flags, query, 0, false, true, false, userId); 4708 // Add the new activity as the last chosen for this filter 4709 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4710 "Setting last chosen"); 4711 } 4712 4713 @Override 4714 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4715 final int userId = UserHandle.getCallingUserId(); 4716 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4717 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4718 userId); 4719 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4720 false, false, false, userId); 4721 } 4722 4723 4724 private boolean isEphemeralAllowed( 4725 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4726 // Short circuit and return early if possible. 4727 if (DISABLE_EPHEMERAL_APPS) { 4728 return false; 4729 } 4730 final int callingUser = UserHandle.getCallingUserId(); 4731 if (callingUser != UserHandle.USER_SYSTEM) { 4732 return false; 4733 } 4734 if (mEphemeralResolverConnection == null) { 4735 return false; 4736 } 4737 if (intent.getComponent() != null) { 4738 return false; 4739 } 4740 if (intent.getPackage() != null) { 4741 return false; 4742 } 4743 final boolean isWebUri = hasWebURI(intent); 4744 if (!isWebUri) { 4745 return false; 4746 } 4747 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4748 synchronized (mPackages) { 4749 final int count = resolvedActivites.size(); 4750 for (int n = 0; n < count; n++) { 4751 ResolveInfo info = resolvedActivites.get(n); 4752 String packageName = info.activityInfo.packageName; 4753 PackageSetting ps = mSettings.mPackages.get(packageName); 4754 if (ps != null) { 4755 // Try to get the status from User settings first 4756 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4757 int status = (int) (packedStatus >> 32); 4758 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4759 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4760 if (DEBUG_EPHEMERAL) { 4761 Slog.v(TAG, "DENY ephemeral apps;" 4762 + " pkg: " + packageName + ", status: " + status); 4763 } 4764 return false; 4765 } 4766 } 4767 } 4768 } 4769 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4770 return true; 4771 } 4772 4773 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4774 int userId) { 4775 MessageDigest digest = null; 4776 try { 4777 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4778 } catch (NoSuchAlgorithmException e) { 4779 // If we can't create a digest, ignore ephemeral apps. 4780 return null; 4781 } 4782 4783 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4784 final byte[] digestBytes = digest.digest(hostBytes); 4785 int shaPrefix = 4786 digestBytes[0] << 24 4787 | digestBytes[1] << 16 4788 | digestBytes[2] << 8 4789 | digestBytes[3] << 0; 4790 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4791 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4792 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4793 // No hash prefix match; there are no ephemeral apps for this domain. 4794 return null; 4795 } 4796 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4797 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4798 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4799 continue; 4800 } 4801 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4802 // No filters; this should never happen. 4803 if (filters.isEmpty()) { 4804 continue; 4805 } 4806 // We have a domain match; resolve the filters to see if anything matches. 4807 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4808 for (int j = filters.size() - 1; j >= 0; --j) { 4809 final EphemeralResolveIntentInfo intentInfo = 4810 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4811 ephemeralResolver.addFilter(intentInfo); 4812 } 4813 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4814 intent, resolvedType, false /*defaultOnly*/, userId); 4815 if (!matchedResolveInfoList.isEmpty()) { 4816 return matchedResolveInfoList.get(0); 4817 } 4818 } 4819 // Hash or filter mis-match; no ephemeral apps for this domain. 4820 return null; 4821 } 4822 4823 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4824 int flags, List<ResolveInfo> query, int userId) { 4825 if (query != null) { 4826 final int N = query.size(); 4827 if (N == 1) { 4828 return query.get(0); 4829 } else if (N > 1) { 4830 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4831 // If there is more than one activity with the same priority, 4832 // then let the user decide between them. 4833 ResolveInfo r0 = query.get(0); 4834 ResolveInfo r1 = query.get(1); 4835 if (DEBUG_INTENT_MATCHING || debug) { 4836 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4837 + r1.activityInfo.name + "=" + r1.priority); 4838 } 4839 // If the first activity has a higher priority, or a different 4840 // default, then it is always desirable to pick it. 4841 if (r0.priority != r1.priority 4842 || r0.preferredOrder != r1.preferredOrder 4843 || r0.isDefault != r1.isDefault) { 4844 return query.get(0); 4845 } 4846 // If we have saved a preference for a preferred activity for 4847 // this Intent, use that. 4848 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4849 flags, query, r0.priority, true, false, debug, userId); 4850 if (ri != null) { 4851 return ri; 4852 } 4853 ri = new ResolveInfo(mResolveInfo); 4854 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4855 ri.activityInfo.applicationInfo = new ApplicationInfo( 4856 ri.activityInfo.applicationInfo); 4857 if (userId != 0) { 4858 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4859 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4860 } 4861 // Make sure that the resolver is displayable in car mode 4862 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4863 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4864 return ri; 4865 } 4866 } 4867 return null; 4868 } 4869 4870 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4871 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4872 final int N = query.size(); 4873 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4874 .get(userId); 4875 // Get the list of persistent preferred activities that handle the intent 4876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4877 List<PersistentPreferredActivity> pprefs = ppir != null 4878 ? ppir.queryIntent(intent, resolvedType, 4879 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4880 : null; 4881 if (pprefs != null && pprefs.size() > 0) { 4882 final int M = pprefs.size(); 4883 for (int i=0; i<M; i++) { 4884 final PersistentPreferredActivity ppa = pprefs.get(i); 4885 if (DEBUG_PREFERRED || debug) { 4886 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4887 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4888 + "\n component=" + ppa.mComponent); 4889 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4890 } 4891 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4892 flags | MATCH_DISABLED_COMPONENTS, userId); 4893 if (DEBUG_PREFERRED || debug) { 4894 Slog.v(TAG, "Found persistent preferred activity:"); 4895 if (ai != null) { 4896 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4897 } else { 4898 Slog.v(TAG, " null"); 4899 } 4900 } 4901 if (ai == null) { 4902 // This previously registered persistent preferred activity 4903 // component is no longer known. Ignore it and do NOT remove it. 4904 continue; 4905 } 4906 for (int j=0; j<N; j++) { 4907 final ResolveInfo ri = query.get(j); 4908 if (!ri.activityInfo.applicationInfo.packageName 4909 .equals(ai.applicationInfo.packageName)) { 4910 continue; 4911 } 4912 if (!ri.activityInfo.name.equals(ai.name)) { 4913 continue; 4914 } 4915 // Found a persistent preference that can handle the intent. 4916 if (DEBUG_PREFERRED || debug) { 4917 Slog.v(TAG, "Returning persistent preferred activity: " + 4918 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4919 } 4920 return ri; 4921 } 4922 } 4923 } 4924 return null; 4925 } 4926 4927 // TODO: handle preferred activities missing while user has amnesia 4928 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4929 List<ResolveInfo> query, int priority, boolean always, 4930 boolean removeMatches, boolean debug, int userId) { 4931 if (!sUserManager.exists(userId)) return null; 4932 flags = updateFlagsForResolve(flags, userId, intent); 4933 // writer 4934 synchronized (mPackages) { 4935 if (intent.getSelector() != null) { 4936 intent = intent.getSelector(); 4937 } 4938 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4939 4940 // Try to find a matching persistent preferred activity. 4941 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4942 debug, userId); 4943 4944 // If a persistent preferred activity matched, use it. 4945 if (pri != null) { 4946 return pri; 4947 } 4948 4949 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4950 // Get the list of preferred activities that handle the intent 4951 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4952 List<PreferredActivity> prefs = pir != null 4953 ? pir.queryIntent(intent, resolvedType, 4954 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4955 : null; 4956 if (prefs != null && prefs.size() > 0) { 4957 boolean changed = false; 4958 try { 4959 // First figure out how good the original match set is. 4960 // We will only allow preferred activities that came 4961 // from the same match quality. 4962 int match = 0; 4963 4964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4965 4966 final int N = query.size(); 4967 for (int j=0; j<N; j++) { 4968 final ResolveInfo ri = query.get(j); 4969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4970 + ": 0x" + Integer.toHexString(match)); 4971 if (ri.match > match) { 4972 match = ri.match; 4973 } 4974 } 4975 4976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4977 + Integer.toHexString(match)); 4978 4979 match &= IntentFilter.MATCH_CATEGORY_MASK; 4980 final int M = prefs.size(); 4981 for (int i=0; i<M; i++) { 4982 final PreferredActivity pa = prefs.get(i); 4983 if (DEBUG_PREFERRED || debug) { 4984 Slog.v(TAG, "Checking PreferredActivity ds=" 4985 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4986 + "\n component=" + pa.mPref.mComponent); 4987 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4988 } 4989 if (pa.mPref.mMatch != match) { 4990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4991 + Integer.toHexString(pa.mPref.mMatch)); 4992 continue; 4993 } 4994 // If it's not an "always" type preferred activity and that's what we're 4995 // looking for, skip it. 4996 if (always && !pa.mPref.mAlways) { 4997 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4998 continue; 4999 } 5000 final ActivityInfo ai = getActivityInfo( 5001 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5002 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5003 userId); 5004 if (DEBUG_PREFERRED || debug) { 5005 Slog.v(TAG, "Found preferred activity:"); 5006 if (ai != null) { 5007 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5008 } else { 5009 Slog.v(TAG, " null"); 5010 } 5011 } 5012 if (ai == null) { 5013 // This previously registered preferred activity 5014 // component is no longer known. Most likely an update 5015 // to the app was installed and in the new version this 5016 // component no longer exists. Clean it up by removing 5017 // it from the preferred activities list, and skip it. 5018 Slog.w(TAG, "Removing dangling preferred activity: " 5019 + pa.mPref.mComponent); 5020 pir.removeFilter(pa); 5021 changed = true; 5022 continue; 5023 } 5024 for (int j=0; j<N; j++) { 5025 final ResolveInfo ri = query.get(j); 5026 if (!ri.activityInfo.applicationInfo.packageName 5027 .equals(ai.applicationInfo.packageName)) { 5028 continue; 5029 } 5030 if (!ri.activityInfo.name.equals(ai.name)) { 5031 continue; 5032 } 5033 5034 if (removeMatches) { 5035 pir.removeFilter(pa); 5036 changed = true; 5037 if (DEBUG_PREFERRED) { 5038 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5039 } 5040 break; 5041 } 5042 5043 // Okay we found a previously set preferred or last chosen app. 5044 // If the result set is different from when this 5045 // was created, we need to clear it and re-ask the 5046 // user their preference, if we're looking for an "always" type entry. 5047 if (always && !pa.mPref.sameSet(query)) { 5048 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5049 + intent + " type " + resolvedType); 5050 if (DEBUG_PREFERRED) { 5051 Slog.v(TAG, "Removing preferred activity since set changed " 5052 + pa.mPref.mComponent); 5053 } 5054 pir.removeFilter(pa); 5055 // Re-add the filter as a "last chosen" entry (!always) 5056 PreferredActivity lastChosen = new PreferredActivity( 5057 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5058 pir.addFilter(lastChosen); 5059 changed = true; 5060 return null; 5061 } 5062 5063 // Yay! Either the set matched or we're looking for the last chosen 5064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5065 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5066 return ri; 5067 } 5068 } 5069 } finally { 5070 if (changed) { 5071 if (DEBUG_PREFERRED) { 5072 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5073 } 5074 scheduleWritePackageRestrictionsLocked(userId); 5075 } 5076 } 5077 } 5078 } 5079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5080 return null; 5081 } 5082 5083 /* 5084 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5085 */ 5086 @Override 5087 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5088 int targetUserId) { 5089 mContext.enforceCallingOrSelfPermission( 5090 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5091 List<CrossProfileIntentFilter> matches = 5092 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5093 if (matches != null) { 5094 int size = matches.size(); 5095 for (int i = 0; i < size; i++) { 5096 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5097 } 5098 } 5099 if (hasWebURI(intent)) { 5100 // cross-profile app linking works only towards the parent. 5101 final UserInfo parent = getProfileParent(sourceUserId); 5102 synchronized(mPackages) { 5103 int flags = updateFlagsForResolve(0, parent.id, intent); 5104 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5105 intent, resolvedType, flags, sourceUserId, parent.id); 5106 return xpDomainInfo != null; 5107 } 5108 } 5109 return false; 5110 } 5111 5112 private UserInfo getProfileParent(int userId) { 5113 final long identity = Binder.clearCallingIdentity(); 5114 try { 5115 return sUserManager.getProfileParent(userId); 5116 } finally { 5117 Binder.restoreCallingIdentity(identity); 5118 } 5119 } 5120 5121 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5122 String resolvedType, int userId) { 5123 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5124 if (resolver != null) { 5125 return resolver.queryIntent(intent, resolvedType, false, userId); 5126 } 5127 return null; 5128 } 5129 5130 @Override 5131 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5132 String resolvedType, int flags, int userId) { 5133 return new ParceledListSlice<>( 5134 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5135 } 5136 5137 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5138 String resolvedType, int flags, int userId) { 5139 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5140 flags = updateFlagsForResolve(flags, userId, intent); 5141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5142 false /* requireFullPermission */, false /* checkShell */, 5143 "query intent activities"); 5144 ComponentName comp = intent.getComponent(); 5145 if (comp == null) { 5146 if (intent.getSelector() != null) { 5147 intent = intent.getSelector(); 5148 comp = intent.getComponent(); 5149 } 5150 } 5151 5152 if (comp != null) { 5153 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5154 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5155 if (ai != null) { 5156 final ResolveInfo ri = new ResolveInfo(); 5157 ri.activityInfo = ai; 5158 list.add(ri); 5159 } 5160 return list; 5161 } 5162 5163 // reader 5164 synchronized (mPackages) { 5165 final String pkgName = intent.getPackage(); 5166 if (pkgName == null) { 5167 List<CrossProfileIntentFilter> matchingFilters = 5168 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5169 // Check for results that need to skip the current profile. 5170 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5171 resolvedType, flags, userId); 5172 if (xpResolveInfo != null) { 5173 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5174 result.add(xpResolveInfo); 5175 return filterIfNotSystemUser(result, userId); 5176 } 5177 5178 // Check for results in the current profile. 5179 List<ResolveInfo> result = mActivities.queryIntent( 5180 intent, resolvedType, flags, userId); 5181 result = filterIfNotSystemUser(result, userId); 5182 5183 // Check for cross profile results. 5184 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5185 xpResolveInfo = queryCrossProfileIntents( 5186 matchingFilters, intent, resolvedType, flags, userId, 5187 hasNonNegativePriorityResult); 5188 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5189 boolean isVisibleToUser = filterIfNotSystemUser( 5190 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5191 if (isVisibleToUser) { 5192 result.add(xpResolveInfo); 5193 Collections.sort(result, mResolvePrioritySorter); 5194 } 5195 } 5196 if (hasWebURI(intent)) { 5197 CrossProfileDomainInfo xpDomainInfo = null; 5198 final UserInfo parent = getProfileParent(userId); 5199 if (parent != null) { 5200 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5201 flags, userId, parent.id); 5202 } 5203 if (xpDomainInfo != null) { 5204 if (xpResolveInfo != null) { 5205 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5206 // in the result. 5207 result.remove(xpResolveInfo); 5208 } 5209 if (result.size() == 0) { 5210 result.add(xpDomainInfo.resolveInfo); 5211 return result; 5212 } 5213 } else if (result.size() <= 1) { 5214 return result; 5215 } 5216 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5217 xpDomainInfo, userId); 5218 Collections.sort(result, mResolvePrioritySorter); 5219 } 5220 return result; 5221 } 5222 final PackageParser.Package pkg = mPackages.get(pkgName); 5223 if (pkg != null) { 5224 return filterIfNotSystemUser( 5225 mActivities.queryIntentForPackage( 5226 intent, resolvedType, flags, pkg.activities, userId), 5227 userId); 5228 } 5229 return new ArrayList<ResolveInfo>(); 5230 } 5231 } 5232 5233 private static class CrossProfileDomainInfo { 5234 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5235 ResolveInfo resolveInfo; 5236 /* Best domain verification status of the activities found in the other profile */ 5237 int bestDomainVerificationStatus; 5238 } 5239 5240 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5241 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5242 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5243 sourceUserId)) { 5244 return null; 5245 } 5246 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5247 resolvedType, flags, parentUserId); 5248 5249 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5250 return null; 5251 } 5252 CrossProfileDomainInfo result = null; 5253 int size = resultTargetUser.size(); 5254 for (int i = 0; i < size; i++) { 5255 ResolveInfo riTargetUser = resultTargetUser.get(i); 5256 // Intent filter verification is only for filters that specify a host. So don't return 5257 // those that handle all web uris. 5258 if (riTargetUser.handleAllWebDataURI) { 5259 continue; 5260 } 5261 String packageName = riTargetUser.activityInfo.packageName; 5262 PackageSetting ps = mSettings.mPackages.get(packageName); 5263 if (ps == null) { 5264 continue; 5265 } 5266 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5267 int status = (int)(verificationState >> 32); 5268 if (result == null) { 5269 result = new CrossProfileDomainInfo(); 5270 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5271 sourceUserId, parentUserId); 5272 result.bestDomainVerificationStatus = status; 5273 } else { 5274 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5275 result.bestDomainVerificationStatus); 5276 } 5277 } 5278 // Don't consider matches with status NEVER across profiles. 5279 if (result != null && result.bestDomainVerificationStatus 5280 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5281 return null; 5282 } 5283 return result; 5284 } 5285 5286 /** 5287 * Verification statuses are ordered from the worse to the best, except for 5288 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5289 */ 5290 private int bestDomainVerificationStatus(int status1, int status2) { 5291 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5292 return status2; 5293 } 5294 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5295 return status1; 5296 } 5297 return (int) MathUtils.max(status1, status2); 5298 } 5299 5300 private boolean isUserEnabled(int userId) { 5301 long callingId = Binder.clearCallingIdentity(); 5302 try { 5303 UserInfo userInfo = sUserManager.getUserInfo(userId); 5304 return userInfo != null && userInfo.isEnabled(); 5305 } finally { 5306 Binder.restoreCallingIdentity(callingId); 5307 } 5308 } 5309 5310 /** 5311 * Filter out activities with systemUserOnly flag set, when current user is not System. 5312 * 5313 * @return filtered list 5314 */ 5315 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5316 if (userId == UserHandle.USER_SYSTEM) { 5317 return resolveInfos; 5318 } 5319 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5320 ResolveInfo info = resolveInfos.get(i); 5321 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5322 resolveInfos.remove(i); 5323 } 5324 } 5325 return resolveInfos; 5326 } 5327 5328 /** 5329 * @param resolveInfos list of resolve infos in descending priority order 5330 * @return if the list contains a resolve info with non-negative priority 5331 */ 5332 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5333 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5334 } 5335 5336 private static boolean hasWebURI(Intent intent) { 5337 if (intent.getData() == null) { 5338 return false; 5339 } 5340 final String scheme = intent.getScheme(); 5341 if (TextUtils.isEmpty(scheme)) { 5342 return false; 5343 } 5344 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5345 } 5346 5347 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5348 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5349 int userId) { 5350 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5351 5352 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5353 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5354 candidates.size()); 5355 } 5356 5357 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5358 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5359 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5360 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5361 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5362 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5363 5364 synchronized (mPackages) { 5365 final int count = candidates.size(); 5366 // First, try to use linked apps. Partition the candidates into four lists: 5367 // one for the final results, one for the "do not use ever", one for "undefined status" 5368 // and finally one for "browser app type". 5369 for (int n=0; n<count; n++) { 5370 ResolveInfo info = candidates.get(n); 5371 String packageName = info.activityInfo.packageName; 5372 PackageSetting ps = mSettings.mPackages.get(packageName); 5373 if (ps != null) { 5374 // Add to the special match all list (Browser use case) 5375 if (info.handleAllWebDataURI) { 5376 matchAllList.add(info); 5377 continue; 5378 } 5379 // Try to get the status from User settings first 5380 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5381 int status = (int)(packedStatus >> 32); 5382 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5383 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5384 if (DEBUG_DOMAIN_VERIFICATION) { 5385 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5386 + " : linkgen=" + linkGeneration); 5387 } 5388 // Use link-enabled generation as preferredOrder, i.e. 5389 // prefer newly-enabled over earlier-enabled. 5390 info.preferredOrder = linkGeneration; 5391 alwaysList.add(info); 5392 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5393 if (DEBUG_DOMAIN_VERIFICATION) { 5394 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5395 } 5396 neverList.add(info); 5397 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5398 if (DEBUG_DOMAIN_VERIFICATION) { 5399 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5400 } 5401 alwaysAskList.add(info); 5402 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5403 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5404 if (DEBUG_DOMAIN_VERIFICATION) { 5405 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5406 } 5407 undefinedList.add(info); 5408 } 5409 } 5410 } 5411 5412 // We'll want to include browser possibilities in a few cases 5413 boolean includeBrowser = false; 5414 5415 // First try to add the "always" resolution(s) for the current user, if any 5416 if (alwaysList.size() > 0) { 5417 result.addAll(alwaysList); 5418 } else { 5419 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5420 result.addAll(undefinedList); 5421 // Maybe add one for the other profile. 5422 if (xpDomainInfo != null && ( 5423 xpDomainInfo.bestDomainVerificationStatus 5424 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5425 result.add(xpDomainInfo.resolveInfo); 5426 } 5427 includeBrowser = true; 5428 } 5429 5430 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5431 // If there were 'always' entries their preferred order has been set, so we also 5432 // back that off to make the alternatives equivalent 5433 if (alwaysAskList.size() > 0) { 5434 for (ResolveInfo i : result) { 5435 i.preferredOrder = 0; 5436 } 5437 result.addAll(alwaysAskList); 5438 includeBrowser = true; 5439 } 5440 5441 if (includeBrowser) { 5442 // Also add browsers (all of them or only the default one) 5443 if (DEBUG_DOMAIN_VERIFICATION) { 5444 Slog.v(TAG, " ...including browsers in candidate set"); 5445 } 5446 if ((matchFlags & MATCH_ALL) != 0) { 5447 result.addAll(matchAllList); 5448 } else { 5449 // Browser/generic handling case. If there's a default browser, go straight 5450 // to that (but only if there is no other higher-priority match). 5451 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5452 int maxMatchPrio = 0; 5453 ResolveInfo defaultBrowserMatch = null; 5454 final int numCandidates = matchAllList.size(); 5455 for (int n = 0; n < numCandidates; n++) { 5456 ResolveInfo info = matchAllList.get(n); 5457 // track the highest overall match priority... 5458 if (info.priority > maxMatchPrio) { 5459 maxMatchPrio = info.priority; 5460 } 5461 // ...and the highest-priority default browser match 5462 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5463 if (defaultBrowserMatch == null 5464 || (defaultBrowserMatch.priority < info.priority)) { 5465 if (debug) { 5466 Slog.v(TAG, "Considering default browser match " + info); 5467 } 5468 defaultBrowserMatch = info; 5469 } 5470 } 5471 } 5472 if (defaultBrowserMatch != null 5473 && defaultBrowserMatch.priority >= maxMatchPrio 5474 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5475 { 5476 if (debug) { 5477 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5478 } 5479 result.add(defaultBrowserMatch); 5480 } else { 5481 result.addAll(matchAllList); 5482 } 5483 } 5484 5485 // If there is nothing selected, add all candidates and remove the ones that the user 5486 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5487 if (result.size() == 0) { 5488 result.addAll(candidates); 5489 result.removeAll(neverList); 5490 } 5491 } 5492 } 5493 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5494 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5495 result.size()); 5496 for (ResolveInfo info : result) { 5497 Slog.v(TAG, " + " + info.activityInfo); 5498 } 5499 } 5500 return result; 5501 } 5502 5503 // Returns a packed value as a long: 5504 // 5505 // high 'int'-sized word: link status: undefined/ask/never/always. 5506 // low 'int'-sized word: relative priority among 'always' results. 5507 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5508 long result = ps.getDomainVerificationStatusForUser(userId); 5509 // if none available, get the master status 5510 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5511 if (ps.getIntentFilterVerificationInfo() != null) { 5512 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5513 } 5514 } 5515 return result; 5516 } 5517 5518 private ResolveInfo querySkipCurrentProfileIntents( 5519 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5520 int flags, int sourceUserId) { 5521 if (matchingFilters != null) { 5522 int size = matchingFilters.size(); 5523 for (int i = 0; i < size; i ++) { 5524 CrossProfileIntentFilter filter = matchingFilters.get(i); 5525 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5526 // Checking if there are activities in the target user that can handle the 5527 // intent. 5528 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5529 resolvedType, flags, sourceUserId); 5530 if (resolveInfo != null) { 5531 return resolveInfo; 5532 } 5533 } 5534 } 5535 } 5536 return null; 5537 } 5538 5539 // Return matching ResolveInfo in target user if any. 5540 private ResolveInfo queryCrossProfileIntents( 5541 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5542 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5543 if (matchingFilters != null) { 5544 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5545 // match the same intent. For performance reasons, it is better not to 5546 // run queryIntent twice for the same userId 5547 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5548 int size = matchingFilters.size(); 5549 for (int i = 0; i < size; i++) { 5550 CrossProfileIntentFilter filter = matchingFilters.get(i); 5551 int targetUserId = filter.getTargetUserId(); 5552 boolean skipCurrentProfile = 5553 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5554 boolean skipCurrentProfileIfNoMatchFound = 5555 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5556 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5557 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5558 // Checking if there are activities in the target user that can handle the 5559 // intent. 5560 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5561 resolvedType, flags, sourceUserId); 5562 if (resolveInfo != null) return resolveInfo; 5563 alreadyTriedUserIds.put(targetUserId, true); 5564 } 5565 } 5566 } 5567 return null; 5568 } 5569 5570 /** 5571 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5572 * will forward the intent to the filter's target user. 5573 * Otherwise, returns null. 5574 */ 5575 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5576 String resolvedType, int flags, int sourceUserId) { 5577 int targetUserId = filter.getTargetUserId(); 5578 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5579 resolvedType, flags, targetUserId); 5580 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5581 // If all the matches in the target profile are suspended, return null. 5582 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5583 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5584 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5585 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5586 targetUserId); 5587 } 5588 } 5589 } 5590 return null; 5591 } 5592 5593 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5594 int sourceUserId, int targetUserId) { 5595 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5596 long ident = Binder.clearCallingIdentity(); 5597 boolean targetIsProfile; 5598 try { 5599 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5600 } finally { 5601 Binder.restoreCallingIdentity(ident); 5602 } 5603 String className; 5604 if (targetIsProfile) { 5605 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5606 } else { 5607 className = FORWARD_INTENT_TO_PARENT; 5608 } 5609 ComponentName forwardingActivityComponentName = new ComponentName( 5610 mAndroidApplication.packageName, className); 5611 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5612 sourceUserId); 5613 if (!targetIsProfile) { 5614 forwardingActivityInfo.showUserIcon = targetUserId; 5615 forwardingResolveInfo.noResourceId = true; 5616 } 5617 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5618 forwardingResolveInfo.priority = 0; 5619 forwardingResolveInfo.preferredOrder = 0; 5620 forwardingResolveInfo.match = 0; 5621 forwardingResolveInfo.isDefault = true; 5622 forwardingResolveInfo.filter = filter; 5623 forwardingResolveInfo.targetUserId = targetUserId; 5624 return forwardingResolveInfo; 5625 } 5626 5627 @Override 5628 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5629 Intent[] specifics, String[] specificTypes, Intent intent, 5630 String resolvedType, int flags, int userId) { 5631 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5632 specificTypes, intent, resolvedType, flags, userId)); 5633 } 5634 5635 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5636 Intent[] specifics, String[] specificTypes, Intent intent, 5637 String resolvedType, int flags, int userId) { 5638 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5639 flags = updateFlagsForResolve(flags, userId, intent); 5640 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5641 false /* requireFullPermission */, false /* checkShell */, 5642 "query intent activity options"); 5643 final String resultsAction = intent.getAction(); 5644 5645 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5646 | PackageManager.GET_RESOLVED_FILTER, userId); 5647 5648 if (DEBUG_INTENT_MATCHING) { 5649 Log.v(TAG, "Query " + intent + ": " + results); 5650 } 5651 5652 int specificsPos = 0; 5653 int N; 5654 5655 // todo: note that the algorithm used here is O(N^2). This 5656 // isn't a problem in our current environment, but if we start running 5657 // into situations where we have more than 5 or 10 matches then this 5658 // should probably be changed to something smarter... 5659 5660 // First we go through and resolve each of the specific items 5661 // that were supplied, taking care of removing any corresponding 5662 // duplicate items in the generic resolve list. 5663 if (specifics != null) { 5664 for (int i=0; i<specifics.length; i++) { 5665 final Intent sintent = specifics[i]; 5666 if (sintent == null) { 5667 continue; 5668 } 5669 5670 if (DEBUG_INTENT_MATCHING) { 5671 Log.v(TAG, "Specific #" + i + ": " + sintent); 5672 } 5673 5674 String action = sintent.getAction(); 5675 if (resultsAction != null && resultsAction.equals(action)) { 5676 // If this action was explicitly requested, then don't 5677 // remove things that have it. 5678 action = null; 5679 } 5680 5681 ResolveInfo ri = null; 5682 ActivityInfo ai = null; 5683 5684 ComponentName comp = sintent.getComponent(); 5685 if (comp == null) { 5686 ri = resolveIntent( 5687 sintent, 5688 specificTypes != null ? specificTypes[i] : null, 5689 flags, userId); 5690 if (ri == null) { 5691 continue; 5692 } 5693 if (ri == mResolveInfo) { 5694 // ACK! Must do something better with this. 5695 } 5696 ai = ri.activityInfo; 5697 comp = new ComponentName(ai.applicationInfo.packageName, 5698 ai.name); 5699 } else { 5700 ai = getActivityInfo(comp, flags, userId); 5701 if (ai == null) { 5702 continue; 5703 } 5704 } 5705 5706 // Look for any generic query activities that are duplicates 5707 // of this specific one, and remove them from the results. 5708 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5709 N = results.size(); 5710 int j; 5711 for (j=specificsPos; j<N; j++) { 5712 ResolveInfo sri = results.get(j); 5713 if ((sri.activityInfo.name.equals(comp.getClassName()) 5714 && sri.activityInfo.applicationInfo.packageName.equals( 5715 comp.getPackageName())) 5716 || (action != null && sri.filter.matchAction(action))) { 5717 results.remove(j); 5718 if (DEBUG_INTENT_MATCHING) Log.v( 5719 TAG, "Removing duplicate item from " + j 5720 + " due to specific " + specificsPos); 5721 if (ri == null) { 5722 ri = sri; 5723 } 5724 j--; 5725 N--; 5726 } 5727 } 5728 5729 // Add this specific item to its proper place. 5730 if (ri == null) { 5731 ri = new ResolveInfo(); 5732 ri.activityInfo = ai; 5733 } 5734 results.add(specificsPos, ri); 5735 ri.specificIndex = i; 5736 specificsPos++; 5737 } 5738 } 5739 5740 // Now we go through the remaining generic results and remove any 5741 // duplicate actions that are found here. 5742 N = results.size(); 5743 for (int i=specificsPos; i<N-1; i++) { 5744 final ResolveInfo rii = results.get(i); 5745 if (rii.filter == null) { 5746 continue; 5747 } 5748 5749 // Iterate over all of the actions of this result's intent 5750 // filter... typically this should be just one. 5751 final Iterator<String> it = rii.filter.actionsIterator(); 5752 if (it == null) { 5753 continue; 5754 } 5755 while (it.hasNext()) { 5756 final String action = it.next(); 5757 if (resultsAction != null && resultsAction.equals(action)) { 5758 // If this action was explicitly requested, then don't 5759 // remove things that have it. 5760 continue; 5761 } 5762 for (int j=i+1; j<N; j++) { 5763 final ResolveInfo rij = results.get(j); 5764 if (rij.filter != null && rij.filter.hasAction(action)) { 5765 results.remove(j); 5766 if (DEBUG_INTENT_MATCHING) Log.v( 5767 TAG, "Removing duplicate item from " + j 5768 + " due to action " + action + " at " + i); 5769 j--; 5770 N--; 5771 } 5772 } 5773 } 5774 5775 // If the caller didn't request filter information, drop it now 5776 // so we don't have to marshall/unmarshall it. 5777 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5778 rii.filter = null; 5779 } 5780 } 5781 5782 // Filter out the caller activity if so requested. 5783 if (caller != null) { 5784 N = results.size(); 5785 for (int i=0; i<N; i++) { 5786 ActivityInfo ainfo = results.get(i).activityInfo; 5787 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5788 && caller.getClassName().equals(ainfo.name)) { 5789 results.remove(i); 5790 break; 5791 } 5792 } 5793 } 5794 5795 // If the caller didn't request filter information, 5796 // drop them now so we don't have to 5797 // marshall/unmarshall it. 5798 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5799 N = results.size(); 5800 for (int i=0; i<N; i++) { 5801 results.get(i).filter = null; 5802 } 5803 } 5804 5805 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5806 return results; 5807 } 5808 5809 @Override 5810 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5811 String resolvedType, int flags, int userId) { 5812 return new ParceledListSlice<>( 5813 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5814 } 5815 5816 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5817 String resolvedType, int flags, int userId) { 5818 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5819 flags = updateFlagsForResolve(flags, userId, intent); 5820 ComponentName comp = intent.getComponent(); 5821 if (comp == null) { 5822 if (intent.getSelector() != null) { 5823 intent = intent.getSelector(); 5824 comp = intent.getComponent(); 5825 } 5826 } 5827 if (comp != null) { 5828 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5829 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5830 if (ai != null) { 5831 ResolveInfo ri = new ResolveInfo(); 5832 ri.activityInfo = ai; 5833 list.add(ri); 5834 } 5835 return list; 5836 } 5837 5838 // reader 5839 synchronized (mPackages) { 5840 String pkgName = intent.getPackage(); 5841 if (pkgName == null) { 5842 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5843 } 5844 final PackageParser.Package pkg = mPackages.get(pkgName); 5845 if (pkg != null) { 5846 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5847 userId); 5848 } 5849 return Collections.emptyList(); 5850 } 5851 } 5852 5853 @Override 5854 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5855 if (!sUserManager.exists(userId)) return null; 5856 flags = updateFlagsForResolve(flags, userId, intent); 5857 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5858 if (query != null) { 5859 if (query.size() >= 1) { 5860 // If there is more than one service with the same priority, 5861 // just arbitrarily pick the first one. 5862 return query.get(0); 5863 } 5864 } 5865 return null; 5866 } 5867 5868 @Override 5869 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5870 String resolvedType, int flags, int userId) { 5871 return new ParceledListSlice<>( 5872 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5873 } 5874 5875 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5876 String resolvedType, int flags, int userId) { 5877 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5878 flags = updateFlagsForResolve(flags, userId, intent); 5879 ComponentName comp = intent.getComponent(); 5880 if (comp == null) { 5881 if (intent.getSelector() != null) { 5882 intent = intent.getSelector(); 5883 comp = intent.getComponent(); 5884 } 5885 } 5886 if (comp != null) { 5887 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5888 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5889 if (si != null) { 5890 final ResolveInfo ri = new ResolveInfo(); 5891 ri.serviceInfo = si; 5892 list.add(ri); 5893 } 5894 return list; 5895 } 5896 5897 // reader 5898 synchronized (mPackages) { 5899 String pkgName = intent.getPackage(); 5900 if (pkgName == null) { 5901 return mServices.queryIntent(intent, resolvedType, flags, userId); 5902 } 5903 final PackageParser.Package pkg = mPackages.get(pkgName); 5904 if (pkg != null) { 5905 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5906 userId); 5907 } 5908 return Collections.emptyList(); 5909 } 5910 } 5911 5912 @Override 5913 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5914 String resolvedType, int flags, int userId) { 5915 return new ParceledListSlice<>( 5916 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5917 } 5918 5919 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5920 Intent intent, String resolvedType, int flags, int userId) { 5921 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5922 flags = updateFlagsForResolve(flags, userId, intent); 5923 ComponentName comp = intent.getComponent(); 5924 if (comp == null) { 5925 if (intent.getSelector() != null) { 5926 intent = intent.getSelector(); 5927 comp = intent.getComponent(); 5928 } 5929 } 5930 if (comp != null) { 5931 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5932 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5933 if (pi != null) { 5934 final ResolveInfo ri = new ResolveInfo(); 5935 ri.providerInfo = pi; 5936 list.add(ri); 5937 } 5938 return list; 5939 } 5940 5941 // reader 5942 synchronized (mPackages) { 5943 String pkgName = intent.getPackage(); 5944 if (pkgName == null) { 5945 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5946 } 5947 final PackageParser.Package pkg = mPackages.get(pkgName); 5948 if (pkg != null) { 5949 return mProviders.queryIntentForPackage( 5950 intent, resolvedType, flags, pkg.providers, userId); 5951 } 5952 return Collections.emptyList(); 5953 } 5954 } 5955 5956 @Override 5957 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5958 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5959 flags = updateFlagsForPackage(flags, userId, null); 5960 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5961 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5962 true /* requireFullPermission */, false /* checkShell */, 5963 "get installed packages"); 5964 5965 // writer 5966 synchronized (mPackages) { 5967 ArrayList<PackageInfo> list; 5968 if (listUninstalled) { 5969 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5970 for (PackageSetting ps : mSettings.mPackages.values()) { 5971 final PackageInfo pi; 5972 if (ps.pkg != null) { 5973 pi = generatePackageInfo(ps, flags, userId); 5974 } else { 5975 pi = generatePackageInfo(ps, flags, userId); 5976 } 5977 if (pi != null) { 5978 list.add(pi); 5979 } 5980 } 5981 } else { 5982 list = new ArrayList<PackageInfo>(mPackages.size()); 5983 for (PackageParser.Package p : mPackages.values()) { 5984 final PackageInfo pi = 5985 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 5986 if (pi != null) { 5987 list.add(pi); 5988 } 5989 } 5990 } 5991 5992 return new ParceledListSlice<PackageInfo>(list); 5993 } 5994 } 5995 5996 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5997 String[] permissions, boolean[] tmp, int flags, int userId) { 5998 int numMatch = 0; 5999 final PermissionsState permissionsState = ps.getPermissionsState(); 6000 for (int i=0; i<permissions.length; i++) { 6001 final String permission = permissions[i]; 6002 if (permissionsState.hasPermission(permission, userId)) { 6003 tmp[i] = true; 6004 numMatch++; 6005 } else { 6006 tmp[i] = false; 6007 } 6008 } 6009 if (numMatch == 0) { 6010 return; 6011 } 6012 final PackageInfo pi; 6013 if (ps.pkg != null) { 6014 pi = generatePackageInfo(ps, flags, userId); 6015 } else { 6016 pi = generatePackageInfo(ps, flags, userId); 6017 } 6018 // The above might return null in cases of uninstalled apps or install-state 6019 // skew across users/profiles. 6020 if (pi != null) { 6021 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6022 if (numMatch == permissions.length) { 6023 pi.requestedPermissions = permissions; 6024 } else { 6025 pi.requestedPermissions = new String[numMatch]; 6026 numMatch = 0; 6027 for (int i=0; i<permissions.length; i++) { 6028 if (tmp[i]) { 6029 pi.requestedPermissions[numMatch] = permissions[i]; 6030 numMatch++; 6031 } 6032 } 6033 } 6034 } 6035 list.add(pi); 6036 } 6037 } 6038 6039 @Override 6040 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6041 String[] permissions, int flags, int userId) { 6042 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6043 flags = updateFlagsForPackage(flags, userId, permissions); 6044 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6045 6046 // writer 6047 synchronized (mPackages) { 6048 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6049 boolean[] tmpBools = new boolean[permissions.length]; 6050 if (listUninstalled) { 6051 for (PackageSetting ps : mSettings.mPackages.values()) { 6052 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6053 } 6054 } else { 6055 for (PackageParser.Package pkg : mPackages.values()) { 6056 PackageSetting ps = (PackageSetting)pkg.mExtras; 6057 if (ps != null) { 6058 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6059 userId); 6060 } 6061 } 6062 } 6063 6064 return new ParceledListSlice<PackageInfo>(list); 6065 } 6066 } 6067 6068 @Override 6069 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6070 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6071 flags = updateFlagsForApplication(flags, userId, null); 6072 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6073 6074 // writer 6075 synchronized (mPackages) { 6076 ArrayList<ApplicationInfo> list; 6077 if (listUninstalled) { 6078 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6079 for (PackageSetting ps : mSettings.mPackages.values()) { 6080 ApplicationInfo ai; 6081 if (ps.pkg != null) { 6082 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6083 ps.readUserState(userId), userId); 6084 } else { 6085 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6086 } 6087 if (ai != null) { 6088 list.add(ai); 6089 } 6090 } 6091 } else { 6092 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6093 for (PackageParser.Package p : mPackages.values()) { 6094 if (p.mExtras != null) { 6095 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6096 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6097 if (ai != null) { 6098 list.add(ai); 6099 } 6100 } 6101 } 6102 } 6103 6104 return new ParceledListSlice<ApplicationInfo>(list); 6105 } 6106 } 6107 6108 @Override 6109 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6110 if (DISABLE_EPHEMERAL_APPS) { 6111 return null; 6112 } 6113 6114 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6115 "getEphemeralApplications"); 6116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6117 true /* requireFullPermission */, false /* checkShell */, 6118 "getEphemeralApplications"); 6119 synchronized (mPackages) { 6120 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6121 .getEphemeralApplicationsLPw(userId); 6122 if (ephemeralApps != null) { 6123 return new ParceledListSlice<>(ephemeralApps); 6124 } 6125 } 6126 return null; 6127 } 6128 6129 @Override 6130 public boolean isEphemeralApplication(String packageName, int userId) { 6131 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6132 true /* requireFullPermission */, false /* checkShell */, 6133 "isEphemeral"); 6134 if (DISABLE_EPHEMERAL_APPS) { 6135 return false; 6136 } 6137 6138 if (!isCallerSameApp(packageName)) { 6139 return false; 6140 } 6141 synchronized (mPackages) { 6142 PackageParser.Package pkg = mPackages.get(packageName); 6143 if (pkg != null) { 6144 return pkg.applicationInfo.isEphemeralApp(); 6145 } 6146 } 6147 return false; 6148 } 6149 6150 @Override 6151 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6152 if (DISABLE_EPHEMERAL_APPS) { 6153 return null; 6154 } 6155 6156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6157 true /* requireFullPermission */, false /* checkShell */, 6158 "getCookie"); 6159 if (!isCallerSameApp(packageName)) { 6160 return null; 6161 } 6162 synchronized (mPackages) { 6163 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6164 packageName, userId); 6165 } 6166 } 6167 6168 @Override 6169 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6170 if (DISABLE_EPHEMERAL_APPS) { 6171 return true; 6172 } 6173 6174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6175 true /* requireFullPermission */, true /* checkShell */, 6176 "setCookie"); 6177 if (!isCallerSameApp(packageName)) { 6178 return false; 6179 } 6180 synchronized (mPackages) { 6181 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6182 packageName, cookie, userId); 6183 } 6184 } 6185 6186 @Override 6187 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6188 if (DISABLE_EPHEMERAL_APPS) { 6189 return null; 6190 } 6191 6192 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6193 "getEphemeralApplicationIcon"); 6194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6195 true /* requireFullPermission */, false /* checkShell */, 6196 "getEphemeralApplicationIcon"); 6197 synchronized (mPackages) { 6198 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6199 packageName, userId); 6200 } 6201 } 6202 6203 private boolean isCallerSameApp(String packageName) { 6204 PackageParser.Package pkg = mPackages.get(packageName); 6205 return pkg != null 6206 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6207 } 6208 6209 @Override 6210 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6211 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6212 } 6213 6214 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6215 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6216 6217 // reader 6218 synchronized (mPackages) { 6219 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6220 final int userId = UserHandle.getCallingUserId(); 6221 while (i.hasNext()) { 6222 final PackageParser.Package p = i.next(); 6223 if (p.applicationInfo == null) continue; 6224 6225 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6226 && !p.applicationInfo.isDirectBootAware(); 6227 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6228 && p.applicationInfo.isDirectBootAware(); 6229 6230 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6231 && (!mSafeMode || isSystemApp(p)) 6232 && (matchesUnaware || matchesAware)) { 6233 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6234 if (ps != null) { 6235 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6236 ps.readUserState(userId), userId); 6237 if (ai != null) { 6238 finalList.add(ai); 6239 } 6240 } 6241 } 6242 } 6243 } 6244 6245 return finalList; 6246 } 6247 6248 @Override 6249 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6250 if (!sUserManager.exists(userId)) return null; 6251 flags = updateFlagsForComponent(flags, userId, name); 6252 // reader 6253 synchronized (mPackages) { 6254 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6255 PackageSetting ps = provider != null 6256 ? mSettings.mPackages.get(provider.owner.packageName) 6257 : null; 6258 return ps != null 6259 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6260 ? PackageParser.generateProviderInfo(provider, flags, 6261 ps.readUserState(userId), userId) 6262 : null; 6263 } 6264 } 6265 6266 /** 6267 * @deprecated 6268 */ 6269 @Deprecated 6270 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6271 // reader 6272 synchronized (mPackages) { 6273 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6274 .entrySet().iterator(); 6275 final int userId = UserHandle.getCallingUserId(); 6276 while (i.hasNext()) { 6277 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6278 PackageParser.Provider p = entry.getValue(); 6279 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6280 6281 if (ps != null && p.syncable 6282 && (!mSafeMode || (p.info.applicationInfo.flags 6283 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6284 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6285 ps.readUserState(userId), userId); 6286 if (info != null) { 6287 outNames.add(entry.getKey()); 6288 outInfo.add(info); 6289 } 6290 } 6291 } 6292 } 6293 } 6294 6295 @Override 6296 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6297 int uid, int flags) { 6298 final int userId = processName != null ? UserHandle.getUserId(uid) 6299 : UserHandle.getCallingUserId(); 6300 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6301 flags = updateFlagsForComponent(flags, userId, processName); 6302 6303 ArrayList<ProviderInfo> finalList = null; 6304 // reader 6305 synchronized (mPackages) { 6306 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6307 while (i.hasNext()) { 6308 final PackageParser.Provider p = i.next(); 6309 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6310 if (ps != null && p.info.authority != null 6311 && (processName == null 6312 || (p.info.processName.equals(processName) 6313 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6314 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6315 if (finalList == null) { 6316 finalList = new ArrayList<ProviderInfo>(3); 6317 } 6318 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6319 ps.readUserState(userId), userId); 6320 if (info != null) { 6321 finalList.add(info); 6322 } 6323 } 6324 } 6325 } 6326 6327 if (finalList != null) { 6328 Collections.sort(finalList, mProviderInitOrderSorter); 6329 return new ParceledListSlice<ProviderInfo>(finalList); 6330 } 6331 6332 return ParceledListSlice.emptyList(); 6333 } 6334 6335 @Override 6336 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6337 // reader 6338 synchronized (mPackages) { 6339 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6340 return PackageParser.generateInstrumentationInfo(i, flags); 6341 } 6342 } 6343 6344 @Override 6345 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6346 String targetPackage, int flags) { 6347 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6348 } 6349 6350 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6351 int flags) { 6352 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6353 6354 // reader 6355 synchronized (mPackages) { 6356 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6357 while (i.hasNext()) { 6358 final PackageParser.Instrumentation p = i.next(); 6359 if (targetPackage == null 6360 || targetPackage.equals(p.info.targetPackage)) { 6361 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6362 flags); 6363 if (ii != null) { 6364 finalList.add(ii); 6365 } 6366 } 6367 } 6368 } 6369 6370 return finalList; 6371 } 6372 6373 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6374 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6375 if (overlays == null) { 6376 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6377 return; 6378 } 6379 for (PackageParser.Package opkg : overlays.values()) { 6380 // Not much to do if idmap fails: we already logged the error 6381 // and we certainly don't want to abort installation of pkg simply 6382 // because an overlay didn't fit properly. For these reasons, 6383 // ignore the return value of createIdmapForPackagePairLI. 6384 createIdmapForPackagePairLI(pkg, opkg); 6385 } 6386 } 6387 6388 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6389 PackageParser.Package opkg) { 6390 if (!opkg.mTrustedOverlay) { 6391 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6392 opkg.baseCodePath + ": overlay not trusted"); 6393 return false; 6394 } 6395 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6396 if (overlaySet == null) { 6397 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6398 opkg.baseCodePath + " but target package has no known overlays"); 6399 return false; 6400 } 6401 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6402 // TODO: generate idmap for split APKs 6403 try { 6404 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6405 } catch (InstallerException e) { 6406 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6407 + opkg.baseCodePath); 6408 return false; 6409 } 6410 PackageParser.Package[] overlayArray = 6411 overlaySet.values().toArray(new PackageParser.Package[0]); 6412 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6413 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6414 return p1.mOverlayPriority - p2.mOverlayPriority; 6415 } 6416 }; 6417 Arrays.sort(overlayArray, cmp); 6418 6419 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6420 int i = 0; 6421 for (PackageParser.Package p : overlayArray) { 6422 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6423 } 6424 return true; 6425 } 6426 6427 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6429 try { 6430 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6431 } finally { 6432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6433 } 6434 } 6435 6436 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6437 final File[] files = dir.listFiles(); 6438 if (ArrayUtils.isEmpty(files)) { 6439 Log.d(TAG, "No files in app dir " + dir); 6440 return; 6441 } 6442 6443 if (DEBUG_PACKAGE_SCANNING) { 6444 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6445 + " flags=0x" + Integer.toHexString(parseFlags)); 6446 } 6447 6448 for (File file : files) { 6449 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6450 && !PackageInstallerService.isStageName(file.getName()); 6451 if (!isPackage) { 6452 // Ignore entries which are not packages 6453 continue; 6454 } 6455 try { 6456 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6457 scanFlags, currentTime, null); 6458 } catch (PackageManagerException e) { 6459 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6460 6461 // Delete invalid userdata apps 6462 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6463 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6464 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6465 removeCodePathLI(file); 6466 } 6467 } 6468 } 6469 } 6470 6471 private static File getSettingsProblemFile() { 6472 File dataDir = Environment.getDataDirectory(); 6473 File systemDir = new File(dataDir, "system"); 6474 File fname = new File(systemDir, "uiderrors.txt"); 6475 return fname; 6476 } 6477 6478 static void reportSettingsProblem(int priority, String msg) { 6479 logCriticalInfo(priority, msg); 6480 } 6481 6482 static void logCriticalInfo(int priority, String msg) { 6483 Slog.println(priority, TAG, msg); 6484 EventLogTags.writePmCriticalInfo(msg); 6485 try { 6486 File fname = getSettingsProblemFile(); 6487 FileOutputStream out = new FileOutputStream(fname, true); 6488 PrintWriter pw = new FastPrintWriter(out); 6489 SimpleDateFormat formatter = new SimpleDateFormat(); 6490 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6491 pw.println(dateString + ": " + msg); 6492 pw.close(); 6493 FileUtils.setPermissions( 6494 fname.toString(), 6495 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6496 -1, -1); 6497 } catch (java.io.IOException e) { 6498 } 6499 } 6500 6501 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6502 int parseFlags) throws PackageManagerException { 6503 if (ps != null 6504 && ps.codePath.equals(srcFile) 6505 && ps.timeStamp == srcFile.lastModified() 6506 && !isCompatSignatureUpdateNeeded(pkg) 6507 && !isRecoverSignatureUpdateNeeded(pkg)) { 6508 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6509 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6510 ArraySet<PublicKey> signingKs; 6511 synchronized (mPackages) { 6512 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6513 } 6514 if (ps.signatures.mSignatures != null 6515 && ps.signatures.mSignatures.length != 0 6516 && signingKs != null) { 6517 // Optimization: reuse the existing cached certificates 6518 // if the package appears to be unchanged. 6519 pkg.mSignatures = ps.signatures.mSignatures; 6520 pkg.mSigningKeys = signingKs; 6521 return; 6522 } 6523 6524 Slog.w(TAG, "PackageSetting for " + ps.name 6525 + " is missing signatures. Collecting certs again to recover them."); 6526 } else { 6527 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6528 } 6529 6530 try { 6531 PackageParser.collectCertificates(pkg, parseFlags); 6532 } catch (PackageParserException e) { 6533 throw PackageManagerException.from(e); 6534 } 6535 } 6536 6537 /** 6538 * Traces a package scan. 6539 * @see #scanPackageLI(File, int, int, long, UserHandle) 6540 */ 6541 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6542 long currentTime, UserHandle user) throws PackageManagerException { 6543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6544 try { 6545 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6546 } finally { 6547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6548 } 6549 } 6550 6551 /** 6552 * Scans a package and returns the newly parsed package. 6553 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6554 */ 6555 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6556 long currentTime, UserHandle user) throws PackageManagerException { 6557 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6558 parseFlags |= mDefParseFlags; 6559 PackageParser pp = new PackageParser(); 6560 pp.setSeparateProcesses(mSeparateProcesses); 6561 pp.setOnlyCoreApps(mOnlyCore); 6562 pp.setDisplayMetrics(mMetrics); 6563 6564 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6565 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6566 } 6567 6568 final PackageParser.Package pkg; 6569 try { 6570 pkg = pp.parsePackage(scanFile, parseFlags); 6571 } catch (PackageParserException e) { 6572 throw PackageManagerException.from(e); 6573 } 6574 6575 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6576 } 6577 6578 /** 6579 * Scans a package and returns the newly parsed package. 6580 * @throws PackageManagerException on a parse error. 6581 */ 6582 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6583 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6584 throws PackageManagerException { 6585 // If the package has children and this is the first dive in the function 6586 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6587 // packages (parent and children) would be successfully scanned before the 6588 // actual scan since scanning mutates internal state and we want to atomically 6589 // install the package and its children. 6590 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6591 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6592 scanFlags |= SCAN_CHECK_ONLY; 6593 } 6594 } else { 6595 scanFlags &= ~SCAN_CHECK_ONLY; 6596 } 6597 6598 // Scan the parent 6599 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6600 scanFlags, currentTime, user); 6601 6602 // Scan the children 6603 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6604 for (int i = 0; i < childCount; i++) { 6605 PackageParser.Package childPackage = pkg.childPackages.get(i); 6606 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6607 currentTime, user); 6608 } 6609 6610 6611 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6612 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6613 } 6614 6615 return scannedPkg; 6616 } 6617 6618 /** 6619 * Scans a package and returns the newly parsed package. 6620 * @throws PackageManagerException on a parse error. 6621 */ 6622 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6623 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6624 throws PackageManagerException { 6625 PackageSetting ps = null; 6626 PackageSetting updatedPkg; 6627 // reader 6628 synchronized (mPackages) { 6629 // Look to see if we already know about this package. 6630 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6631 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6632 // This package has been renamed to its original name. Let's 6633 // use that. 6634 ps = mSettings.peekPackageLPr(oldName); 6635 } 6636 // If there was no original package, see one for the real package name. 6637 if (ps == null) { 6638 ps = mSettings.peekPackageLPr(pkg.packageName); 6639 } 6640 // Check to see if this package could be hiding/updating a system 6641 // package. Must look for it either under the original or real 6642 // package name depending on our state. 6643 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6644 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6645 6646 // If this is a package we don't know about on the system partition, we 6647 // may need to remove disabled child packages on the system partition 6648 // or may need to not add child packages if the parent apk is updated 6649 // on the data partition and no longer defines this child package. 6650 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6651 // If this is a parent package for an updated system app and this system 6652 // app got an OTA update which no longer defines some of the child packages 6653 // we have to prune them from the disabled system packages. 6654 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6655 if (disabledPs != null) { 6656 final int scannedChildCount = (pkg.childPackages != null) 6657 ? pkg.childPackages.size() : 0; 6658 final int disabledChildCount = disabledPs.childPackageNames != null 6659 ? disabledPs.childPackageNames.size() : 0; 6660 for (int i = 0; i < disabledChildCount; i++) { 6661 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6662 boolean disabledPackageAvailable = false; 6663 for (int j = 0; j < scannedChildCount; j++) { 6664 PackageParser.Package childPkg = pkg.childPackages.get(j); 6665 if (childPkg.packageName.equals(disabledChildPackageName)) { 6666 disabledPackageAvailable = true; 6667 break; 6668 } 6669 } 6670 if (!disabledPackageAvailable) { 6671 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6672 } 6673 } 6674 } 6675 } 6676 } 6677 6678 boolean updatedPkgBetter = false; 6679 // First check if this is a system package that may involve an update 6680 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6681 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6682 // it needs to drop FLAG_PRIVILEGED. 6683 if (locationIsPrivileged(scanFile)) { 6684 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6685 } else { 6686 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6687 } 6688 6689 if (ps != null && !ps.codePath.equals(scanFile)) { 6690 // The path has changed from what was last scanned... check the 6691 // version of the new path against what we have stored to determine 6692 // what to do. 6693 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6694 if (pkg.mVersionCode <= ps.versionCode) { 6695 // The system package has been updated and the code path does not match 6696 // Ignore entry. Skip it. 6697 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6698 + " ignored: updated version " + ps.versionCode 6699 + " better than this " + pkg.mVersionCode); 6700 if (!updatedPkg.codePath.equals(scanFile)) { 6701 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6702 + ps.name + " changing from " + updatedPkg.codePathString 6703 + " to " + scanFile); 6704 updatedPkg.codePath = scanFile; 6705 updatedPkg.codePathString = scanFile.toString(); 6706 updatedPkg.resourcePath = scanFile; 6707 updatedPkg.resourcePathString = scanFile.toString(); 6708 } 6709 updatedPkg.pkg = pkg; 6710 updatedPkg.versionCode = pkg.mVersionCode; 6711 6712 // Update the disabled system child packages to point to the package too. 6713 final int childCount = updatedPkg.childPackageNames != null 6714 ? updatedPkg.childPackageNames.size() : 0; 6715 for (int i = 0; i < childCount; i++) { 6716 String childPackageName = updatedPkg.childPackageNames.get(i); 6717 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6718 childPackageName); 6719 if (updatedChildPkg != null) { 6720 updatedChildPkg.pkg = pkg; 6721 updatedChildPkg.versionCode = pkg.mVersionCode; 6722 } 6723 } 6724 6725 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6726 + scanFile + " ignored: updated version " + ps.versionCode 6727 + " better than this " + pkg.mVersionCode); 6728 } else { 6729 // The current app on the system partition is better than 6730 // what we have updated to on the data partition; switch 6731 // back to the system partition version. 6732 // At this point, its safely assumed that package installation for 6733 // apps in system partition will go through. If not there won't be a working 6734 // version of the app 6735 // writer 6736 synchronized (mPackages) { 6737 // Just remove the loaded entries from package lists. 6738 mPackages.remove(ps.name); 6739 } 6740 6741 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6742 + " reverting from " + ps.codePathString 6743 + ": new version " + pkg.mVersionCode 6744 + " better than installed " + ps.versionCode); 6745 6746 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6747 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6748 synchronized (mInstallLock) { 6749 args.cleanUpResourcesLI(); 6750 } 6751 synchronized (mPackages) { 6752 mSettings.enableSystemPackageLPw(ps.name); 6753 } 6754 updatedPkgBetter = true; 6755 } 6756 } 6757 } 6758 6759 if (updatedPkg != null) { 6760 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6761 // initially 6762 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6763 6764 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6765 // flag set initially 6766 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6767 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6768 } 6769 } 6770 6771 // Verify certificates against what was last scanned 6772 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6773 6774 /* 6775 * A new system app appeared, but we already had a non-system one of the 6776 * same name installed earlier. 6777 */ 6778 boolean shouldHideSystemApp = false; 6779 if (updatedPkg == null && ps != null 6780 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6781 /* 6782 * Check to make sure the signatures match first. If they don't, 6783 * wipe the installed application and its data. 6784 */ 6785 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6786 != PackageManager.SIGNATURE_MATCH) { 6787 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6788 + " signatures don't match existing userdata copy; removing"); 6789 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6790 ps = null; 6791 } else { 6792 /* 6793 * If the newly-added system app is an older version than the 6794 * already installed version, hide it. It will be scanned later 6795 * and re-added like an update. 6796 */ 6797 if (pkg.mVersionCode <= ps.versionCode) { 6798 shouldHideSystemApp = true; 6799 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6800 + " but new version " + pkg.mVersionCode + " better than installed " 6801 + ps.versionCode + "; hiding system"); 6802 } else { 6803 /* 6804 * The newly found system app is a newer version that the 6805 * one previously installed. Simply remove the 6806 * already-installed application and replace it with our own 6807 * while keeping the application data. 6808 */ 6809 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6810 + " reverting from " + ps.codePathString + ": new version " 6811 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6812 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6813 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6814 synchronized (mInstallLock) { 6815 args.cleanUpResourcesLI(); 6816 } 6817 } 6818 } 6819 } 6820 6821 // The apk is forward locked (not public) if its code and resources 6822 // are kept in different files. (except for app in either system or 6823 // vendor path). 6824 // TODO grab this value from PackageSettings 6825 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6826 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6827 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6828 } 6829 } 6830 6831 // TODO: extend to support forward-locked splits 6832 String resourcePath = null; 6833 String baseResourcePath = null; 6834 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6835 if (ps != null && ps.resourcePathString != null) { 6836 resourcePath = ps.resourcePathString; 6837 baseResourcePath = ps.resourcePathString; 6838 } else { 6839 // Should not happen at all. Just log an error. 6840 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6841 } 6842 } else { 6843 resourcePath = pkg.codePath; 6844 baseResourcePath = pkg.baseCodePath; 6845 } 6846 6847 // Set application objects path explicitly. 6848 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6849 pkg.setApplicationInfoCodePath(pkg.codePath); 6850 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6851 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6852 pkg.setApplicationInfoResourcePath(resourcePath); 6853 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6854 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6855 6856 // Note that we invoke the following method only if we are about to unpack an application 6857 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6858 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6859 6860 /* 6861 * If the system app should be overridden by a previously installed 6862 * data, hide the system app now and let the /data/app scan pick it up 6863 * again. 6864 */ 6865 if (shouldHideSystemApp) { 6866 synchronized (mPackages) { 6867 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6868 } 6869 } 6870 6871 return scannedPkg; 6872 } 6873 6874 private static String fixProcessName(String defProcessName, 6875 String processName, int uid) { 6876 if (processName == null) { 6877 return defProcessName; 6878 } 6879 return processName; 6880 } 6881 6882 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6883 throws PackageManagerException { 6884 if (pkgSetting.signatures.mSignatures != null) { 6885 // Already existing package. Make sure signatures match 6886 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6887 == PackageManager.SIGNATURE_MATCH; 6888 if (!match) { 6889 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6890 == PackageManager.SIGNATURE_MATCH; 6891 } 6892 if (!match) { 6893 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6894 == PackageManager.SIGNATURE_MATCH; 6895 } 6896 if (!match) { 6897 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6898 + pkg.packageName + " signatures do not match the " 6899 + "previously installed version; ignoring!"); 6900 } 6901 } 6902 6903 // Check for shared user signatures 6904 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6905 // Already existing package. Make sure signatures match 6906 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6907 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6908 if (!match) { 6909 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6910 == PackageManager.SIGNATURE_MATCH; 6911 } 6912 if (!match) { 6913 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6914 == PackageManager.SIGNATURE_MATCH; 6915 } 6916 if (!match) { 6917 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6918 "Package " + pkg.packageName 6919 + " has no signatures that match those in shared user " 6920 + pkgSetting.sharedUser.name + "; ignoring!"); 6921 } 6922 } 6923 } 6924 6925 /** 6926 * Enforces that only the system UID or root's UID can call a method exposed 6927 * via Binder. 6928 * 6929 * @param message used as message if SecurityException is thrown 6930 * @throws SecurityException if the caller is not system or root 6931 */ 6932 private static final void enforceSystemOrRoot(String message) { 6933 final int uid = Binder.getCallingUid(); 6934 if (uid != Process.SYSTEM_UID && uid != 0) { 6935 throw new SecurityException(message); 6936 } 6937 } 6938 6939 @Override 6940 public void performFstrimIfNeeded() { 6941 enforceSystemOrRoot("Only the system can request fstrim"); 6942 6943 // Before everything else, see whether we need to fstrim. 6944 try { 6945 IMountService ms = PackageHelper.getMountService(); 6946 if (ms != null) { 6947 final boolean isUpgrade = isUpgrade(); 6948 boolean doTrim = isUpgrade; 6949 if (doTrim) { 6950 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6951 } else { 6952 final long interval = android.provider.Settings.Global.getLong( 6953 mContext.getContentResolver(), 6954 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6955 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6956 if (interval > 0) { 6957 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6958 if (timeSinceLast > interval) { 6959 doTrim = true; 6960 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6961 + "; running immediately"); 6962 } 6963 } 6964 } 6965 if (doTrim) { 6966 if (!isFirstBoot()) { 6967 try { 6968 ActivityManagerNative.getDefault().showBootMessage( 6969 mContext.getResources().getString( 6970 R.string.android_upgrading_fstrim), true); 6971 } catch (RemoteException e) { 6972 } 6973 } 6974 ms.runMaintenance(); 6975 } 6976 } else { 6977 Slog.e(TAG, "Mount service unavailable!"); 6978 } 6979 } catch (RemoteException e) { 6980 // Can't happen; MountService is local 6981 } 6982 } 6983 6984 @Override 6985 public void updatePackagesIfNeeded() { 6986 enforceSystemOrRoot("Only the system can request package update"); 6987 6988 // We need to re-extract after an OTA. 6989 boolean causeUpgrade = isUpgrade(); 6990 6991 // First boot or factory reset. 6992 // Note: we also handle devices that are upgrading to N right now as if it is their 6993 // first boot, as they do not have profile data. 6994 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6995 6996 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6997 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6998 6999 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7000 return; 7001 } 7002 7003 List<PackageParser.Package> pkgs; 7004 synchronized (mPackages) { 7005 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7006 } 7007 7008 int curr = 0; 7009 int total = pkgs.size(); 7010 for (PackageParser.Package pkg : pkgs) { 7011 curr++; 7012 7013 if (DEBUG_DEXOPT) { 7014 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7015 } 7016 7017 if (!isFirstBoot()) { 7018 try { 7019 ActivityManagerNative.getDefault().showBootMessage( 7020 mContext.getResources().getString(R.string.android_upgrading_apk, 7021 curr, total), true); 7022 } catch (RemoteException e) { 7023 } 7024 } 7025 7026 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 7027 // If the cache was pruned, any compiled odex files will likely be out of date 7028 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 7029 // Instead, force the extraction in this case. 7030 performDexOpt(pkg.packageName, 7031 null /* instructionSet */, 7032 false /* checkProfiles */, 7033 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7034 false /* force */); 7035 } 7036 } 7037 } 7038 7039 @Override 7040 public void notifyPackageUse(String packageName) { 7041 synchronized (mPackages) { 7042 PackageParser.Package p = mPackages.get(packageName); 7043 if (p == null) { 7044 return; 7045 } 7046 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7047 } 7048 } 7049 7050 // TODO: this is not used nor needed. Delete it. 7051 @Override 7052 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7053 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7054 getFullCompilerFilter(), false /* force */); 7055 } 7056 7057 @Override 7058 public boolean performDexOpt(String packageName, String instructionSet, 7059 boolean checkProfiles, int compileReason, boolean force) { 7060 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7061 getCompilerFilterForReason(compileReason), force); 7062 } 7063 7064 @Override 7065 public boolean performDexOptMode(String packageName, String instructionSet, 7066 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7067 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7068 targetCompilerFilter, force); 7069 } 7070 7071 private boolean performDexOptTraced(String packageName, String instructionSet, 7072 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7074 try { 7075 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7076 targetCompilerFilter, force); 7077 } finally { 7078 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7079 } 7080 } 7081 7082 private boolean performDexOptInternal(String packageName, String instructionSet, 7083 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7084 PackageParser.Package p; 7085 final String targetInstructionSet; 7086 synchronized (mPackages) { 7087 p = mPackages.get(packageName); 7088 if (p == null) { 7089 return false; 7090 } 7091 mPackageUsage.write(false); 7092 7093 targetInstructionSet = instructionSet != null ? instructionSet : 7094 getPrimaryInstructionSet(p.applicationInfo); 7095 } 7096 long callingId = Binder.clearCallingIdentity(); 7097 try { 7098 synchronized (mInstallLock) { 7099 final String[] instructionSets = new String[] { targetInstructionSet }; 7100 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7101 checkProfiles, targetCompilerFilter, force); 7102 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7103 } 7104 } finally { 7105 Binder.restoreCallingIdentity(callingId); 7106 } 7107 } 7108 7109 public ArraySet<String> getOptimizablePackages() { 7110 ArraySet<String> pkgs = new ArraySet<String>(); 7111 synchronized (mPackages) { 7112 for (PackageParser.Package p : mPackages.values()) { 7113 if (PackageDexOptimizer.canOptimizePackage(p)) { 7114 pkgs.add(p.packageName); 7115 } 7116 } 7117 } 7118 return pkgs; 7119 } 7120 7121 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7122 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7123 boolean force) { 7124 // Select the dex optimizer based on the force parameter. 7125 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7126 // allocate an object here. 7127 PackageDexOptimizer pdo = force 7128 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7129 : mPackageDexOptimizer; 7130 7131 // Optimize all dependencies first. Note: we ignore the return value and march on 7132 // on errors. 7133 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7134 if (!deps.isEmpty()) { 7135 for (PackageParser.Package depPackage : deps) { 7136 // TODO: Analyze and investigate if we (should) profile libraries. 7137 // Currently this will do a full compilation of the library by default. 7138 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7139 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7140 } 7141 } 7142 7143 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7144 } 7145 7146 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7147 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7148 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7149 Set<String> collectedNames = new HashSet<>(); 7150 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7151 7152 retValue.remove(p); 7153 7154 return retValue; 7155 } else { 7156 return Collections.emptyList(); 7157 } 7158 } 7159 7160 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7161 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7162 if (!collectedNames.contains(p.packageName)) { 7163 collectedNames.add(p.packageName); 7164 collected.add(p); 7165 7166 if (p.usesLibraries != null) { 7167 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7168 } 7169 if (p.usesOptionalLibraries != null) { 7170 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7171 collectedNames); 7172 } 7173 } 7174 } 7175 7176 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7177 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7178 for (String libName : libs) { 7179 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7180 if (libPkg != null) { 7181 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7182 } 7183 } 7184 } 7185 7186 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7187 synchronized (mPackages) { 7188 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7189 if (lib != null && lib.apk != null) { 7190 return mPackages.get(lib.apk); 7191 } 7192 } 7193 return null; 7194 } 7195 7196 public void shutdown() { 7197 mPackageUsage.write(true); 7198 } 7199 7200 @Override 7201 public void forceDexOpt(String packageName) { 7202 enforceSystemOrRoot("forceDexOpt"); 7203 7204 PackageParser.Package pkg; 7205 synchronized (mPackages) { 7206 pkg = mPackages.get(packageName); 7207 if (pkg == null) { 7208 throw new IllegalArgumentException("Unknown package: " + packageName); 7209 } 7210 } 7211 7212 synchronized (mInstallLock) { 7213 final String[] instructionSets = new String[] { 7214 getPrimaryInstructionSet(pkg.applicationInfo) }; 7215 7216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7217 7218 // Whoever is calling forceDexOpt wants a fully compiled package. 7219 // Don't use profiles since that may cause compilation to be skipped. 7220 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7221 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7222 true /* force */); 7223 7224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7225 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7226 throw new IllegalStateException("Failed to dexopt: " + res); 7227 } 7228 } 7229 } 7230 7231 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7232 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7233 Slog.w(TAG, "Unable to update from " + oldPkg.name 7234 + " to " + newPkg.packageName 7235 + ": old package not in system partition"); 7236 return false; 7237 } else if (mPackages.get(oldPkg.name) != null) { 7238 Slog.w(TAG, "Unable to update from " + oldPkg.name 7239 + " to " + newPkg.packageName 7240 + ": old package still exists"); 7241 return false; 7242 } 7243 return true; 7244 } 7245 7246 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7247 // TODO: triage flags as part of 26466827 7248 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7249 7250 boolean res = true; 7251 final int[] users = sUserManager.getUserIds(); 7252 for (int user : users) { 7253 try { 7254 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7255 } catch (InstallerException e) { 7256 Slog.w(TAG, "Failed to delete data directory", e); 7257 res = false; 7258 } 7259 } 7260 return res; 7261 } 7262 7263 void removeCodePathLI(File codePath) { 7264 if (codePath.isDirectory()) { 7265 try { 7266 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7267 } catch (InstallerException e) { 7268 Slog.w(TAG, "Failed to remove code path", e); 7269 } 7270 } else { 7271 codePath.delete(); 7272 } 7273 } 7274 7275 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7276 try { 7277 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7278 } catch (InstallerException e) { 7279 Slog.w(TAG, "Failed to destroy app data", e); 7280 } 7281 } 7282 7283 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7284 int appId, String seinfo) { 7285 try { 7286 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7287 } catch (InstallerException e) { 7288 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7289 } 7290 } 7291 7292 private void deleteProfilesLI(String packageName, boolean destroy) { 7293 final PackageParser.Package pkg; 7294 synchronized (mPackages) { 7295 pkg = mPackages.get(packageName); 7296 } 7297 if (pkg == null) { 7298 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7299 return; 7300 } 7301 deleteProfilesLI(pkg, destroy); 7302 } 7303 7304 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7305 try { 7306 if (destroy) { 7307 mInstaller.destroyAppProfiles(pkg.packageName); 7308 } else { 7309 mInstaller.clearAppProfiles(pkg.packageName); 7310 } 7311 } catch (InstallerException ex) { 7312 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7313 } 7314 } 7315 7316 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7317 final PackageParser.Package pkg; 7318 synchronized (mPackages) { 7319 pkg = mPackages.get(packageName); 7320 } 7321 if (pkg == null) { 7322 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7323 return; 7324 } 7325 deleteCodeCacheDirsLI(pkg); 7326 } 7327 7328 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7329 // TODO: triage flags as part of 26466827 7330 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7331 7332 int[] users = sUserManager.getUserIds(); 7333 int res = 0; 7334 for (int user : users) { 7335 // Remove the parent code cache 7336 try { 7337 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7338 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7339 } catch (InstallerException e) { 7340 Slog.w(TAG, "Failed to delete code cache directory", e); 7341 } 7342 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7343 for (int i = 0; i < childCount; i++) { 7344 PackageParser.Package childPkg = pkg.childPackages.get(i); 7345 // Remove the child code cache 7346 try { 7347 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7348 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7349 } catch (InstallerException e) { 7350 Slog.w(TAG, "Failed to delete code cache directory", e); 7351 } 7352 } 7353 } 7354 } 7355 7356 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7357 long lastUpdateTime) { 7358 // Set parent install/update time 7359 PackageSetting ps = (PackageSetting) pkg.mExtras; 7360 if (ps != null) { 7361 ps.firstInstallTime = firstInstallTime; 7362 ps.lastUpdateTime = lastUpdateTime; 7363 } 7364 // Set children install/update time 7365 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7366 for (int i = 0; i < childCount; i++) { 7367 PackageParser.Package childPkg = pkg.childPackages.get(i); 7368 ps = (PackageSetting) childPkg.mExtras; 7369 if (ps != null) { 7370 ps.firstInstallTime = firstInstallTime; 7371 ps.lastUpdateTime = lastUpdateTime; 7372 } 7373 } 7374 } 7375 7376 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7377 PackageParser.Package changingLib) { 7378 if (file.path != null) { 7379 usesLibraryFiles.add(file.path); 7380 return; 7381 } 7382 PackageParser.Package p = mPackages.get(file.apk); 7383 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7384 // If we are doing this while in the middle of updating a library apk, 7385 // then we need to make sure to use that new apk for determining the 7386 // dependencies here. (We haven't yet finished committing the new apk 7387 // to the package manager state.) 7388 if (p == null || p.packageName.equals(changingLib.packageName)) { 7389 p = changingLib; 7390 } 7391 } 7392 if (p != null) { 7393 usesLibraryFiles.addAll(p.getAllCodePaths()); 7394 } 7395 } 7396 7397 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7398 PackageParser.Package changingLib) throws PackageManagerException { 7399 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7400 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7401 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7402 for (int i=0; i<N; i++) { 7403 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7404 if (file == null) { 7405 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7406 "Package " + pkg.packageName + " requires unavailable shared library " 7407 + pkg.usesLibraries.get(i) + "; failing!"); 7408 } 7409 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7410 } 7411 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7412 for (int i=0; i<N; i++) { 7413 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7414 if (file == null) { 7415 Slog.w(TAG, "Package " + pkg.packageName 7416 + " desires unavailable shared library " 7417 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7418 } else { 7419 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7420 } 7421 } 7422 N = usesLibraryFiles.size(); 7423 if (N > 0) { 7424 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7425 } else { 7426 pkg.usesLibraryFiles = null; 7427 } 7428 } 7429 } 7430 7431 private static boolean hasString(List<String> list, List<String> which) { 7432 if (list == null) { 7433 return false; 7434 } 7435 for (int i=list.size()-1; i>=0; i--) { 7436 for (int j=which.size()-1; j>=0; j--) { 7437 if (which.get(j).equals(list.get(i))) { 7438 return true; 7439 } 7440 } 7441 } 7442 return false; 7443 } 7444 7445 private void updateAllSharedLibrariesLPw() { 7446 for (PackageParser.Package pkg : mPackages.values()) { 7447 try { 7448 updateSharedLibrariesLPw(pkg, null); 7449 } catch (PackageManagerException e) { 7450 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7451 } 7452 } 7453 } 7454 7455 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7456 PackageParser.Package changingPkg) { 7457 ArrayList<PackageParser.Package> res = null; 7458 for (PackageParser.Package pkg : mPackages.values()) { 7459 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7460 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7461 if (res == null) { 7462 res = new ArrayList<PackageParser.Package>(); 7463 } 7464 res.add(pkg); 7465 try { 7466 updateSharedLibrariesLPw(pkg, changingPkg); 7467 } catch (PackageManagerException e) { 7468 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7469 } 7470 } 7471 } 7472 return res; 7473 } 7474 7475 /** 7476 * Derive the value of the {@code cpuAbiOverride} based on the provided 7477 * value and an optional stored value from the package settings. 7478 */ 7479 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7480 String cpuAbiOverride = null; 7481 7482 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7483 cpuAbiOverride = null; 7484 } else if (abiOverride != null) { 7485 cpuAbiOverride = abiOverride; 7486 } else if (settings != null) { 7487 cpuAbiOverride = settings.cpuAbiOverrideString; 7488 } 7489 7490 return cpuAbiOverride; 7491 } 7492 7493 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7494 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7496 // If the package has children and this is the first dive in the function 7497 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7498 // whether all packages (parent and children) would be successfully scanned 7499 // before the actual scan since scanning mutates internal state and we want 7500 // to atomically install the package and its children. 7501 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7502 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7503 scanFlags |= SCAN_CHECK_ONLY; 7504 } 7505 } else { 7506 scanFlags &= ~SCAN_CHECK_ONLY; 7507 } 7508 7509 final PackageParser.Package scannedPkg; 7510 try { 7511 // Scan the parent 7512 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7513 // Scan the children 7514 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7515 for (int i = 0; i < childCount; i++) { 7516 PackageParser.Package childPkg = pkg.childPackages.get(i); 7517 scanPackageLI(childPkg, parseFlags, 7518 scanFlags, currentTime, user); 7519 } 7520 } finally { 7521 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7522 } 7523 7524 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7525 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7526 } 7527 7528 return scannedPkg; 7529 } 7530 7531 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7532 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7533 boolean success = false; 7534 try { 7535 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7536 currentTime, user); 7537 success = true; 7538 return res; 7539 } finally { 7540 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7541 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7542 } 7543 } 7544 } 7545 7546 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7547 int scanFlags, long currentTime, UserHandle user) 7548 throws PackageManagerException { 7549 final File scanFile = new File(pkg.codePath); 7550 if (pkg.applicationInfo.getCodePath() == null || 7551 pkg.applicationInfo.getResourcePath() == null) { 7552 // Bail out. The resource and code paths haven't been set. 7553 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7554 "Code and resource paths haven't been set correctly"); 7555 } 7556 7557 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7558 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7559 } else { 7560 // Only allow system apps to be flagged as core apps. 7561 pkg.coreApp = false; 7562 } 7563 7564 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7565 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7566 } 7567 7568 if (mCustomResolverComponentName != null && 7569 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7570 setUpCustomResolverActivity(pkg); 7571 } 7572 7573 if (pkg.packageName.equals("android")) { 7574 synchronized (mPackages) { 7575 if (mAndroidApplication != null) { 7576 Slog.w(TAG, "*************************************************"); 7577 Slog.w(TAG, "Core android package being redefined. Skipping."); 7578 Slog.w(TAG, " file=" + scanFile); 7579 Slog.w(TAG, "*************************************************"); 7580 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7581 "Core android package being redefined. Skipping."); 7582 } 7583 7584 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7585 // Set up information for our fall-back user intent resolution activity. 7586 mPlatformPackage = pkg; 7587 pkg.mVersionCode = mSdkVersion; 7588 mAndroidApplication = pkg.applicationInfo; 7589 7590 if (!mResolverReplaced) { 7591 mResolveActivity.applicationInfo = mAndroidApplication; 7592 mResolveActivity.name = ResolverActivity.class.getName(); 7593 mResolveActivity.packageName = mAndroidApplication.packageName; 7594 mResolveActivity.processName = "system:ui"; 7595 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7596 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7597 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7598 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7599 mResolveActivity.exported = true; 7600 mResolveActivity.enabled = true; 7601 mResolveInfo.activityInfo = mResolveActivity; 7602 mResolveInfo.priority = 0; 7603 mResolveInfo.preferredOrder = 0; 7604 mResolveInfo.match = 0; 7605 mResolveComponentName = new ComponentName( 7606 mAndroidApplication.packageName, mResolveActivity.name); 7607 } 7608 } 7609 } 7610 } 7611 7612 if (DEBUG_PACKAGE_SCANNING) { 7613 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7614 Log.d(TAG, "Scanning package " + pkg.packageName); 7615 } 7616 7617 synchronized (mPackages) { 7618 if (mPackages.containsKey(pkg.packageName) 7619 || mSharedLibraries.containsKey(pkg.packageName)) { 7620 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7621 "Application package " + pkg.packageName 7622 + " already installed. Skipping duplicate."); 7623 } 7624 7625 // If we're only installing presumed-existing packages, require that the 7626 // scanned APK is both already known and at the path previously established 7627 // for it. Previously unknown packages we pick up normally, but if we have an 7628 // a priori expectation about this package's install presence, enforce it. 7629 // With a singular exception for new system packages. When an OTA contains 7630 // a new system package, we allow the codepath to change from a system location 7631 // to the user-installed location. If we don't allow this change, any newer, 7632 // user-installed version of the application will be ignored. 7633 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7634 if (mExpectingBetter.containsKey(pkg.packageName)) { 7635 logCriticalInfo(Log.WARN, 7636 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7637 } else { 7638 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7639 if (known != null) { 7640 if (DEBUG_PACKAGE_SCANNING) { 7641 Log.d(TAG, "Examining " + pkg.codePath 7642 + " and requiring known paths " + known.codePathString 7643 + " & " + known.resourcePathString); 7644 } 7645 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7646 || !pkg.applicationInfo.getResourcePath().equals( 7647 known.resourcePathString)) { 7648 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7649 "Application package " + pkg.packageName 7650 + " found at " + pkg.applicationInfo.getCodePath() 7651 + " but expected at " + known.codePathString 7652 + "; ignoring."); 7653 } 7654 } 7655 } 7656 } 7657 } 7658 7659 // Initialize package source and resource directories 7660 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7661 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7662 7663 SharedUserSetting suid = null; 7664 PackageSetting pkgSetting = null; 7665 7666 if (!isSystemApp(pkg)) { 7667 // Only system apps can use these features. 7668 pkg.mOriginalPackages = null; 7669 pkg.mRealPackage = null; 7670 pkg.mAdoptPermissions = null; 7671 } 7672 7673 // Getting the package setting may have a side-effect, so if we 7674 // are only checking if scan would succeed, stash a copy of the 7675 // old setting to restore at the end. 7676 PackageSetting nonMutatedPs = null; 7677 7678 // writer 7679 synchronized (mPackages) { 7680 if (pkg.mSharedUserId != null) { 7681 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7682 if (suid == null) { 7683 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7684 "Creating application package " + pkg.packageName 7685 + " for shared user failed"); 7686 } 7687 if (DEBUG_PACKAGE_SCANNING) { 7688 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7689 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7690 + "): packages=" + suid.packages); 7691 } 7692 } 7693 7694 // Check if we are renaming from an original package name. 7695 PackageSetting origPackage = null; 7696 String realName = null; 7697 if (pkg.mOriginalPackages != null) { 7698 // This package may need to be renamed to a previously 7699 // installed name. Let's check on that... 7700 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7701 if (pkg.mOriginalPackages.contains(renamed)) { 7702 // This package had originally been installed as the 7703 // original name, and we have already taken care of 7704 // transitioning to the new one. Just update the new 7705 // one to continue using the old name. 7706 realName = pkg.mRealPackage; 7707 if (!pkg.packageName.equals(renamed)) { 7708 // Callers into this function may have already taken 7709 // care of renaming the package; only do it here if 7710 // it is not already done. 7711 pkg.setPackageName(renamed); 7712 } 7713 7714 } else { 7715 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7716 if ((origPackage = mSettings.peekPackageLPr( 7717 pkg.mOriginalPackages.get(i))) != null) { 7718 // We do have the package already installed under its 7719 // original name... should we use it? 7720 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7721 // New package is not compatible with original. 7722 origPackage = null; 7723 continue; 7724 } else if (origPackage.sharedUser != null) { 7725 // Make sure uid is compatible between packages. 7726 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7727 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7728 + " to " + pkg.packageName + ": old uid " 7729 + origPackage.sharedUser.name 7730 + " differs from " + pkg.mSharedUserId); 7731 origPackage = null; 7732 continue; 7733 } 7734 } else { 7735 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7736 + pkg.packageName + " to old name " + origPackage.name); 7737 } 7738 break; 7739 } 7740 } 7741 } 7742 } 7743 7744 if (mTransferedPackages.contains(pkg.packageName)) { 7745 Slog.w(TAG, "Package " + pkg.packageName 7746 + " was transferred to another, but its .apk remains"); 7747 } 7748 7749 // See comments in nonMutatedPs declaration 7750 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7751 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7752 if (foundPs != null) { 7753 nonMutatedPs = new PackageSetting(foundPs); 7754 } 7755 } 7756 7757 // Just create the setting, don't add it yet. For already existing packages 7758 // the PkgSetting exists already and doesn't have to be created. 7759 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7760 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7761 pkg.applicationInfo.primaryCpuAbi, 7762 pkg.applicationInfo.secondaryCpuAbi, 7763 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7764 user, false); 7765 if (pkgSetting == null) { 7766 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7767 "Creating application package " + pkg.packageName + " failed"); 7768 } 7769 7770 if (pkgSetting.origPackage != null) { 7771 // If we are first transitioning from an original package, 7772 // fix up the new package's name now. We need to do this after 7773 // looking up the package under its new name, so getPackageLP 7774 // can take care of fiddling things correctly. 7775 pkg.setPackageName(origPackage.name); 7776 7777 // File a report about this. 7778 String msg = "New package " + pkgSetting.realName 7779 + " renamed to replace old package " + pkgSetting.name; 7780 reportSettingsProblem(Log.WARN, msg); 7781 7782 // Make a note of it. 7783 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7784 mTransferedPackages.add(origPackage.name); 7785 } 7786 7787 // No longer need to retain this. 7788 pkgSetting.origPackage = null; 7789 } 7790 7791 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7792 // Make a note of it. 7793 mTransferedPackages.add(pkg.packageName); 7794 } 7795 7796 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7797 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7798 } 7799 7800 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7801 // Check all shared libraries and map to their actual file path. 7802 // We only do this here for apps not on a system dir, because those 7803 // are the only ones that can fail an install due to this. We 7804 // will take care of the system apps by updating all of their 7805 // library paths after the scan is done. 7806 updateSharedLibrariesLPw(pkg, null); 7807 } 7808 7809 if (mFoundPolicyFile) { 7810 SELinuxMMAC.assignSeinfoValue(pkg); 7811 } 7812 7813 pkg.applicationInfo.uid = pkgSetting.appId; 7814 pkg.mExtras = pkgSetting; 7815 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7816 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7817 // We just determined the app is signed correctly, so bring 7818 // over the latest parsed certs. 7819 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7820 } else { 7821 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7822 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7823 "Package " + pkg.packageName + " upgrade keys do not match the " 7824 + "previously installed version"); 7825 } else { 7826 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7827 String msg = "System package " + pkg.packageName 7828 + " signature changed; retaining data."; 7829 reportSettingsProblem(Log.WARN, msg); 7830 } 7831 } 7832 } else { 7833 try { 7834 verifySignaturesLP(pkgSetting, pkg); 7835 // We just determined the app is signed correctly, so bring 7836 // over the latest parsed certs. 7837 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7838 } catch (PackageManagerException e) { 7839 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7840 throw e; 7841 } 7842 // The signature has changed, but this package is in the system 7843 // image... let's recover! 7844 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7845 // However... if this package is part of a shared user, but it 7846 // doesn't match the signature of the shared user, let's fail. 7847 // What this means is that you can't change the signatures 7848 // associated with an overall shared user, which doesn't seem all 7849 // that unreasonable. 7850 if (pkgSetting.sharedUser != null) { 7851 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7852 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7853 throw new PackageManagerException( 7854 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7855 "Signature mismatch for shared user: " 7856 + pkgSetting.sharedUser); 7857 } 7858 } 7859 // File a report about this. 7860 String msg = "System package " + pkg.packageName 7861 + " signature changed; retaining data."; 7862 reportSettingsProblem(Log.WARN, msg); 7863 } 7864 } 7865 // Verify that this new package doesn't have any content providers 7866 // that conflict with existing packages. Only do this if the 7867 // package isn't already installed, since we don't want to break 7868 // things that are installed. 7869 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7870 final int N = pkg.providers.size(); 7871 int i; 7872 for (i=0; i<N; i++) { 7873 PackageParser.Provider p = pkg.providers.get(i); 7874 if (p.info.authority != null) { 7875 String names[] = p.info.authority.split(";"); 7876 for (int j = 0; j < names.length; j++) { 7877 if (mProvidersByAuthority.containsKey(names[j])) { 7878 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7879 final String otherPackageName = 7880 ((other != null && other.getComponentName() != null) ? 7881 other.getComponentName().getPackageName() : "?"); 7882 throw new PackageManagerException( 7883 INSTALL_FAILED_CONFLICTING_PROVIDER, 7884 "Can't install because provider name " + names[j] 7885 + " (in package " + pkg.applicationInfo.packageName 7886 + ") is already used by " + otherPackageName); 7887 } 7888 } 7889 } 7890 } 7891 } 7892 7893 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7894 // This package wants to adopt ownership of permissions from 7895 // another package. 7896 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7897 final String origName = pkg.mAdoptPermissions.get(i); 7898 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7899 if (orig != null) { 7900 if (verifyPackageUpdateLPr(orig, pkg)) { 7901 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7902 + pkg.packageName); 7903 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7904 } 7905 } 7906 } 7907 } 7908 } 7909 7910 final String pkgName = pkg.packageName; 7911 7912 final long scanFileTime = scanFile.lastModified(); 7913 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7914 pkg.applicationInfo.processName = fixProcessName( 7915 pkg.applicationInfo.packageName, 7916 pkg.applicationInfo.processName, 7917 pkg.applicationInfo.uid); 7918 7919 if (pkg != mPlatformPackage) { 7920 // Get all of our default paths setup 7921 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7922 } 7923 7924 final String path = scanFile.getPath(); 7925 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7926 7927 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7928 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7929 7930 // Some system apps still use directory structure for native libraries 7931 // in which case we might end up not detecting abi solely based on apk 7932 // structure. Try to detect abi based on directory structure. 7933 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7934 pkg.applicationInfo.primaryCpuAbi == null) { 7935 setBundledAppAbisAndRoots(pkg, pkgSetting); 7936 setNativeLibraryPaths(pkg); 7937 } 7938 7939 } else { 7940 if ((scanFlags & SCAN_MOVE) != 0) { 7941 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7942 // but we already have this packages package info in the PackageSetting. We just 7943 // use that and derive the native library path based on the new codepath. 7944 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7945 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7946 } 7947 7948 // Set native library paths again. For moves, the path will be updated based on the 7949 // ABIs we've determined above. For non-moves, the path will be updated based on the 7950 // ABIs we determined during compilation, but the path will depend on the final 7951 // package path (after the rename away from the stage path). 7952 setNativeLibraryPaths(pkg); 7953 } 7954 7955 // This is a special case for the "system" package, where the ABI is 7956 // dictated by the zygote configuration (and init.rc). We should keep track 7957 // of this ABI so that we can deal with "normal" applications that run under 7958 // the same UID correctly. 7959 if (mPlatformPackage == pkg) { 7960 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7961 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7962 } 7963 7964 // If there's a mismatch between the abi-override in the package setting 7965 // and the abiOverride specified for the install. Warn about this because we 7966 // would've already compiled the app without taking the package setting into 7967 // account. 7968 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7969 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7970 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7971 " for package " + pkg.packageName); 7972 } 7973 } 7974 7975 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7976 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7977 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7978 7979 // Copy the derived override back to the parsed package, so that we can 7980 // update the package settings accordingly. 7981 pkg.cpuAbiOverride = cpuAbiOverride; 7982 7983 if (DEBUG_ABI_SELECTION) { 7984 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7985 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7986 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7987 } 7988 7989 // Push the derived path down into PackageSettings so we know what to 7990 // clean up at uninstall time. 7991 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7992 7993 if (DEBUG_ABI_SELECTION) { 7994 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7995 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7996 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7997 } 7998 7999 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8000 // We don't do this here during boot because we can do it all 8001 // at once after scanning all existing packages. 8002 // 8003 // We also do this *before* we perform dexopt on this package, so that 8004 // we can avoid redundant dexopts, and also to make sure we've got the 8005 // code and package path correct. 8006 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8007 pkg, true /* boot complete */); 8008 } 8009 8010 if (mFactoryTest && pkg.requestedPermissions.contains( 8011 android.Manifest.permission.FACTORY_TEST)) { 8012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8013 } 8014 8015 ArrayList<PackageParser.Package> clientLibPkgs = null; 8016 8017 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8018 if (nonMutatedPs != null) { 8019 synchronized (mPackages) { 8020 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8021 } 8022 } 8023 return pkg; 8024 } 8025 8026 // Only privileged apps and updated privileged apps can add child packages. 8027 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8028 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8029 throw new PackageManagerException("Only privileged apps and updated " 8030 + "privileged apps can add child packages. Ignoring package " 8031 + pkg.packageName); 8032 } 8033 final int childCount = pkg.childPackages.size(); 8034 for (int i = 0; i < childCount; i++) { 8035 PackageParser.Package childPkg = pkg.childPackages.get(i); 8036 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8037 childPkg.packageName)) { 8038 throw new PackageManagerException("Cannot override a child package of " 8039 + "another disabled system app. Ignoring package " + pkg.packageName); 8040 } 8041 } 8042 } 8043 8044 // writer 8045 synchronized (mPackages) { 8046 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8047 // Only system apps can add new shared libraries. 8048 if (pkg.libraryNames != null) { 8049 for (int i=0; i<pkg.libraryNames.size(); i++) { 8050 String name = pkg.libraryNames.get(i); 8051 boolean allowed = false; 8052 if (pkg.isUpdatedSystemApp()) { 8053 // New library entries can only be added through the 8054 // system image. This is important to get rid of a lot 8055 // of nasty edge cases: for example if we allowed a non- 8056 // system update of the app to add a library, then uninstalling 8057 // the update would make the library go away, and assumptions 8058 // we made such as through app install filtering would now 8059 // have allowed apps on the device which aren't compatible 8060 // with it. Better to just have the restriction here, be 8061 // conservative, and create many fewer cases that can negatively 8062 // impact the user experience. 8063 final PackageSetting sysPs = mSettings 8064 .getDisabledSystemPkgLPr(pkg.packageName); 8065 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8066 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8067 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8068 allowed = true; 8069 break; 8070 } 8071 } 8072 } 8073 } else { 8074 allowed = true; 8075 } 8076 if (allowed) { 8077 if (!mSharedLibraries.containsKey(name)) { 8078 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8079 } else if (!name.equals(pkg.packageName)) { 8080 Slog.w(TAG, "Package " + pkg.packageName + " library " 8081 + name + " already exists; skipping"); 8082 } 8083 } else { 8084 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8085 + name + " that is not declared on system image; skipping"); 8086 } 8087 } 8088 if ((scanFlags & SCAN_BOOTING) == 0) { 8089 // If we are not booting, we need to update any applications 8090 // that are clients of our shared library. If we are booting, 8091 // this will all be done once the scan is complete. 8092 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8093 } 8094 } 8095 } 8096 } 8097 8098 // Request the ActivityManager to kill the process(only for existing packages) 8099 // so that we do not end up in a confused state while the user is still using the older 8100 // version of the application while the new one gets installed. 8101 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8102 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8103 if (killApp) { 8104 if (isReplacing) { 8105 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8106 8107 killApplication(pkg.applicationInfo.packageName, 8108 pkg.applicationInfo.uid, "replace pkg"); 8109 8110 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8111 } 8112 } 8113 8114 // Also need to kill any apps that are dependent on the library. 8115 if (clientLibPkgs != null) { 8116 for (int i=0; i<clientLibPkgs.size(); i++) { 8117 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8118 killApplication(clientPkg.applicationInfo.packageName, 8119 clientPkg.applicationInfo.uid, "update lib"); 8120 } 8121 } 8122 8123 // Make sure we're not adding any bogus keyset info 8124 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8125 ksms.assertScannedPackageValid(pkg); 8126 8127 // writer 8128 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8129 8130 boolean createIdmapFailed = false; 8131 synchronized (mPackages) { 8132 // We don't expect installation to fail beyond this point 8133 8134 // Add the new setting to mSettings 8135 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8136 // Add the new setting to mPackages 8137 mPackages.put(pkg.applicationInfo.packageName, pkg); 8138 // Make sure we don't accidentally delete its data. 8139 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8140 while (iter.hasNext()) { 8141 PackageCleanItem item = iter.next(); 8142 if (pkgName.equals(item.packageName)) { 8143 iter.remove(); 8144 } 8145 } 8146 8147 // Take care of first install / last update times. 8148 if (currentTime != 0) { 8149 if (pkgSetting.firstInstallTime == 0) { 8150 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8151 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8152 pkgSetting.lastUpdateTime = currentTime; 8153 } 8154 } else if (pkgSetting.firstInstallTime == 0) { 8155 // We need *something*. Take time time stamp of the file. 8156 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8157 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8158 if (scanFileTime != pkgSetting.timeStamp) { 8159 // A package on the system image has changed; consider this 8160 // to be an update. 8161 pkgSetting.lastUpdateTime = scanFileTime; 8162 } 8163 } 8164 8165 // Add the package's KeySets to the global KeySetManagerService 8166 ksms.addScannedPackageLPw(pkg); 8167 8168 int N = pkg.providers.size(); 8169 StringBuilder r = null; 8170 int i; 8171 for (i=0; i<N; i++) { 8172 PackageParser.Provider p = pkg.providers.get(i); 8173 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8174 p.info.processName, pkg.applicationInfo.uid); 8175 mProviders.addProvider(p); 8176 p.syncable = p.info.isSyncable; 8177 if (p.info.authority != null) { 8178 String names[] = p.info.authority.split(";"); 8179 p.info.authority = null; 8180 for (int j = 0; j < names.length; j++) { 8181 if (j == 1 && p.syncable) { 8182 // We only want the first authority for a provider to possibly be 8183 // syncable, so if we already added this provider using a different 8184 // authority clear the syncable flag. We copy the provider before 8185 // changing it because the mProviders object contains a reference 8186 // to a provider that we don't want to change. 8187 // Only do this for the second authority since the resulting provider 8188 // object can be the same for all future authorities for this provider. 8189 p = new PackageParser.Provider(p); 8190 p.syncable = false; 8191 } 8192 if (!mProvidersByAuthority.containsKey(names[j])) { 8193 mProvidersByAuthority.put(names[j], p); 8194 if (p.info.authority == null) { 8195 p.info.authority = names[j]; 8196 } else { 8197 p.info.authority = p.info.authority + ";" + names[j]; 8198 } 8199 if (DEBUG_PACKAGE_SCANNING) { 8200 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8201 Log.d(TAG, "Registered content provider: " + names[j] 8202 + ", className = " + p.info.name + ", isSyncable = " 8203 + p.info.isSyncable); 8204 } 8205 } else { 8206 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8207 Slog.w(TAG, "Skipping provider name " + names[j] + 8208 " (in package " + pkg.applicationInfo.packageName + 8209 "): name already used by " 8210 + ((other != null && other.getComponentName() != null) 8211 ? other.getComponentName().getPackageName() : "?")); 8212 } 8213 } 8214 } 8215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8216 if (r == null) { 8217 r = new StringBuilder(256); 8218 } else { 8219 r.append(' '); 8220 } 8221 r.append(p.info.name); 8222 } 8223 } 8224 if (r != null) { 8225 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8226 } 8227 8228 N = pkg.services.size(); 8229 r = null; 8230 for (i=0; i<N; i++) { 8231 PackageParser.Service s = pkg.services.get(i); 8232 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8233 s.info.processName, pkg.applicationInfo.uid); 8234 mServices.addService(s); 8235 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8236 if (r == null) { 8237 r = new StringBuilder(256); 8238 } else { 8239 r.append(' '); 8240 } 8241 r.append(s.info.name); 8242 } 8243 } 8244 if (r != null) { 8245 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8246 } 8247 8248 N = pkg.receivers.size(); 8249 r = null; 8250 for (i=0; i<N; i++) { 8251 PackageParser.Activity a = pkg.receivers.get(i); 8252 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8253 a.info.processName, pkg.applicationInfo.uid); 8254 mReceivers.addActivity(a, "receiver"); 8255 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8256 if (r == null) { 8257 r = new StringBuilder(256); 8258 } else { 8259 r.append(' '); 8260 } 8261 r.append(a.info.name); 8262 } 8263 } 8264 if (r != null) { 8265 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8266 } 8267 8268 N = pkg.activities.size(); 8269 r = null; 8270 for (i=0; i<N; i++) { 8271 PackageParser.Activity a = pkg.activities.get(i); 8272 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8273 a.info.processName, pkg.applicationInfo.uid); 8274 mActivities.addActivity(a, "activity"); 8275 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8276 if (r == null) { 8277 r = new StringBuilder(256); 8278 } else { 8279 r.append(' '); 8280 } 8281 r.append(a.info.name); 8282 } 8283 } 8284 if (r != null) { 8285 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8286 } 8287 8288 N = pkg.permissionGroups.size(); 8289 r = null; 8290 for (i=0; i<N; i++) { 8291 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8292 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8293 if (cur == null) { 8294 mPermissionGroups.put(pg.info.name, pg); 8295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8296 if (r == null) { 8297 r = new StringBuilder(256); 8298 } else { 8299 r.append(' '); 8300 } 8301 r.append(pg.info.name); 8302 } 8303 } else { 8304 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8305 + pg.info.packageName + " ignored: original from " 8306 + cur.info.packageName); 8307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8308 if (r == null) { 8309 r = new StringBuilder(256); 8310 } else { 8311 r.append(' '); 8312 } 8313 r.append("DUP:"); 8314 r.append(pg.info.name); 8315 } 8316 } 8317 } 8318 if (r != null) { 8319 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8320 } 8321 8322 N = pkg.permissions.size(); 8323 r = null; 8324 for (i=0; i<N; i++) { 8325 PackageParser.Permission p = pkg.permissions.get(i); 8326 8327 // Assume by default that we did not install this permission into the system. 8328 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8329 8330 // Now that permission groups have a special meaning, we ignore permission 8331 // groups for legacy apps to prevent unexpected behavior. In particular, 8332 // permissions for one app being granted to someone just becase they happen 8333 // to be in a group defined by another app (before this had no implications). 8334 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8335 p.group = mPermissionGroups.get(p.info.group); 8336 // Warn for a permission in an unknown group. 8337 if (p.info.group != null && p.group == null) { 8338 Slog.w(TAG, "Permission " + p.info.name + " from package " 8339 + p.info.packageName + " in an unknown group " + p.info.group); 8340 } 8341 } 8342 8343 ArrayMap<String, BasePermission> permissionMap = 8344 p.tree ? mSettings.mPermissionTrees 8345 : mSettings.mPermissions; 8346 BasePermission bp = permissionMap.get(p.info.name); 8347 8348 // Allow system apps to redefine non-system permissions 8349 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8350 final boolean currentOwnerIsSystem = (bp.perm != null 8351 && isSystemApp(bp.perm.owner)); 8352 if (isSystemApp(p.owner)) { 8353 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8354 // It's a built-in permission and no owner, take ownership now 8355 bp.packageSetting = pkgSetting; 8356 bp.perm = p; 8357 bp.uid = pkg.applicationInfo.uid; 8358 bp.sourcePackage = p.info.packageName; 8359 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8360 } else if (!currentOwnerIsSystem) { 8361 String msg = "New decl " + p.owner + " of permission " 8362 + p.info.name + " is system; overriding " + bp.sourcePackage; 8363 reportSettingsProblem(Log.WARN, msg); 8364 bp = null; 8365 } 8366 } 8367 } 8368 8369 if (bp == null) { 8370 bp = new BasePermission(p.info.name, p.info.packageName, 8371 BasePermission.TYPE_NORMAL); 8372 permissionMap.put(p.info.name, bp); 8373 } 8374 8375 if (bp.perm == null) { 8376 if (bp.sourcePackage == null 8377 || bp.sourcePackage.equals(p.info.packageName)) { 8378 BasePermission tree = findPermissionTreeLP(p.info.name); 8379 if (tree == null 8380 || tree.sourcePackage.equals(p.info.packageName)) { 8381 bp.packageSetting = pkgSetting; 8382 bp.perm = p; 8383 bp.uid = pkg.applicationInfo.uid; 8384 bp.sourcePackage = p.info.packageName; 8385 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8386 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8387 if (r == null) { 8388 r = new StringBuilder(256); 8389 } else { 8390 r.append(' '); 8391 } 8392 r.append(p.info.name); 8393 } 8394 } else { 8395 Slog.w(TAG, "Permission " + p.info.name + " from package " 8396 + p.info.packageName + " ignored: base tree " 8397 + tree.name + " is from package " 8398 + tree.sourcePackage); 8399 } 8400 } else { 8401 Slog.w(TAG, "Permission " + p.info.name + " from package " 8402 + p.info.packageName + " ignored: original from " 8403 + bp.sourcePackage); 8404 } 8405 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8406 if (r == null) { 8407 r = new StringBuilder(256); 8408 } else { 8409 r.append(' '); 8410 } 8411 r.append("DUP:"); 8412 r.append(p.info.name); 8413 } 8414 if (bp.perm == p) { 8415 bp.protectionLevel = p.info.protectionLevel; 8416 } 8417 } 8418 8419 if (r != null) { 8420 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8421 } 8422 8423 N = pkg.instrumentation.size(); 8424 r = null; 8425 for (i=0; i<N; i++) { 8426 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8427 a.info.packageName = pkg.applicationInfo.packageName; 8428 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8429 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8430 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8431 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8432 a.info.dataDir = pkg.applicationInfo.dataDir; 8433 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8434 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8435 8436 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8437 // need other information about the application, like the ABI and what not ? 8438 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8439 mInstrumentation.put(a.getComponentName(), a); 8440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8441 if (r == null) { 8442 r = new StringBuilder(256); 8443 } else { 8444 r.append(' '); 8445 } 8446 r.append(a.info.name); 8447 } 8448 } 8449 if (r != null) { 8450 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8451 } 8452 8453 if (pkg.protectedBroadcasts != null) { 8454 N = pkg.protectedBroadcasts.size(); 8455 for (i=0; i<N; i++) { 8456 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8457 } 8458 } 8459 8460 pkgSetting.setTimeStamp(scanFileTime); 8461 8462 // Create idmap files for pairs of (packages, overlay packages). 8463 // Note: "android", ie framework-res.apk, is handled by native layers. 8464 if (pkg.mOverlayTarget != null) { 8465 // This is an overlay package. 8466 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8467 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8468 mOverlays.put(pkg.mOverlayTarget, 8469 new ArrayMap<String, PackageParser.Package>()); 8470 } 8471 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8472 map.put(pkg.packageName, pkg); 8473 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8474 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8475 createIdmapFailed = true; 8476 } 8477 } 8478 } else if (mOverlays.containsKey(pkg.packageName) && 8479 !pkg.packageName.equals("android")) { 8480 // This is a regular package, with one or more known overlay packages. 8481 createIdmapsForPackageLI(pkg); 8482 } 8483 } 8484 8485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8486 8487 if (createIdmapFailed) { 8488 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8489 "scanPackageLI failed to createIdmap"); 8490 } 8491 return pkg; 8492 } 8493 8494 /** 8495 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8496 * is derived purely on the basis of the contents of {@code scanFile} and 8497 * {@code cpuAbiOverride}. 8498 * 8499 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8500 */ 8501 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8502 String cpuAbiOverride, boolean extractLibs) 8503 throws PackageManagerException { 8504 // TODO: We can probably be smarter about this stuff. For installed apps, 8505 // we can calculate this information at install time once and for all. For 8506 // system apps, we can probably assume that this information doesn't change 8507 // after the first boot scan. As things stand, we do lots of unnecessary work. 8508 8509 // Give ourselves some initial paths; we'll come back for another 8510 // pass once we've determined ABI below. 8511 setNativeLibraryPaths(pkg); 8512 8513 // We would never need to extract libs for forward-locked and external packages, 8514 // since the container service will do it for us. We shouldn't attempt to 8515 // extract libs from system app when it was not updated. 8516 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8517 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8518 extractLibs = false; 8519 } 8520 8521 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8522 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8523 8524 NativeLibraryHelper.Handle handle = null; 8525 try { 8526 handle = NativeLibraryHelper.Handle.create(pkg); 8527 // TODO(multiArch): This can be null for apps that didn't go through the 8528 // usual installation process. We can calculate it again, like we 8529 // do during install time. 8530 // 8531 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8532 // unnecessary. 8533 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8534 8535 // Null out the abis so that they can be recalculated. 8536 pkg.applicationInfo.primaryCpuAbi = null; 8537 pkg.applicationInfo.secondaryCpuAbi = null; 8538 if (isMultiArch(pkg.applicationInfo)) { 8539 // Warn if we've set an abiOverride for multi-lib packages.. 8540 // By definition, we need to copy both 32 and 64 bit libraries for 8541 // such packages. 8542 if (pkg.cpuAbiOverride != null 8543 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8544 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8545 } 8546 8547 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8548 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8549 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8550 if (extractLibs) { 8551 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8552 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8553 useIsaSpecificSubdirs); 8554 } else { 8555 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8556 } 8557 } 8558 8559 maybeThrowExceptionForMultiArchCopy( 8560 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8561 8562 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8563 if (extractLibs) { 8564 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8565 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8566 useIsaSpecificSubdirs); 8567 } else { 8568 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8569 } 8570 } 8571 8572 maybeThrowExceptionForMultiArchCopy( 8573 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8574 8575 if (abi64 >= 0) { 8576 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8577 } 8578 8579 if (abi32 >= 0) { 8580 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8581 if (abi64 >= 0) { 8582 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8583 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8584 pkg.applicationInfo.primaryCpuAbi = abi; 8585 } else { 8586 pkg.applicationInfo.secondaryCpuAbi = abi; 8587 } 8588 } else { 8589 pkg.applicationInfo.primaryCpuAbi = abi; 8590 } 8591 } 8592 8593 } else { 8594 String[] abiList = (cpuAbiOverride != null) ? 8595 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8596 8597 // Enable gross and lame hacks for apps that are built with old 8598 // SDK tools. We must scan their APKs for renderscript bitcode and 8599 // not launch them if it's present. Don't bother checking on devices 8600 // that don't have 64 bit support. 8601 boolean needsRenderScriptOverride = false; 8602 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8603 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8604 abiList = Build.SUPPORTED_32_BIT_ABIS; 8605 needsRenderScriptOverride = true; 8606 } 8607 8608 final int copyRet; 8609 if (extractLibs) { 8610 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8611 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8612 } else { 8613 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8614 } 8615 8616 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8617 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8618 "Error unpackaging native libs for app, errorCode=" + copyRet); 8619 } 8620 8621 if (copyRet >= 0) { 8622 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8623 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8624 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8625 } else if (needsRenderScriptOverride) { 8626 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8627 } 8628 } 8629 } catch (IOException ioe) { 8630 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8631 } finally { 8632 IoUtils.closeQuietly(handle); 8633 } 8634 8635 // Now that we've calculated the ABIs and determined if it's an internal app, 8636 // we will go ahead and populate the nativeLibraryPath. 8637 setNativeLibraryPaths(pkg); 8638 } 8639 8640 /** 8641 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8642 * i.e, so that all packages can be run inside a single process if required. 8643 * 8644 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8645 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8646 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8647 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8648 * updating a package that belongs to a shared user. 8649 * 8650 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8651 * adds unnecessary complexity. 8652 */ 8653 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8654 PackageParser.Package scannedPackage, boolean bootComplete) { 8655 String requiredInstructionSet = null; 8656 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8657 requiredInstructionSet = VMRuntime.getInstructionSet( 8658 scannedPackage.applicationInfo.primaryCpuAbi); 8659 } 8660 8661 PackageSetting requirer = null; 8662 for (PackageSetting ps : packagesForUser) { 8663 // If packagesForUser contains scannedPackage, we skip it. This will happen 8664 // when scannedPackage is an update of an existing package. Without this check, 8665 // we will never be able to change the ABI of any package belonging to a shared 8666 // user, even if it's compatible with other packages. 8667 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8668 if (ps.primaryCpuAbiString == null) { 8669 continue; 8670 } 8671 8672 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8673 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8674 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8675 // this but there's not much we can do. 8676 String errorMessage = "Instruction set mismatch, " 8677 + ((requirer == null) ? "[caller]" : requirer) 8678 + " requires " + requiredInstructionSet + " whereas " + ps 8679 + " requires " + instructionSet; 8680 Slog.w(TAG, errorMessage); 8681 } 8682 8683 if (requiredInstructionSet == null) { 8684 requiredInstructionSet = instructionSet; 8685 requirer = ps; 8686 } 8687 } 8688 } 8689 8690 if (requiredInstructionSet != null) { 8691 String adjustedAbi; 8692 if (requirer != null) { 8693 // requirer != null implies that either scannedPackage was null or that scannedPackage 8694 // did not require an ABI, in which case we have to adjust scannedPackage to match 8695 // the ABI of the set (which is the same as requirer's ABI) 8696 adjustedAbi = requirer.primaryCpuAbiString; 8697 if (scannedPackage != null) { 8698 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8699 } 8700 } else { 8701 // requirer == null implies that we're updating all ABIs in the set to 8702 // match scannedPackage. 8703 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8704 } 8705 8706 for (PackageSetting ps : packagesForUser) { 8707 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8708 if (ps.primaryCpuAbiString != null) { 8709 continue; 8710 } 8711 8712 ps.primaryCpuAbiString = adjustedAbi; 8713 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8714 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8715 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8716 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8717 + " (requirer=" 8718 + (requirer == null ? "null" : requirer.pkg.packageName) 8719 + ", scannedPackage=" 8720 + (scannedPackage != null ? scannedPackage.packageName : "null") 8721 + ")"); 8722 try { 8723 mInstaller.rmdex(ps.codePathString, 8724 getDexCodeInstructionSet(getPreferredInstructionSet())); 8725 } catch (InstallerException ignored) { 8726 } 8727 } 8728 } 8729 } 8730 } 8731 } 8732 8733 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8734 synchronized (mPackages) { 8735 mResolverReplaced = true; 8736 // Set up information for custom user intent resolution activity. 8737 mResolveActivity.applicationInfo = pkg.applicationInfo; 8738 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8739 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8740 mResolveActivity.processName = pkg.applicationInfo.packageName; 8741 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8742 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8743 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8744 mResolveActivity.theme = 0; 8745 mResolveActivity.exported = true; 8746 mResolveActivity.enabled = true; 8747 mResolveInfo.activityInfo = mResolveActivity; 8748 mResolveInfo.priority = 0; 8749 mResolveInfo.preferredOrder = 0; 8750 mResolveInfo.match = 0; 8751 mResolveComponentName = mCustomResolverComponentName; 8752 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8753 mResolveComponentName); 8754 } 8755 } 8756 8757 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8758 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8759 8760 // Set up information for ephemeral installer activity 8761 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8762 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8763 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8764 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8765 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8766 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8767 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8768 mEphemeralInstallerActivity.theme = 0; 8769 mEphemeralInstallerActivity.exported = true; 8770 mEphemeralInstallerActivity.enabled = true; 8771 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8772 mEphemeralInstallerInfo.priority = 0; 8773 mEphemeralInstallerInfo.preferredOrder = 0; 8774 mEphemeralInstallerInfo.match = 0; 8775 8776 if (DEBUG_EPHEMERAL) { 8777 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8778 } 8779 } 8780 8781 private static String calculateBundledApkRoot(final String codePathString) { 8782 final File codePath = new File(codePathString); 8783 final File codeRoot; 8784 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8785 codeRoot = Environment.getRootDirectory(); 8786 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8787 codeRoot = Environment.getOemDirectory(); 8788 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8789 codeRoot = Environment.getVendorDirectory(); 8790 } else { 8791 // Unrecognized code path; take its top real segment as the apk root: 8792 // e.g. /something/app/blah.apk => /something 8793 try { 8794 File f = codePath.getCanonicalFile(); 8795 File parent = f.getParentFile(); // non-null because codePath is a file 8796 File tmp; 8797 while ((tmp = parent.getParentFile()) != null) { 8798 f = parent; 8799 parent = tmp; 8800 } 8801 codeRoot = f; 8802 Slog.w(TAG, "Unrecognized code path " 8803 + codePath + " - using " + codeRoot); 8804 } catch (IOException e) { 8805 // Can't canonicalize the code path -- shenanigans? 8806 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8807 return Environment.getRootDirectory().getPath(); 8808 } 8809 } 8810 return codeRoot.getPath(); 8811 } 8812 8813 /** 8814 * Derive and set the location of native libraries for the given package, 8815 * which varies depending on where and how the package was installed. 8816 */ 8817 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8818 final ApplicationInfo info = pkg.applicationInfo; 8819 final String codePath = pkg.codePath; 8820 final File codeFile = new File(codePath); 8821 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8822 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8823 8824 info.nativeLibraryRootDir = null; 8825 info.nativeLibraryRootRequiresIsa = false; 8826 info.nativeLibraryDir = null; 8827 info.secondaryNativeLibraryDir = null; 8828 8829 if (isApkFile(codeFile)) { 8830 // Monolithic install 8831 if (bundledApp) { 8832 // If "/system/lib64/apkname" exists, assume that is the per-package 8833 // native library directory to use; otherwise use "/system/lib/apkname". 8834 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8835 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8836 getPrimaryInstructionSet(info)); 8837 8838 // This is a bundled system app so choose the path based on the ABI. 8839 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8840 // is just the default path. 8841 final String apkName = deriveCodePathName(codePath); 8842 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8843 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8844 apkName).getAbsolutePath(); 8845 8846 if (info.secondaryCpuAbi != null) { 8847 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8848 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8849 secondaryLibDir, apkName).getAbsolutePath(); 8850 } 8851 } else if (asecApp) { 8852 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8853 .getAbsolutePath(); 8854 } else { 8855 final String apkName = deriveCodePathName(codePath); 8856 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8857 .getAbsolutePath(); 8858 } 8859 8860 info.nativeLibraryRootRequiresIsa = false; 8861 info.nativeLibraryDir = info.nativeLibraryRootDir; 8862 } else { 8863 // Cluster install 8864 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8865 info.nativeLibraryRootRequiresIsa = true; 8866 8867 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8868 getPrimaryInstructionSet(info)).getAbsolutePath(); 8869 8870 if (info.secondaryCpuAbi != null) { 8871 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8872 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8873 } 8874 } 8875 } 8876 8877 /** 8878 * Calculate the abis and roots for a bundled app. These can uniquely 8879 * be determined from the contents of the system partition, i.e whether 8880 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8881 * of this information, and instead assume that the system was built 8882 * sensibly. 8883 */ 8884 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8885 PackageSetting pkgSetting) { 8886 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8887 8888 // If "/system/lib64/apkname" exists, assume that is the per-package 8889 // native library directory to use; otherwise use "/system/lib/apkname". 8890 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8891 setBundledAppAbi(pkg, apkRoot, apkName); 8892 // pkgSetting might be null during rescan following uninstall of updates 8893 // to a bundled app, so accommodate that possibility. The settings in 8894 // that case will be established later from the parsed package. 8895 // 8896 // If the settings aren't null, sync them up with what we've just derived. 8897 // note that apkRoot isn't stored in the package settings. 8898 if (pkgSetting != null) { 8899 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8900 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8901 } 8902 } 8903 8904 /** 8905 * Deduces the ABI of a bundled app and sets the relevant fields on the 8906 * parsed pkg object. 8907 * 8908 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8909 * under which system libraries are installed. 8910 * @param apkName the name of the installed package. 8911 */ 8912 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8913 final File codeFile = new File(pkg.codePath); 8914 8915 final boolean has64BitLibs; 8916 final boolean has32BitLibs; 8917 if (isApkFile(codeFile)) { 8918 // Monolithic install 8919 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8920 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8921 } else { 8922 // Cluster install 8923 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8924 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8925 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8926 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8927 has64BitLibs = (new File(rootDir, isa)).exists(); 8928 } else { 8929 has64BitLibs = false; 8930 } 8931 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8932 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8933 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8934 has32BitLibs = (new File(rootDir, isa)).exists(); 8935 } else { 8936 has32BitLibs = false; 8937 } 8938 } 8939 8940 if (has64BitLibs && !has32BitLibs) { 8941 // The package has 64 bit libs, but not 32 bit libs. Its primary 8942 // ABI should be 64 bit. We can safely assume here that the bundled 8943 // native libraries correspond to the most preferred ABI in the list. 8944 8945 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8946 pkg.applicationInfo.secondaryCpuAbi = null; 8947 } else if (has32BitLibs && !has64BitLibs) { 8948 // The package has 32 bit libs but not 64 bit libs. Its primary 8949 // ABI should be 32 bit. 8950 8951 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8952 pkg.applicationInfo.secondaryCpuAbi = null; 8953 } else if (has32BitLibs && has64BitLibs) { 8954 // The application has both 64 and 32 bit bundled libraries. We check 8955 // here that the app declares multiArch support, and warn if it doesn't. 8956 // 8957 // We will be lenient here and record both ABIs. The primary will be the 8958 // ABI that's higher on the list, i.e, a device that's configured to prefer 8959 // 64 bit apps will see a 64 bit primary ABI, 8960 8961 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8962 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8963 } 8964 8965 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8966 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8967 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8968 } else { 8969 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8970 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8971 } 8972 } else { 8973 pkg.applicationInfo.primaryCpuAbi = null; 8974 pkg.applicationInfo.secondaryCpuAbi = null; 8975 } 8976 } 8977 8978 private void killPackage(PackageParser.Package pkg, String reason) { 8979 // Kill the parent package 8980 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8981 // Kill the child packages 8982 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8983 for (int i = 0; i < childCount; i++) { 8984 PackageParser.Package childPkg = pkg.childPackages.get(i); 8985 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8986 } 8987 } 8988 8989 private void killApplication(String pkgName, int appId, String reason) { 8990 // Request the ActivityManager to kill the process(only for existing packages) 8991 // so that we do not end up in a confused state while the user is still using the older 8992 // version of the application while the new one gets installed. 8993 IActivityManager am = ActivityManagerNative.getDefault(); 8994 if (am != null) { 8995 try { 8996 am.killApplicationWithAppId(pkgName, appId, reason); 8997 } catch (RemoteException e) { 8998 } 8999 } 9000 } 9001 9002 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9003 // Remove the parent package setting 9004 PackageSetting ps = (PackageSetting) pkg.mExtras; 9005 if (ps != null) { 9006 removePackageLI(ps, chatty); 9007 } 9008 // Remove the child package setting 9009 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9010 for (int i = 0; i < childCount; i++) { 9011 PackageParser.Package childPkg = pkg.childPackages.get(i); 9012 ps = (PackageSetting) childPkg.mExtras; 9013 if (ps != null) { 9014 removePackageLI(ps, chatty); 9015 } 9016 } 9017 } 9018 9019 void removePackageLI(PackageSetting ps, boolean chatty) { 9020 if (DEBUG_INSTALL) { 9021 if (chatty) 9022 Log.d(TAG, "Removing package " + ps.name); 9023 } 9024 9025 // writer 9026 synchronized (mPackages) { 9027 mPackages.remove(ps.name); 9028 final PackageParser.Package pkg = ps.pkg; 9029 if (pkg != null) { 9030 cleanPackageDataStructuresLILPw(pkg, chatty); 9031 } 9032 } 9033 } 9034 9035 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9036 if (DEBUG_INSTALL) { 9037 if (chatty) 9038 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9039 } 9040 9041 // writer 9042 synchronized (mPackages) { 9043 // Remove the parent package 9044 mPackages.remove(pkg.applicationInfo.packageName); 9045 cleanPackageDataStructuresLILPw(pkg, chatty); 9046 9047 // Remove the child packages 9048 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9049 for (int i = 0; i < childCount; i++) { 9050 PackageParser.Package childPkg = pkg.childPackages.get(i); 9051 mPackages.remove(childPkg.applicationInfo.packageName); 9052 cleanPackageDataStructuresLILPw(childPkg, chatty); 9053 } 9054 } 9055 } 9056 9057 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9058 int N = pkg.providers.size(); 9059 StringBuilder r = null; 9060 int i; 9061 for (i=0; i<N; i++) { 9062 PackageParser.Provider p = pkg.providers.get(i); 9063 mProviders.removeProvider(p); 9064 if (p.info.authority == null) { 9065 9066 /* There was another ContentProvider with this authority when 9067 * this app was installed so this authority is null, 9068 * Ignore it as we don't have to unregister the provider. 9069 */ 9070 continue; 9071 } 9072 String names[] = p.info.authority.split(";"); 9073 for (int j = 0; j < names.length; j++) { 9074 if (mProvidersByAuthority.get(names[j]) == p) { 9075 mProvidersByAuthority.remove(names[j]); 9076 if (DEBUG_REMOVE) { 9077 if (chatty) 9078 Log.d(TAG, "Unregistered content provider: " + names[j] 9079 + ", className = " + p.info.name + ", isSyncable = " 9080 + p.info.isSyncable); 9081 } 9082 } 9083 } 9084 if (DEBUG_REMOVE && chatty) { 9085 if (r == null) { 9086 r = new StringBuilder(256); 9087 } else { 9088 r.append(' '); 9089 } 9090 r.append(p.info.name); 9091 } 9092 } 9093 if (r != null) { 9094 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9095 } 9096 9097 N = pkg.services.size(); 9098 r = null; 9099 for (i=0; i<N; i++) { 9100 PackageParser.Service s = pkg.services.get(i); 9101 mServices.removeService(s); 9102 if (chatty) { 9103 if (r == null) { 9104 r = new StringBuilder(256); 9105 } else { 9106 r.append(' '); 9107 } 9108 r.append(s.info.name); 9109 } 9110 } 9111 if (r != null) { 9112 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9113 } 9114 9115 N = pkg.receivers.size(); 9116 r = null; 9117 for (i=0; i<N; i++) { 9118 PackageParser.Activity a = pkg.receivers.get(i); 9119 mReceivers.removeActivity(a, "receiver"); 9120 if (DEBUG_REMOVE && chatty) { 9121 if (r == null) { 9122 r = new StringBuilder(256); 9123 } else { 9124 r.append(' '); 9125 } 9126 r.append(a.info.name); 9127 } 9128 } 9129 if (r != null) { 9130 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9131 } 9132 9133 N = pkg.activities.size(); 9134 r = null; 9135 for (i=0; i<N; i++) { 9136 PackageParser.Activity a = pkg.activities.get(i); 9137 mActivities.removeActivity(a, "activity"); 9138 if (DEBUG_REMOVE && chatty) { 9139 if (r == null) { 9140 r = new StringBuilder(256); 9141 } else { 9142 r.append(' '); 9143 } 9144 r.append(a.info.name); 9145 } 9146 } 9147 if (r != null) { 9148 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9149 } 9150 9151 N = pkg.permissions.size(); 9152 r = null; 9153 for (i=0; i<N; i++) { 9154 PackageParser.Permission p = pkg.permissions.get(i); 9155 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9156 if (bp == null) { 9157 bp = mSettings.mPermissionTrees.get(p.info.name); 9158 } 9159 if (bp != null && bp.perm == p) { 9160 bp.perm = null; 9161 if (DEBUG_REMOVE && chatty) { 9162 if (r == null) { 9163 r = new StringBuilder(256); 9164 } else { 9165 r.append(' '); 9166 } 9167 r.append(p.info.name); 9168 } 9169 } 9170 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9171 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9172 if (appOpPkgs != null) { 9173 appOpPkgs.remove(pkg.packageName); 9174 } 9175 } 9176 } 9177 if (r != null) { 9178 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9179 } 9180 9181 N = pkg.requestedPermissions.size(); 9182 r = null; 9183 for (i=0; i<N; i++) { 9184 String perm = pkg.requestedPermissions.get(i); 9185 BasePermission bp = mSettings.mPermissions.get(perm); 9186 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9187 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9188 if (appOpPkgs != null) { 9189 appOpPkgs.remove(pkg.packageName); 9190 if (appOpPkgs.isEmpty()) { 9191 mAppOpPermissionPackages.remove(perm); 9192 } 9193 } 9194 } 9195 } 9196 if (r != null) { 9197 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9198 } 9199 9200 N = pkg.instrumentation.size(); 9201 r = null; 9202 for (i=0; i<N; i++) { 9203 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9204 mInstrumentation.remove(a.getComponentName()); 9205 if (DEBUG_REMOVE && chatty) { 9206 if (r == null) { 9207 r = new StringBuilder(256); 9208 } else { 9209 r.append(' '); 9210 } 9211 r.append(a.info.name); 9212 } 9213 } 9214 if (r != null) { 9215 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9216 } 9217 9218 r = null; 9219 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9220 // Only system apps can hold shared libraries. 9221 if (pkg.libraryNames != null) { 9222 for (i=0; i<pkg.libraryNames.size(); i++) { 9223 String name = pkg.libraryNames.get(i); 9224 SharedLibraryEntry cur = mSharedLibraries.get(name); 9225 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9226 mSharedLibraries.remove(name); 9227 if (DEBUG_REMOVE && chatty) { 9228 if (r == null) { 9229 r = new StringBuilder(256); 9230 } else { 9231 r.append(' '); 9232 } 9233 r.append(name); 9234 } 9235 } 9236 } 9237 } 9238 } 9239 if (r != null) { 9240 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9241 } 9242 } 9243 9244 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9245 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9246 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9247 return true; 9248 } 9249 } 9250 return false; 9251 } 9252 9253 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9254 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9255 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9256 9257 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9258 // Update the parent permissions 9259 updatePermissionsLPw(pkg.packageName, pkg, flags); 9260 // Update the child permissions 9261 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9262 for (int i = 0; i < childCount; i++) { 9263 PackageParser.Package childPkg = pkg.childPackages.get(i); 9264 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9265 } 9266 } 9267 9268 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9269 int flags) { 9270 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9271 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9272 } 9273 9274 private void updatePermissionsLPw(String changingPkg, 9275 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9276 // Make sure there are no dangling permission trees. 9277 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9278 while (it.hasNext()) { 9279 final BasePermission bp = it.next(); 9280 if (bp.packageSetting == null) { 9281 // We may not yet have parsed the package, so just see if 9282 // we still know about its settings. 9283 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9284 } 9285 if (bp.packageSetting == null) { 9286 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9287 + " from package " + bp.sourcePackage); 9288 it.remove(); 9289 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9290 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9291 Slog.i(TAG, "Removing old permission tree: " + bp.name 9292 + " from package " + bp.sourcePackage); 9293 flags |= UPDATE_PERMISSIONS_ALL; 9294 it.remove(); 9295 } 9296 } 9297 } 9298 9299 // Make sure all dynamic permissions have been assigned to a package, 9300 // and make sure there are no dangling permissions. 9301 it = mSettings.mPermissions.values().iterator(); 9302 while (it.hasNext()) { 9303 final BasePermission bp = it.next(); 9304 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9305 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9306 + bp.name + " pkg=" + bp.sourcePackage 9307 + " info=" + bp.pendingInfo); 9308 if (bp.packageSetting == null && bp.pendingInfo != null) { 9309 final BasePermission tree = findPermissionTreeLP(bp.name); 9310 if (tree != null && tree.perm != null) { 9311 bp.packageSetting = tree.packageSetting; 9312 bp.perm = new PackageParser.Permission(tree.perm.owner, 9313 new PermissionInfo(bp.pendingInfo)); 9314 bp.perm.info.packageName = tree.perm.info.packageName; 9315 bp.perm.info.name = bp.name; 9316 bp.uid = tree.uid; 9317 } 9318 } 9319 } 9320 if (bp.packageSetting == null) { 9321 // We may not yet have parsed the package, so just see if 9322 // we still know about its settings. 9323 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9324 } 9325 if (bp.packageSetting == null) { 9326 Slog.w(TAG, "Removing dangling permission: " + bp.name 9327 + " from package " + bp.sourcePackage); 9328 it.remove(); 9329 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9330 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9331 Slog.i(TAG, "Removing old permission: " + bp.name 9332 + " from package " + bp.sourcePackage); 9333 flags |= UPDATE_PERMISSIONS_ALL; 9334 it.remove(); 9335 } 9336 } 9337 } 9338 9339 // Now update the permissions for all packages, in particular 9340 // replace the granted permissions of the system packages. 9341 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9342 for (PackageParser.Package pkg : mPackages.values()) { 9343 if (pkg != pkgInfo) { 9344 // Only replace for packages on requested volume 9345 final String volumeUuid = getVolumeUuidForPackage(pkg); 9346 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9347 && Objects.equals(replaceVolumeUuid, volumeUuid); 9348 grantPermissionsLPw(pkg, replace, changingPkg); 9349 } 9350 } 9351 } 9352 9353 if (pkgInfo != null) { 9354 // Only replace for packages on requested volume 9355 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9356 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9357 && Objects.equals(replaceVolumeUuid, volumeUuid); 9358 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9359 } 9360 } 9361 9362 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9363 String packageOfInterest) { 9364 // IMPORTANT: There are two types of permissions: install and runtime. 9365 // Install time permissions are granted when the app is installed to 9366 // all device users and users added in the future. Runtime permissions 9367 // are granted at runtime explicitly to specific users. Normal and signature 9368 // protected permissions are install time permissions. Dangerous permissions 9369 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9370 // otherwise they are runtime permissions. This function does not manage 9371 // runtime permissions except for the case an app targeting Lollipop MR1 9372 // being upgraded to target a newer SDK, in which case dangerous permissions 9373 // are transformed from install time to runtime ones. 9374 9375 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9376 if (ps == null) { 9377 return; 9378 } 9379 9380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9381 9382 PermissionsState permissionsState = ps.getPermissionsState(); 9383 PermissionsState origPermissions = permissionsState; 9384 9385 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9386 9387 boolean runtimePermissionsRevoked = false; 9388 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9389 9390 boolean changedInstallPermission = false; 9391 9392 if (replace) { 9393 ps.installPermissionsFixed = false; 9394 if (!ps.isSharedUser()) { 9395 origPermissions = new PermissionsState(permissionsState); 9396 permissionsState.reset(); 9397 } else { 9398 // We need to know only about runtime permission changes since the 9399 // calling code always writes the install permissions state but 9400 // the runtime ones are written only if changed. The only cases of 9401 // changed runtime permissions here are promotion of an install to 9402 // runtime and revocation of a runtime from a shared user. 9403 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9404 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9405 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9406 runtimePermissionsRevoked = true; 9407 } 9408 } 9409 } 9410 9411 permissionsState.setGlobalGids(mGlobalGids); 9412 9413 final int N = pkg.requestedPermissions.size(); 9414 for (int i=0; i<N; i++) { 9415 final String name = pkg.requestedPermissions.get(i); 9416 final BasePermission bp = mSettings.mPermissions.get(name); 9417 9418 if (DEBUG_INSTALL) { 9419 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9420 } 9421 9422 if (bp == null || bp.packageSetting == null) { 9423 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9424 Slog.w(TAG, "Unknown permission " + name 9425 + " in package " + pkg.packageName); 9426 } 9427 continue; 9428 } 9429 9430 final String perm = bp.name; 9431 boolean allowedSig = false; 9432 int grant = GRANT_DENIED; 9433 9434 // Keep track of app op permissions. 9435 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9436 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9437 if (pkgs == null) { 9438 pkgs = new ArraySet<>(); 9439 mAppOpPermissionPackages.put(bp.name, pkgs); 9440 } 9441 pkgs.add(pkg.packageName); 9442 } 9443 9444 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9445 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9446 >= Build.VERSION_CODES.M; 9447 switch (level) { 9448 case PermissionInfo.PROTECTION_NORMAL: { 9449 // For all apps normal permissions are install time ones. 9450 grant = GRANT_INSTALL; 9451 } break; 9452 9453 case PermissionInfo.PROTECTION_DANGEROUS: { 9454 // If a permission review is required for legacy apps we represent 9455 // their permissions as always granted runtime ones since we need 9456 // to keep the review required permission flag per user while an 9457 // install permission's state is shared across all users. 9458 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9459 // For legacy apps dangerous permissions are install time ones. 9460 grant = GRANT_INSTALL; 9461 } else if (origPermissions.hasInstallPermission(bp.name)) { 9462 // For legacy apps that became modern, install becomes runtime. 9463 grant = GRANT_UPGRADE; 9464 } else if (mPromoteSystemApps 9465 && isSystemApp(ps) 9466 && mExistingSystemPackages.contains(ps.name)) { 9467 // For legacy system apps, install becomes runtime. 9468 // We cannot check hasInstallPermission() for system apps since those 9469 // permissions were granted implicitly and not persisted pre-M. 9470 grant = GRANT_UPGRADE; 9471 } else { 9472 // For modern apps keep runtime permissions unchanged. 9473 grant = GRANT_RUNTIME; 9474 } 9475 } break; 9476 9477 case PermissionInfo.PROTECTION_SIGNATURE: { 9478 // For all apps signature permissions are install time ones. 9479 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9480 if (allowedSig) { 9481 grant = GRANT_INSTALL; 9482 } 9483 } break; 9484 } 9485 9486 if (DEBUG_INSTALL) { 9487 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9488 } 9489 9490 if (grant != GRANT_DENIED) { 9491 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9492 // If this is an existing, non-system package, then 9493 // we can't add any new permissions to it. 9494 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9495 // Except... if this is a permission that was added 9496 // to the platform (note: need to only do this when 9497 // updating the platform). 9498 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9499 grant = GRANT_DENIED; 9500 } 9501 } 9502 } 9503 9504 switch (grant) { 9505 case GRANT_INSTALL: { 9506 // Revoke this as runtime permission to handle the case of 9507 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9508 for (int userId : UserManagerService.getInstance().getUserIds()) { 9509 if (origPermissions.getRuntimePermissionState( 9510 bp.name, userId) != null) { 9511 // Revoke the runtime permission and clear the flags. 9512 origPermissions.revokeRuntimePermission(bp, userId); 9513 origPermissions.updatePermissionFlags(bp, userId, 9514 PackageManager.MASK_PERMISSION_FLAGS, 0); 9515 // If we revoked a permission permission, we have to write. 9516 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9517 changedRuntimePermissionUserIds, userId); 9518 } 9519 } 9520 // Grant an install permission. 9521 if (permissionsState.grantInstallPermission(bp) != 9522 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9523 changedInstallPermission = true; 9524 } 9525 } break; 9526 9527 case GRANT_RUNTIME: { 9528 // Grant previously granted runtime permissions. 9529 for (int userId : UserManagerService.getInstance().getUserIds()) { 9530 PermissionState permissionState = origPermissions 9531 .getRuntimePermissionState(bp.name, userId); 9532 int flags = permissionState != null 9533 ? permissionState.getFlags() : 0; 9534 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9535 if (permissionsState.grantRuntimePermission(bp, userId) == 9536 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9537 // If we cannot put the permission as it was, we have to write. 9538 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9539 changedRuntimePermissionUserIds, userId); 9540 } 9541 // If the app supports runtime permissions no need for a review. 9542 if (Build.PERMISSIONS_REVIEW_REQUIRED 9543 && appSupportsRuntimePermissions 9544 && (flags & PackageManager 9545 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9546 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9547 // Since we changed the flags, we have to write. 9548 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9549 changedRuntimePermissionUserIds, userId); 9550 } 9551 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9552 && !appSupportsRuntimePermissions) { 9553 // For legacy apps that need a permission review, every new 9554 // runtime permission is granted but it is pending a review. 9555 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9556 permissionsState.grantRuntimePermission(bp, userId); 9557 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9558 // We changed the permission and flags, hence have to write. 9559 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9560 changedRuntimePermissionUserIds, userId); 9561 } 9562 } 9563 // Propagate the permission flags. 9564 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9565 } 9566 } break; 9567 9568 case GRANT_UPGRADE: { 9569 // Grant runtime permissions for a previously held install permission. 9570 PermissionState permissionState = origPermissions 9571 .getInstallPermissionState(bp.name); 9572 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9573 9574 if (origPermissions.revokeInstallPermission(bp) 9575 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9576 // We will be transferring the permission flags, so clear them. 9577 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9578 PackageManager.MASK_PERMISSION_FLAGS, 0); 9579 changedInstallPermission = true; 9580 } 9581 9582 // If the permission is not to be promoted to runtime we ignore it and 9583 // also its other flags as they are not applicable to install permissions. 9584 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9585 for (int userId : currentUserIds) { 9586 if (permissionsState.grantRuntimePermission(bp, userId) != 9587 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9588 // Transfer the permission flags. 9589 permissionsState.updatePermissionFlags(bp, userId, 9590 flags, flags); 9591 // If we granted the permission, we have to write. 9592 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9593 changedRuntimePermissionUserIds, userId); 9594 } 9595 } 9596 } 9597 } break; 9598 9599 default: { 9600 if (packageOfInterest == null 9601 || packageOfInterest.equals(pkg.packageName)) { 9602 Slog.w(TAG, "Not granting permission " + perm 9603 + " to package " + pkg.packageName 9604 + " because it was previously installed without"); 9605 } 9606 } break; 9607 } 9608 } else { 9609 if (permissionsState.revokeInstallPermission(bp) != 9610 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9611 // Also drop the permission flags. 9612 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9613 PackageManager.MASK_PERMISSION_FLAGS, 0); 9614 changedInstallPermission = true; 9615 Slog.i(TAG, "Un-granting permission " + perm 9616 + " from package " + pkg.packageName 9617 + " (protectionLevel=" + bp.protectionLevel 9618 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9619 + ")"); 9620 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9621 // Don't print warning for app op permissions, since it is fine for them 9622 // not to be granted, there is a UI for the user to decide. 9623 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9624 Slog.w(TAG, "Not granting permission " + perm 9625 + " to package " + pkg.packageName 9626 + " (protectionLevel=" + bp.protectionLevel 9627 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9628 + ")"); 9629 } 9630 } 9631 } 9632 } 9633 9634 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9635 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9636 // This is the first that we have heard about this package, so the 9637 // permissions we have now selected are fixed until explicitly 9638 // changed. 9639 ps.installPermissionsFixed = true; 9640 } 9641 9642 // Persist the runtime permissions state for users with changes. If permissions 9643 // were revoked because no app in the shared user declares them we have to 9644 // write synchronously to avoid losing runtime permissions state. 9645 for (int userId : changedRuntimePermissionUserIds) { 9646 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9647 } 9648 9649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9650 } 9651 9652 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9653 boolean allowed = false; 9654 final int NP = PackageParser.NEW_PERMISSIONS.length; 9655 for (int ip=0; ip<NP; ip++) { 9656 final PackageParser.NewPermissionInfo npi 9657 = PackageParser.NEW_PERMISSIONS[ip]; 9658 if (npi.name.equals(perm) 9659 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9660 allowed = true; 9661 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9662 + pkg.packageName); 9663 break; 9664 } 9665 } 9666 return allowed; 9667 } 9668 9669 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9670 BasePermission bp, PermissionsState origPermissions) { 9671 boolean allowed; 9672 allowed = (compareSignatures( 9673 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9674 == PackageManager.SIGNATURE_MATCH) 9675 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9676 == PackageManager.SIGNATURE_MATCH); 9677 if (!allowed && (bp.protectionLevel 9678 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9679 if (isSystemApp(pkg)) { 9680 // For updated system applications, a system permission 9681 // is granted only if it had been defined by the original application. 9682 if (pkg.isUpdatedSystemApp()) { 9683 final PackageSetting sysPs = mSettings 9684 .getDisabledSystemPkgLPr(pkg.packageName); 9685 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9686 // If the original was granted this permission, we take 9687 // that grant decision as read and propagate it to the 9688 // update. 9689 if (sysPs.isPrivileged()) { 9690 allowed = true; 9691 } 9692 } else { 9693 // The system apk may have been updated with an older 9694 // version of the one on the data partition, but which 9695 // granted a new system permission that it didn't have 9696 // before. In this case we do want to allow the app to 9697 // now get the new permission if the ancestral apk is 9698 // privileged to get it. 9699 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9700 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9701 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9702 allowed = true; 9703 break; 9704 } 9705 } 9706 } 9707 // Also if a privileged parent package on the system image or any of 9708 // its children requested a privileged permission, the updated child 9709 // packages can also get the permission. 9710 if (pkg.parentPackage != null) { 9711 final PackageSetting disabledSysParentPs = mSettings 9712 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9713 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9714 && disabledSysParentPs.isPrivileged()) { 9715 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9716 allowed = true; 9717 } else if (disabledSysParentPs.pkg.childPackages != null) { 9718 final int count = disabledSysParentPs.pkg.childPackages.size(); 9719 for (int i = 0; i < count; i++) { 9720 PackageParser.Package disabledSysChildPkg = 9721 disabledSysParentPs.pkg.childPackages.get(i); 9722 if (isPackageRequestingPermission(disabledSysChildPkg, 9723 perm)) { 9724 allowed = true; 9725 break; 9726 } 9727 } 9728 } 9729 } 9730 } 9731 } 9732 } else { 9733 allowed = isPrivilegedApp(pkg); 9734 } 9735 } 9736 } 9737 if (!allowed) { 9738 if (!allowed && (bp.protectionLevel 9739 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9740 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9741 // If this was a previously normal/dangerous permission that got moved 9742 // to a system permission as part of the runtime permission redesign, then 9743 // we still want to blindly grant it to old apps. 9744 allowed = true; 9745 } 9746 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9747 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9748 // If this permission is to be granted to the system installer and 9749 // this app is an installer, then it gets the permission. 9750 allowed = true; 9751 } 9752 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9753 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9754 // If this permission is to be granted to the system verifier and 9755 // this app is a verifier, then it gets the permission. 9756 allowed = true; 9757 } 9758 if (!allowed && (bp.protectionLevel 9759 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9760 && isSystemApp(pkg)) { 9761 // Any pre-installed system app is allowed to get this permission. 9762 allowed = true; 9763 } 9764 if (!allowed && (bp.protectionLevel 9765 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9766 // For development permissions, a development permission 9767 // is granted only if it was already granted. 9768 allowed = origPermissions.hasInstallPermission(perm); 9769 } 9770 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9771 && pkg.packageName.equals(mSetupWizardPackage)) { 9772 // If this permission is to be granted to the system setup wizard and 9773 // this app is a setup wizard, then it gets the permission. 9774 allowed = true; 9775 } 9776 } 9777 return allowed; 9778 } 9779 9780 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9781 final int permCount = pkg.requestedPermissions.size(); 9782 for (int j = 0; j < permCount; j++) { 9783 String requestedPermission = pkg.requestedPermissions.get(j); 9784 if (permission.equals(requestedPermission)) { 9785 return true; 9786 } 9787 } 9788 return false; 9789 } 9790 9791 final class ActivityIntentResolver 9792 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9793 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9794 boolean defaultOnly, int userId) { 9795 if (!sUserManager.exists(userId)) return null; 9796 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9797 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9798 } 9799 9800 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9801 int userId) { 9802 if (!sUserManager.exists(userId)) return null; 9803 mFlags = flags; 9804 return super.queryIntent(intent, resolvedType, 9805 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9806 } 9807 9808 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9809 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9810 if (!sUserManager.exists(userId)) return null; 9811 if (packageActivities == null) { 9812 return null; 9813 } 9814 mFlags = flags; 9815 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9816 final int N = packageActivities.size(); 9817 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9818 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9819 9820 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9821 for (int i = 0; i < N; ++i) { 9822 intentFilters = packageActivities.get(i).intents; 9823 if (intentFilters != null && intentFilters.size() > 0) { 9824 PackageParser.ActivityIntentInfo[] array = 9825 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9826 intentFilters.toArray(array); 9827 listCut.add(array); 9828 } 9829 } 9830 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9831 } 9832 9833 /** 9834 * Finds a privileged activity that matches the specified activity names. 9835 */ 9836 private PackageParser.Activity findMatchingActivity( 9837 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9838 for (PackageParser.Activity sysActivity : activityList) { 9839 if (sysActivity.info.name.equals(activityInfo.name)) { 9840 return sysActivity; 9841 } 9842 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9843 return sysActivity; 9844 } 9845 if (sysActivity.info.targetActivity != null) { 9846 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9847 return sysActivity; 9848 } 9849 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9850 return sysActivity; 9851 } 9852 } 9853 } 9854 return null; 9855 } 9856 9857 public class IterGenerator<E> { 9858 public Iterator<E> generate(ActivityIntentInfo info) { 9859 return null; 9860 } 9861 } 9862 9863 public class ActionIterGenerator extends IterGenerator<String> { 9864 @Override 9865 public Iterator<String> generate(ActivityIntentInfo info) { 9866 return info.actionsIterator(); 9867 } 9868 } 9869 9870 public class CategoriesIterGenerator extends IterGenerator<String> { 9871 @Override 9872 public Iterator<String> generate(ActivityIntentInfo info) { 9873 return info.categoriesIterator(); 9874 } 9875 } 9876 9877 public class SchemesIterGenerator extends IterGenerator<String> { 9878 @Override 9879 public Iterator<String> generate(ActivityIntentInfo info) { 9880 return info.schemesIterator(); 9881 } 9882 } 9883 9884 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9885 @Override 9886 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9887 return info.authoritiesIterator(); 9888 } 9889 } 9890 9891 /** 9892 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9893 * MODIFIED. Do not pass in a list that should not be changed. 9894 */ 9895 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9896 IterGenerator<T> generator, Iterator<T> searchIterator) { 9897 // loop through the set of actions; every one must be found in the intent filter 9898 while (searchIterator.hasNext()) { 9899 // we must have at least one filter in the list to consider a match 9900 if (intentList.size() == 0) { 9901 break; 9902 } 9903 9904 final T searchAction = searchIterator.next(); 9905 9906 // loop through the set of intent filters 9907 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9908 while (intentIter.hasNext()) { 9909 final ActivityIntentInfo intentInfo = intentIter.next(); 9910 boolean selectionFound = false; 9911 9912 // loop through the intent filter's selection criteria; at least one 9913 // of them must match the searched criteria 9914 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9915 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9916 final T intentSelection = intentSelectionIter.next(); 9917 if (intentSelection != null && intentSelection.equals(searchAction)) { 9918 selectionFound = true; 9919 break; 9920 } 9921 } 9922 9923 // the selection criteria wasn't found in this filter's set; this filter 9924 // is not a potential match 9925 if (!selectionFound) { 9926 intentIter.remove(); 9927 } 9928 } 9929 } 9930 } 9931 9932 private boolean isProtectedAction(ActivityIntentInfo filter) { 9933 final Iterator<String> actionsIter = filter.actionsIterator(); 9934 while (actionsIter != null && actionsIter.hasNext()) { 9935 final String filterAction = actionsIter.next(); 9936 if (PROTECTED_ACTIONS.contains(filterAction)) { 9937 return true; 9938 } 9939 } 9940 return false; 9941 } 9942 9943 /** 9944 * Adjusts the priority of the given intent filter according to policy. 9945 * <p> 9946 * <ul> 9947 * <li>The priority for non privileged applications is capped to '0'</li> 9948 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9949 * <li>The priority for unbundled updates to privileged applications is capped to the 9950 * priority defined on the system partition</li> 9951 * </ul> 9952 * <p> 9953 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9954 * allowed to obtain any priority on any action. 9955 */ 9956 private void adjustPriority( 9957 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9958 // nothing to do; priority is fine as-is 9959 if (intent.getPriority() <= 0) { 9960 return; 9961 } 9962 9963 final ActivityInfo activityInfo = intent.activity.info; 9964 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9965 9966 final boolean privilegedApp = 9967 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9968 if (!privilegedApp) { 9969 // non-privileged applications can never define a priority >0 9970 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9971 + " package: " + applicationInfo.packageName 9972 + " activity: " + intent.activity.className 9973 + " origPrio: " + intent.getPriority()); 9974 intent.setPriority(0); 9975 return; 9976 } 9977 9978 if (systemActivities == null) { 9979 // the system package is not disabled; we're parsing the system partition 9980 if (isProtectedAction(intent)) { 9981 if (mDeferProtectedFilters) { 9982 // We can't deal with these just yet. No component should ever obtain a 9983 // >0 priority for a protected actions, with ONE exception -- the setup 9984 // wizard. The setup wizard, however, cannot be known until we're able to 9985 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 9986 // until all intent filters have been processed. Chicken, meet egg. 9987 // Let the filter temporarily have a high priority and rectify the 9988 // priorities after all system packages have been scanned. 9989 mProtectedFilters.add(intent); 9990 if (DEBUG_FILTERS) { 9991 Slog.i(TAG, "Protected action; save for later;" 9992 + " package: " + applicationInfo.packageName 9993 + " activity: " + intent.activity.className 9994 + " origPrio: " + intent.getPriority()); 9995 } 9996 return; 9997 } else { 9998 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 9999 Slog.i(TAG, "No setup wizard;" 10000 + " All protected intents capped to priority 0"); 10001 } 10002 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10003 if (DEBUG_FILTERS) { 10004 Slog.i(TAG, "Found setup wizard;" 10005 + " allow priority " + intent.getPriority() + ";" 10006 + " package: " + intent.activity.info.packageName 10007 + " activity: " + intent.activity.className 10008 + " priority: " + intent.getPriority()); 10009 } 10010 // setup wizard gets whatever it wants 10011 return; 10012 } 10013 Slog.w(TAG, "Protected action; cap priority to 0;" 10014 + " package: " + intent.activity.info.packageName 10015 + " activity: " + intent.activity.className 10016 + " origPrio: " + intent.getPriority()); 10017 intent.setPriority(0); 10018 return; 10019 } 10020 } 10021 // privileged apps on the system image get whatever priority they request 10022 return; 10023 } 10024 10025 // privileged app unbundled update ... try to find the same activity 10026 final PackageParser.Activity foundActivity = 10027 findMatchingActivity(systemActivities, activityInfo); 10028 if (foundActivity == null) { 10029 // this is a new activity; it cannot obtain >0 priority 10030 if (DEBUG_FILTERS) { 10031 Slog.i(TAG, "New activity; cap priority to 0;" 10032 + " package: " + applicationInfo.packageName 10033 + " activity: " + intent.activity.className 10034 + " origPrio: " + intent.getPriority()); 10035 } 10036 intent.setPriority(0); 10037 return; 10038 } 10039 10040 // found activity, now check for filter equivalence 10041 10042 // a shallow copy is enough; we modify the list, not its contents 10043 final List<ActivityIntentInfo> intentListCopy = 10044 new ArrayList<>(foundActivity.intents); 10045 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10046 10047 // find matching action subsets 10048 final Iterator<String> actionsIterator = intent.actionsIterator(); 10049 if (actionsIterator != null) { 10050 getIntentListSubset( 10051 intentListCopy, new ActionIterGenerator(), actionsIterator); 10052 if (intentListCopy.size() == 0) { 10053 // no more intents to match; we're not equivalent 10054 if (DEBUG_FILTERS) { 10055 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10056 + " package: " + applicationInfo.packageName 10057 + " activity: " + intent.activity.className 10058 + " origPrio: " + intent.getPriority()); 10059 } 10060 intent.setPriority(0); 10061 return; 10062 } 10063 } 10064 10065 // find matching category subsets 10066 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10067 if (categoriesIterator != null) { 10068 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10069 categoriesIterator); 10070 if (intentListCopy.size() == 0) { 10071 // no more intents to match; we're not equivalent 10072 if (DEBUG_FILTERS) { 10073 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10074 + " package: " + applicationInfo.packageName 10075 + " activity: " + intent.activity.className 10076 + " origPrio: " + intent.getPriority()); 10077 } 10078 intent.setPriority(0); 10079 return; 10080 } 10081 } 10082 10083 // find matching schemes subsets 10084 final Iterator<String> schemesIterator = intent.schemesIterator(); 10085 if (schemesIterator != null) { 10086 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10087 schemesIterator); 10088 if (intentListCopy.size() == 0) { 10089 // no more intents to match; we're not equivalent 10090 if (DEBUG_FILTERS) { 10091 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10092 + " package: " + applicationInfo.packageName 10093 + " activity: " + intent.activity.className 10094 + " origPrio: " + intent.getPriority()); 10095 } 10096 intent.setPriority(0); 10097 return; 10098 } 10099 } 10100 10101 // find matching authorities subsets 10102 final Iterator<IntentFilter.AuthorityEntry> 10103 authoritiesIterator = intent.authoritiesIterator(); 10104 if (authoritiesIterator != null) { 10105 getIntentListSubset(intentListCopy, 10106 new AuthoritiesIterGenerator(), 10107 authoritiesIterator); 10108 if (intentListCopy.size() == 0) { 10109 // no more intents to match; we're not equivalent 10110 if (DEBUG_FILTERS) { 10111 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10112 + " package: " + applicationInfo.packageName 10113 + " activity: " + intent.activity.className 10114 + " origPrio: " + intent.getPriority()); 10115 } 10116 intent.setPriority(0); 10117 return; 10118 } 10119 } 10120 10121 // we found matching filter(s); app gets the max priority of all intents 10122 int cappedPriority = 0; 10123 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10124 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10125 } 10126 if (intent.getPriority() > cappedPriority) { 10127 if (DEBUG_FILTERS) { 10128 Slog.i(TAG, "Found matching filter(s);" 10129 + " cap priority to " + cappedPriority + ";" 10130 + " package: " + applicationInfo.packageName 10131 + " activity: " + intent.activity.className 10132 + " origPrio: " + intent.getPriority()); 10133 } 10134 intent.setPriority(cappedPriority); 10135 return; 10136 } 10137 // all this for nothing; the requested priority was <= what was on the system 10138 } 10139 10140 public final void addActivity(PackageParser.Activity a, String type) { 10141 mActivities.put(a.getComponentName(), a); 10142 if (DEBUG_SHOW_INFO) 10143 Log.v( 10144 TAG, " " + type + " " + 10145 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10146 if (DEBUG_SHOW_INFO) 10147 Log.v(TAG, " Class=" + a.info.name); 10148 final int NI = a.intents.size(); 10149 for (int j=0; j<NI; j++) { 10150 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10151 if ("activity".equals(type)) { 10152 final PackageSetting ps = 10153 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10154 final List<PackageParser.Activity> systemActivities = 10155 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10156 adjustPriority(systemActivities, intent); 10157 } 10158 if (DEBUG_SHOW_INFO) { 10159 Log.v(TAG, " IntentFilter:"); 10160 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10161 } 10162 if (!intent.debugCheck()) { 10163 Log.w(TAG, "==> For Activity " + a.info.name); 10164 } 10165 addFilter(intent); 10166 } 10167 } 10168 10169 public final void removeActivity(PackageParser.Activity a, String type) { 10170 mActivities.remove(a.getComponentName()); 10171 if (DEBUG_SHOW_INFO) { 10172 Log.v(TAG, " " + type + " " 10173 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10174 : a.info.name) + ":"); 10175 Log.v(TAG, " Class=" + a.info.name); 10176 } 10177 final int NI = a.intents.size(); 10178 for (int j=0; j<NI; j++) { 10179 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10180 if (DEBUG_SHOW_INFO) { 10181 Log.v(TAG, " IntentFilter:"); 10182 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10183 } 10184 removeFilter(intent); 10185 } 10186 } 10187 10188 @Override 10189 protected boolean allowFilterResult( 10190 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10191 ActivityInfo filterAi = filter.activity.info; 10192 for (int i=dest.size()-1; i>=0; i--) { 10193 ActivityInfo destAi = dest.get(i).activityInfo; 10194 if (destAi.name == filterAi.name 10195 && destAi.packageName == filterAi.packageName) { 10196 return false; 10197 } 10198 } 10199 return true; 10200 } 10201 10202 @Override 10203 protected ActivityIntentInfo[] newArray(int size) { 10204 return new ActivityIntentInfo[size]; 10205 } 10206 10207 @Override 10208 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10209 if (!sUserManager.exists(userId)) return true; 10210 PackageParser.Package p = filter.activity.owner; 10211 if (p != null) { 10212 PackageSetting ps = (PackageSetting)p.mExtras; 10213 if (ps != null) { 10214 // System apps are never considered stopped for purposes of 10215 // filtering, because there may be no way for the user to 10216 // actually re-launch them. 10217 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10218 && ps.getStopped(userId); 10219 } 10220 } 10221 return false; 10222 } 10223 10224 @Override 10225 protected boolean isPackageForFilter(String packageName, 10226 PackageParser.ActivityIntentInfo info) { 10227 return packageName.equals(info.activity.owner.packageName); 10228 } 10229 10230 @Override 10231 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10232 int match, int userId) { 10233 if (!sUserManager.exists(userId)) return null; 10234 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10235 return null; 10236 } 10237 final PackageParser.Activity activity = info.activity; 10238 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10239 if (ps == null) { 10240 return null; 10241 } 10242 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10243 ps.readUserState(userId), userId); 10244 if (ai == null) { 10245 return null; 10246 } 10247 final ResolveInfo res = new ResolveInfo(); 10248 res.activityInfo = ai; 10249 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10250 res.filter = info; 10251 } 10252 if (info != null) { 10253 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10254 } 10255 res.priority = info.getPriority(); 10256 res.preferredOrder = activity.owner.mPreferredOrder; 10257 //System.out.println("Result: " + res.activityInfo.className + 10258 // " = " + res.priority); 10259 res.match = match; 10260 res.isDefault = info.hasDefault; 10261 res.labelRes = info.labelRes; 10262 res.nonLocalizedLabel = info.nonLocalizedLabel; 10263 if (userNeedsBadging(userId)) { 10264 res.noResourceId = true; 10265 } else { 10266 res.icon = info.icon; 10267 } 10268 res.iconResourceId = info.icon; 10269 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10270 return res; 10271 } 10272 10273 @Override 10274 protected void sortResults(List<ResolveInfo> results) { 10275 Collections.sort(results, mResolvePrioritySorter); 10276 } 10277 10278 @Override 10279 protected void dumpFilter(PrintWriter out, String prefix, 10280 PackageParser.ActivityIntentInfo filter) { 10281 out.print(prefix); out.print( 10282 Integer.toHexString(System.identityHashCode(filter.activity))); 10283 out.print(' '); 10284 filter.activity.printComponentShortName(out); 10285 out.print(" filter "); 10286 out.println(Integer.toHexString(System.identityHashCode(filter))); 10287 } 10288 10289 @Override 10290 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10291 return filter.activity; 10292 } 10293 10294 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10295 PackageParser.Activity activity = (PackageParser.Activity)label; 10296 out.print(prefix); out.print( 10297 Integer.toHexString(System.identityHashCode(activity))); 10298 out.print(' '); 10299 activity.printComponentShortName(out); 10300 if (count > 1) { 10301 out.print(" ("); out.print(count); out.print(" filters)"); 10302 } 10303 out.println(); 10304 } 10305 10306 // Keys are String (activity class name), values are Activity. 10307 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10308 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10309 private int mFlags; 10310 } 10311 10312 private final class ServiceIntentResolver 10313 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10314 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10315 boolean defaultOnly, int userId) { 10316 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10317 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10318 } 10319 10320 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10321 int userId) { 10322 if (!sUserManager.exists(userId)) return null; 10323 mFlags = flags; 10324 return super.queryIntent(intent, resolvedType, 10325 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10326 } 10327 10328 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10329 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10330 if (!sUserManager.exists(userId)) return null; 10331 if (packageServices == null) { 10332 return null; 10333 } 10334 mFlags = flags; 10335 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10336 final int N = packageServices.size(); 10337 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10338 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10339 10340 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10341 for (int i = 0; i < N; ++i) { 10342 intentFilters = packageServices.get(i).intents; 10343 if (intentFilters != null && intentFilters.size() > 0) { 10344 PackageParser.ServiceIntentInfo[] array = 10345 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10346 intentFilters.toArray(array); 10347 listCut.add(array); 10348 } 10349 } 10350 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10351 } 10352 10353 public final void addService(PackageParser.Service s) { 10354 mServices.put(s.getComponentName(), s); 10355 if (DEBUG_SHOW_INFO) { 10356 Log.v(TAG, " " 10357 + (s.info.nonLocalizedLabel != null 10358 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10359 Log.v(TAG, " Class=" + s.info.name); 10360 } 10361 final int NI = s.intents.size(); 10362 int j; 10363 for (j=0; j<NI; j++) { 10364 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10365 if (DEBUG_SHOW_INFO) { 10366 Log.v(TAG, " IntentFilter:"); 10367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10368 } 10369 if (!intent.debugCheck()) { 10370 Log.w(TAG, "==> For Service " + s.info.name); 10371 } 10372 addFilter(intent); 10373 } 10374 } 10375 10376 public final void removeService(PackageParser.Service s) { 10377 mServices.remove(s.getComponentName()); 10378 if (DEBUG_SHOW_INFO) { 10379 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10380 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10381 Log.v(TAG, " Class=" + s.info.name); 10382 } 10383 final int NI = s.intents.size(); 10384 int j; 10385 for (j=0; j<NI; j++) { 10386 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10387 if (DEBUG_SHOW_INFO) { 10388 Log.v(TAG, " IntentFilter:"); 10389 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10390 } 10391 removeFilter(intent); 10392 } 10393 } 10394 10395 @Override 10396 protected boolean allowFilterResult( 10397 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10398 ServiceInfo filterSi = filter.service.info; 10399 for (int i=dest.size()-1; i>=0; i--) { 10400 ServiceInfo destAi = dest.get(i).serviceInfo; 10401 if (destAi.name == filterSi.name 10402 && destAi.packageName == filterSi.packageName) { 10403 return false; 10404 } 10405 } 10406 return true; 10407 } 10408 10409 @Override 10410 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10411 return new PackageParser.ServiceIntentInfo[size]; 10412 } 10413 10414 @Override 10415 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10416 if (!sUserManager.exists(userId)) return true; 10417 PackageParser.Package p = filter.service.owner; 10418 if (p != null) { 10419 PackageSetting ps = (PackageSetting)p.mExtras; 10420 if (ps != null) { 10421 // System apps are never considered stopped for purposes of 10422 // filtering, because there may be no way for the user to 10423 // actually re-launch them. 10424 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10425 && ps.getStopped(userId); 10426 } 10427 } 10428 return false; 10429 } 10430 10431 @Override 10432 protected boolean isPackageForFilter(String packageName, 10433 PackageParser.ServiceIntentInfo info) { 10434 return packageName.equals(info.service.owner.packageName); 10435 } 10436 10437 @Override 10438 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10439 int match, int userId) { 10440 if (!sUserManager.exists(userId)) return null; 10441 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10442 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10443 return null; 10444 } 10445 final PackageParser.Service service = info.service; 10446 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10447 if (ps == null) { 10448 return null; 10449 } 10450 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10451 ps.readUserState(userId), userId); 10452 if (si == null) { 10453 return null; 10454 } 10455 final ResolveInfo res = new ResolveInfo(); 10456 res.serviceInfo = si; 10457 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10458 res.filter = filter; 10459 } 10460 res.priority = info.getPriority(); 10461 res.preferredOrder = service.owner.mPreferredOrder; 10462 res.match = match; 10463 res.isDefault = info.hasDefault; 10464 res.labelRes = info.labelRes; 10465 res.nonLocalizedLabel = info.nonLocalizedLabel; 10466 res.icon = info.icon; 10467 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10468 return res; 10469 } 10470 10471 @Override 10472 protected void sortResults(List<ResolveInfo> results) { 10473 Collections.sort(results, mResolvePrioritySorter); 10474 } 10475 10476 @Override 10477 protected void dumpFilter(PrintWriter out, String prefix, 10478 PackageParser.ServiceIntentInfo filter) { 10479 out.print(prefix); out.print( 10480 Integer.toHexString(System.identityHashCode(filter.service))); 10481 out.print(' '); 10482 filter.service.printComponentShortName(out); 10483 out.print(" filter "); 10484 out.println(Integer.toHexString(System.identityHashCode(filter))); 10485 } 10486 10487 @Override 10488 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10489 return filter.service; 10490 } 10491 10492 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10493 PackageParser.Service service = (PackageParser.Service)label; 10494 out.print(prefix); out.print( 10495 Integer.toHexString(System.identityHashCode(service))); 10496 out.print(' '); 10497 service.printComponentShortName(out); 10498 if (count > 1) { 10499 out.print(" ("); out.print(count); out.print(" filters)"); 10500 } 10501 out.println(); 10502 } 10503 10504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10505// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10506// final List<ResolveInfo> retList = Lists.newArrayList(); 10507// while (i.hasNext()) { 10508// final ResolveInfo resolveInfo = (ResolveInfo) i; 10509// if (isEnabledLP(resolveInfo.serviceInfo)) { 10510// retList.add(resolveInfo); 10511// } 10512// } 10513// return retList; 10514// } 10515 10516 // Keys are String (activity class name), values are Activity. 10517 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10518 = new ArrayMap<ComponentName, PackageParser.Service>(); 10519 private int mFlags; 10520 }; 10521 10522 private final class ProviderIntentResolver 10523 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10525 boolean defaultOnly, int userId) { 10526 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10527 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10528 } 10529 10530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10531 int userId) { 10532 if (!sUserManager.exists(userId)) 10533 return null; 10534 mFlags = flags; 10535 return super.queryIntent(intent, resolvedType, 10536 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10537 } 10538 10539 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10540 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10541 if (!sUserManager.exists(userId)) 10542 return null; 10543 if (packageProviders == null) { 10544 return null; 10545 } 10546 mFlags = flags; 10547 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10548 final int N = packageProviders.size(); 10549 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10550 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10551 10552 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10553 for (int i = 0; i < N; ++i) { 10554 intentFilters = packageProviders.get(i).intents; 10555 if (intentFilters != null && intentFilters.size() > 0) { 10556 PackageParser.ProviderIntentInfo[] array = 10557 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10558 intentFilters.toArray(array); 10559 listCut.add(array); 10560 } 10561 } 10562 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10563 } 10564 10565 public final void addProvider(PackageParser.Provider p) { 10566 if (mProviders.containsKey(p.getComponentName())) { 10567 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10568 return; 10569 } 10570 10571 mProviders.put(p.getComponentName(), p); 10572 if (DEBUG_SHOW_INFO) { 10573 Log.v(TAG, " " 10574 + (p.info.nonLocalizedLabel != null 10575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10576 Log.v(TAG, " Class=" + p.info.name); 10577 } 10578 final int NI = p.intents.size(); 10579 int j; 10580 for (j = 0; j < NI; j++) { 10581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10582 if (DEBUG_SHOW_INFO) { 10583 Log.v(TAG, " IntentFilter:"); 10584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10585 } 10586 if (!intent.debugCheck()) { 10587 Log.w(TAG, "==> For Provider " + p.info.name); 10588 } 10589 addFilter(intent); 10590 } 10591 } 10592 10593 public final void removeProvider(PackageParser.Provider p) { 10594 mProviders.remove(p.getComponentName()); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10597 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10598 Log.v(TAG, " Class=" + p.info.name); 10599 } 10600 final int NI = p.intents.size(); 10601 int j; 10602 for (j = 0; j < NI; j++) { 10603 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10604 if (DEBUG_SHOW_INFO) { 10605 Log.v(TAG, " IntentFilter:"); 10606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10607 } 10608 removeFilter(intent); 10609 } 10610 } 10611 10612 @Override 10613 protected boolean allowFilterResult( 10614 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10615 ProviderInfo filterPi = filter.provider.info; 10616 for (int i = dest.size() - 1; i >= 0; i--) { 10617 ProviderInfo destPi = dest.get(i).providerInfo; 10618 if (destPi.name == filterPi.name 10619 && destPi.packageName == filterPi.packageName) { 10620 return false; 10621 } 10622 } 10623 return true; 10624 } 10625 10626 @Override 10627 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10628 return new PackageParser.ProviderIntentInfo[size]; 10629 } 10630 10631 @Override 10632 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10633 if (!sUserManager.exists(userId)) 10634 return true; 10635 PackageParser.Package p = filter.provider.owner; 10636 if (p != null) { 10637 PackageSetting ps = (PackageSetting) p.mExtras; 10638 if (ps != null) { 10639 // System apps are never considered stopped for purposes of 10640 // filtering, because there may be no way for the user to 10641 // actually re-launch them. 10642 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10643 && ps.getStopped(userId); 10644 } 10645 } 10646 return false; 10647 } 10648 10649 @Override 10650 protected boolean isPackageForFilter(String packageName, 10651 PackageParser.ProviderIntentInfo info) { 10652 return packageName.equals(info.provider.owner.packageName); 10653 } 10654 10655 @Override 10656 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10657 int match, int userId) { 10658 if (!sUserManager.exists(userId)) 10659 return null; 10660 final PackageParser.ProviderIntentInfo info = filter; 10661 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10662 return null; 10663 } 10664 final PackageParser.Provider provider = info.provider; 10665 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10666 if (ps == null) { 10667 return null; 10668 } 10669 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10670 ps.readUserState(userId), userId); 10671 if (pi == null) { 10672 return null; 10673 } 10674 final ResolveInfo res = new ResolveInfo(); 10675 res.providerInfo = pi; 10676 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10677 res.filter = filter; 10678 } 10679 res.priority = info.getPriority(); 10680 res.preferredOrder = provider.owner.mPreferredOrder; 10681 res.match = match; 10682 res.isDefault = info.hasDefault; 10683 res.labelRes = info.labelRes; 10684 res.nonLocalizedLabel = info.nonLocalizedLabel; 10685 res.icon = info.icon; 10686 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10687 return res; 10688 } 10689 10690 @Override 10691 protected void sortResults(List<ResolveInfo> results) { 10692 Collections.sort(results, mResolvePrioritySorter); 10693 } 10694 10695 @Override 10696 protected void dumpFilter(PrintWriter out, String prefix, 10697 PackageParser.ProviderIntentInfo filter) { 10698 out.print(prefix); 10699 out.print( 10700 Integer.toHexString(System.identityHashCode(filter.provider))); 10701 out.print(' '); 10702 filter.provider.printComponentShortName(out); 10703 out.print(" filter "); 10704 out.println(Integer.toHexString(System.identityHashCode(filter))); 10705 } 10706 10707 @Override 10708 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10709 return filter.provider; 10710 } 10711 10712 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10713 PackageParser.Provider provider = (PackageParser.Provider)label; 10714 out.print(prefix); out.print( 10715 Integer.toHexString(System.identityHashCode(provider))); 10716 out.print(' '); 10717 provider.printComponentShortName(out); 10718 if (count > 1) { 10719 out.print(" ("); out.print(count); out.print(" filters)"); 10720 } 10721 out.println(); 10722 } 10723 10724 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10725 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10726 private int mFlags; 10727 } 10728 10729 private static final class EphemeralIntentResolver 10730 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10731 @Override 10732 protected EphemeralResolveIntentInfo[] newArray(int size) { 10733 return new EphemeralResolveIntentInfo[size]; 10734 } 10735 10736 @Override 10737 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10738 return true; 10739 } 10740 10741 @Override 10742 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10743 int userId) { 10744 if (!sUserManager.exists(userId)) { 10745 return null; 10746 } 10747 return info.getEphemeralResolveInfo(); 10748 } 10749 } 10750 10751 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10752 new Comparator<ResolveInfo>() { 10753 public int compare(ResolveInfo r1, ResolveInfo r2) { 10754 int v1 = r1.priority; 10755 int v2 = r2.priority; 10756 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10757 if (v1 != v2) { 10758 return (v1 > v2) ? -1 : 1; 10759 } 10760 v1 = r1.preferredOrder; 10761 v2 = r2.preferredOrder; 10762 if (v1 != v2) { 10763 return (v1 > v2) ? -1 : 1; 10764 } 10765 if (r1.isDefault != r2.isDefault) { 10766 return r1.isDefault ? -1 : 1; 10767 } 10768 v1 = r1.match; 10769 v2 = r2.match; 10770 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10771 if (v1 != v2) { 10772 return (v1 > v2) ? -1 : 1; 10773 } 10774 if (r1.system != r2.system) { 10775 return r1.system ? -1 : 1; 10776 } 10777 if (r1.activityInfo != null) { 10778 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10779 } 10780 if (r1.serviceInfo != null) { 10781 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10782 } 10783 if (r1.providerInfo != null) { 10784 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10785 } 10786 return 0; 10787 } 10788 }; 10789 10790 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10791 new Comparator<ProviderInfo>() { 10792 public int compare(ProviderInfo p1, ProviderInfo p2) { 10793 final int v1 = p1.initOrder; 10794 final int v2 = p2.initOrder; 10795 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10796 } 10797 }; 10798 10799 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10800 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10801 final int[] userIds) { 10802 mHandler.post(new Runnable() { 10803 @Override 10804 public void run() { 10805 try { 10806 final IActivityManager am = ActivityManagerNative.getDefault(); 10807 if (am == null) return; 10808 final int[] resolvedUserIds; 10809 if (userIds == null) { 10810 resolvedUserIds = am.getRunningUserIds(); 10811 } else { 10812 resolvedUserIds = userIds; 10813 } 10814 for (int id : resolvedUserIds) { 10815 final Intent intent = new Intent(action, 10816 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10817 if (extras != null) { 10818 intent.putExtras(extras); 10819 } 10820 if (targetPkg != null) { 10821 intent.setPackage(targetPkg); 10822 } 10823 // Modify the UID when posting to other users 10824 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10825 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10826 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10827 intent.putExtra(Intent.EXTRA_UID, uid); 10828 } 10829 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10830 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10831 if (DEBUG_BROADCASTS) { 10832 RuntimeException here = new RuntimeException("here"); 10833 here.fillInStackTrace(); 10834 Slog.d(TAG, "Sending to user " + id + ": " 10835 + intent.toShortString(false, true, false, false) 10836 + " " + intent.getExtras(), here); 10837 } 10838 am.broadcastIntent(null, intent, null, finishedReceiver, 10839 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10840 null, finishedReceiver != null, false, id); 10841 } 10842 } catch (RemoteException ex) { 10843 } 10844 } 10845 }); 10846 } 10847 10848 /** 10849 * Check if the external storage media is available. This is true if there 10850 * is a mounted external storage medium or if the external storage is 10851 * emulated. 10852 */ 10853 private boolean isExternalMediaAvailable() { 10854 return mMediaMounted || Environment.isExternalStorageEmulated(); 10855 } 10856 10857 @Override 10858 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10859 // writer 10860 synchronized (mPackages) { 10861 if (!isExternalMediaAvailable()) { 10862 // If the external storage is no longer mounted at this point, 10863 // the caller may not have been able to delete all of this 10864 // packages files and can not delete any more. Bail. 10865 return null; 10866 } 10867 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10868 if (lastPackage != null) { 10869 pkgs.remove(lastPackage); 10870 } 10871 if (pkgs.size() > 0) { 10872 return pkgs.get(0); 10873 } 10874 } 10875 return null; 10876 } 10877 10878 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10879 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10880 userId, andCode ? 1 : 0, packageName); 10881 if (mSystemReady) { 10882 msg.sendToTarget(); 10883 } else { 10884 if (mPostSystemReadyMessages == null) { 10885 mPostSystemReadyMessages = new ArrayList<>(); 10886 } 10887 mPostSystemReadyMessages.add(msg); 10888 } 10889 } 10890 10891 void startCleaningPackages() { 10892 // reader 10893 if (!isExternalMediaAvailable()) { 10894 return; 10895 } 10896 synchronized (mPackages) { 10897 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10898 return; 10899 } 10900 } 10901 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10902 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10903 IActivityManager am = ActivityManagerNative.getDefault(); 10904 if (am != null) { 10905 try { 10906 am.startService(null, intent, null, mContext.getOpPackageName(), 10907 UserHandle.USER_SYSTEM); 10908 } catch (RemoteException e) { 10909 } 10910 } 10911 } 10912 10913 @Override 10914 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10915 int installFlags, String installerPackageName, int userId) { 10916 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10917 10918 final int callingUid = Binder.getCallingUid(); 10919 enforceCrossUserPermission(callingUid, userId, 10920 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10921 10922 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10923 try { 10924 if (observer != null) { 10925 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10926 } 10927 } catch (RemoteException re) { 10928 } 10929 return; 10930 } 10931 10932 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10933 installFlags |= PackageManager.INSTALL_FROM_ADB; 10934 10935 } else { 10936 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10937 // about installerPackageName. 10938 10939 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10940 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10941 } 10942 10943 UserHandle user; 10944 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10945 user = UserHandle.ALL; 10946 } else { 10947 user = new UserHandle(userId); 10948 } 10949 10950 // Only system components can circumvent runtime permissions when installing. 10951 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10952 && mContext.checkCallingOrSelfPermission(Manifest.permission 10953 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10954 throw new SecurityException("You need the " 10955 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10956 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10957 } 10958 10959 final File originFile = new File(originPath); 10960 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10961 10962 final Message msg = mHandler.obtainMessage(INIT_COPY); 10963 final VerificationInfo verificationInfo = new VerificationInfo( 10964 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10965 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10966 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10967 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10968 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10969 msg.obj = params; 10970 10971 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10972 System.identityHashCode(msg.obj)); 10973 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10974 System.identityHashCode(msg.obj)); 10975 10976 mHandler.sendMessage(msg); 10977 } 10978 10979 void installStage(String packageName, File stagedDir, String stagedCid, 10980 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10981 String installerPackageName, int installerUid, UserHandle user) { 10982 if (DEBUG_EPHEMERAL) { 10983 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10984 Slog.d(TAG, "Ephemeral install of " + packageName); 10985 } 10986 } 10987 final VerificationInfo verificationInfo = new VerificationInfo( 10988 sessionParams.originatingUri, sessionParams.referrerUri, 10989 sessionParams.originatingUid, installerUid); 10990 10991 final OriginInfo origin; 10992 if (stagedDir != null) { 10993 origin = OriginInfo.fromStagedFile(stagedDir); 10994 } else { 10995 origin = OriginInfo.fromStagedContainer(stagedCid); 10996 } 10997 10998 final Message msg = mHandler.obtainMessage(INIT_COPY); 10999 final InstallParams params = new InstallParams(origin, null, observer, 11000 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11001 verificationInfo, user, sessionParams.abiOverride, 11002 sessionParams.grantedRuntimePermissions); 11003 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11004 msg.obj = params; 11005 11006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11007 System.identityHashCode(msg.obj)); 11008 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11009 System.identityHashCode(msg.obj)); 11010 11011 mHandler.sendMessage(msg); 11012 } 11013 11014 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11015 int userId) { 11016 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11017 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11018 } 11019 11020 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11021 int appId, int userId) { 11022 Bundle extras = new Bundle(1); 11023 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11024 11025 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11026 packageName, extras, 0, null, null, new int[] {userId}); 11027 try { 11028 IActivityManager am = ActivityManagerNative.getDefault(); 11029 if (isSystem && am.isUserRunning(userId, 0)) { 11030 // The just-installed/enabled app is bundled on the system, so presumed 11031 // to be able to run automatically without needing an explicit launch. 11032 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11033 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11034 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11035 .setPackage(packageName); 11036 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11037 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11038 } 11039 } catch (RemoteException e) { 11040 // shouldn't happen 11041 Slog.w(TAG, "Unable to bootstrap installed package", e); 11042 } 11043 } 11044 11045 @Override 11046 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11047 int userId) { 11048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11049 PackageSetting pkgSetting; 11050 final int uid = Binder.getCallingUid(); 11051 enforceCrossUserPermission(uid, userId, 11052 true /* requireFullPermission */, true /* checkShell */, 11053 "setApplicationHiddenSetting for user " + userId); 11054 11055 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11056 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11057 return false; 11058 } 11059 11060 long callingId = Binder.clearCallingIdentity(); 11061 try { 11062 boolean sendAdded = false; 11063 boolean sendRemoved = false; 11064 // writer 11065 synchronized (mPackages) { 11066 pkgSetting = mSettings.mPackages.get(packageName); 11067 if (pkgSetting == null) { 11068 return false; 11069 } 11070 if (pkgSetting.getHidden(userId) != hidden) { 11071 pkgSetting.setHidden(hidden, userId); 11072 mSettings.writePackageRestrictionsLPr(userId); 11073 if (hidden) { 11074 sendRemoved = true; 11075 } else { 11076 sendAdded = true; 11077 } 11078 } 11079 } 11080 if (sendAdded) { 11081 sendPackageAddedForUser(packageName, pkgSetting, userId); 11082 return true; 11083 } 11084 if (sendRemoved) { 11085 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11086 "hiding pkg"); 11087 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11088 return true; 11089 } 11090 } finally { 11091 Binder.restoreCallingIdentity(callingId); 11092 } 11093 return false; 11094 } 11095 11096 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11097 int userId) { 11098 final PackageRemovedInfo info = new PackageRemovedInfo(); 11099 info.removedPackage = packageName; 11100 info.removedUsers = new int[] {userId}; 11101 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11102 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11103 } 11104 11105 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11106 if (pkgList.length > 0) { 11107 Bundle extras = new Bundle(1); 11108 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11109 11110 sendPackageBroadcast( 11111 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11112 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11113 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11114 new int[] {userId}); 11115 } 11116 } 11117 11118 /** 11119 * Returns true if application is not found or there was an error. Otherwise it returns 11120 * the hidden state of the package for the given user. 11121 */ 11122 @Override 11123 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11126 true /* requireFullPermission */, false /* checkShell */, 11127 "getApplicationHidden for user " + userId); 11128 PackageSetting pkgSetting; 11129 long callingId = Binder.clearCallingIdentity(); 11130 try { 11131 // writer 11132 synchronized (mPackages) { 11133 pkgSetting = mSettings.mPackages.get(packageName); 11134 if (pkgSetting == null) { 11135 return true; 11136 } 11137 return pkgSetting.getHidden(userId); 11138 } 11139 } finally { 11140 Binder.restoreCallingIdentity(callingId); 11141 } 11142 } 11143 11144 /** 11145 * @hide 11146 */ 11147 @Override 11148 public int installExistingPackageAsUser(String packageName, int userId) { 11149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11150 null); 11151 PackageSetting pkgSetting; 11152 final int uid = Binder.getCallingUid(); 11153 enforceCrossUserPermission(uid, userId, 11154 true /* requireFullPermission */, true /* checkShell */, 11155 "installExistingPackage for user " + userId); 11156 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11157 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11158 } 11159 11160 long callingId = Binder.clearCallingIdentity(); 11161 try { 11162 boolean installed = false; 11163 11164 // writer 11165 synchronized (mPackages) { 11166 pkgSetting = mSettings.mPackages.get(packageName); 11167 if (pkgSetting == null) { 11168 return PackageManager.INSTALL_FAILED_INVALID_URI; 11169 } 11170 if (!pkgSetting.getInstalled(userId)) { 11171 pkgSetting.setInstalled(true, userId); 11172 pkgSetting.setHidden(false, userId); 11173 mSettings.writePackageRestrictionsLPr(userId); 11174 installed = true; 11175 } 11176 } 11177 11178 if (installed) { 11179 if (pkgSetting.pkg != null) { 11180 prepareAppDataAfterInstall(pkgSetting.pkg); 11181 } 11182 sendPackageAddedForUser(packageName, pkgSetting, userId); 11183 } 11184 } finally { 11185 Binder.restoreCallingIdentity(callingId); 11186 } 11187 11188 return PackageManager.INSTALL_SUCCEEDED; 11189 } 11190 11191 boolean isUserRestricted(int userId, String restrictionKey) { 11192 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11193 if (restrictions.getBoolean(restrictionKey, false)) { 11194 Log.w(TAG, "User is restricted: " + restrictionKey); 11195 return true; 11196 } 11197 return false; 11198 } 11199 11200 @Override 11201 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11202 int userId) { 11203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11205 true /* requireFullPermission */, true /* checkShell */, 11206 "setPackagesSuspended for user " + userId); 11207 11208 if (ArrayUtils.isEmpty(packageNames)) { 11209 return packageNames; 11210 } 11211 11212 // List of package names for whom the suspended state has changed. 11213 List<String> changedPackages = new ArrayList<>(packageNames.length); 11214 // List of package names for whom the suspended state is not set as requested in this 11215 // method. 11216 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11217 for (int i = 0; i < packageNames.length; i++) { 11218 String packageName = packageNames[i]; 11219 long callingId = Binder.clearCallingIdentity(); 11220 try { 11221 boolean changed = false; 11222 final int appId; 11223 synchronized (mPackages) { 11224 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11225 if (pkgSetting == null) { 11226 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11227 + "\". Skipping suspending/un-suspending."); 11228 unactionedPackages.add(packageName); 11229 continue; 11230 } 11231 appId = pkgSetting.appId; 11232 if (pkgSetting.getSuspended(userId) != suspended) { 11233 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11234 unactionedPackages.add(packageName); 11235 continue; 11236 } 11237 pkgSetting.setSuspended(suspended, userId); 11238 mSettings.writePackageRestrictionsLPr(userId); 11239 changed = true; 11240 changedPackages.add(packageName); 11241 } 11242 } 11243 11244 if (changed && suspended) { 11245 killApplication(packageName, UserHandle.getUid(userId, appId), 11246 "suspending package"); 11247 } 11248 } finally { 11249 Binder.restoreCallingIdentity(callingId); 11250 } 11251 } 11252 11253 if (!changedPackages.isEmpty()) { 11254 sendPackagesSuspendedForUser(changedPackages.toArray( 11255 new String[changedPackages.size()]), userId, suspended); 11256 } 11257 11258 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11259 } 11260 11261 @Override 11262 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11264 true /* requireFullPermission */, false /* checkShell */, 11265 "isPackageSuspendedForUser for user " + userId); 11266 synchronized (mPackages) { 11267 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11268 if (pkgSetting == null) { 11269 throw new IllegalArgumentException("Unknown target package: " + packageName); 11270 } 11271 return pkgSetting.getSuspended(userId); 11272 } 11273 } 11274 11275 /** 11276 * TODO: cache and disallow blocking the active dialer. 11277 * 11278 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11279 */ 11280 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11281 if (isPackageDeviceAdmin(packageName, userId)) { 11282 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11283 + "\": has an active device admin"); 11284 return false; 11285 } 11286 11287 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11288 if (packageName.equals(activeLauncherPackageName)) { 11289 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11290 + "\": contains the active launcher"); 11291 return false; 11292 } 11293 11294 if (packageName.equals(mRequiredInstallerPackage)) { 11295 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11296 + "\": required for package installation"); 11297 return false; 11298 } 11299 11300 if (packageName.equals(mRequiredVerifierPackage)) { 11301 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11302 + "\": required for package verification"); 11303 return false; 11304 } 11305 11306 final PackageParser.Package pkg = mPackages.get(packageName); 11307 if (pkg != null && isPrivilegedApp(pkg)) { 11308 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11309 + "\": is a privileged app"); 11310 return false; 11311 } 11312 11313 return true; 11314 } 11315 11316 private String getActiveLauncherPackageName(int userId) { 11317 Intent intent = new Intent(Intent.ACTION_MAIN); 11318 intent.addCategory(Intent.CATEGORY_HOME); 11319 ResolveInfo resolveInfo = resolveIntent( 11320 intent, 11321 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11322 PackageManager.MATCH_DEFAULT_ONLY, 11323 userId); 11324 11325 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11326 } 11327 11328 @Override 11329 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11330 mContext.enforceCallingOrSelfPermission( 11331 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11332 "Only package verification agents can verify applications"); 11333 11334 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11335 final PackageVerificationResponse response = new PackageVerificationResponse( 11336 verificationCode, Binder.getCallingUid()); 11337 msg.arg1 = id; 11338 msg.obj = response; 11339 mHandler.sendMessage(msg); 11340 } 11341 11342 @Override 11343 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11344 long millisecondsToDelay) { 11345 mContext.enforceCallingOrSelfPermission( 11346 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11347 "Only package verification agents can extend verification timeouts"); 11348 11349 final PackageVerificationState state = mPendingVerification.get(id); 11350 final PackageVerificationResponse response = new PackageVerificationResponse( 11351 verificationCodeAtTimeout, Binder.getCallingUid()); 11352 11353 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11354 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11355 } 11356 if (millisecondsToDelay < 0) { 11357 millisecondsToDelay = 0; 11358 } 11359 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11360 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11361 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11362 } 11363 11364 if ((state != null) && !state.timeoutExtended()) { 11365 state.extendTimeout(); 11366 11367 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11368 msg.arg1 = id; 11369 msg.obj = response; 11370 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11371 } 11372 } 11373 11374 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11375 int verificationCode, UserHandle user) { 11376 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11377 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11378 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11379 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11380 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11381 11382 mContext.sendBroadcastAsUser(intent, user, 11383 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11384 } 11385 11386 private ComponentName matchComponentForVerifier(String packageName, 11387 List<ResolveInfo> receivers) { 11388 ActivityInfo targetReceiver = null; 11389 11390 final int NR = receivers.size(); 11391 for (int i = 0; i < NR; i++) { 11392 final ResolveInfo info = receivers.get(i); 11393 if (info.activityInfo == null) { 11394 continue; 11395 } 11396 11397 if (packageName.equals(info.activityInfo.packageName)) { 11398 targetReceiver = info.activityInfo; 11399 break; 11400 } 11401 } 11402 11403 if (targetReceiver == null) { 11404 return null; 11405 } 11406 11407 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11408 } 11409 11410 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11411 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11412 if (pkgInfo.verifiers.length == 0) { 11413 return null; 11414 } 11415 11416 final int N = pkgInfo.verifiers.length; 11417 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11418 for (int i = 0; i < N; i++) { 11419 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11420 11421 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11422 receivers); 11423 if (comp == null) { 11424 continue; 11425 } 11426 11427 final int verifierUid = getUidForVerifier(verifierInfo); 11428 if (verifierUid == -1) { 11429 continue; 11430 } 11431 11432 if (DEBUG_VERIFY) { 11433 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11434 + " with the correct signature"); 11435 } 11436 sufficientVerifiers.add(comp); 11437 verificationState.addSufficientVerifier(verifierUid); 11438 } 11439 11440 return sufficientVerifiers; 11441 } 11442 11443 private int getUidForVerifier(VerifierInfo verifierInfo) { 11444 synchronized (mPackages) { 11445 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11446 if (pkg == null) { 11447 return -1; 11448 } else if (pkg.mSignatures.length != 1) { 11449 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11450 + " has more than one signature; ignoring"); 11451 return -1; 11452 } 11453 11454 /* 11455 * If the public key of the package's signature does not match 11456 * our expected public key, then this is a different package and 11457 * we should skip. 11458 */ 11459 11460 final byte[] expectedPublicKey; 11461 try { 11462 final Signature verifierSig = pkg.mSignatures[0]; 11463 final PublicKey publicKey = verifierSig.getPublicKey(); 11464 expectedPublicKey = publicKey.getEncoded(); 11465 } catch (CertificateException e) { 11466 return -1; 11467 } 11468 11469 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11470 11471 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11472 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11473 + " does not have the expected public key; ignoring"); 11474 return -1; 11475 } 11476 11477 return pkg.applicationInfo.uid; 11478 } 11479 } 11480 11481 @Override 11482 public void finishPackageInstall(int token) { 11483 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11484 11485 if (DEBUG_INSTALL) { 11486 Slog.v(TAG, "BM finishing package install for " + token); 11487 } 11488 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11489 11490 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11491 mHandler.sendMessage(msg); 11492 } 11493 11494 /** 11495 * Get the verification agent timeout. 11496 * 11497 * @return verification timeout in milliseconds 11498 */ 11499 private long getVerificationTimeout() { 11500 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11501 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11502 DEFAULT_VERIFICATION_TIMEOUT); 11503 } 11504 11505 /** 11506 * Get the default verification agent response code. 11507 * 11508 * @return default verification response code 11509 */ 11510 private int getDefaultVerificationResponse() { 11511 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11512 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11513 DEFAULT_VERIFICATION_RESPONSE); 11514 } 11515 11516 /** 11517 * Check whether or not package verification has been enabled. 11518 * 11519 * @return true if verification should be performed 11520 */ 11521 private boolean isVerificationEnabled(int userId, int installFlags) { 11522 if (!DEFAULT_VERIFY_ENABLE) { 11523 return false; 11524 } 11525 // Ephemeral apps don't get the full verification treatment 11526 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11527 if (DEBUG_EPHEMERAL) { 11528 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11529 } 11530 return false; 11531 } 11532 11533 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11534 11535 // Check if installing from ADB 11536 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11537 // Do not run verification in a test harness environment 11538 if (ActivityManager.isRunningInTestHarness()) { 11539 return false; 11540 } 11541 if (ensureVerifyAppsEnabled) { 11542 return true; 11543 } 11544 // Check if the developer does not want package verification for ADB installs 11545 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11546 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11547 return false; 11548 } 11549 } 11550 11551 if (ensureVerifyAppsEnabled) { 11552 return true; 11553 } 11554 11555 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11556 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11557 } 11558 11559 @Override 11560 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11561 throws RemoteException { 11562 mContext.enforceCallingOrSelfPermission( 11563 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11564 "Only intentfilter verification agents can verify applications"); 11565 11566 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11567 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11568 Binder.getCallingUid(), verificationCode, failedDomains); 11569 msg.arg1 = id; 11570 msg.obj = response; 11571 mHandler.sendMessage(msg); 11572 } 11573 11574 @Override 11575 public int getIntentVerificationStatus(String packageName, int userId) { 11576 synchronized (mPackages) { 11577 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11578 } 11579 } 11580 11581 @Override 11582 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11583 mContext.enforceCallingOrSelfPermission( 11584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11585 11586 boolean result = false; 11587 synchronized (mPackages) { 11588 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11589 } 11590 if (result) { 11591 scheduleWritePackageRestrictionsLocked(userId); 11592 } 11593 return result; 11594 } 11595 11596 @Override 11597 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11598 String packageName) { 11599 synchronized (mPackages) { 11600 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11601 } 11602 } 11603 11604 @Override 11605 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11606 if (TextUtils.isEmpty(packageName)) { 11607 return ParceledListSlice.emptyList(); 11608 } 11609 synchronized (mPackages) { 11610 PackageParser.Package pkg = mPackages.get(packageName); 11611 if (pkg == null || pkg.activities == null) { 11612 return ParceledListSlice.emptyList(); 11613 } 11614 final int count = pkg.activities.size(); 11615 ArrayList<IntentFilter> result = new ArrayList<>(); 11616 for (int n=0; n<count; n++) { 11617 PackageParser.Activity activity = pkg.activities.get(n); 11618 if (activity.intents != null && activity.intents.size() > 0) { 11619 result.addAll(activity.intents); 11620 } 11621 } 11622 return new ParceledListSlice<>(result); 11623 } 11624 } 11625 11626 @Override 11627 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11628 mContext.enforceCallingOrSelfPermission( 11629 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11630 11631 synchronized (mPackages) { 11632 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11633 if (packageName != null) { 11634 result |= updateIntentVerificationStatus(packageName, 11635 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11636 userId); 11637 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11638 packageName, userId); 11639 } 11640 return result; 11641 } 11642 } 11643 11644 @Override 11645 public String getDefaultBrowserPackageName(int userId) { 11646 synchronized (mPackages) { 11647 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11648 } 11649 } 11650 11651 /** 11652 * Get the "allow unknown sources" setting. 11653 * 11654 * @return the current "allow unknown sources" setting 11655 */ 11656 private int getUnknownSourcesSettings() { 11657 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11658 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11659 -1); 11660 } 11661 11662 @Override 11663 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11664 final int uid = Binder.getCallingUid(); 11665 // writer 11666 synchronized (mPackages) { 11667 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11668 if (targetPackageSetting == null) { 11669 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11670 } 11671 11672 PackageSetting installerPackageSetting; 11673 if (installerPackageName != null) { 11674 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11675 if (installerPackageSetting == null) { 11676 throw new IllegalArgumentException("Unknown installer package: " 11677 + installerPackageName); 11678 } 11679 } else { 11680 installerPackageSetting = null; 11681 } 11682 11683 Signature[] callerSignature; 11684 Object obj = mSettings.getUserIdLPr(uid); 11685 if (obj != null) { 11686 if (obj instanceof SharedUserSetting) { 11687 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11688 } else if (obj instanceof PackageSetting) { 11689 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11690 } else { 11691 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11692 } 11693 } else { 11694 throw new SecurityException("Unknown calling UID: " + uid); 11695 } 11696 11697 // Verify: can't set installerPackageName to a package that is 11698 // not signed with the same cert as the caller. 11699 if (installerPackageSetting != null) { 11700 if (compareSignatures(callerSignature, 11701 installerPackageSetting.signatures.mSignatures) 11702 != PackageManager.SIGNATURE_MATCH) { 11703 throw new SecurityException( 11704 "Caller does not have same cert as new installer package " 11705 + installerPackageName); 11706 } 11707 } 11708 11709 // Verify: if target already has an installer package, it must 11710 // be signed with the same cert as the caller. 11711 if (targetPackageSetting.installerPackageName != null) { 11712 PackageSetting setting = mSettings.mPackages.get( 11713 targetPackageSetting.installerPackageName); 11714 // If the currently set package isn't valid, then it's always 11715 // okay to change it. 11716 if (setting != null) { 11717 if (compareSignatures(callerSignature, 11718 setting.signatures.mSignatures) 11719 != PackageManager.SIGNATURE_MATCH) { 11720 throw new SecurityException( 11721 "Caller does not have same cert as old installer package " 11722 + targetPackageSetting.installerPackageName); 11723 } 11724 } 11725 } 11726 11727 // Okay! 11728 targetPackageSetting.installerPackageName = installerPackageName; 11729 scheduleWriteSettingsLocked(); 11730 } 11731 } 11732 11733 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11734 // Queue up an async operation since the package installation may take a little while. 11735 mHandler.post(new Runnable() { 11736 public void run() { 11737 mHandler.removeCallbacks(this); 11738 // Result object to be returned 11739 PackageInstalledInfo res = new PackageInstalledInfo(); 11740 res.setReturnCode(currentStatus); 11741 res.uid = -1; 11742 res.pkg = null; 11743 res.removedInfo = null; 11744 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11745 args.doPreInstall(res.returnCode); 11746 synchronized (mInstallLock) { 11747 installPackageTracedLI(args, res); 11748 } 11749 args.doPostInstall(res.returnCode, res.uid); 11750 } 11751 11752 // A restore should be performed at this point if (a) the install 11753 // succeeded, (b) the operation is not an update, and (c) the new 11754 // package has not opted out of backup participation. 11755 final boolean update = res.removedInfo != null 11756 && res.removedInfo.removedPackage != null; 11757 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11758 boolean doRestore = !update 11759 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11760 11761 // Set up the post-install work request bookkeeping. This will be used 11762 // and cleaned up by the post-install event handling regardless of whether 11763 // there's a restore pass performed. Token values are >= 1. 11764 int token; 11765 if (mNextInstallToken < 0) mNextInstallToken = 1; 11766 token = mNextInstallToken++; 11767 11768 PostInstallData data = new PostInstallData(args, res); 11769 mRunningInstalls.put(token, data); 11770 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11771 11772 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11773 // Pass responsibility to the Backup Manager. It will perform a 11774 // restore if appropriate, then pass responsibility back to the 11775 // Package Manager to run the post-install observer callbacks 11776 // and broadcasts. 11777 IBackupManager bm = IBackupManager.Stub.asInterface( 11778 ServiceManager.getService(Context.BACKUP_SERVICE)); 11779 if (bm != null) { 11780 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11781 + " to BM for possible restore"); 11782 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11783 try { 11784 // TODO: http://b/22388012 11785 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11786 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11787 } else { 11788 doRestore = false; 11789 } 11790 } catch (RemoteException e) { 11791 // can't happen; the backup manager is local 11792 } catch (Exception e) { 11793 Slog.e(TAG, "Exception trying to enqueue restore", e); 11794 doRestore = false; 11795 } 11796 } else { 11797 Slog.e(TAG, "Backup Manager not found!"); 11798 doRestore = false; 11799 } 11800 } 11801 11802 if (!doRestore) { 11803 // No restore possible, or the Backup Manager was mysteriously not 11804 // available -- just fire the post-install work request directly. 11805 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11806 11807 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11808 11809 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11810 mHandler.sendMessage(msg); 11811 } 11812 } 11813 }); 11814 } 11815 11816 private abstract class HandlerParams { 11817 private static final int MAX_RETRIES = 4; 11818 11819 /** 11820 * Number of times startCopy() has been attempted and had a non-fatal 11821 * error. 11822 */ 11823 private int mRetries = 0; 11824 11825 /** User handle for the user requesting the information or installation. */ 11826 private final UserHandle mUser; 11827 String traceMethod; 11828 int traceCookie; 11829 11830 HandlerParams(UserHandle user) { 11831 mUser = user; 11832 } 11833 11834 UserHandle getUser() { 11835 return mUser; 11836 } 11837 11838 HandlerParams setTraceMethod(String traceMethod) { 11839 this.traceMethod = traceMethod; 11840 return this; 11841 } 11842 11843 HandlerParams setTraceCookie(int traceCookie) { 11844 this.traceCookie = traceCookie; 11845 return this; 11846 } 11847 11848 final boolean startCopy() { 11849 boolean res; 11850 try { 11851 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11852 11853 if (++mRetries > MAX_RETRIES) { 11854 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11855 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11856 handleServiceError(); 11857 return false; 11858 } else { 11859 handleStartCopy(); 11860 res = true; 11861 } 11862 } catch (RemoteException e) { 11863 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11864 mHandler.sendEmptyMessage(MCS_RECONNECT); 11865 res = false; 11866 } 11867 handleReturnCode(); 11868 return res; 11869 } 11870 11871 final void serviceError() { 11872 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11873 handleServiceError(); 11874 handleReturnCode(); 11875 } 11876 11877 abstract void handleStartCopy() throws RemoteException; 11878 abstract void handleServiceError(); 11879 abstract void handleReturnCode(); 11880 } 11881 11882 class MeasureParams extends HandlerParams { 11883 private final PackageStats mStats; 11884 private boolean mSuccess; 11885 11886 private final IPackageStatsObserver mObserver; 11887 11888 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11889 super(new UserHandle(stats.userHandle)); 11890 mObserver = observer; 11891 mStats = stats; 11892 } 11893 11894 @Override 11895 public String toString() { 11896 return "MeasureParams{" 11897 + Integer.toHexString(System.identityHashCode(this)) 11898 + " " + mStats.packageName + "}"; 11899 } 11900 11901 @Override 11902 void handleStartCopy() throws RemoteException { 11903 synchronized (mInstallLock) { 11904 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11905 } 11906 11907 if (mSuccess) { 11908 final boolean mounted; 11909 if (Environment.isExternalStorageEmulated()) { 11910 mounted = true; 11911 } else { 11912 final String status = Environment.getExternalStorageState(); 11913 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11914 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11915 } 11916 11917 if (mounted) { 11918 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11919 11920 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11921 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11922 11923 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11924 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11925 11926 // Always subtract cache size, since it's a subdirectory 11927 mStats.externalDataSize -= mStats.externalCacheSize; 11928 11929 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11930 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11931 11932 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11933 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11934 } 11935 } 11936 } 11937 11938 @Override 11939 void handleReturnCode() { 11940 if (mObserver != null) { 11941 try { 11942 mObserver.onGetStatsCompleted(mStats, mSuccess); 11943 } catch (RemoteException e) { 11944 Slog.i(TAG, "Observer no longer exists."); 11945 } 11946 } 11947 } 11948 11949 @Override 11950 void handleServiceError() { 11951 Slog.e(TAG, "Could not measure application " + mStats.packageName 11952 + " external storage"); 11953 } 11954 } 11955 11956 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11957 throws RemoteException { 11958 long result = 0; 11959 for (File path : paths) { 11960 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11961 } 11962 return result; 11963 } 11964 11965 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11966 for (File path : paths) { 11967 try { 11968 mcs.clearDirectory(path.getAbsolutePath()); 11969 } catch (RemoteException e) { 11970 } 11971 } 11972 } 11973 11974 static class OriginInfo { 11975 /** 11976 * Location where install is coming from, before it has been 11977 * copied/renamed into place. This could be a single monolithic APK 11978 * file, or a cluster directory. This location may be untrusted. 11979 */ 11980 final File file; 11981 final String cid; 11982 11983 /** 11984 * Flag indicating that {@link #file} or {@link #cid} has already been 11985 * staged, meaning downstream users don't need to defensively copy the 11986 * contents. 11987 */ 11988 final boolean staged; 11989 11990 /** 11991 * Flag indicating that {@link #file} or {@link #cid} is an already 11992 * installed app that is being moved. 11993 */ 11994 final boolean existing; 11995 11996 final String resolvedPath; 11997 final File resolvedFile; 11998 11999 static OriginInfo fromNothing() { 12000 return new OriginInfo(null, null, false, false); 12001 } 12002 12003 static OriginInfo fromUntrustedFile(File file) { 12004 return new OriginInfo(file, null, false, false); 12005 } 12006 12007 static OriginInfo fromExistingFile(File file) { 12008 return new OriginInfo(file, null, false, true); 12009 } 12010 12011 static OriginInfo fromStagedFile(File file) { 12012 return new OriginInfo(file, null, true, false); 12013 } 12014 12015 static OriginInfo fromStagedContainer(String cid) { 12016 return new OriginInfo(null, cid, true, false); 12017 } 12018 12019 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12020 this.file = file; 12021 this.cid = cid; 12022 this.staged = staged; 12023 this.existing = existing; 12024 12025 if (cid != null) { 12026 resolvedPath = PackageHelper.getSdDir(cid); 12027 resolvedFile = new File(resolvedPath); 12028 } else if (file != null) { 12029 resolvedPath = file.getAbsolutePath(); 12030 resolvedFile = file; 12031 } else { 12032 resolvedPath = null; 12033 resolvedFile = null; 12034 } 12035 } 12036 } 12037 12038 static class MoveInfo { 12039 final int moveId; 12040 final String fromUuid; 12041 final String toUuid; 12042 final String packageName; 12043 final String dataAppName; 12044 final int appId; 12045 final String seinfo; 12046 final int targetSdkVersion; 12047 12048 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12049 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12050 this.moveId = moveId; 12051 this.fromUuid = fromUuid; 12052 this.toUuid = toUuid; 12053 this.packageName = packageName; 12054 this.dataAppName = dataAppName; 12055 this.appId = appId; 12056 this.seinfo = seinfo; 12057 this.targetSdkVersion = targetSdkVersion; 12058 } 12059 } 12060 12061 static class VerificationInfo { 12062 /** A constant used to indicate that a uid value is not present. */ 12063 public static final int NO_UID = -1; 12064 12065 /** URI referencing where the package was downloaded from. */ 12066 final Uri originatingUri; 12067 12068 /** HTTP referrer URI associated with the originatingURI. */ 12069 final Uri referrer; 12070 12071 /** UID of the application that the install request originated from. */ 12072 final int originatingUid; 12073 12074 /** UID of application requesting the install */ 12075 final int installerUid; 12076 12077 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12078 this.originatingUri = originatingUri; 12079 this.referrer = referrer; 12080 this.originatingUid = originatingUid; 12081 this.installerUid = installerUid; 12082 } 12083 } 12084 12085 class InstallParams extends HandlerParams { 12086 final OriginInfo origin; 12087 final MoveInfo move; 12088 final IPackageInstallObserver2 observer; 12089 int installFlags; 12090 final String installerPackageName; 12091 final String volumeUuid; 12092 private InstallArgs mArgs; 12093 private int mRet; 12094 final String packageAbiOverride; 12095 final String[] grantedRuntimePermissions; 12096 final VerificationInfo verificationInfo; 12097 12098 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12099 int installFlags, String installerPackageName, String volumeUuid, 12100 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12101 String[] grantedPermissions) { 12102 super(user); 12103 this.origin = origin; 12104 this.move = move; 12105 this.observer = observer; 12106 this.installFlags = installFlags; 12107 this.installerPackageName = installerPackageName; 12108 this.volumeUuid = volumeUuid; 12109 this.verificationInfo = verificationInfo; 12110 this.packageAbiOverride = packageAbiOverride; 12111 this.grantedRuntimePermissions = grantedPermissions; 12112 } 12113 12114 @Override 12115 public String toString() { 12116 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12117 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12118 } 12119 12120 private int installLocationPolicy(PackageInfoLite pkgLite) { 12121 String packageName = pkgLite.packageName; 12122 int installLocation = pkgLite.installLocation; 12123 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12124 // reader 12125 synchronized (mPackages) { 12126 // Currently installed package which the new package is attempting to replace or 12127 // null if no such package is installed. 12128 PackageParser.Package installedPkg = mPackages.get(packageName); 12129 // Package which currently owns the data which the new package will own if installed. 12130 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12131 // will be null whereas dataOwnerPkg will contain information about the package 12132 // which was uninstalled while keeping its data. 12133 PackageParser.Package dataOwnerPkg = installedPkg; 12134 if (dataOwnerPkg == null) { 12135 PackageSetting ps = mSettings.mPackages.get(packageName); 12136 if (ps != null) { 12137 dataOwnerPkg = ps.pkg; 12138 } 12139 } 12140 12141 if (dataOwnerPkg != null) { 12142 // If installed, the package will get access to data left on the device by its 12143 // predecessor. As a security measure, this is permited only if this is not a 12144 // version downgrade or if the predecessor package is marked as debuggable and 12145 // a downgrade is explicitly requested. 12146 // 12147 // On debuggable platform builds, downgrades are permitted even for 12148 // non-debuggable packages to make testing easier. Debuggable platform builds do 12149 // not offer security guarantees and thus it's OK to disable some security 12150 // mechanisms to make debugging/testing easier on those builds. However, even on 12151 // debuggable builds downgrades of packages are permitted only if requested via 12152 // installFlags. This is because we aim to keep the behavior of debuggable 12153 // platform builds as close as possible to the behavior of non-debuggable 12154 // platform builds. 12155 final boolean downgradeRequested = 12156 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12157 final boolean packageDebuggable = 12158 (dataOwnerPkg.applicationInfo.flags 12159 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12160 final boolean downgradePermitted = 12161 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12162 if (!downgradePermitted) { 12163 try { 12164 checkDowngrade(dataOwnerPkg, pkgLite); 12165 } catch (PackageManagerException e) { 12166 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12167 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12168 } 12169 } 12170 } 12171 12172 if (installedPkg != null) { 12173 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12174 // Check for updated system application. 12175 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12176 if (onSd) { 12177 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12178 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12179 } 12180 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12181 } else { 12182 if (onSd) { 12183 // Install flag overrides everything. 12184 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12185 } 12186 // If current upgrade specifies particular preference 12187 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12188 // Application explicitly specified internal. 12189 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12190 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12191 // App explictly prefers external. Let policy decide 12192 } else { 12193 // Prefer previous location 12194 if (isExternal(installedPkg)) { 12195 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12196 } 12197 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12198 } 12199 } 12200 } else { 12201 // Invalid install. Return error code 12202 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12203 } 12204 } 12205 } 12206 // All the special cases have been taken care of. 12207 // Return result based on recommended install location. 12208 if (onSd) { 12209 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12210 } 12211 return pkgLite.recommendedInstallLocation; 12212 } 12213 12214 /* 12215 * Invoke remote method to get package information and install 12216 * location values. Override install location based on default 12217 * policy if needed and then create install arguments based 12218 * on the install location. 12219 */ 12220 public void handleStartCopy() throws RemoteException { 12221 int ret = PackageManager.INSTALL_SUCCEEDED; 12222 12223 // If we're already staged, we've firmly committed to an install location 12224 if (origin.staged) { 12225 if (origin.file != null) { 12226 installFlags |= PackageManager.INSTALL_INTERNAL; 12227 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12228 } else if (origin.cid != null) { 12229 installFlags |= PackageManager.INSTALL_EXTERNAL; 12230 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12231 } else { 12232 throw new IllegalStateException("Invalid stage location"); 12233 } 12234 } 12235 12236 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12237 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12238 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12239 PackageInfoLite pkgLite = null; 12240 12241 if (onInt && onSd) { 12242 // Check if both bits are set. 12243 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12244 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12245 } else if (onSd && ephemeral) { 12246 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12247 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12248 } else { 12249 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12250 packageAbiOverride); 12251 12252 if (DEBUG_EPHEMERAL && ephemeral) { 12253 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12254 } 12255 12256 /* 12257 * If we have too little free space, try to free cache 12258 * before giving up. 12259 */ 12260 if (!origin.staged && pkgLite.recommendedInstallLocation 12261 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12262 // TODO: focus freeing disk space on the target device 12263 final StorageManager storage = StorageManager.from(mContext); 12264 final long lowThreshold = storage.getStorageLowBytes( 12265 Environment.getDataDirectory()); 12266 12267 final long sizeBytes = mContainerService.calculateInstalledSize( 12268 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12269 12270 try { 12271 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12272 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12273 installFlags, packageAbiOverride); 12274 } catch (InstallerException e) { 12275 Slog.w(TAG, "Failed to free cache", e); 12276 } 12277 12278 /* 12279 * The cache free must have deleted the file we 12280 * downloaded to install. 12281 * 12282 * TODO: fix the "freeCache" call to not delete 12283 * the file we care about. 12284 */ 12285 if (pkgLite.recommendedInstallLocation 12286 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12287 pkgLite.recommendedInstallLocation 12288 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12289 } 12290 } 12291 } 12292 12293 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12294 int loc = pkgLite.recommendedInstallLocation; 12295 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12296 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12297 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12298 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12299 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12300 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12301 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12302 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12303 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12304 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12305 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12306 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12307 } else { 12308 // Override with defaults if needed. 12309 loc = installLocationPolicy(pkgLite); 12310 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12311 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12312 } else if (!onSd && !onInt) { 12313 // Override install location with flags 12314 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12315 // Set the flag to install on external media. 12316 installFlags |= PackageManager.INSTALL_EXTERNAL; 12317 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12318 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12319 if (DEBUG_EPHEMERAL) { 12320 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12321 } 12322 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12323 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12324 |PackageManager.INSTALL_INTERNAL); 12325 } else { 12326 // Make sure the flag for installing on external 12327 // media is unset 12328 installFlags |= PackageManager.INSTALL_INTERNAL; 12329 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12330 } 12331 } 12332 } 12333 } 12334 12335 final InstallArgs args = createInstallArgs(this); 12336 mArgs = args; 12337 12338 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12339 // TODO: http://b/22976637 12340 // Apps installed for "all" users use the device owner to verify the app 12341 UserHandle verifierUser = getUser(); 12342 if (verifierUser == UserHandle.ALL) { 12343 verifierUser = UserHandle.SYSTEM; 12344 } 12345 12346 /* 12347 * Determine if we have any installed package verifiers. If we 12348 * do, then we'll defer to them to verify the packages. 12349 */ 12350 final int requiredUid = mRequiredVerifierPackage == null ? -1 12351 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12352 verifierUser.getIdentifier()); 12353 if (!origin.existing && requiredUid != -1 12354 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12355 final Intent verification = new Intent( 12356 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12357 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12358 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12359 PACKAGE_MIME_TYPE); 12360 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12361 12362 // Query all live verifiers based on current user state 12363 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12364 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12365 12366 if (DEBUG_VERIFY) { 12367 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12368 + verification.toString() + " with " + pkgLite.verifiers.length 12369 + " optional verifiers"); 12370 } 12371 12372 final int verificationId = mPendingVerificationToken++; 12373 12374 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12375 12376 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12377 installerPackageName); 12378 12379 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12380 installFlags); 12381 12382 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12383 pkgLite.packageName); 12384 12385 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12386 pkgLite.versionCode); 12387 12388 if (verificationInfo != null) { 12389 if (verificationInfo.originatingUri != null) { 12390 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12391 verificationInfo.originatingUri); 12392 } 12393 if (verificationInfo.referrer != null) { 12394 verification.putExtra(Intent.EXTRA_REFERRER, 12395 verificationInfo.referrer); 12396 } 12397 if (verificationInfo.originatingUid >= 0) { 12398 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12399 verificationInfo.originatingUid); 12400 } 12401 if (verificationInfo.installerUid >= 0) { 12402 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12403 verificationInfo.installerUid); 12404 } 12405 } 12406 12407 final PackageVerificationState verificationState = new PackageVerificationState( 12408 requiredUid, args); 12409 12410 mPendingVerification.append(verificationId, verificationState); 12411 12412 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12413 receivers, verificationState); 12414 12415 /* 12416 * If any sufficient verifiers were listed in the package 12417 * manifest, attempt to ask them. 12418 */ 12419 if (sufficientVerifiers != null) { 12420 final int N = sufficientVerifiers.size(); 12421 if (N == 0) { 12422 Slog.i(TAG, "Additional verifiers required, but none installed."); 12423 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12424 } else { 12425 for (int i = 0; i < N; i++) { 12426 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12427 12428 final Intent sufficientIntent = new Intent(verification); 12429 sufficientIntent.setComponent(verifierComponent); 12430 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12431 } 12432 } 12433 } 12434 12435 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12436 mRequiredVerifierPackage, receivers); 12437 if (ret == PackageManager.INSTALL_SUCCEEDED 12438 && mRequiredVerifierPackage != null) { 12439 Trace.asyncTraceBegin( 12440 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12441 /* 12442 * Send the intent to the required verification agent, 12443 * but only start the verification timeout after the 12444 * target BroadcastReceivers have run. 12445 */ 12446 verification.setComponent(requiredVerifierComponent); 12447 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12448 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12449 new BroadcastReceiver() { 12450 @Override 12451 public void onReceive(Context context, Intent intent) { 12452 final Message msg = mHandler 12453 .obtainMessage(CHECK_PENDING_VERIFICATION); 12454 msg.arg1 = verificationId; 12455 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12456 } 12457 }, null, 0, null, null); 12458 12459 /* 12460 * We don't want the copy to proceed until verification 12461 * succeeds, so null out this field. 12462 */ 12463 mArgs = null; 12464 } 12465 } else { 12466 /* 12467 * No package verification is enabled, so immediately start 12468 * the remote call to initiate copy using temporary file. 12469 */ 12470 ret = args.copyApk(mContainerService, true); 12471 } 12472 } 12473 12474 mRet = ret; 12475 } 12476 12477 @Override 12478 void handleReturnCode() { 12479 // If mArgs is null, then MCS couldn't be reached. When it 12480 // reconnects, it will try again to install. At that point, this 12481 // will succeed. 12482 if (mArgs != null) { 12483 processPendingInstall(mArgs, mRet); 12484 } 12485 } 12486 12487 @Override 12488 void handleServiceError() { 12489 mArgs = createInstallArgs(this); 12490 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12491 } 12492 12493 public boolean isForwardLocked() { 12494 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12495 } 12496 } 12497 12498 /** 12499 * Used during creation of InstallArgs 12500 * 12501 * @param installFlags package installation flags 12502 * @return true if should be installed on external storage 12503 */ 12504 private static boolean installOnExternalAsec(int installFlags) { 12505 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12506 return false; 12507 } 12508 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12509 return true; 12510 } 12511 return false; 12512 } 12513 12514 /** 12515 * Used during creation of InstallArgs 12516 * 12517 * @param installFlags package installation flags 12518 * @return true if should be installed as forward locked 12519 */ 12520 private static boolean installForwardLocked(int installFlags) { 12521 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12522 } 12523 12524 private InstallArgs createInstallArgs(InstallParams params) { 12525 if (params.move != null) { 12526 return new MoveInstallArgs(params); 12527 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12528 return new AsecInstallArgs(params); 12529 } else { 12530 return new FileInstallArgs(params); 12531 } 12532 } 12533 12534 /** 12535 * Create args that describe an existing installed package. Typically used 12536 * when cleaning up old installs, or used as a move source. 12537 */ 12538 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12539 String resourcePath, String[] instructionSets) { 12540 final boolean isInAsec; 12541 if (installOnExternalAsec(installFlags)) { 12542 /* Apps on SD card are always in ASEC containers. */ 12543 isInAsec = true; 12544 } else if (installForwardLocked(installFlags) 12545 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12546 /* 12547 * Forward-locked apps are only in ASEC containers if they're the 12548 * new style 12549 */ 12550 isInAsec = true; 12551 } else { 12552 isInAsec = false; 12553 } 12554 12555 if (isInAsec) { 12556 return new AsecInstallArgs(codePath, instructionSets, 12557 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12558 } else { 12559 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12560 } 12561 } 12562 12563 static abstract class InstallArgs { 12564 /** @see InstallParams#origin */ 12565 final OriginInfo origin; 12566 /** @see InstallParams#move */ 12567 final MoveInfo move; 12568 12569 final IPackageInstallObserver2 observer; 12570 // Always refers to PackageManager flags only 12571 final int installFlags; 12572 final String installerPackageName; 12573 final String volumeUuid; 12574 final UserHandle user; 12575 final String abiOverride; 12576 final String[] installGrantPermissions; 12577 /** If non-null, drop an async trace when the install completes */ 12578 final String traceMethod; 12579 final int traceCookie; 12580 12581 // The list of instruction sets supported by this app. This is currently 12582 // only used during the rmdex() phase to clean up resources. We can get rid of this 12583 // if we move dex files under the common app path. 12584 /* nullable */ String[] instructionSets; 12585 12586 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12587 int installFlags, String installerPackageName, String volumeUuid, 12588 UserHandle user, String[] instructionSets, 12589 String abiOverride, String[] installGrantPermissions, 12590 String traceMethod, int traceCookie) { 12591 this.origin = origin; 12592 this.move = move; 12593 this.installFlags = installFlags; 12594 this.observer = observer; 12595 this.installerPackageName = installerPackageName; 12596 this.volumeUuid = volumeUuid; 12597 this.user = user; 12598 this.instructionSets = instructionSets; 12599 this.abiOverride = abiOverride; 12600 this.installGrantPermissions = installGrantPermissions; 12601 this.traceMethod = traceMethod; 12602 this.traceCookie = traceCookie; 12603 } 12604 12605 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12606 abstract int doPreInstall(int status); 12607 12608 /** 12609 * Rename package into final resting place. All paths on the given 12610 * scanned package should be updated to reflect the rename. 12611 */ 12612 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12613 abstract int doPostInstall(int status, int uid); 12614 12615 /** @see PackageSettingBase#codePathString */ 12616 abstract String getCodePath(); 12617 /** @see PackageSettingBase#resourcePathString */ 12618 abstract String getResourcePath(); 12619 12620 // Need installer lock especially for dex file removal. 12621 abstract void cleanUpResourcesLI(); 12622 abstract boolean doPostDeleteLI(boolean delete); 12623 12624 /** 12625 * Called before the source arguments are copied. This is used mostly 12626 * for MoveParams when it needs to read the source file to put it in the 12627 * destination. 12628 */ 12629 int doPreCopy() { 12630 return PackageManager.INSTALL_SUCCEEDED; 12631 } 12632 12633 /** 12634 * Called after the source arguments are copied. This is used mostly for 12635 * MoveParams when it needs to read the source file to put it in the 12636 * destination. 12637 */ 12638 int doPostCopy(int uid) { 12639 return PackageManager.INSTALL_SUCCEEDED; 12640 } 12641 12642 protected boolean isFwdLocked() { 12643 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12644 } 12645 12646 protected boolean isExternalAsec() { 12647 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12648 } 12649 12650 protected boolean isEphemeral() { 12651 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12652 } 12653 12654 UserHandle getUser() { 12655 return user; 12656 } 12657 } 12658 12659 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12660 if (!allCodePaths.isEmpty()) { 12661 if (instructionSets == null) { 12662 throw new IllegalStateException("instructionSet == null"); 12663 } 12664 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12665 for (String codePath : allCodePaths) { 12666 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12667 try { 12668 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12669 } catch (InstallerException ignored) { 12670 } 12671 } 12672 } 12673 } 12674 } 12675 12676 /** 12677 * Logic to handle installation of non-ASEC applications, including copying 12678 * and renaming logic. 12679 */ 12680 class FileInstallArgs extends InstallArgs { 12681 private File codeFile; 12682 private File resourceFile; 12683 12684 // Example topology: 12685 // /data/app/com.example/base.apk 12686 // /data/app/com.example/split_foo.apk 12687 // /data/app/com.example/lib/arm/libfoo.so 12688 // /data/app/com.example/lib/arm64/libfoo.so 12689 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12690 12691 /** New install */ 12692 FileInstallArgs(InstallParams params) { 12693 super(params.origin, params.move, params.observer, params.installFlags, 12694 params.installerPackageName, params.volumeUuid, 12695 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12696 params.grantedRuntimePermissions, 12697 params.traceMethod, params.traceCookie); 12698 if (isFwdLocked()) { 12699 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12700 } 12701 } 12702 12703 /** Existing install */ 12704 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12705 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12706 null, null, null, 0); 12707 this.codeFile = (codePath != null) ? new File(codePath) : null; 12708 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12709 } 12710 12711 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12713 try { 12714 return doCopyApk(imcs, temp); 12715 } finally { 12716 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12717 } 12718 } 12719 12720 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12721 if (origin.staged) { 12722 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12723 codeFile = origin.file; 12724 resourceFile = origin.file; 12725 return PackageManager.INSTALL_SUCCEEDED; 12726 } 12727 12728 try { 12729 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12730 final File tempDir = 12731 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12732 codeFile = tempDir; 12733 resourceFile = tempDir; 12734 } catch (IOException e) { 12735 Slog.w(TAG, "Failed to create copy file: " + e); 12736 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12737 } 12738 12739 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12740 @Override 12741 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12742 if (!FileUtils.isValidExtFilename(name)) { 12743 throw new IllegalArgumentException("Invalid filename: " + name); 12744 } 12745 try { 12746 final File file = new File(codeFile, name); 12747 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12748 O_RDWR | O_CREAT, 0644); 12749 Os.chmod(file.getAbsolutePath(), 0644); 12750 return new ParcelFileDescriptor(fd); 12751 } catch (ErrnoException e) { 12752 throw new RemoteException("Failed to open: " + e.getMessage()); 12753 } 12754 } 12755 }; 12756 12757 int ret = PackageManager.INSTALL_SUCCEEDED; 12758 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12759 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12760 Slog.e(TAG, "Failed to copy package"); 12761 return ret; 12762 } 12763 12764 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12765 NativeLibraryHelper.Handle handle = null; 12766 try { 12767 handle = NativeLibraryHelper.Handle.create(codeFile); 12768 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12769 abiOverride); 12770 } catch (IOException e) { 12771 Slog.e(TAG, "Copying native libraries failed", e); 12772 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12773 } finally { 12774 IoUtils.closeQuietly(handle); 12775 } 12776 12777 return ret; 12778 } 12779 12780 int doPreInstall(int status) { 12781 if (status != PackageManager.INSTALL_SUCCEEDED) { 12782 cleanUp(); 12783 } 12784 return status; 12785 } 12786 12787 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12788 if (status != PackageManager.INSTALL_SUCCEEDED) { 12789 cleanUp(); 12790 return false; 12791 } 12792 12793 final File targetDir = codeFile.getParentFile(); 12794 final File beforeCodeFile = codeFile; 12795 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12796 12797 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12798 try { 12799 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12800 } catch (ErrnoException e) { 12801 Slog.w(TAG, "Failed to rename", e); 12802 return false; 12803 } 12804 12805 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12806 Slog.w(TAG, "Failed to restorecon"); 12807 return false; 12808 } 12809 12810 // Reflect the rename internally 12811 codeFile = afterCodeFile; 12812 resourceFile = afterCodeFile; 12813 12814 // Reflect the rename in scanned details 12815 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12816 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12817 afterCodeFile, pkg.baseCodePath)); 12818 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12819 afterCodeFile, pkg.splitCodePaths)); 12820 12821 // Reflect the rename in app info 12822 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12823 pkg.setApplicationInfoCodePath(pkg.codePath); 12824 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12825 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12826 pkg.setApplicationInfoResourcePath(pkg.codePath); 12827 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12828 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12829 12830 return true; 12831 } 12832 12833 int doPostInstall(int status, int uid) { 12834 if (status != PackageManager.INSTALL_SUCCEEDED) { 12835 cleanUp(); 12836 } 12837 return status; 12838 } 12839 12840 @Override 12841 String getCodePath() { 12842 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12843 } 12844 12845 @Override 12846 String getResourcePath() { 12847 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12848 } 12849 12850 private boolean cleanUp() { 12851 if (codeFile == null || !codeFile.exists()) { 12852 return false; 12853 } 12854 12855 removeCodePathLI(codeFile); 12856 12857 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12858 resourceFile.delete(); 12859 } 12860 12861 return true; 12862 } 12863 12864 void cleanUpResourcesLI() { 12865 // Try enumerating all code paths before deleting 12866 List<String> allCodePaths = Collections.EMPTY_LIST; 12867 if (codeFile != null && codeFile.exists()) { 12868 try { 12869 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12870 allCodePaths = pkg.getAllCodePaths(); 12871 } catch (PackageParserException e) { 12872 // Ignored; we tried our best 12873 } 12874 } 12875 12876 cleanUp(); 12877 removeDexFiles(allCodePaths, instructionSets); 12878 } 12879 12880 boolean doPostDeleteLI(boolean delete) { 12881 // XXX err, shouldn't we respect the delete flag? 12882 cleanUpResourcesLI(); 12883 return true; 12884 } 12885 } 12886 12887 private boolean isAsecExternal(String cid) { 12888 final String asecPath = PackageHelper.getSdFilesystem(cid); 12889 return !asecPath.startsWith(mAsecInternalPath); 12890 } 12891 12892 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12893 PackageManagerException { 12894 if (copyRet < 0) { 12895 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12896 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12897 throw new PackageManagerException(copyRet, message); 12898 } 12899 } 12900 } 12901 12902 /** 12903 * Extract the MountService "container ID" from the full code path of an 12904 * .apk. 12905 */ 12906 static String cidFromCodePath(String fullCodePath) { 12907 int eidx = fullCodePath.lastIndexOf("/"); 12908 String subStr1 = fullCodePath.substring(0, eidx); 12909 int sidx = subStr1.lastIndexOf("/"); 12910 return subStr1.substring(sidx+1, eidx); 12911 } 12912 12913 /** 12914 * Logic to handle installation of ASEC applications, including copying and 12915 * renaming logic. 12916 */ 12917 class AsecInstallArgs extends InstallArgs { 12918 static final String RES_FILE_NAME = "pkg.apk"; 12919 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12920 12921 String cid; 12922 String packagePath; 12923 String resourcePath; 12924 12925 /** New install */ 12926 AsecInstallArgs(InstallParams params) { 12927 super(params.origin, params.move, params.observer, params.installFlags, 12928 params.installerPackageName, params.volumeUuid, 12929 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12930 params.grantedRuntimePermissions, 12931 params.traceMethod, params.traceCookie); 12932 } 12933 12934 /** Existing install */ 12935 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12936 boolean isExternal, boolean isForwardLocked) { 12937 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12938 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12939 instructionSets, null, null, null, 0); 12940 // Hackily pretend we're still looking at a full code path 12941 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12942 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12943 } 12944 12945 // Extract cid from fullCodePath 12946 int eidx = fullCodePath.lastIndexOf("/"); 12947 String subStr1 = fullCodePath.substring(0, eidx); 12948 int sidx = subStr1.lastIndexOf("/"); 12949 cid = subStr1.substring(sidx+1, eidx); 12950 setMountPath(subStr1); 12951 } 12952 12953 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12954 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12955 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12956 instructionSets, null, null, null, 0); 12957 this.cid = cid; 12958 setMountPath(PackageHelper.getSdDir(cid)); 12959 } 12960 12961 void createCopyFile() { 12962 cid = mInstallerService.allocateExternalStageCidLegacy(); 12963 } 12964 12965 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12966 if (origin.staged && origin.cid != null) { 12967 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12968 cid = origin.cid; 12969 setMountPath(PackageHelper.getSdDir(cid)); 12970 return PackageManager.INSTALL_SUCCEEDED; 12971 } 12972 12973 if (temp) { 12974 createCopyFile(); 12975 } else { 12976 /* 12977 * Pre-emptively destroy the container since it's destroyed if 12978 * copying fails due to it existing anyway. 12979 */ 12980 PackageHelper.destroySdDir(cid); 12981 } 12982 12983 final String newMountPath = imcs.copyPackageToContainer( 12984 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12985 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12986 12987 if (newMountPath != null) { 12988 setMountPath(newMountPath); 12989 return PackageManager.INSTALL_SUCCEEDED; 12990 } else { 12991 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12992 } 12993 } 12994 12995 @Override 12996 String getCodePath() { 12997 return packagePath; 12998 } 12999 13000 @Override 13001 String getResourcePath() { 13002 return resourcePath; 13003 } 13004 13005 int doPreInstall(int status) { 13006 if (status != PackageManager.INSTALL_SUCCEEDED) { 13007 // Destroy container 13008 PackageHelper.destroySdDir(cid); 13009 } else { 13010 boolean mounted = PackageHelper.isContainerMounted(cid); 13011 if (!mounted) { 13012 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13013 Process.SYSTEM_UID); 13014 if (newMountPath != null) { 13015 setMountPath(newMountPath); 13016 } else { 13017 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13018 } 13019 } 13020 } 13021 return status; 13022 } 13023 13024 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13025 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13026 String newMountPath = null; 13027 if (PackageHelper.isContainerMounted(cid)) { 13028 // Unmount the container 13029 if (!PackageHelper.unMountSdDir(cid)) { 13030 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13031 return false; 13032 } 13033 } 13034 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13035 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13036 " which might be stale. Will try to clean up."); 13037 // Clean up the stale container and proceed to recreate. 13038 if (!PackageHelper.destroySdDir(newCacheId)) { 13039 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13040 return false; 13041 } 13042 // Successfully cleaned up stale container. Try to rename again. 13043 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13044 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13045 + " inspite of cleaning it up."); 13046 return false; 13047 } 13048 } 13049 if (!PackageHelper.isContainerMounted(newCacheId)) { 13050 Slog.w(TAG, "Mounting container " + newCacheId); 13051 newMountPath = PackageHelper.mountSdDir(newCacheId, 13052 getEncryptKey(), Process.SYSTEM_UID); 13053 } else { 13054 newMountPath = PackageHelper.getSdDir(newCacheId); 13055 } 13056 if (newMountPath == null) { 13057 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13058 return false; 13059 } 13060 Log.i(TAG, "Succesfully renamed " + cid + 13061 " to " + newCacheId + 13062 " at new path: " + newMountPath); 13063 cid = newCacheId; 13064 13065 final File beforeCodeFile = new File(packagePath); 13066 setMountPath(newMountPath); 13067 final File afterCodeFile = new File(packagePath); 13068 13069 // Reflect the rename in scanned details 13070 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13071 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13072 afterCodeFile, pkg.baseCodePath)); 13073 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13074 afterCodeFile, pkg.splitCodePaths)); 13075 13076 // Reflect the rename in app info 13077 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13078 pkg.setApplicationInfoCodePath(pkg.codePath); 13079 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13080 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13081 pkg.setApplicationInfoResourcePath(pkg.codePath); 13082 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13083 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13084 13085 return true; 13086 } 13087 13088 private void setMountPath(String mountPath) { 13089 final File mountFile = new File(mountPath); 13090 13091 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13092 if (monolithicFile.exists()) { 13093 packagePath = monolithicFile.getAbsolutePath(); 13094 if (isFwdLocked()) { 13095 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13096 } else { 13097 resourcePath = packagePath; 13098 } 13099 } else { 13100 packagePath = mountFile.getAbsolutePath(); 13101 resourcePath = packagePath; 13102 } 13103 } 13104 13105 int doPostInstall(int status, int uid) { 13106 if (status != PackageManager.INSTALL_SUCCEEDED) { 13107 cleanUp(); 13108 } else { 13109 final int groupOwner; 13110 final String protectedFile; 13111 if (isFwdLocked()) { 13112 groupOwner = UserHandle.getSharedAppGid(uid); 13113 protectedFile = RES_FILE_NAME; 13114 } else { 13115 groupOwner = -1; 13116 protectedFile = null; 13117 } 13118 13119 if (uid < Process.FIRST_APPLICATION_UID 13120 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13121 Slog.e(TAG, "Failed to finalize " + cid); 13122 PackageHelper.destroySdDir(cid); 13123 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13124 } 13125 13126 boolean mounted = PackageHelper.isContainerMounted(cid); 13127 if (!mounted) { 13128 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13129 } 13130 } 13131 return status; 13132 } 13133 13134 private void cleanUp() { 13135 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13136 13137 // Destroy secure container 13138 PackageHelper.destroySdDir(cid); 13139 } 13140 13141 private List<String> getAllCodePaths() { 13142 final File codeFile = new File(getCodePath()); 13143 if (codeFile != null && codeFile.exists()) { 13144 try { 13145 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13146 return pkg.getAllCodePaths(); 13147 } catch (PackageParserException e) { 13148 // Ignored; we tried our best 13149 } 13150 } 13151 return Collections.EMPTY_LIST; 13152 } 13153 13154 void cleanUpResourcesLI() { 13155 // Enumerate all code paths before deleting 13156 cleanUpResourcesLI(getAllCodePaths()); 13157 } 13158 13159 private void cleanUpResourcesLI(List<String> allCodePaths) { 13160 cleanUp(); 13161 removeDexFiles(allCodePaths, instructionSets); 13162 } 13163 13164 String getPackageName() { 13165 return getAsecPackageName(cid); 13166 } 13167 13168 boolean doPostDeleteLI(boolean delete) { 13169 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13170 final List<String> allCodePaths = getAllCodePaths(); 13171 boolean mounted = PackageHelper.isContainerMounted(cid); 13172 if (mounted) { 13173 // Unmount first 13174 if (PackageHelper.unMountSdDir(cid)) { 13175 mounted = false; 13176 } 13177 } 13178 if (!mounted && delete) { 13179 cleanUpResourcesLI(allCodePaths); 13180 } 13181 return !mounted; 13182 } 13183 13184 @Override 13185 int doPreCopy() { 13186 if (isFwdLocked()) { 13187 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13188 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13189 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13190 } 13191 } 13192 13193 return PackageManager.INSTALL_SUCCEEDED; 13194 } 13195 13196 @Override 13197 int doPostCopy(int uid) { 13198 if (isFwdLocked()) { 13199 if (uid < Process.FIRST_APPLICATION_UID 13200 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13201 RES_FILE_NAME)) { 13202 Slog.e(TAG, "Failed to finalize " + cid); 13203 PackageHelper.destroySdDir(cid); 13204 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13205 } 13206 } 13207 13208 return PackageManager.INSTALL_SUCCEEDED; 13209 } 13210 } 13211 13212 /** 13213 * Logic to handle movement of existing installed applications. 13214 */ 13215 class MoveInstallArgs extends InstallArgs { 13216 private File codeFile; 13217 private File resourceFile; 13218 13219 /** New install */ 13220 MoveInstallArgs(InstallParams params) { 13221 super(params.origin, params.move, params.observer, params.installFlags, 13222 params.installerPackageName, params.volumeUuid, 13223 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13224 params.grantedRuntimePermissions, 13225 params.traceMethod, params.traceCookie); 13226 } 13227 13228 int copyApk(IMediaContainerService imcs, boolean temp) { 13229 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13230 + move.fromUuid + " to " + move.toUuid); 13231 synchronized (mInstaller) { 13232 try { 13233 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13234 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13235 } catch (InstallerException e) { 13236 Slog.w(TAG, "Failed to move app", e); 13237 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13238 } 13239 } 13240 13241 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13242 resourceFile = codeFile; 13243 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13244 13245 return PackageManager.INSTALL_SUCCEEDED; 13246 } 13247 13248 int doPreInstall(int status) { 13249 if (status != PackageManager.INSTALL_SUCCEEDED) { 13250 cleanUp(move.toUuid); 13251 } 13252 return status; 13253 } 13254 13255 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13256 if (status != PackageManager.INSTALL_SUCCEEDED) { 13257 cleanUp(move.toUuid); 13258 return false; 13259 } 13260 13261 // Reflect the move in app info 13262 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13263 pkg.setApplicationInfoCodePath(pkg.codePath); 13264 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13265 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13266 pkg.setApplicationInfoResourcePath(pkg.codePath); 13267 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13268 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13269 13270 return true; 13271 } 13272 13273 int doPostInstall(int status, int uid) { 13274 if (status == PackageManager.INSTALL_SUCCEEDED) { 13275 cleanUp(move.fromUuid); 13276 } else { 13277 cleanUp(move.toUuid); 13278 } 13279 return status; 13280 } 13281 13282 @Override 13283 String getCodePath() { 13284 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13285 } 13286 13287 @Override 13288 String getResourcePath() { 13289 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13290 } 13291 13292 private boolean cleanUp(String volumeUuid) { 13293 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13294 move.dataAppName); 13295 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13296 synchronized (mInstallLock) { 13297 // Clean up both app data and code 13298 removeDataDirsLI(volumeUuid, move.packageName); 13299 removeCodePathLI(codeFile); 13300 } 13301 return true; 13302 } 13303 13304 void cleanUpResourcesLI() { 13305 throw new UnsupportedOperationException(); 13306 } 13307 13308 boolean doPostDeleteLI(boolean delete) { 13309 throw new UnsupportedOperationException(); 13310 } 13311 } 13312 13313 static String getAsecPackageName(String packageCid) { 13314 int idx = packageCid.lastIndexOf("-"); 13315 if (idx == -1) { 13316 return packageCid; 13317 } 13318 return packageCid.substring(0, idx); 13319 } 13320 13321 // Utility method used to create code paths based on package name and available index. 13322 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13323 String idxStr = ""; 13324 int idx = 1; 13325 // Fall back to default value of idx=1 if prefix is not 13326 // part of oldCodePath 13327 if (oldCodePath != null) { 13328 String subStr = oldCodePath; 13329 // Drop the suffix right away 13330 if (suffix != null && subStr.endsWith(suffix)) { 13331 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13332 } 13333 // If oldCodePath already contains prefix find out the 13334 // ending index to either increment or decrement. 13335 int sidx = subStr.lastIndexOf(prefix); 13336 if (sidx != -1) { 13337 subStr = subStr.substring(sidx + prefix.length()); 13338 if (subStr != null) { 13339 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13340 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13341 } 13342 try { 13343 idx = Integer.parseInt(subStr); 13344 if (idx <= 1) { 13345 idx++; 13346 } else { 13347 idx--; 13348 } 13349 } catch(NumberFormatException e) { 13350 } 13351 } 13352 } 13353 } 13354 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13355 return prefix + idxStr; 13356 } 13357 13358 private File getNextCodePath(File targetDir, String packageName) { 13359 int suffix = 1; 13360 File result; 13361 do { 13362 result = new File(targetDir, packageName + "-" + suffix); 13363 suffix++; 13364 } while (result.exists()); 13365 return result; 13366 } 13367 13368 // Utility method that returns the relative package path with respect 13369 // to the installation directory. Like say for /data/data/com.test-1.apk 13370 // string com.test-1 is returned. 13371 static String deriveCodePathName(String codePath) { 13372 if (codePath == null) { 13373 return null; 13374 } 13375 final File codeFile = new File(codePath); 13376 final String name = codeFile.getName(); 13377 if (codeFile.isDirectory()) { 13378 return name; 13379 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13380 final int lastDot = name.lastIndexOf('.'); 13381 return name.substring(0, lastDot); 13382 } else { 13383 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13384 return null; 13385 } 13386 } 13387 13388 static class PackageInstalledInfo { 13389 String name; 13390 int uid; 13391 // The set of users that originally had this package installed. 13392 int[] origUsers; 13393 // The set of users that now have this package installed. 13394 int[] newUsers; 13395 PackageParser.Package pkg; 13396 int returnCode; 13397 String returnMsg; 13398 PackageRemovedInfo removedInfo; 13399 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13400 13401 public void setError(int code, String msg) { 13402 setReturnCode(code); 13403 setReturnMessage(msg); 13404 Slog.w(TAG, msg); 13405 } 13406 13407 public void setError(String msg, PackageParserException e) { 13408 setReturnCode(e.error); 13409 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13410 Slog.w(TAG, msg, e); 13411 } 13412 13413 public void setError(String msg, PackageManagerException e) { 13414 returnCode = e.error; 13415 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13416 Slog.w(TAG, msg, e); 13417 } 13418 13419 public void setReturnCode(int returnCode) { 13420 this.returnCode = returnCode; 13421 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13422 for (int i = 0; i < childCount; i++) { 13423 addedChildPackages.valueAt(i).returnCode = returnCode; 13424 } 13425 } 13426 13427 private void setReturnMessage(String returnMsg) { 13428 this.returnMsg = returnMsg; 13429 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13430 for (int i = 0; i < childCount; i++) { 13431 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13432 } 13433 } 13434 13435 // In some error cases we want to convey more info back to the observer 13436 String origPackage; 13437 String origPermission; 13438 } 13439 13440 /* 13441 * Install a non-existing package. 13442 */ 13443 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13444 UserHandle user, String installerPackageName, String volumeUuid, 13445 PackageInstalledInfo res) { 13446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13447 13448 // Remember this for later, in case we need to rollback this install 13449 String pkgName = pkg.packageName; 13450 13451 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13452 13453 synchronized(mPackages) { 13454 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13455 // A package with the same name is already installed, though 13456 // it has been renamed to an older name. The package we 13457 // are trying to install should be installed as an update to 13458 // the existing one, but that has not been requested, so bail. 13459 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13460 + " without first uninstalling package running as " 13461 + mSettings.mRenamedPackages.get(pkgName)); 13462 return; 13463 } 13464 if (mPackages.containsKey(pkgName)) { 13465 // Don't allow installation over an existing package with the same name. 13466 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13467 + " without first uninstalling."); 13468 return; 13469 } 13470 } 13471 13472 try { 13473 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13474 System.currentTimeMillis(), user); 13475 13476 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13477 13478 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13479 prepareAppDataAfterInstall(newPackage); 13480 13481 } else { 13482 // Remove package from internal structures, but keep around any 13483 // data that might have already existed 13484 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13485 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13486 } 13487 } catch (PackageManagerException e) { 13488 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13489 } 13490 13491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13492 } 13493 13494 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13495 // Can't rotate keys during boot or if sharedUser. 13496 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13497 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13498 return false; 13499 } 13500 // app is using upgradeKeySets; make sure all are valid 13501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13502 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13503 for (int i = 0; i < upgradeKeySets.length; i++) { 13504 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13505 Slog.wtf(TAG, "Package " 13506 + (oldPs.name != null ? oldPs.name : "<null>") 13507 + " contains upgrade-key-set reference to unknown key-set: " 13508 + upgradeKeySets[i] 13509 + " reverting to signatures check."); 13510 return false; 13511 } 13512 } 13513 return true; 13514 } 13515 13516 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13517 // Upgrade keysets are being used. Determine if new package has a superset of the 13518 // required keys. 13519 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13520 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13521 for (int i = 0; i < upgradeKeySets.length; i++) { 13522 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13523 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13524 return true; 13525 } 13526 } 13527 return false; 13528 } 13529 13530 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13531 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13532 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13533 13534 final PackageParser.Package oldPackage; 13535 final String pkgName = pkg.packageName; 13536 final int[] allUsers; 13537 final boolean weFroze; 13538 13539 // First find the old package info and check signatures 13540 synchronized(mPackages) { 13541 oldPackage = mPackages.get(pkgName); 13542 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13543 if (isEphemeral && !oldIsEphemeral) { 13544 // can't downgrade from full to ephemeral 13545 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13546 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13547 return; 13548 } 13549 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13550 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13551 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13552 if (!checkUpgradeKeySetLP(ps, pkg)) { 13553 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13554 "New package not signed by keys specified by upgrade-keysets: " 13555 + pkgName); 13556 return; 13557 } 13558 } else { 13559 // default to original signature matching 13560 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13561 != PackageManager.SIGNATURE_MATCH) { 13562 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13563 "New package has a different signature: " + pkgName); 13564 return; 13565 } 13566 } 13567 13568 // In case of rollback, remember per-user/profile install state 13569 allUsers = sUserManager.getUserIds(); 13570 13571 // Mark the app as frozen to prevent launching during the upgrade 13572 // process, and then kill all running instances 13573 if (!ps.frozen) { 13574 ps.frozen = true; 13575 weFroze = true; 13576 } else { 13577 weFroze = false; 13578 } 13579 } 13580 13581 try { 13582 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13583 installerPackageName, res); 13584 } finally { 13585 // Regardless of success or failure of upgrade steps above, always 13586 // unfreeze the package if we froze it 13587 if (weFroze) { 13588 unfreezePackage(pkgName); 13589 } 13590 } 13591 } 13592 13593 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13594 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13595 String installerPackageName, PackageInstalledInfo res) { 13596 // Update what is removed 13597 res.removedInfo = new PackageRemovedInfo(); 13598 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13599 res.removedInfo.removedPackage = oldPackage.packageName; 13600 res.removedInfo.isUpdate = true; 13601 final int childCount = (oldPackage.childPackages != null) 13602 ? oldPackage.childPackages.size() : 0; 13603 for (int i = 0; i < childCount; i++) { 13604 boolean childPackageUpdated = false; 13605 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13606 if (res.addedChildPackages != null) { 13607 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13608 if (childRes != null) { 13609 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13610 childRes.removedInfo.removedPackage = childPkg.packageName; 13611 childRes.removedInfo.isUpdate = true; 13612 childPackageUpdated = true; 13613 } 13614 } 13615 if (!childPackageUpdated) { 13616 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13617 childRemovedRes.removedPackage = childPkg.packageName; 13618 childRemovedRes.isUpdate = false; 13619 childRemovedRes.dataRemoved = true; 13620 synchronized (mPackages) { 13621 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13622 if (childPs != null) { 13623 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13624 } 13625 } 13626 if (res.removedInfo.removedChildPackages == null) { 13627 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13628 } 13629 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13630 } 13631 } 13632 13633 boolean sysPkg = (isSystemApp(oldPackage)); 13634 if (sysPkg) { 13635 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13636 user, allUsers, installerPackageName, res); 13637 } else { 13638 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13639 user, allUsers, installerPackageName, res); 13640 } 13641 } 13642 13643 public List<String> getPreviousCodePaths(String packageName) { 13644 final PackageSetting ps = mSettings.mPackages.get(packageName); 13645 final List<String> result = new ArrayList<String>(); 13646 if (ps != null && ps.oldCodePaths != null) { 13647 result.addAll(ps.oldCodePaths); 13648 } 13649 return result; 13650 } 13651 13652 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13653 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13654 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13655 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13656 + deletedPackage); 13657 13658 String pkgName = deletedPackage.packageName; 13659 boolean deletedPkg = true; 13660 boolean addedPkg = false; 13661 boolean updatedSettings = false; 13662 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13663 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13664 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13665 13666 final long origUpdateTime = (pkg.mExtras != null) 13667 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13668 13669 // First delete the existing package while retaining the data directory 13670 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13671 res.removedInfo, true, pkg)) { 13672 // If the existing package wasn't successfully deleted 13673 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13674 deletedPkg = false; 13675 } else { 13676 // Successfully deleted the old package; proceed with replace. 13677 13678 // If deleted package lived in a container, give users a chance to 13679 // relinquish resources before killing. 13680 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13681 if (DEBUG_INSTALL) { 13682 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13683 } 13684 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13685 final ArrayList<String> pkgList = new ArrayList<String>(1); 13686 pkgList.add(deletedPackage.applicationInfo.packageName); 13687 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13688 } 13689 13690 deleteCodeCacheDirsLI(pkg); 13691 deleteProfilesLI(pkg, /*destroy*/ false); 13692 13693 try { 13694 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13695 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13696 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13697 13698 // Update the in-memory copy of the previous code paths. 13699 PackageSetting ps = mSettings.mPackages.get(pkgName); 13700 if (!killApp) { 13701 if (ps.oldCodePaths == null) { 13702 ps.oldCodePaths = new ArraySet<>(); 13703 } 13704 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13705 if (deletedPackage.splitCodePaths != null) { 13706 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13707 } 13708 } else { 13709 ps.oldCodePaths = null; 13710 } 13711 if (ps.childPackageNames != null) { 13712 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13713 final String childPkgName = ps.childPackageNames.get(i); 13714 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13715 childPs.oldCodePaths = ps.oldCodePaths; 13716 } 13717 } 13718 prepareAppDataAfterInstall(newPackage); 13719 addedPkg = true; 13720 } catch (PackageManagerException e) { 13721 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13722 } 13723 } 13724 13725 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13726 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13727 13728 // Revert all internal state mutations and added folders for the failed install 13729 if (addedPkg) { 13730 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13731 res.removedInfo, true, null); 13732 } 13733 13734 // Restore the old package 13735 if (deletedPkg) { 13736 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13737 File restoreFile = new File(deletedPackage.codePath); 13738 // Parse old package 13739 boolean oldExternal = isExternal(deletedPackage); 13740 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13741 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13742 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13743 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13744 try { 13745 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13746 null); 13747 } catch (PackageManagerException e) { 13748 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13749 + e.getMessage()); 13750 return; 13751 } 13752 13753 synchronized (mPackages) { 13754 // Ensure the installer package name up to date 13755 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13756 13757 // Update permissions for restored package 13758 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13759 13760 mSettings.writeLPr(); 13761 } 13762 13763 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13764 } 13765 } else { 13766 synchronized (mPackages) { 13767 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13768 if (ps != null) { 13769 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13770 if (res.removedInfo.removedChildPackages != null) { 13771 final int childCount = res.removedInfo.removedChildPackages.size(); 13772 // Iterate in reverse as we may modify the collection 13773 for (int i = childCount - 1; i >= 0; i--) { 13774 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13775 if (res.addedChildPackages.containsKey(childPackageName)) { 13776 res.removedInfo.removedChildPackages.removeAt(i); 13777 } else { 13778 PackageRemovedInfo childInfo = res.removedInfo 13779 .removedChildPackages.valueAt(i); 13780 childInfo.removedForAllUsers = mPackages.get( 13781 childInfo.removedPackage) == null; 13782 } 13783 } 13784 } 13785 } 13786 } 13787 } 13788 } 13789 13790 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13791 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13792 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13793 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13794 + ", old=" + deletedPackage); 13795 13796 final boolean disabledSystem; 13797 13798 // Set the system/privileged flags as needed 13799 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13800 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13801 != 0) { 13802 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13803 } 13804 13805 // Kill package processes including services, providers, etc. 13806 killPackage(deletedPackage, "replace sys pkg"); 13807 13808 // Remove existing system package 13809 removePackageLI(deletedPackage, true); 13810 13811 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13812 if (!disabledSystem) { 13813 // We didn't need to disable the .apk as a current system package, 13814 // which means we are replacing another update that is already 13815 // installed. We need to make sure to delete the older one's .apk. 13816 res.removedInfo.args = createInstallArgsForExisting(0, 13817 deletedPackage.applicationInfo.getCodePath(), 13818 deletedPackage.applicationInfo.getResourcePath(), 13819 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13820 } else { 13821 res.removedInfo.args = null; 13822 } 13823 13824 // Successfully disabled the old package. Now proceed with re-installation 13825 deleteCodeCacheDirsLI(pkg); 13826 deleteProfilesLI(pkg, /*destroy*/ false); 13827 13828 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13829 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13830 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13831 13832 PackageParser.Package newPackage = null; 13833 try { 13834 // Add the package to the internal data structures 13835 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13836 13837 // Set the update and install times 13838 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13839 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13840 System.currentTimeMillis()); 13841 13842 // Check for shared user id changes 13843 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13844 deletedPackage, newPackage); 13845 if (invalidPackageName != null) { 13846 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13847 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13848 + " to " + invalidPackageName); 13849 } 13850 13851 // Update the package dynamic state if succeeded 13852 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13853 // Now that the install succeeded make sure we remove data 13854 // directories for any child package the update removed. 13855 final int deletedChildCount = (deletedPackage.childPackages != null) 13856 ? deletedPackage.childPackages.size() : 0; 13857 final int newChildCount = (newPackage.childPackages != null) 13858 ? newPackage.childPackages.size() : 0; 13859 for (int i = 0; i < deletedChildCount; i++) { 13860 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13861 boolean childPackageDeleted = true; 13862 for (int j = 0; j < newChildCount; j++) { 13863 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13864 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13865 childPackageDeleted = false; 13866 break; 13867 } 13868 } 13869 if (childPackageDeleted) { 13870 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13871 deletedChildPkg.packageName); 13872 if (ps != null && res.removedInfo.removedChildPackages != null) { 13873 PackageRemovedInfo removedChildRes = res.removedInfo 13874 .removedChildPackages.get(deletedChildPkg.packageName); 13875 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13876 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13877 } 13878 } 13879 } 13880 13881 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13882 prepareAppDataAfterInstall(newPackage); 13883 } 13884 } catch (PackageManagerException e) { 13885 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13886 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13887 } 13888 13889 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13890 // Re installation failed. Restore old information 13891 // Remove new pkg information 13892 if (newPackage != null) { 13893 removeInstalledPackageLI(newPackage, true); 13894 } 13895 // Add back the old system package 13896 try { 13897 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13898 } catch (PackageManagerException e) { 13899 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13900 } 13901 13902 synchronized (mPackages) { 13903 if (disabledSystem) { 13904 enableSystemPackageLPw(deletedPackage); 13905 } 13906 13907 // Ensure the installer package name up to date 13908 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13909 13910 // Update permissions for restored package 13911 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13912 13913 mSettings.writeLPr(); 13914 } 13915 13916 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13917 + " after failed upgrade"); 13918 } 13919 } 13920 13921 /** 13922 * Checks whether the parent or any of the child packages have a change shared 13923 * user. For a package to be a valid update the shred users of the parent and 13924 * the children should match. We may later support changing child shared users. 13925 * @param oldPkg The updated package. 13926 * @param newPkg The update package. 13927 * @return The shared user that change between the versions. 13928 */ 13929 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13930 PackageParser.Package newPkg) { 13931 // Check parent shared user 13932 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13933 return newPkg.packageName; 13934 } 13935 // Check child shared users 13936 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13937 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13938 for (int i = 0; i < newChildCount; i++) { 13939 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13940 // If this child was present, did it have the same shared user? 13941 for (int j = 0; j < oldChildCount; j++) { 13942 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13943 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13944 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13945 return newChildPkg.packageName; 13946 } 13947 } 13948 } 13949 return null; 13950 } 13951 13952 private void removeNativeBinariesLI(PackageSetting ps) { 13953 // Remove the lib path for the parent package 13954 if (ps != null) { 13955 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13956 // Remove the lib path for the child packages 13957 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13958 for (int i = 0; i < childCount; i++) { 13959 PackageSetting childPs = null; 13960 synchronized (mPackages) { 13961 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13962 } 13963 if (childPs != null) { 13964 NativeLibraryHelper.removeNativeBinariesLI(childPs 13965 .legacyNativeLibraryPathString); 13966 } 13967 } 13968 } 13969 } 13970 13971 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13972 // Enable the parent package 13973 mSettings.enableSystemPackageLPw(pkg.packageName); 13974 // Enable the child packages 13975 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13976 for (int i = 0; i < childCount; i++) { 13977 PackageParser.Package childPkg = pkg.childPackages.get(i); 13978 mSettings.enableSystemPackageLPw(childPkg.packageName); 13979 } 13980 } 13981 13982 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13983 PackageParser.Package newPkg) { 13984 // Disable the parent package (parent always replaced) 13985 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13986 // Disable the child packages 13987 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13988 for (int i = 0; i < childCount; i++) { 13989 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13990 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13991 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13992 } 13993 return disabled; 13994 } 13995 13996 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13997 String installerPackageName) { 13998 // Enable the parent package 13999 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14000 // Enable the child packages 14001 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14002 for (int i = 0; i < childCount; i++) { 14003 PackageParser.Package childPkg = pkg.childPackages.get(i); 14004 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14005 } 14006 } 14007 14008 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14009 // Collect all used permissions in the UID 14010 ArraySet<String> usedPermissions = new ArraySet<>(); 14011 final int packageCount = su.packages.size(); 14012 for (int i = 0; i < packageCount; i++) { 14013 PackageSetting ps = su.packages.valueAt(i); 14014 if (ps.pkg == null) { 14015 continue; 14016 } 14017 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14018 for (int j = 0; j < requestedPermCount; j++) { 14019 String permission = ps.pkg.requestedPermissions.get(j); 14020 BasePermission bp = mSettings.mPermissions.get(permission); 14021 if (bp != null) { 14022 usedPermissions.add(permission); 14023 } 14024 } 14025 } 14026 14027 PermissionsState permissionsState = su.getPermissionsState(); 14028 // Prune install permissions 14029 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14030 final int installPermCount = installPermStates.size(); 14031 for (int i = installPermCount - 1; i >= 0; i--) { 14032 PermissionState permissionState = installPermStates.get(i); 14033 if (!usedPermissions.contains(permissionState.getName())) { 14034 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14035 if (bp != null) { 14036 permissionsState.revokeInstallPermission(bp); 14037 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14038 PackageManager.MASK_PERMISSION_FLAGS, 0); 14039 } 14040 } 14041 } 14042 14043 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14044 14045 // Prune runtime permissions 14046 for (int userId : allUserIds) { 14047 List<PermissionState> runtimePermStates = permissionsState 14048 .getRuntimePermissionStates(userId); 14049 final int runtimePermCount = runtimePermStates.size(); 14050 for (int i = runtimePermCount - 1; i >= 0; i--) { 14051 PermissionState permissionState = runtimePermStates.get(i); 14052 if (!usedPermissions.contains(permissionState.getName())) { 14053 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14054 if (bp != null) { 14055 permissionsState.revokeRuntimePermission(bp, userId); 14056 permissionsState.updatePermissionFlags(bp, userId, 14057 PackageManager.MASK_PERMISSION_FLAGS, 0); 14058 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14059 runtimePermissionChangedUserIds, userId); 14060 } 14061 } 14062 } 14063 } 14064 14065 return runtimePermissionChangedUserIds; 14066 } 14067 14068 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14069 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14070 // Update the parent package setting 14071 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14072 res, user); 14073 // Update the child packages setting 14074 final int childCount = (newPackage.childPackages != null) 14075 ? newPackage.childPackages.size() : 0; 14076 for (int i = 0; i < childCount; i++) { 14077 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14078 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14079 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14080 childRes.origUsers, childRes, user); 14081 } 14082 } 14083 14084 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14085 String installerPackageName, int[] allUsers, int[] installedForUsers, 14086 PackageInstalledInfo res, UserHandle user) { 14087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14088 14089 String pkgName = newPackage.packageName; 14090 synchronized (mPackages) { 14091 //write settings. the installStatus will be incomplete at this stage. 14092 //note that the new package setting would have already been 14093 //added to mPackages. It hasn't been persisted yet. 14094 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14095 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14096 mSettings.writeLPr(); 14097 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14098 } 14099 14100 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14101 synchronized (mPackages) { 14102 updatePermissionsLPw(newPackage.packageName, newPackage, 14103 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14104 ? UPDATE_PERMISSIONS_ALL : 0)); 14105 // For system-bundled packages, we assume that installing an upgraded version 14106 // of the package implies that the user actually wants to run that new code, 14107 // so we enable the package. 14108 PackageSetting ps = mSettings.mPackages.get(pkgName); 14109 final int userId = user.getIdentifier(); 14110 if (ps != null) { 14111 if (isSystemApp(newPackage)) { 14112 if (DEBUG_INSTALL) { 14113 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14114 } 14115 // Enable system package for requested users 14116 if (res.origUsers != null) { 14117 for (int origUserId : res.origUsers) { 14118 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14119 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14120 origUserId, installerPackageName); 14121 } 14122 } 14123 } 14124 // Also convey the prior install/uninstall state 14125 if (allUsers != null && installedForUsers != null) { 14126 for (int currentUserId : allUsers) { 14127 final boolean installed = ArrayUtils.contains( 14128 installedForUsers, currentUserId); 14129 if (DEBUG_INSTALL) { 14130 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14131 } 14132 ps.setInstalled(installed, currentUserId); 14133 } 14134 // these install state changes will be persisted in the 14135 // upcoming call to mSettings.writeLPr(). 14136 } 14137 } 14138 // It's implied that when a user requests installation, they want the app to be 14139 // installed and enabled. 14140 if (userId != UserHandle.USER_ALL) { 14141 ps.setInstalled(true, userId); 14142 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14143 } 14144 } 14145 res.name = pkgName; 14146 res.uid = newPackage.applicationInfo.uid; 14147 res.pkg = newPackage; 14148 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14149 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14150 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14151 //to update install status 14152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14153 mSettings.writeLPr(); 14154 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14155 } 14156 14157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14158 } 14159 14160 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14161 try { 14162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14163 installPackageLI(args, res); 14164 } finally { 14165 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14166 } 14167 } 14168 14169 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14170 final int installFlags = args.installFlags; 14171 final String installerPackageName = args.installerPackageName; 14172 final String volumeUuid = args.volumeUuid; 14173 final File tmpPackageFile = new File(args.getCodePath()); 14174 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14175 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14176 || (args.volumeUuid != null)); 14177 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14178 boolean replace = false; 14179 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14180 if (args.move != null) { 14181 // moving a complete application; perform an initial scan on the new install location 14182 scanFlags |= SCAN_INITIAL; 14183 } 14184 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14185 scanFlags |= SCAN_DONT_KILL_APP; 14186 } 14187 14188 // Result object to be returned 14189 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14190 14191 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14192 14193 // Sanity check 14194 if (ephemeral && (forwardLocked || onExternal)) { 14195 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14196 + " external=" + onExternal); 14197 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14198 return; 14199 } 14200 14201 // Retrieve PackageSettings and parse package 14202 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14203 | PackageParser.PARSE_ENFORCE_CODE 14204 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14205 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14206 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14207 PackageParser pp = new PackageParser(); 14208 pp.setSeparateProcesses(mSeparateProcesses); 14209 pp.setDisplayMetrics(mMetrics); 14210 14211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14212 final PackageParser.Package pkg; 14213 try { 14214 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14215 } catch (PackageParserException e) { 14216 res.setError("Failed parse during installPackageLI", e); 14217 return; 14218 } finally { 14219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14220 } 14221 14222 // If we are installing a clustered package add results for the children 14223 if (pkg.childPackages != null) { 14224 synchronized (mPackages) { 14225 final int childCount = pkg.childPackages.size(); 14226 for (int i = 0; i < childCount; i++) { 14227 PackageParser.Package childPkg = pkg.childPackages.get(i); 14228 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14229 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14230 childRes.pkg = childPkg; 14231 childRes.name = childPkg.packageName; 14232 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14233 if (childPs != null) { 14234 childRes.origUsers = childPs.queryInstalledUsers( 14235 sUserManager.getUserIds(), true); 14236 } 14237 if ((mPackages.containsKey(childPkg.packageName))) { 14238 childRes.removedInfo = new PackageRemovedInfo(); 14239 childRes.removedInfo.removedPackage = childPkg.packageName; 14240 } 14241 if (res.addedChildPackages == null) { 14242 res.addedChildPackages = new ArrayMap<>(); 14243 } 14244 res.addedChildPackages.put(childPkg.packageName, childRes); 14245 } 14246 } 14247 } 14248 14249 // If package doesn't declare API override, mark that we have an install 14250 // time CPU ABI override. 14251 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14252 pkg.cpuAbiOverride = args.abiOverride; 14253 } 14254 14255 String pkgName = res.name = pkg.packageName; 14256 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14257 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14258 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14259 return; 14260 } 14261 } 14262 14263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 14264 try { 14265 PackageParser.collectCertificates(pkg, parseFlags); 14266 } catch (PackageParserException e) { 14267 res.setError("Failed collect during installPackageLI", e); 14268 return; 14269 } finally { 14270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14271 } 14272 14273 // Get rid of all references to package scan path via parser. 14274 pp = null; 14275 String oldCodePath = null; 14276 boolean systemApp = false; 14277 synchronized (mPackages) { 14278 // Check if installing already existing package 14279 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14280 String oldName = mSettings.mRenamedPackages.get(pkgName); 14281 if (pkg.mOriginalPackages != null 14282 && pkg.mOriginalPackages.contains(oldName) 14283 && mPackages.containsKey(oldName)) { 14284 // This package is derived from an original package, 14285 // and this device has been updating from that original 14286 // name. We must continue using the original name, so 14287 // rename the new package here. 14288 pkg.setPackageName(oldName); 14289 pkgName = pkg.packageName; 14290 replace = true; 14291 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14292 + oldName + " pkgName=" + pkgName); 14293 } else if (mPackages.containsKey(pkgName)) { 14294 // This package, under its official name, already exists 14295 // on the device; we should replace it. 14296 replace = true; 14297 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14298 } 14299 14300 // Child packages are installed through the parent package 14301 if (pkg.parentPackage != null) { 14302 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14303 "Package " + pkg.packageName + " is child of package " 14304 + pkg.parentPackage.parentPackage + ". Child packages " 14305 + "can be updated only through the parent package."); 14306 return; 14307 } 14308 14309 if (replace) { 14310 // Prevent apps opting out from runtime permissions 14311 PackageParser.Package oldPackage = mPackages.get(pkgName); 14312 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14313 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14314 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14315 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14316 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14317 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14318 + " doesn't support runtime permissions but the old" 14319 + " target SDK " + oldTargetSdk + " does."); 14320 return; 14321 } 14322 14323 // Prevent installing of child packages 14324 if (oldPackage.parentPackage != null) { 14325 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14326 "Package " + pkg.packageName + " is child of package " 14327 + oldPackage.parentPackage + ". Child packages " 14328 + "can be updated only through the parent package."); 14329 return; 14330 } 14331 } 14332 } 14333 14334 PackageSetting ps = mSettings.mPackages.get(pkgName); 14335 if (ps != null) { 14336 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14337 14338 // Quick sanity check that we're signed correctly if updating; 14339 // we'll check this again later when scanning, but we want to 14340 // bail early here before tripping over redefined permissions. 14341 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14342 if (!checkUpgradeKeySetLP(ps, pkg)) { 14343 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14344 + pkg.packageName + " upgrade keys do not match the " 14345 + "previously installed version"); 14346 return; 14347 } 14348 } else { 14349 try { 14350 verifySignaturesLP(ps, pkg); 14351 } catch (PackageManagerException e) { 14352 res.setError(e.error, e.getMessage()); 14353 return; 14354 } 14355 } 14356 14357 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14358 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14359 systemApp = (ps.pkg.applicationInfo.flags & 14360 ApplicationInfo.FLAG_SYSTEM) != 0; 14361 } 14362 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14363 } 14364 14365 // Check whether the newly-scanned package wants to define an already-defined perm 14366 int N = pkg.permissions.size(); 14367 for (int i = N-1; i >= 0; i--) { 14368 PackageParser.Permission perm = pkg.permissions.get(i); 14369 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14370 if (bp != null) { 14371 // If the defining package is signed with our cert, it's okay. This 14372 // also includes the "updating the same package" case, of course. 14373 // "updating same package" could also involve key-rotation. 14374 final boolean sigsOk; 14375 if (bp.sourcePackage.equals(pkg.packageName) 14376 && (bp.packageSetting instanceof PackageSetting) 14377 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14378 scanFlags))) { 14379 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14380 } else { 14381 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14382 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14383 } 14384 if (!sigsOk) { 14385 // If the owning package is the system itself, we log but allow 14386 // install to proceed; we fail the install on all other permission 14387 // redefinitions. 14388 if (!bp.sourcePackage.equals("android")) { 14389 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14390 + pkg.packageName + " attempting to redeclare permission " 14391 + perm.info.name + " already owned by " + bp.sourcePackage); 14392 res.origPermission = perm.info.name; 14393 res.origPackage = bp.sourcePackage; 14394 return; 14395 } else { 14396 Slog.w(TAG, "Package " + pkg.packageName 14397 + " attempting to redeclare system permission " 14398 + perm.info.name + "; ignoring new declaration"); 14399 pkg.permissions.remove(i); 14400 } 14401 } 14402 } 14403 } 14404 } 14405 14406 if (systemApp) { 14407 if (onExternal) { 14408 // Abort update; system app can't be replaced with app on sdcard 14409 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14410 "Cannot install updates to system apps on sdcard"); 14411 return; 14412 } else if (ephemeral) { 14413 // Abort update; system app can't be replaced with an ephemeral app 14414 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14415 "Cannot update a system app with an ephemeral app"); 14416 return; 14417 } 14418 } 14419 14420 if (args.move != null) { 14421 // We did an in-place move, so dex is ready to roll 14422 scanFlags |= SCAN_NO_DEX; 14423 scanFlags |= SCAN_MOVE; 14424 14425 synchronized (mPackages) { 14426 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14427 if (ps == null) { 14428 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14429 "Missing settings for moved package " + pkgName); 14430 } 14431 14432 // We moved the entire application as-is, so bring over the 14433 // previously derived ABI information. 14434 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14435 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14436 } 14437 14438 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14439 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14440 scanFlags |= SCAN_NO_DEX; 14441 14442 try { 14443 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14444 args.abiOverride : pkg.cpuAbiOverride); 14445 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14446 true /* extract libs */); 14447 } catch (PackageManagerException pme) { 14448 Slog.e(TAG, "Error deriving application ABI", pme); 14449 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14450 return; 14451 } 14452 14453 14454 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14455 // Do not run PackageDexOptimizer through the local performDexOpt 14456 // method because `pkg` is not in `mPackages` yet. 14457 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14458 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14459 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14460 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14461 String msg = "Extracking package failed for " + pkgName; 14462 res.setError(INSTALL_FAILED_DEXOPT, msg); 14463 return; 14464 } 14465 } 14466 14467 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14468 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14469 return; 14470 } 14471 14472 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14473 14474 if (replace) { 14475 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14476 installerPackageName, res); 14477 } else { 14478 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14479 args.user, installerPackageName, volumeUuid, res); 14480 } 14481 synchronized (mPackages) { 14482 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14483 if (ps != null) { 14484 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14485 } 14486 14487 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14488 for (int i = 0; i < childCount; i++) { 14489 PackageParser.Package childPkg = pkg.childPackages.get(i); 14490 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14491 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14492 if (childPs != null) { 14493 childRes.newUsers = childPs.queryInstalledUsers( 14494 sUserManager.getUserIds(), true); 14495 } 14496 } 14497 } 14498 } 14499 14500 private void startIntentFilterVerifications(int userId, boolean replacing, 14501 PackageParser.Package pkg) { 14502 if (mIntentFilterVerifierComponent == null) { 14503 Slog.w(TAG, "No IntentFilter verification will not be done as " 14504 + "there is no IntentFilterVerifier available!"); 14505 return; 14506 } 14507 14508 final int verifierUid = getPackageUid( 14509 mIntentFilterVerifierComponent.getPackageName(), 14510 MATCH_DEBUG_TRIAGED_MISSING, 14511 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14512 14513 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14514 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14515 mHandler.sendMessage(msg); 14516 14517 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14518 for (int i = 0; i < childCount; i++) { 14519 PackageParser.Package childPkg = pkg.childPackages.get(i); 14520 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14521 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14522 mHandler.sendMessage(msg); 14523 } 14524 } 14525 14526 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14527 PackageParser.Package pkg) { 14528 int size = pkg.activities.size(); 14529 if (size == 0) { 14530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14531 "No activity, so no need to verify any IntentFilter!"); 14532 return; 14533 } 14534 14535 final boolean hasDomainURLs = hasDomainURLs(pkg); 14536 if (!hasDomainURLs) { 14537 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14538 "No domain URLs, so no need to verify any IntentFilter!"); 14539 return; 14540 } 14541 14542 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14543 + " if any IntentFilter from the " + size 14544 + " Activities needs verification ..."); 14545 14546 int count = 0; 14547 final String packageName = pkg.packageName; 14548 14549 synchronized (mPackages) { 14550 // If this is a new install and we see that we've already run verification for this 14551 // package, we have nothing to do: it means the state was restored from backup. 14552 if (!replacing) { 14553 IntentFilterVerificationInfo ivi = 14554 mSettings.getIntentFilterVerificationLPr(packageName); 14555 if (ivi != null) { 14556 if (DEBUG_DOMAIN_VERIFICATION) { 14557 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14558 + ivi.getStatusString()); 14559 } 14560 return; 14561 } 14562 } 14563 14564 // If any filters need to be verified, then all need to be. 14565 boolean needToVerify = false; 14566 for (PackageParser.Activity a : pkg.activities) { 14567 for (ActivityIntentInfo filter : a.intents) { 14568 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14569 if (DEBUG_DOMAIN_VERIFICATION) { 14570 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14571 } 14572 needToVerify = true; 14573 break; 14574 } 14575 } 14576 } 14577 14578 if (needToVerify) { 14579 final int verificationId = mIntentFilterVerificationToken++; 14580 for (PackageParser.Activity a : pkg.activities) { 14581 for (ActivityIntentInfo filter : a.intents) { 14582 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14584 "Verification needed for IntentFilter:" + filter.toString()); 14585 mIntentFilterVerifier.addOneIntentFilterVerification( 14586 verifierUid, userId, verificationId, filter, packageName); 14587 count++; 14588 } 14589 } 14590 } 14591 } 14592 } 14593 14594 if (count > 0) { 14595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14596 + " IntentFilter verification" + (count > 1 ? "s" : "") 14597 + " for userId:" + userId); 14598 mIntentFilterVerifier.startVerifications(userId); 14599 } else { 14600 if (DEBUG_DOMAIN_VERIFICATION) { 14601 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14602 } 14603 } 14604 } 14605 14606 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14607 final ComponentName cn = filter.activity.getComponentName(); 14608 final String packageName = cn.getPackageName(); 14609 14610 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14611 packageName); 14612 if (ivi == null) { 14613 return true; 14614 } 14615 int status = ivi.getStatus(); 14616 switch (status) { 14617 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14618 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14619 return true; 14620 14621 default: 14622 // Nothing to do 14623 return false; 14624 } 14625 } 14626 14627 private static boolean isMultiArch(ApplicationInfo info) { 14628 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14629 } 14630 14631 private static boolean isExternal(PackageParser.Package pkg) { 14632 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14633 } 14634 14635 private static boolean isExternal(PackageSetting ps) { 14636 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14637 } 14638 14639 private static boolean isEphemeral(PackageParser.Package pkg) { 14640 return pkg.applicationInfo.isEphemeralApp(); 14641 } 14642 14643 private static boolean isEphemeral(PackageSetting ps) { 14644 return ps.pkg != null && isEphemeral(ps.pkg); 14645 } 14646 14647 private static boolean isSystemApp(PackageParser.Package pkg) { 14648 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14649 } 14650 14651 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14652 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14653 } 14654 14655 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14656 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14657 } 14658 14659 private static boolean isSystemApp(PackageSetting ps) { 14660 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14661 } 14662 14663 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14664 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14665 } 14666 14667 private int packageFlagsToInstallFlags(PackageSetting ps) { 14668 int installFlags = 0; 14669 if (isEphemeral(ps)) { 14670 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14671 } 14672 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14673 // This existing package was an external ASEC install when we have 14674 // the external flag without a UUID 14675 installFlags |= PackageManager.INSTALL_EXTERNAL; 14676 } 14677 if (ps.isForwardLocked()) { 14678 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14679 } 14680 return installFlags; 14681 } 14682 14683 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14684 if (isExternal(pkg)) { 14685 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14686 return StorageManager.UUID_PRIMARY_PHYSICAL; 14687 } else { 14688 return pkg.volumeUuid; 14689 } 14690 } else { 14691 return StorageManager.UUID_PRIVATE_INTERNAL; 14692 } 14693 } 14694 14695 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14696 if (isExternal(pkg)) { 14697 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14698 return mSettings.getExternalVersion(); 14699 } else { 14700 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14701 } 14702 } else { 14703 return mSettings.getInternalVersion(); 14704 } 14705 } 14706 14707 private void deleteTempPackageFiles() { 14708 final FilenameFilter filter = new FilenameFilter() { 14709 public boolean accept(File dir, String name) { 14710 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14711 } 14712 }; 14713 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14714 file.delete(); 14715 } 14716 } 14717 14718 @Override 14719 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14720 int flags) { 14721 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14722 flags); 14723 } 14724 14725 @Override 14726 public void deletePackage(final String packageName, 14727 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14728 mContext.enforceCallingOrSelfPermission( 14729 android.Manifest.permission.DELETE_PACKAGES, null); 14730 Preconditions.checkNotNull(packageName); 14731 Preconditions.checkNotNull(observer); 14732 final int uid = Binder.getCallingUid(); 14733 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14734 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14735 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14736 mContext.enforceCallingOrSelfPermission( 14737 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14738 "deletePackage for user " + userId); 14739 } 14740 14741 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14742 try { 14743 observer.onPackageDeleted(packageName, 14744 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14745 } catch (RemoteException re) { 14746 } 14747 return; 14748 } 14749 14750 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14751 try { 14752 observer.onPackageDeleted(packageName, 14753 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14754 } catch (RemoteException re) { 14755 } 14756 return; 14757 } 14758 14759 if (DEBUG_REMOVE) { 14760 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14761 + " deleteAllUsers: " + deleteAllUsers ); 14762 } 14763 // Queue up an async operation since the package deletion may take a little while. 14764 mHandler.post(new Runnable() { 14765 public void run() { 14766 mHandler.removeCallbacks(this); 14767 int returnCode; 14768 if (!deleteAllUsers) { 14769 returnCode = deletePackageX(packageName, userId, flags); 14770 } else { 14771 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14772 // If nobody is blocking uninstall, proceed with delete for all users 14773 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14774 returnCode = deletePackageX(packageName, userId, flags); 14775 } else { 14776 // Otherwise uninstall individually for users with blockUninstalls=false 14777 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14778 for (int userId : users) { 14779 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14780 returnCode = deletePackageX(packageName, userId, userFlags); 14781 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14782 Slog.w(TAG, "Package delete failed for user " + userId 14783 + ", returnCode " + returnCode); 14784 } 14785 } 14786 } 14787 // The app has only been marked uninstalled for certain users. 14788 // We still need to report that delete was blocked 14789 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14790 } 14791 } 14792 try { 14793 observer.onPackageDeleted(packageName, returnCode, null); 14794 } catch (RemoteException e) { 14795 Log.i(TAG, "Observer no longer exists."); 14796 } //end catch 14797 } //end run 14798 }); 14799 } 14800 14801 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14802 int[] result = EMPTY_INT_ARRAY; 14803 for (int userId : userIds) { 14804 if (getBlockUninstallForUser(packageName, userId)) { 14805 result = ArrayUtils.appendInt(result, userId); 14806 } 14807 } 14808 return result; 14809 } 14810 14811 @Override 14812 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14813 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14814 } 14815 14816 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14817 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14818 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14819 try { 14820 if (dpm != null) { 14821 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14822 /* callingUserOnly =*/ false); 14823 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14824 : deviceOwnerComponentName.getPackageName(); 14825 // Does the package contains the device owner? 14826 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14827 // this check is probably not needed, since DO should be registered as a device 14828 // admin on some user too. (Original bug for this: b/17657954) 14829 if (packageName.equals(deviceOwnerPackageName)) { 14830 return true; 14831 } 14832 // Does it contain a device admin for any user? 14833 int[] users; 14834 if (userId == UserHandle.USER_ALL) { 14835 users = sUserManager.getUserIds(); 14836 } else { 14837 users = new int[]{userId}; 14838 } 14839 for (int i = 0; i < users.length; ++i) { 14840 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14841 return true; 14842 } 14843 } 14844 } 14845 } catch (RemoteException e) { 14846 } 14847 return false; 14848 } 14849 14850 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14851 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14852 } 14853 14854 /** 14855 * This method is an internal method that could be get invoked either 14856 * to delete an installed package or to clean up a failed installation. 14857 * After deleting an installed package, a broadcast is sent to notify any 14858 * listeners that the package has been installed. For cleaning up a failed 14859 * installation, the broadcast is not necessary since the package's 14860 * installation wouldn't have sent the initial broadcast either 14861 * The key steps in deleting a package are 14862 * deleting the package information in internal structures like mPackages, 14863 * deleting the packages base directories through installd 14864 * updating mSettings to reflect current status 14865 * persisting settings for later use 14866 * sending a broadcast if necessary 14867 */ 14868 private int deletePackageX(String packageName, int userId, int flags) { 14869 final PackageRemovedInfo info = new PackageRemovedInfo(); 14870 final boolean res; 14871 14872 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14873 ? UserHandle.ALL : new UserHandle(userId); 14874 14875 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14876 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14877 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14878 } 14879 14880 PackageSetting uninstalledPs = null; 14881 14882 // for the uninstall-updates case and restricted profiles, remember the per- 14883 // user handle installed state 14884 int[] allUsers; 14885 synchronized (mPackages) { 14886 uninstalledPs = mSettings.mPackages.get(packageName); 14887 if (uninstalledPs == null) { 14888 Slog.w(TAG, "Not removing non-existent package " + packageName); 14889 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14890 } 14891 allUsers = sUserManager.getUserIds(); 14892 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14893 } 14894 14895 synchronized (mInstallLock) { 14896 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14897 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14898 flags | REMOVE_CHATTY, info, true, null); 14899 synchronized (mPackages) { 14900 if (res) { 14901 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14902 } 14903 } 14904 } 14905 14906 if (res) { 14907 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14908 info.sendPackageRemovedBroadcasts(killApp); 14909 info.sendSystemPackageUpdatedBroadcasts(); 14910 info.sendSystemPackageAppearedBroadcasts(); 14911 } 14912 // Force a gc here. 14913 Runtime.getRuntime().gc(); 14914 // Delete the resources here after sending the broadcast to let 14915 // other processes clean up before deleting resources. 14916 if (info.args != null) { 14917 synchronized (mInstallLock) { 14918 info.args.doPostDeleteLI(true); 14919 } 14920 } 14921 14922 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14923 } 14924 14925 class PackageRemovedInfo { 14926 String removedPackage; 14927 int uid = -1; 14928 int removedAppId = -1; 14929 int[] origUsers; 14930 int[] removedUsers = null; 14931 boolean isRemovedPackageSystemUpdate = false; 14932 boolean isUpdate; 14933 boolean dataRemoved; 14934 boolean removedForAllUsers; 14935 // Clean up resources deleted packages. 14936 InstallArgs args = null; 14937 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14938 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14939 14940 void sendPackageRemovedBroadcasts(boolean killApp) { 14941 sendPackageRemovedBroadcastInternal(killApp); 14942 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14943 for (int i = 0; i < childCount; i++) { 14944 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14945 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14946 } 14947 } 14948 14949 void sendSystemPackageUpdatedBroadcasts() { 14950 if (isRemovedPackageSystemUpdate) { 14951 sendSystemPackageUpdatedBroadcastsInternal(); 14952 final int childCount = (removedChildPackages != null) 14953 ? removedChildPackages.size() : 0; 14954 for (int i = 0; i < childCount; i++) { 14955 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14956 if (childInfo.isRemovedPackageSystemUpdate) { 14957 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14958 } 14959 } 14960 } 14961 } 14962 14963 void sendSystemPackageAppearedBroadcasts() { 14964 final int packageCount = (appearedChildPackages != null) 14965 ? appearedChildPackages.size() : 0; 14966 for (int i = 0; i < packageCount; i++) { 14967 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14968 for (int userId : installedInfo.newUsers) { 14969 sendPackageAddedForUser(installedInfo.name, true, 14970 UserHandle.getAppId(installedInfo.uid), userId); 14971 } 14972 } 14973 } 14974 14975 private void sendSystemPackageUpdatedBroadcastsInternal() { 14976 Bundle extras = new Bundle(2); 14977 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14978 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14979 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14980 extras, 0, null, null, null); 14981 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14982 extras, 0, null, null, null); 14983 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14984 null, 0, removedPackage, null, null); 14985 } 14986 14987 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14988 Bundle extras = new Bundle(2); 14989 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14990 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14991 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14992 if (isUpdate || isRemovedPackageSystemUpdate) { 14993 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14994 } 14995 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14996 if (removedPackage != null) { 14997 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14998 extras, 0, null, null, removedUsers); 14999 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15000 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15001 removedPackage, extras, 0, null, null, removedUsers); 15002 } 15003 } 15004 if (removedAppId >= 0) { 15005 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15006 removedUsers); 15007 } 15008 } 15009 } 15010 15011 /* 15012 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15013 * flag is not set, the data directory is removed as well. 15014 * make sure this flag is set for partially installed apps. If not its meaningless to 15015 * delete a partially installed application. 15016 */ 15017 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 15018 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15019 String packageName = ps.name; 15020 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15021 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15022 // Retrieve object to delete permissions for shared user later on 15023 final PackageSetting deletedPs; 15024 // reader 15025 synchronized (mPackages) { 15026 deletedPs = mSettings.mPackages.get(packageName); 15027 if (outInfo != null) { 15028 outInfo.removedPackage = packageName; 15029 outInfo.removedUsers = deletedPs != null 15030 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15031 : null; 15032 } 15033 } 15034 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15035 removeDataDirsLI(ps.volumeUuid, packageName); 15036 if (outInfo != null) { 15037 outInfo.dataRemoved = true; 15038 } 15039 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15040 } 15041 // writer 15042 synchronized (mPackages) { 15043 if (deletedPs != null) { 15044 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15045 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15046 clearDefaultBrowserIfNeeded(packageName); 15047 if (outInfo != null) { 15048 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15049 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15050 } 15051 updatePermissionsLPw(deletedPs.name, null, 0); 15052 if (deletedPs.sharedUser != null) { 15053 // Remove permissions associated with package. Since runtime 15054 // permissions are per user we have to kill the removed package 15055 // or packages running under the shared user of the removed 15056 // package if revoking the permissions requested only by the removed 15057 // package is successful and this causes a change in gids. 15058 for (int userId : UserManagerService.getInstance().getUserIds()) { 15059 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15060 userId); 15061 if (userIdToKill == UserHandle.USER_ALL 15062 || userIdToKill >= UserHandle.USER_SYSTEM) { 15063 // If gids changed for this user, kill all affected packages. 15064 mHandler.post(new Runnable() { 15065 @Override 15066 public void run() { 15067 // This has to happen with no lock held. 15068 killApplication(deletedPs.name, deletedPs.appId, 15069 KILL_APP_REASON_GIDS_CHANGED); 15070 } 15071 }); 15072 break; 15073 } 15074 } 15075 } 15076 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15077 } 15078 // make sure to preserve per-user disabled state if this removal was just 15079 // a downgrade of a system app to the factory package 15080 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15081 if (DEBUG_REMOVE) { 15082 Slog.d(TAG, "Propagating install state across downgrade"); 15083 } 15084 for (int userId : allUserHandles) { 15085 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15086 if (DEBUG_REMOVE) { 15087 Slog.d(TAG, " user " + userId + " => " + installed); 15088 } 15089 ps.setInstalled(installed, userId); 15090 } 15091 } 15092 } 15093 // can downgrade to reader 15094 if (writeSettings) { 15095 // Save settings now 15096 mSettings.writeLPr(); 15097 } 15098 } 15099 if (outInfo != null) { 15100 // A user ID was deleted here. Go through all users and remove it 15101 // from KeyStore. 15102 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15103 } 15104 } 15105 15106 static boolean locationIsPrivileged(File path) { 15107 try { 15108 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15109 .getCanonicalPath(); 15110 return path.getCanonicalPath().startsWith(privilegedAppDir); 15111 } catch (IOException e) { 15112 Slog.e(TAG, "Unable to access code path " + path); 15113 } 15114 return false; 15115 } 15116 15117 /* 15118 * Tries to delete system package. 15119 */ 15120 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15121 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15122 boolean writeSettings) { 15123 if (deletedPs.parentPackageName != null) { 15124 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15125 return false; 15126 } 15127 15128 final boolean applyUserRestrictions 15129 = (allUserHandles != null) && (outInfo.origUsers != null); 15130 final PackageSetting disabledPs; 15131 // Confirm if the system package has been updated 15132 // An updated system app can be deleted. This will also have to restore 15133 // the system pkg from system partition 15134 // reader 15135 synchronized (mPackages) { 15136 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15137 } 15138 15139 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15140 + " disabledPs=" + disabledPs); 15141 15142 if (disabledPs == null) { 15143 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15144 return false; 15145 } else if (DEBUG_REMOVE) { 15146 Slog.d(TAG, "Deleting system pkg from data partition"); 15147 } 15148 15149 if (DEBUG_REMOVE) { 15150 if (applyUserRestrictions) { 15151 Slog.d(TAG, "Remembering install states:"); 15152 for (int userId : allUserHandles) { 15153 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15154 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15155 } 15156 } 15157 } 15158 15159 // Delete the updated package 15160 outInfo.isRemovedPackageSystemUpdate = true; 15161 if (outInfo.removedChildPackages != null) { 15162 final int childCount = (deletedPs.childPackageNames != null) 15163 ? deletedPs.childPackageNames.size() : 0; 15164 for (int i = 0; i < childCount; i++) { 15165 String childPackageName = deletedPs.childPackageNames.get(i); 15166 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15167 .contains(childPackageName)) { 15168 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15169 childPackageName); 15170 if (childInfo != null) { 15171 childInfo.isRemovedPackageSystemUpdate = true; 15172 } 15173 } 15174 } 15175 } 15176 15177 if (disabledPs.versionCode < deletedPs.versionCode) { 15178 // Delete data for downgrades 15179 flags &= ~PackageManager.DELETE_KEEP_DATA; 15180 } else { 15181 // Preserve data by setting flag 15182 flags |= PackageManager.DELETE_KEEP_DATA; 15183 } 15184 15185 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15186 outInfo, writeSettings, disabledPs.pkg); 15187 if (!ret) { 15188 return false; 15189 } 15190 15191 // writer 15192 synchronized (mPackages) { 15193 // Reinstate the old system package 15194 enableSystemPackageLPw(disabledPs.pkg); 15195 // Remove any native libraries from the upgraded package. 15196 removeNativeBinariesLI(deletedPs); 15197 } 15198 15199 // Install the system package 15200 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15201 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15202 if (locationIsPrivileged(disabledPs.codePath)) { 15203 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15204 } 15205 15206 final PackageParser.Package newPkg; 15207 try { 15208 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15209 } catch (PackageManagerException e) { 15210 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15211 + e.getMessage()); 15212 return false; 15213 } 15214 15215 prepareAppDataAfterInstall(newPkg); 15216 15217 // writer 15218 synchronized (mPackages) { 15219 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15220 15221 // Propagate the permissions state as we do not want to drop on the floor 15222 // runtime permissions. The update permissions method below will take 15223 // care of removing obsolete permissions and grant install permissions. 15224 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15225 updatePermissionsLPw(newPkg.packageName, newPkg, 15226 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15227 15228 if (applyUserRestrictions) { 15229 if (DEBUG_REMOVE) { 15230 Slog.d(TAG, "Propagating install state across reinstall"); 15231 } 15232 for (int userId : allUserHandles) { 15233 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15234 if (DEBUG_REMOVE) { 15235 Slog.d(TAG, " user " + userId + " => " + installed); 15236 } 15237 ps.setInstalled(installed, userId); 15238 15239 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15240 } 15241 // Regardless of writeSettings we need to ensure that this restriction 15242 // state propagation is persisted 15243 mSettings.writeAllUsersPackageRestrictionsLPr(); 15244 } 15245 // can downgrade to reader here 15246 if (writeSettings) { 15247 mSettings.writeLPr(); 15248 } 15249 } 15250 return true; 15251 } 15252 15253 private boolean deleteInstalledPackageLI(PackageSetting ps, 15254 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15255 PackageRemovedInfo outInfo, boolean writeSettings, 15256 PackageParser.Package replacingPackage) { 15257 synchronized (mPackages) { 15258 if (outInfo != null) { 15259 outInfo.uid = ps.appId; 15260 } 15261 15262 if (outInfo != null && outInfo.removedChildPackages != null) { 15263 final int childCount = (ps.childPackageNames != null) 15264 ? ps.childPackageNames.size() : 0; 15265 for (int i = 0; i < childCount; i++) { 15266 String childPackageName = ps.childPackageNames.get(i); 15267 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15268 if (childPs == null) { 15269 return false; 15270 } 15271 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15272 childPackageName); 15273 if (childInfo != null) { 15274 childInfo.uid = childPs.appId; 15275 } 15276 } 15277 } 15278 } 15279 15280 // Delete package data from internal structures and also remove data if flag is set 15281 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15282 15283 // Delete the child packages data 15284 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15285 for (int i = 0; i < childCount; i++) { 15286 PackageSetting childPs; 15287 synchronized (mPackages) { 15288 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15289 } 15290 if (childPs != null) { 15291 PackageRemovedInfo childOutInfo = (outInfo != null 15292 && outInfo.removedChildPackages != null) 15293 ? outInfo.removedChildPackages.get(childPs.name) : null; 15294 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15295 && (replacingPackage != null 15296 && !replacingPackage.hasChildPackage(childPs.name)) 15297 ? flags & ~DELETE_KEEP_DATA : flags; 15298 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15299 deleteFlags, writeSettings); 15300 } 15301 } 15302 15303 // Delete application code and resources only for parent packages 15304 if (ps.parentPackageName == null) { 15305 if (deleteCodeAndResources && (outInfo != null)) { 15306 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15307 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15308 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15309 } 15310 } 15311 15312 return true; 15313 } 15314 15315 @Override 15316 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15317 int userId) { 15318 mContext.enforceCallingOrSelfPermission( 15319 android.Manifest.permission.DELETE_PACKAGES, null); 15320 synchronized (mPackages) { 15321 PackageSetting ps = mSettings.mPackages.get(packageName); 15322 if (ps == null) { 15323 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15324 return false; 15325 } 15326 if (!ps.getInstalled(userId)) { 15327 // Can't block uninstall for an app that is not installed or enabled. 15328 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15329 return false; 15330 } 15331 ps.setBlockUninstall(blockUninstall, userId); 15332 mSettings.writePackageRestrictionsLPr(userId); 15333 } 15334 return true; 15335 } 15336 15337 @Override 15338 public boolean getBlockUninstallForUser(String packageName, int userId) { 15339 synchronized (mPackages) { 15340 PackageSetting ps = mSettings.mPackages.get(packageName); 15341 if (ps == null) { 15342 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15343 return false; 15344 } 15345 return ps.getBlockUninstall(userId); 15346 } 15347 } 15348 15349 @Override 15350 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15351 int callingUid = Binder.getCallingUid(); 15352 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15353 throw new SecurityException( 15354 "setRequiredForSystemUser can only be run by the system or root"); 15355 } 15356 synchronized (mPackages) { 15357 PackageSetting ps = mSettings.mPackages.get(packageName); 15358 if (ps == null) { 15359 Log.w(TAG, "Package doesn't exist: " + packageName); 15360 return false; 15361 } 15362 if (systemUserApp) { 15363 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15364 } else { 15365 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15366 } 15367 mSettings.writeLPr(); 15368 } 15369 return true; 15370 } 15371 15372 /* 15373 * This method handles package deletion in general 15374 */ 15375 private boolean deletePackageLI(String packageName, UserHandle user, 15376 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15377 PackageRemovedInfo outInfo, boolean writeSettings, 15378 PackageParser.Package replacingPackage) { 15379 if (packageName == null) { 15380 Slog.w(TAG, "Attempt to delete null packageName."); 15381 return false; 15382 } 15383 15384 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15385 15386 PackageSetting ps; 15387 15388 synchronized (mPackages) { 15389 ps = mSettings.mPackages.get(packageName); 15390 if (ps == null) { 15391 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15392 return false; 15393 } 15394 15395 if (ps.parentPackageName != null && (!isSystemApp(ps) 15396 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15397 if (DEBUG_REMOVE) { 15398 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15399 + ((user == null) ? UserHandle.USER_ALL : user)); 15400 } 15401 final int removedUserId = (user != null) ? user.getIdentifier() 15402 : UserHandle.USER_ALL; 15403 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15404 return false; 15405 } 15406 markPackageUninstalledForUserLPw(ps, user); 15407 scheduleWritePackageRestrictionsLocked(user); 15408 return true; 15409 } 15410 } 15411 15412 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15413 && user.getIdentifier() != UserHandle.USER_ALL)) { 15414 // The caller is asking that the package only be deleted for a single 15415 // user. To do this, we just mark its uninstalled state and delete 15416 // its data. If this is a system app, we only allow this to happen if 15417 // they have set the special DELETE_SYSTEM_APP which requests different 15418 // semantics than normal for uninstalling system apps. 15419 markPackageUninstalledForUserLPw(ps, user); 15420 15421 if (!isSystemApp(ps)) { 15422 // Do not uninstall the APK if an app should be cached 15423 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15424 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15425 // Other user still have this package installed, so all 15426 // we need to do is clear this user's data and save that 15427 // it is uninstalled. 15428 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15429 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15430 return false; 15431 } 15432 scheduleWritePackageRestrictionsLocked(user); 15433 return true; 15434 } else { 15435 // We need to set it back to 'installed' so the uninstall 15436 // broadcasts will be sent correctly. 15437 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15438 ps.setInstalled(true, user.getIdentifier()); 15439 } 15440 } else { 15441 // This is a system app, so we assume that the 15442 // other users still have this package installed, so all 15443 // we need to do is clear this user's data and save that 15444 // it is uninstalled. 15445 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15446 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15447 return false; 15448 } 15449 scheduleWritePackageRestrictionsLocked(user); 15450 return true; 15451 } 15452 } 15453 15454 // If we are deleting a composite package for all users, keep track 15455 // of result for each child. 15456 if (ps.childPackageNames != null && outInfo != null) { 15457 synchronized (mPackages) { 15458 final int childCount = ps.childPackageNames.size(); 15459 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15460 for (int i = 0; i < childCount; i++) { 15461 String childPackageName = ps.childPackageNames.get(i); 15462 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15463 childInfo.removedPackage = childPackageName; 15464 outInfo.removedChildPackages.put(childPackageName, childInfo); 15465 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15466 if (childPs != null) { 15467 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15468 } 15469 } 15470 } 15471 } 15472 15473 boolean ret = false; 15474 if (isSystemApp(ps)) { 15475 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15476 // When an updated system application is deleted we delete the existing resources 15477 // as well and fall back to existing code in system partition 15478 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15479 } else { 15480 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15481 // Kill application pre-emptively especially for apps on sd. 15482 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15483 if (killApp) { 15484 killApplication(packageName, ps.appId, "uninstall pkg"); 15485 } 15486 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15487 outInfo, writeSettings, replacingPackage); 15488 } 15489 15490 // Take a note whether we deleted the package for all users 15491 if (outInfo != null) { 15492 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15493 if (outInfo.removedChildPackages != null) { 15494 synchronized (mPackages) { 15495 final int childCount = outInfo.removedChildPackages.size(); 15496 for (int i = 0; i < childCount; i++) { 15497 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15498 if (childInfo != null) { 15499 childInfo.removedForAllUsers = mPackages.get( 15500 childInfo.removedPackage) == null; 15501 } 15502 } 15503 } 15504 } 15505 // If we uninstalled an update to a system app there may be some 15506 // child packages that appeared as they are declared in the system 15507 // app but were not declared in the update. 15508 if (isSystemApp(ps)) { 15509 synchronized (mPackages) { 15510 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15511 final int childCount = (updatedPs.childPackageNames != null) 15512 ? updatedPs.childPackageNames.size() : 0; 15513 for (int i = 0; i < childCount; i++) { 15514 String childPackageName = updatedPs.childPackageNames.get(i); 15515 if (outInfo.removedChildPackages == null 15516 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15517 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15518 if (childPs == null) { 15519 continue; 15520 } 15521 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15522 installRes.name = childPackageName; 15523 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15524 installRes.pkg = mPackages.get(childPackageName); 15525 installRes.uid = childPs.pkg.applicationInfo.uid; 15526 if (outInfo.appearedChildPackages == null) { 15527 outInfo.appearedChildPackages = new ArrayMap<>(); 15528 } 15529 outInfo.appearedChildPackages.put(childPackageName, installRes); 15530 } 15531 } 15532 } 15533 } 15534 } 15535 15536 return ret; 15537 } 15538 15539 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15540 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15541 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15542 for (int nextUserId : userIds) { 15543 if (DEBUG_REMOVE) { 15544 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15545 } 15546 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15547 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15548 false /*hidden*/, false /*suspended*/, null, null, null, 15549 false /*blockUninstall*/, 15550 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15551 } 15552 } 15553 15554 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15555 PackageRemovedInfo outInfo) { 15556 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15557 : new int[] {userId}; 15558 for (int nextUserId : userIds) { 15559 if (DEBUG_REMOVE) { 15560 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15561 + nextUserId); 15562 } 15563 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15564 try { 15565 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15566 } catch (InstallerException e) { 15567 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15568 return false; 15569 } 15570 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15571 schedulePackageCleaning(ps.name, nextUserId, false); 15572 synchronized (mPackages) { 15573 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15574 scheduleWritePackageRestrictionsLocked(nextUserId); 15575 } 15576 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15577 } 15578 } 15579 15580 if (outInfo != null) { 15581 outInfo.removedPackage = ps.name; 15582 outInfo.removedAppId = ps.appId; 15583 outInfo.removedUsers = userIds; 15584 } 15585 15586 return true; 15587 } 15588 15589 private final class ClearStorageConnection implements ServiceConnection { 15590 IMediaContainerService mContainerService; 15591 15592 @Override 15593 public void onServiceConnected(ComponentName name, IBinder service) { 15594 synchronized (this) { 15595 mContainerService = IMediaContainerService.Stub.asInterface(service); 15596 notifyAll(); 15597 } 15598 } 15599 15600 @Override 15601 public void onServiceDisconnected(ComponentName name) { 15602 } 15603 } 15604 15605 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15606 final boolean mounted; 15607 if (Environment.isExternalStorageEmulated()) { 15608 mounted = true; 15609 } else { 15610 final String status = Environment.getExternalStorageState(); 15611 15612 mounted = status.equals(Environment.MEDIA_MOUNTED) 15613 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15614 } 15615 15616 if (!mounted) { 15617 return; 15618 } 15619 15620 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15621 int[] users; 15622 if (userId == UserHandle.USER_ALL) { 15623 users = sUserManager.getUserIds(); 15624 } else { 15625 users = new int[] { userId }; 15626 } 15627 final ClearStorageConnection conn = new ClearStorageConnection(); 15628 if (mContext.bindServiceAsUser( 15629 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15630 try { 15631 for (int curUser : users) { 15632 long timeout = SystemClock.uptimeMillis() + 5000; 15633 synchronized (conn) { 15634 long now = SystemClock.uptimeMillis(); 15635 while (conn.mContainerService == null && now < timeout) { 15636 try { 15637 conn.wait(timeout - now); 15638 } catch (InterruptedException e) { 15639 } 15640 } 15641 } 15642 if (conn.mContainerService == null) { 15643 return; 15644 } 15645 15646 final UserEnvironment userEnv = new UserEnvironment(curUser); 15647 clearDirectory(conn.mContainerService, 15648 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15649 if (allData) { 15650 clearDirectory(conn.mContainerService, 15651 userEnv.buildExternalStorageAppDataDirs(packageName)); 15652 clearDirectory(conn.mContainerService, 15653 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15654 } 15655 } 15656 } finally { 15657 mContext.unbindService(conn); 15658 } 15659 } 15660 } 15661 15662 @Override 15663 public void clearApplicationProfileData(String packageName) { 15664 enforceSystemOrRoot("Only the system can clear all profile data"); 15665 try { 15666 mInstaller.clearAppProfiles(packageName); 15667 } catch (InstallerException ex) { 15668 Log.e(TAG, "Could not clear profile data of package " + packageName); 15669 } 15670 } 15671 15672 @Override 15673 public void clearApplicationUserData(final String packageName, 15674 final IPackageDataObserver observer, final int userId) { 15675 mContext.enforceCallingOrSelfPermission( 15676 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15677 15678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15679 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15680 15681 final DevicePolicyManagerInternal dpmi = LocalServices 15682 .getService(DevicePolicyManagerInternal.class); 15683 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15684 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15685 } 15686 // Queue up an async operation since the package deletion may take a little while. 15687 mHandler.post(new Runnable() { 15688 public void run() { 15689 mHandler.removeCallbacks(this); 15690 final boolean succeeded; 15691 synchronized (mInstallLock) { 15692 succeeded = clearApplicationUserDataLI(packageName, userId); 15693 } 15694 clearExternalStorageDataSync(packageName, userId, true); 15695 if (succeeded) { 15696 // invoke DeviceStorageMonitor's update method to clear any notifications 15697 DeviceStorageMonitorInternal dsm = LocalServices 15698 .getService(DeviceStorageMonitorInternal.class); 15699 if (dsm != null) { 15700 dsm.checkMemory(); 15701 } 15702 } 15703 if(observer != null) { 15704 try { 15705 observer.onRemoveCompleted(packageName, succeeded); 15706 } catch (RemoteException e) { 15707 Log.i(TAG, "Observer no longer exists."); 15708 } 15709 } //end if observer 15710 } //end run 15711 }); 15712 } 15713 15714 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15715 if (packageName == null) { 15716 Slog.w(TAG, "Attempt to delete null packageName."); 15717 return false; 15718 } 15719 15720 // Try finding details about the requested package 15721 PackageParser.Package pkg; 15722 synchronized (mPackages) { 15723 pkg = mPackages.get(packageName); 15724 if (pkg == null) { 15725 final PackageSetting ps = mSettings.mPackages.get(packageName); 15726 if (ps != null) { 15727 pkg = ps.pkg; 15728 } 15729 } 15730 15731 if (pkg == null) { 15732 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15733 return false; 15734 } 15735 15736 PackageSetting ps = (PackageSetting) pkg.mExtras; 15737 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15738 } 15739 15740 // Always delete data directories for package, even if we found no other 15741 // record of app. This helps users recover from UID mismatches without 15742 // resorting to a full data wipe. 15743 // TODO: triage flags as part of 26466827 15744 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15745 try { 15746 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15747 } catch (InstallerException e) { 15748 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15749 return false; 15750 } 15751 15752 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15753 removeKeystoreDataIfNeeded(userId, appId); 15754 15755 // Create a native library symlink only if we have native libraries 15756 // and if the native libraries are 32 bit libraries. We do not provide 15757 // this symlink for 64 bit libraries. 15758 if (pkg.applicationInfo.primaryCpuAbi != null && 15759 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15760 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15761 try { 15762 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15763 nativeLibPath, userId); 15764 } catch (InstallerException e) { 15765 Slog.w(TAG, "Failed linking native library dir", e); 15766 return false; 15767 } 15768 } 15769 15770 return true; 15771 } 15772 15773 /** 15774 * Reverts user permission state changes (permissions and flags) in 15775 * all packages for a given user. 15776 * 15777 * @param userId The device user for which to do a reset. 15778 */ 15779 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15780 final int packageCount = mPackages.size(); 15781 for (int i = 0; i < packageCount; i++) { 15782 PackageParser.Package pkg = mPackages.valueAt(i); 15783 PackageSetting ps = (PackageSetting) pkg.mExtras; 15784 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15785 } 15786 } 15787 15788 /** 15789 * Reverts user permission state changes (permissions and flags). 15790 * 15791 * @param ps The package for which to reset. 15792 * @param userId The device user for which to do a reset. 15793 */ 15794 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15795 final PackageSetting ps, final int userId) { 15796 if (ps.pkg == null) { 15797 return; 15798 } 15799 15800 // These are flags that can change base on user actions. 15801 final int userSettableMask = FLAG_PERMISSION_USER_SET 15802 | FLAG_PERMISSION_USER_FIXED 15803 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15804 | FLAG_PERMISSION_REVIEW_REQUIRED; 15805 15806 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15807 | FLAG_PERMISSION_POLICY_FIXED; 15808 15809 boolean writeInstallPermissions = false; 15810 boolean writeRuntimePermissions = false; 15811 15812 final int permissionCount = ps.pkg.requestedPermissions.size(); 15813 for (int i = 0; i < permissionCount; i++) { 15814 String permission = ps.pkg.requestedPermissions.get(i); 15815 15816 BasePermission bp = mSettings.mPermissions.get(permission); 15817 if (bp == null) { 15818 continue; 15819 } 15820 15821 // If shared user we just reset the state to which only this app contributed. 15822 if (ps.sharedUser != null) { 15823 boolean used = false; 15824 final int packageCount = ps.sharedUser.packages.size(); 15825 for (int j = 0; j < packageCount; j++) { 15826 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15827 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15828 && pkg.pkg.requestedPermissions.contains(permission)) { 15829 used = true; 15830 break; 15831 } 15832 } 15833 if (used) { 15834 continue; 15835 } 15836 } 15837 15838 PermissionsState permissionsState = ps.getPermissionsState(); 15839 15840 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15841 15842 // Always clear the user settable flags. 15843 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15844 bp.name) != null; 15845 // If permission review is enabled and this is a legacy app, mark the 15846 // permission as requiring a review as this is the initial state. 15847 int flags = 0; 15848 if (Build.PERMISSIONS_REVIEW_REQUIRED 15849 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15850 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15851 } 15852 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15853 if (hasInstallState) { 15854 writeInstallPermissions = true; 15855 } else { 15856 writeRuntimePermissions = true; 15857 } 15858 } 15859 15860 // Below is only runtime permission handling. 15861 if (!bp.isRuntime()) { 15862 continue; 15863 } 15864 15865 // Never clobber system or policy. 15866 if ((oldFlags & policyOrSystemFlags) != 0) { 15867 continue; 15868 } 15869 15870 // If this permission was granted by default, make sure it is. 15871 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15872 if (permissionsState.grantRuntimePermission(bp, userId) 15873 != PERMISSION_OPERATION_FAILURE) { 15874 writeRuntimePermissions = true; 15875 } 15876 // If permission review is enabled the permissions for a legacy apps 15877 // are represented as constantly granted runtime ones, so don't revoke. 15878 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15879 // Otherwise, reset the permission. 15880 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15881 switch (revokeResult) { 15882 case PERMISSION_OPERATION_SUCCESS: 15883 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15884 writeRuntimePermissions = true; 15885 final int appId = ps.appId; 15886 mHandler.post(new Runnable() { 15887 @Override 15888 public void run() { 15889 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15890 } 15891 }); 15892 } break; 15893 } 15894 } 15895 } 15896 15897 // Synchronously write as we are taking permissions away. 15898 if (writeRuntimePermissions) { 15899 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15900 } 15901 15902 // Synchronously write as we are taking permissions away. 15903 if (writeInstallPermissions) { 15904 mSettings.writeLPr(); 15905 } 15906 } 15907 15908 /** 15909 * Remove entries from the keystore daemon. Will only remove it if the 15910 * {@code appId} is valid. 15911 */ 15912 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15913 if (appId < 0) { 15914 return; 15915 } 15916 15917 final KeyStore keyStore = KeyStore.getInstance(); 15918 if (keyStore != null) { 15919 if (userId == UserHandle.USER_ALL) { 15920 for (final int individual : sUserManager.getUserIds()) { 15921 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15922 } 15923 } else { 15924 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15925 } 15926 } else { 15927 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15928 } 15929 } 15930 15931 @Override 15932 public void deleteApplicationCacheFiles(final String packageName, 15933 final IPackageDataObserver observer) { 15934 mContext.enforceCallingOrSelfPermission( 15935 android.Manifest.permission.DELETE_CACHE_FILES, null); 15936 // Queue up an async operation since the package deletion may take a little while. 15937 final int userId = UserHandle.getCallingUserId(); 15938 mHandler.post(new Runnable() { 15939 public void run() { 15940 mHandler.removeCallbacks(this); 15941 final boolean succeded; 15942 synchronized (mInstallLock) { 15943 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15944 } 15945 clearExternalStorageDataSync(packageName, userId, false); 15946 if (observer != null) { 15947 try { 15948 observer.onRemoveCompleted(packageName, succeded); 15949 } catch (RemoteException e) { 15950 Log.i(TAG, "Observer no longer exists."); 15951 } 15952 } //end if observer 15953 } //end run 15954 }); 15955 } 15956 15957 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15958 if (packageName == null) { 15959 Slog.w(TAG, "Attempt to delete null packageName."); 15960 return false; 15961 } 15962 PackageParser.Package p; 15963 synchronized (mPackages) { 15964 p = mPackages.get(packageName); 15965 } 15966 if (p == null) { 15967 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15968 return false; 15969 } 15970 final ApplicationInfo applicationInfo = p.applicationInfo; 15971 if (applicationInfo == null) { 15972 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15973 return false; 15974 } 15975 // TODO: triage flags as part of 26466827 15976 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15977 try { 15978 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15979 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15980 } catch (InstallerException e) { 15981 Slog.w(TAG, "Couldn't remove cache files for package " 15982 + packageName + " u" + userId, e); 15983 return false; 15984 } 15985 return true; 15986 } 15987 15988 @Override 15989 public void getPackageSizeInfo(final String packageName, int userHandle, 15990 final IPackageStatsObserver observer) { 15991 mContext.enforceCallingOrSelfPermission( 15992 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15993 if (packageName == null) { 15994 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15995 } 15996 15997 PackageStats stats = new PackageStats(packageName, userHandle); 15998 15999 /* 16000 * Queue up an async operation since the package measurement may take a 16001 * little while. 16002 */ 16003 Message msg = mHandler.obtainMessage(INIT_COPY); 16004 msg.obj = new MeasureParams(stats, observer); 16005 mHandler.sendMessage(msg); 16006 } 16007 16008 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 16009 PackageStats pStats) { 16010 if (packageName == null) { 16011 Slog.w(TAG, "Attempt to get size of null packageName."); 16012 return false; 16013 } 16014 PackageParser.Package p; 16015 boolean dataOnly = false; 16016 String libDirRoot = null; 16017 String asecPath = null; 16018 PackageSetting ps = null; 16019 synchronized (mPackages) { 16020 p = mPackages.get(packageName); 16021 ps = mSettings.mPackages.get(packageName); 16022 if(p == null) { 16023 dataOnly = true; 16024 if((ps == null) || (ps.pkg == null)) { 16025 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16026 return false; 16027 } 16028 p = ps.pkg; 16029 } 16030 if (ps != null) { 16031 libDirRoot = ps.legacyNativeLibraryPathString; 16032 } 16033 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16034 final long token = Binder.clearCallingIdentity(); 16035 try { 16036 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16037 if (secureContainerId != null) { 16038 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16039 } 16040 } finally { 16041 Binder.restoreCallingIdentity(token); 16042 } 16043 } 16044 } 16045 String publicSrcDir = null; 16046 if(!dataOnly) { 16047 final ApplicationInfo applicationInfo = p.applicationInfo; 16048 if (applicationInfo == null) { 16049 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16050 return false; 16051 } 16052 if (p.isForwardLocked()) { 16053 publicSrcDir = applicationInfo.getBaseResourcePath(); 16054 } 16055 } 16056 // TODO: extend to measure size of split APKs 16057 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16058 // not just the first level. 16059 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16060 // just the primary. 16061 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16062 16063 String apkPath; 16064 File packageDir = new File(p.codePath); 16065 16066 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16067 apkPath = packageDir.getAbsolutePath(); 16068 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16069 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16070 libDirRoot = null; 16071 } 16072 } else { 16073 apkPath = p.baseCodePath; 16074 } 16075 16076 // TODO: triage flags as part of 26466827 16077 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16078 try { 16079 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16080 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16081 } catch (InstallerException e) { 16082 return false; 16083 } 16084 16085 // Fix-up for forward-locked applications in ASEC containers. 16086 if (!isExternal(p)) { 16087 pStats.codeSize += pStats.externalCodeSize; 16088 pStats.externalCodeSize = 0L; 16089 } 16090 16091 return true; 16092 } 16093 16094 private int getUidTargetSdkVersionLockedLPr(int uid) { 16095 Object obj = mSettings.getUserIdLPr(uid); 16096 if (obj instanceof SharedUserSetting) { 16097 final SharedUserSetting sus = (SharedUserSetting) obj; 16098 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16099 final Iterator<PackageSetting> it = sus.packages.iterator(); 16100 while (it.hasNext()) { 16101 final PackageSetting ps = it.next(); 16102 if (ps.pkg != null) { 16103 int v = ps.pkg.applicationInfo.targetSdkVersion; 16104 if (v < vers) vers = v; 16105 } 16106 } 16107 return vers; 16108 } else if (obj instanceof PackageSetting) { 16109 final PackageSetting ps = (PackageSetting) obj; 16110 if (ps.pkg != null) { 16111 return ps.pkg.applicationInfo.targetSdkVersion; 16112 } 16113 } 16114 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16115 } 16116 16117 @Override 16118 public void addPreferredActivity(IntentFilter filter, int match, 16119 ComponentName[] set, ComponentName activity, int userId) { 16120 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16121 "Adding preferred"); 16122 } 16123 16124 private void addPreferredActivityInternal(IntentFilter filter, int match, 16125 ComponentName[] set, ComponentName activity, boolean always, int userId, 16126 String opname) { 16127 // writer 16128 int callingUid = Binder.getCallingUid(); 16129 enforceCrossUserPermission(callingUid, userId, 16130 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16131 if (filter.countActions() == 0) { 16132 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16133 return; 16134 } 16135 synchronized (mPackages) { 16136 if (mContext.checkCallingOrSelfPermission( 16137 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16138 != PackageManager.PERMISSION_GRANTED) { 16139 if (getUidTargetSdkVersionLockedLPr(callingUid) 16140 < Build.VERSION_CODES.FROYO) { 16141 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16142 + callingUid); 16143 return; 16144 } 16145 mContext.enforceCallingOrSelfPermission( 16146 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16147 } 16148 16149 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16150 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16151 + userId + ":"); 16152 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16153 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16154 scheduleWritePackageRestrictionsLocked(userId); 16155 } 16156 } 16157 16158 @Override 16159 public void replacePreferredActivity(IntentFilter filter, int match, 16160 ComponentName[] set, ComponentName activity, int userId) { 16161 if (filter.countActions() != 1) { 16162 throw new IllegalArgumentException( 16163 "replacePreferredActivity expects filter to have only 1 action."); 16164 } 16165 if (filter.countDataAuthorities() != 0 16166 || filter.countDataPaths() != 0 16167 || filter.countDataSchemes() > 1 16168 || filter.countDataTypes() != 0) { 16169 throw new IllegalArgumentException( 16170 "replacePreferredActivity expects filter to have no data authorities, " + 16171 "paths, or types; and at most one scheme."); 16172 } 16173 16174 final int callingUid = Binder.getCallingUid(); 16175 enforceCrossUserPermission(callingUid, userId, 16176 true /* requireFullPermission */, false /* checkShell */, 16177 "replace preferred activity"); 16178 synchronized (mPackages) { 16179 if (mContext.checkCallingOrSelfPermission( 16180 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16181 != PackageManager.PERMISSION_GRANTED) { 16182 if (getUidTargetSdkVersionLockedLPr(callingUid) 16183 < Build.VERSION_CODES.FROYO) { 16184 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16185 + Binder.getCallingUid()); 16186 return; 16187 } 16188 mContext.enforceCallingOrSelfPermission( 16189 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16190 } 16191 16192 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16193 if (pir != null) { 16194 // Get all of the existing entries that exactly match this filter. 16195 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16196 if (existing != null && existing.size() == 1) { 16197 PreferredActivity cur = existing.get(0); 16198 if (DEBUG_PREFERRED) { 16199 Slog.i(TAG, "Checking replace of preferred:"); 16200 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16201 if (!cur.mPref.mAlways) { 16202 Slog.i(TAG, " -- CUR; not mAlways!"); 16203 } else { 16204 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16205 Slog.i(TAG, " -- CUR: mSet=" 16206 + Arrays.toString(cur.mPref.mSetComponents)); 16207 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16208 Slog.i(TAG, " -- NEW: mMatch=" 16209 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16210 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16211 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16212 } 16213 } 16214 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16215 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16216 && cur.mPref.sameSet(set)) { 16217 // Setting the preferred activity to what it happens to be already 16218 if (DEBUG_PREFERRED) { 16219 Slog.i(TAG, "Replacing with same preferred activity " 16220 + cur.mPref.mShortComponent + " for user " 16221 + userId + ":"); 16222 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16223 } 16224 return; 16225 } 16226 } 16227 16228 if (existing != null) { 16229 if (DEBUG_PREFERRED) { 16230 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16231 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16232 } 16233 for (int i = 0; i < existing.size(); i++) { 16234 PreferredActivity pa = existing.get(i); 16235 if (DEBUG_PREFERRED) { 16236 Slog.i(TAG, "Removing existing preferred activity " 16237 + pa.mPref.mComponent + ":"); 16238 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16239 } 16240 pir.removeFilter(pa); 16241 } 16242 } 16243 } 16244 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16245 "Replacing preferred"); 16246 } 16247 } 16248 16249 @Override 16250 public void clearPackagePreferredActivities(String packageName) { 16251 final int uid = Binder.getCallingUid(); 16252 // writer 16253 synchronized (mPackages) { 16254 PackageParser.Package pkg = mPackages.get(packageName); 16255 if (pkg == null || pkg.applicationInfo.uid != uid) { 16256 if (mContext.checkCallingOrSelfPermission( 16257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16258 != PackageManager.PERMISSION_GRANTED) { 16259 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16260 < Build.VERSION_CODES.FROYO) { 16261 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16262 + Binder.getCallingUid()); 16263 return; 16264 } 16265 mContext.enforceCallingOrSelfPermission( 16266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16267 } 16268 } 16269 16270 int user = UserHandle.getCallingUserId(); 16271 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16272 scheduleWritePackageRestrictionsLocked(user); 16273 } 16274 } 16275 } 16276 16277 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16278 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16279 ArrayList<PreferredActivity> removed = null; 16280 boolean changed = false; 16281 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16282 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16283 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16284 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16285 continue; 16286 } 16287 Iterator<PreferredActivity> it = pir.filterIterator(); 16288 while (it.hasNext()) { 16289 PreferredActivity pa = it.next(); 16290 // Mark entry for removal only if it matches the package name 16291 // and the entry is of type "always". 16292 if (packageName == null || 16293 (pa.mPref.mComponent.getPackageName().equals(packageName) 16294 && pa.mPref.mAlways)) { 16295 if (removed == null) { 16296 removed = new ArrayList<PreferredActivity>(); 16297 } 16298 removed.add(pa); 16299 } 16300 } 16301 if (removed != null) { 16302 for (int j=0; j<removed.size(); j++) { 16303 PreferredActivity pa = removed.get(j); 16304 pir.removeFilter(pa); 16305 } 16306 changed = true; 16307 } 16308 } 16309 return changed; 16310 } 16311 16312 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16313 private void clearIntentFilterVerificationsLPw(int userId) { 16314 final int packageCount = mPackages.size(); 16315 for (int i = 0; i < packageCount; i++) { 16316 PackageParser.Package pkg = mPackages.valueAt(i); 16317 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16318 } 16319 } 16320 16321 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16322 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16323 if (userId == UserHandle.USER_ALL) { 16324 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16325 sUserManager.getUserIds())) { 16326 for (int oneUserId : sUserManager.getUserIds()) { 16327 scheduleWritePackageRestrictionsLocked(oneUserId); 16328 } 16329 } 16330 } else { 16331 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16332 scheduleWritePackageRestrictionsLocked(userId); 16333 } 16334 } 16335 } 16336 16337 void clearDefaultBrowserIfNeeded(String packageName) { 16338 for (int oneUserId : sUserManager.getUserIds()) { 16339 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16340 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16341 if (packageName.equals(defaultBrowserPackageName)) { 16342 setDefaultBrowserPackageName(null, oneUserId); 16343 } 16344 } 16345 } 16346 16347 @Override 16348 public void resetApplicationPreferences(int userId) { 16349 mContext.enforceCallingOrSelfPermission( 16350 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16351 // writer 16352 synchronized (mPackages) { 16353 final long identity = Binder.clearCallingIdentity(); 16354 try { 16355 clearPackagePreferredActivitiesLPw(null, userId); 16356 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16357 // TODO: We have to reset the default SMS and Phone. This requires 16358 // significant refactoring to keep all default apps in the package 16359 // manager (cleaner but more work) or have the services provide 16360 // callbacks to the package manager to request a default app reset. 16361 applyFactoryDefaultBrowserLPw(userId); 16362 clearIntentFilterVerificationsLPw(userId); 16363 primeDomainVerificationsLPw(userId); 16364 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16365 scheduleWritePackageRestrictionsLocked(userId); 16366 } finally { 16367 Binder.restoreCallingIdentity(identity); 16368 } 16369 } 16370 } 16371 16372 @Override 16373 public int getPreferredActivities(List<IntentFilter> outFilters, 16374 List<ComponentName> outActivities, String packageName) { 16375 16376 int num = 0; 16377 final int userId = UserHandle.getCallingUserId(); 16378 // reader 16379 synchronized (mPackages) { 16380 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16381 if (pir != null) { 16382 final Iterator<PreferredActivity> it = pir.filterIterator(); 16383 while (it.hasNext()) { 16384 final PreferredActivity pa = it.next(); 16385 if (packageName == null 16386 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16387 && pa.mPref.mAlways)) { 16388 if (outFilters != null) { 16389 outFilters.add(new IntentFilter(pa)); 16390 } 16391 if (outActivities != null) { 16392 outActivities.add(pa.mPref.mComponent); 16393 } 16394 } 16395 } 16396 } 16397 } 16398 16399 return num; 16400 } 16401 16402 @Override 16403 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16404 int userId) { 16405 int callingUid = Binder.getCallingUid(); 16406 if (callingUid != Process.SYSTEM_UID) { 16407 throw new SecurityException( 16408 "addPersistentPreferredActivity can only be run by the system"); 16409 } 16410 if (filter.countActions() == 0) { 16411 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16412 return; 16413 } 16414 synchronized (mPackages) { 16415 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16416 ":"); 16417 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16418 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16419 new PersistentPreferredActivity(filter, activity)); 16420 scheduleWritePackageRestrictionsLocked(userId); 16421 } 16422 } 16423 16424 @Override 16425 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16426 int callingUid = Binder.getCallingUid(); 16427 if (callingUid != Process.SYSTEM_UID) { 16428 throw new SecurityException( 16429 "clearPackagePersistentPreferredActivities can only be run by the system"); 16430 } 16431 ArrayList<PersistentPreferredActivity> removed = null; 16432 boolean changed = false; 16433 synchronized (mPackages) { 16434 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16435 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16436 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16437 .valueAt(i); 16438 if (userId != thisUserId) { 16439 continue; 16440 } 16441 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16442 while (it.hasNext()) { 16443 PersistentPreferredActivity ppa = it.next(); 16444 // Mark entry for removal only if it matches the package name. 16445 if (ppa.mComponent.getPackageName().equals(packageName)) { 16446 if (removed == null) { 16447 removed = new ArrayList<PersistentPreferredActivity>(); 16448 } 16449 removed.add(ppa); 16450 } 16451 } 16452 if (removed != null) { 16453 for (int j=0; j<removed.size(); j++) { 16454 PersistentPreferredActivity ppa = removed.get(j); 16455 ppir.removeFilter(ppa); 16456 } 16457 changed = true; 16458 } 16459 } 16460 16461 if (changed) { 16462 scheduleWritePackageRestrictionsLocked(userId); 16463 } 16464 } 16465 } 16466 16467 /** 16468 * Common machinery for picking apart a restored XML blob and passing 16469 * it to a caller-supplied functor to be applied to the running system. 16470 */ 16471 private void restoreFromXml(XmlPullParser parser, int userId, 16472 String expectedStartTag, BlobXmlRestorer functor) 16473 throws IOException, XmlPullParserException { 16474 int type; 16475 while ((type = parser.next()) != XmlPullParser.START_TAG 16476 && type != XmlPullParser.END_DOCUMENT) { 16477 } 16478 if (type != XmlPullParser.START_TAG) { 16479 // oops didn't find a start tag?! 16480 if (DEBUG_BACKUP) { 16481 Slog.e(TAG, "Didn't find start tag during restore"); 16482 } 16483 return; 16484 } 16485Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16486 // this is supposed to be TAG_PREFERRED_BACKUP 16487 if (!expectedStartTag.equals(parser.getName())) { 16488 if (DEBUG_BACKUP) { 16489 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16490 } 16491 return; 16492 } 16493 16494 // skip interfering stuff, then we're aligned with the backing implementation 16495 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16496Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16497 functor.apply(parser, userId); 16498 } 16499 16500 private interface BlobXmlRestorer { 16501 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16502 } 16503 16504 /** 16505 * Non-Binder method, support for the backup/restore mechanism: write the 16506 * full set of preferred activities in its canonical XML format. Returns the 16507 * XML output as a byte array, or null if there is none. 16508 */ 16509 @Override 16510 public byte[] getPreferredActivityBackup(int userId) { 16511 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16512 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16513 } 16514 16515 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16516 try { 16517 final XmlSerializer serializer = new FastXmlSerializer(); 16518 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16519 serializer.startDocument(null, true); 16520 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16521 16522 synchronized (mPackages) { 16523 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16524 } 16525 16526 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16527 serializer.endDocument(); 16528 serializer.flush(); 16529 } catch (Exception e) { 16530 if (DEBUG_BACKUP) { 16531 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16532 } 16533 return null; 16534 } 16535 16536 return dataStream.toByteArray(); 16537 } 16538 16539 @Override 16540 public void restorePreferredActivities(byte[] backup, int userId) { 16541 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16542 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16543 } 16544 16545 try { 16546 final XmlPullParser parser = Xml.newPullParser(); 16547 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16548 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16549 new BlobXmlRestorer() { 16550 @Override 16551 public void apply(XmlPullParser parser, int userId) 16552 throws XmlPullParserException, IOException { 16553 synchronized (mPackages) { 16554 mSettings.readPreferredActivitiesLPw(parser, userId); 16555 } 16556 } 16557 } ); 16558 } catch (Exception e) { 16559 if (DEBUG_BACKUP) { 16560 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16561 } 16562 } 16563 } 16564 16565 /** 16566 * Non-Binder method, support for the backup/restore mechanism: write the 16567 * default browser (etc) settings in its canonical XML format. Returns the default 16568 * browser XML representation as a byte array, or null if there is none. 16569 */ 16570 @Override 16571 public byte[] getDefaultAppsBackup(int userId) { 16572 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16573 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16574 } 16575 16576 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16577 try { 16578 final XmlSerializer serializer = new FastXmlSerializer(); 16579 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16580 serializer.startDocument(null, true); 16581 serializer.startTag(null, TAG_DEFAULT_APPS); 16582 16583 synchronized (mPackages) { 16584 mSettings.writeDefaultAppsLPr(serializer, userId); 16585 } 16586 16587 serializer.endTag(null, TAG_DEFAULT_APPS); 16588 serializer.endDocument(); 16589 serializer.flush(); 16590 } catch (Exception e) { 16591 if (DEBUG_BACKUP) { 16592 Slog.e(TAG, "Unable to write default apps for backup", e); 16593 } 16594 return null; 16595 } 16596 16597 return dataStream.toByteArray(); 16598 } 16599 16600 @Override 16601 public void restoreDefaultApps(byte[] backup, int userId) { 16602 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16603 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16604 } 16605 16606 try { 16607 final XmlPullParser parser = Xml.newPullParser(); 16608 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16609 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16610 new BlobXmlRestorer() { 16611 @Override 16612 public void apply(XmlPullParser parser, int userId) 16613 throws XmlPullParserException, IOException { 16614 synchronized (mPackages) { 16615 mSettings.readDefaultAppsLPw(parser, userId); 16616 } 16617 } 16618 } ); 16619 } catch (Exception e) { 16620 if (DEBUG_BACKUP) { 16621 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16622 } 16623 } 16624 } 16625 16626 @Override 16627 public byte[] getIntentFilterVerificationBackup(int userId) { 16628 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16629 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16630 } 16631 16632 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16633 try { 16634 final XmlSerializer serializer = new FastXmlSerializer(); 16635 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16636 serializer.startDocument(null, true); 16637 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16638 16639 synchronized (mPackages) { 16640 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16641 } 16642 16643 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16644 serializer.endDocument(); 16645 serializer.flush(); 16646 } catch (Exception e) { 16647 if (DEBUG_BACKUP) { 16648 Slog.e(TAG, "Unable to write default apps for backup", e); 16649 } 16650 return null; 16651 } 16652 16653 return dataStream.toByteArray(); 16654 } 16655 16656 @Override 16657 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16658 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16659 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16660 } 16661 16662 try { 16663 final XmlPullParser parser = Xml.newPullParser(); 16664 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16665 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16666 new BlobXmlRestorer() { 16667 @Override 16668 public void apply(XmlPullParser parser, int userId) 16669 throws XmlPullParserException, IOException { 16670 synchronized (mPackages) { 16671 mSettings.readAllDomainVerificationsLPr(parser, userId); 16672 mSettings.writeLPr(); 16673 } 16674 } 16675 } ); 16676 } catch (Exception e) { 16677 if (DEBUG_BACKUP) { 16678 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16679 } 16680 } 16681 } 16682 16683 @Override 16684 public byte[] getPermissionGrantBackup(int userId) { 16685 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16686 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16687 } 16688 16689 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16690 try { 16691 final XmlSerializer serializer = new FastXmlSerializer(); 16692 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16693 serializer.startDocument(null, true); 16694 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16695 16696 synchronized (mPackages) { 16697 serializeRuntimePermissionGrantsLPr(serializer, userId); 16698 } 16699 16700 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16701 serializer.endDocument(); 16702 serializer.flush(); 16703 } catch (Exception e) { 16704 if (DEBUG_BACKUP) { 16705 Slog.e(TAG, "Unable to write default apps for backup", e); 16706 } 16707 return null; 16708 } 16709 16710 return dataStream.toByteArray(); 16711 } 16712 16713 @Override 16714 public void restorePermissionGrants(byte[] backup, int userId) { 16715 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16716 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16717 } 16718 16719 try { 16720 final XmlPullParser parser = Xml.newPullParser(); 16721 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16722 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16723 new BlobXmlRestorer() { 16724 @Override 16725 public void apply(XmlPullParser parser, int userId) 16726 throws XmlPullParserException, IOException { 16727 synchronized (mPackages) { 16728 processRestoredPermissionGrantsLPr(parser, userId); 16729 } 16730 } 16731 } ); 16732 } catch (Exception e) { 16733 if (DEBUG_BACKUP) { 16734 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16735 } 16736 } 16737 } 16738 16739 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16740 throws IOException { 16741 serializer.startTag(null, TAG_ALL_GRANTS); 16742 16743 final int N = mSettings.mPackages.size(); 16744 for (int i = 0; i < N; i++) { 16745 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16746 boolean pkgGrantsKnown = false; 16747 16748 PermissionsState packagePerms = ps.getPermissionsState(); 16749 16750 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16751 final int grantFlags = state.getFlags(); 16752 // only look at grants that are not system/policy fixed 16753 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16754 final boolean isGranted = state.isGranted(); 16755 // And only back up the user-twiddled state bits 16756 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16757 final String packageName = mSettings.mPackages.keyAt(i); 16758 if (!pkgGrantsKnown) { 16759 serializer.startTag(null, TAG_GRANT); 16760 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16761 pkgGrantsKnown = true; 16762 } 16763 16764 final boolean userSet = 16765 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16766 final boolean userFixed = 16767 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16768 final boolean revoke = 16769 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16770 16771 serializer.startTag(null, TAG_PERMISSION); 16772 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16773 if (isGranted) { 16774 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16775 } 16776 if (userSet) { 16777 serializer.attribute(null, ATTR_USER_SET, "true"); 16778 } 16779 if (userFixed) { 16780 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16781 } 16782 if (revoke) { 16783 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16784 } 16785 serializer.endTag(null, TAG_PERMISSION); 16786 } 16787 } 16788 } 16789 16790 if (pkgGrantsKnown) { 16791 serializer.endTag(null, TAG_GRANT); 16792 } 16793 } 16794 16795 serializer.endTag(null, TAG_ALL_GRANTS); 16796 } 16797 16798 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16799 throws XmlPullParserException, IOException { 16800 String pkgName = null; 16801 int outerDepth = parser.getDepth(); 16802 int type; 16803 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16804 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16805 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16806 continue; 16807 } 16808 16809 final String tagName = parser.getName(); 16810 if (tagName.equals(TAG_GRANT)) { 16811 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16812 if (DEBUG_BACKUP) { 16813 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16814 } 16815 } else if (tagName.equals(TAG_PERMISSION)) { 16816 16817 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16818 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16819 16820 int newFlagSet = 0; 16821 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16822 newFlagSet |= FLAG_PERMISSION_USER_SET; 16823 } 16824 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16825 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16826 } 16827 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16828 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16829 } 16830 if (DEBUG_BACKUP) { 16831 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16832 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16833 } 16834 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16835 if (ps != null) { 16836 // Already installed so we apply the grant immediately 16837 if (DEBUG_BACKUP) { 16838 Slog.v(TAG, " + already installed; applying"); 16839 } 16840 PermissionsState perms = ps.getPermissionsState(); 16841 BasePermission bp = mSettings.mPermissions.get(permName); 16842 if (bp != null) { 16843 if (isGranted) { 16844 perms.grantRuntimePermission(bp, userId); 16845 } 16846 if (newFlagSet != 0) { 16847 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16848 } 16849 } 16850 } else { 16851 // Need to wait for post-restore install to apply the grant 16852 if (DEBUG_BACKUP) { 16853 Slog.v(TAG, " - not yet installed; saving for later"); 16854 } 16855 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16856 isGranted, newFlagSet, userId); 16857 } 16858 } else { 16859 PackageManagerService.reportSettingsProblem(Log.WARN, 16860 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16861 XmlUtils.skipCurrentTag(parser); 16862 } 16863 } 16864 16865 scheduleWriteSettingsLocked(); 16866 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16867 } 16868 16869 @Override 16870 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16871 int sourceUserId, int targetUserId, int flags) { 16872 mContext.enforceCallingOrSelfPermission( 16873 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16874 int callingUid = Binder.getCallingUid(); 16875 enforceOwnerRights(ownerPackage, callingUid); 16876 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16877 if (intentFilter.countActions() == 0) { 16878 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16879 return; 16880 } 16881 synchronized (mPackages) { 16882 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16883 ownerPackage, targetUserId, flags); 16884 CrossProfileIntentResolver resolver = 16885 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16886 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16887 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16888 if (existing != null) { 16889 int size = existing.size(); 16890 for (int i = 0; i < size; i++) { 16891 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16892 return; 16893 } 16894 } 16895 } 16896 resolver.addFilter(newFilter); 16897 scheduleWritePackageRestrictionsLocked(sourceUserId); 16898 } 16899 } 16900 16901 @Override 16902 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16903 mContext.enforceCallingOrSelfPermission( 16904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16905 int callingUid = Binder.getCallingUid(); 16906 enforceOwnerRights(ownerPackage, callingUid); 16907 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16908 synchronized (mPackages) { 16909 CrossProfileIntentResolver resolver = 16910 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16911 ArraySet<CrossProfileIntentFilter> set = 16912 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16913 for (CrossProfileIntentFilter filter : set) { 16914 if (filter.getOwnerPackage().equals(ownerPackage)) { 16915 resolver.removeFilter(filter); 16916 } 16917 } 16918 scheduleWritePackageRestrictionsLocked(sourceUserId); 16919 } 16920 } 16921 16922 // Enforcing that callingUid is owning pkg on userId 16923 private void enforceOwnerRights(String pkg, int callingUid) { 16924 // The system owns everything. 16925 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16926 return; 16927 } 16928 int callingUserId = UserHandle.getUserId(callingUid); 16929 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16930 if (pi == null) { 16931 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16932 + callingUserId); 16933 } 16934 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16935 throw new SecurityException("Calling uid " + callingUid 16936 + " does not own package " + pkg); 16937 } 16938 } 16939 16940 @Override 16941 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16942 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16943 } 16944 16945 private Intent getHomeIntent() { 16946 Intent intent = new Intent(Intent.ACTION_MAIN); 16947 intent.addCategory(Intent.CATEGORY_HOME); 16948 return intent; 16949 } 16950 16951 private IntentFilter getHomeFilter() { 16952 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16953 filter.addCategory(Intent.CATEGORY_HOME); 16954 filter.addCategory(Intent.CATEGORY_DEFAULT); 16955 return filter; 16956 } 16957 16958 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16959 int userId) { 16960 Intent intent = getHomeIntent(); 16961 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16962 PackageManager.GET_META_DATA, userId); 16963 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16964 true, false, false, userId); 16965 16966 allHomeCandidates.clear(); 16967 if (list != null) { 16968 for (ResolveInfo ri : list) { 16969 allHomeCandidates.add(ri); 16970 } 16971 } 16972 return (preferred == null || preferred.activityInfo == null) 16973 ? null 16974 : new ComponentName(preferred.activityInfo.packageName, 16975 preferred.activityInfo.name); 16976 } 16977 16978 @Override 16979 public void setHomeActivity(ComponentName comp, int userId) { 16980 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16981 getHomeActivitiesAsUser(homeActivities, userId); 16982 16983 boolean found = false; 16984 16985 final int size = homeActivities.size(); 16986 final ComponentName[] set = new ComponentName[size]; 16987 for (int i = 0; i < size; i++) { 16988 final ResolveInfo candidate = homeActivities.get(i); 16989 final ActivityInfo info = candidate.activityInfo; 16990 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16991 set[i] = activityName; 16992 if (!found && activityName.equals(comp)) { 16993 found = true; 16994 } 16995 } 16996 if (!found) { 16997 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16998 + userId); 16999 } 17000 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17001 set, comp, userId); 17002 } 17003 17004 private @Nullable String getSetupWizardPackageName() { 17005 final Intent intent = new Intent(Intent.ACTION_MAIN); 17006 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17007 17008 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17009 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17010 | MATCH_DISABLED_COMPONENTS, 17011 UserHandle.myUserId()); 17012 if (matches.size() == 1) { 17013 return matches.get(0).getComponentInfo().packageName; 17014 } else { 17015 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17016 + ": matches=" + matches); 17017 return null; 17018 } 17019 } 17020 17021 @Override 17022 public void setApplicationEnabledSetting(String appPackageName, 17023 int newState, int flags, int userId, String callingPackage) { 17024 if (!sUserManager.exists(userId)) return; 17025 if (callingPackage == null) { 17026 callingPackage = Integer.toString(Binder.getCallingUid()); 17027 } 17028 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17029 } 17030 17031 @Override 17032 public void setComponentEnabledSetting(ComponentName componentName, 17033 int newState, int flags, int userId) { 17034 if (!sUserManager.exists(userId)) return; 17035 setEnabledSetting(componentName.getPackageName(), 17036 componentName.getClassName(), newState, flags, userId, null); 17037 } 17038 17039 private void setEnabledSetting(final String packageName, String className, int newState, 17040 final int flags, int userId, String callingPackage) { 17041 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17042 || newState == COMPONENT_ENABLED_STATE_ENABLED 17043 || newState == COMPONENT_ENABLED_STATE_DISABLED 17044 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17045 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17046 throw new IllegalArgumentException("Invalid new component state: " 17047 + newState); 17048 } 17049 PackageSetting pkgSetting; 17050 final int uid = Binder.getCallingUid(); 17051 final int permission = mContext.checkCallingOrSelfPermission( 17052 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17053 enforceCrossUserPermission(uid, userId, 17054 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17055 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17056 boolean sendNow = false; 17057 boolean isApp = (className == null); 17058 String componentName = isApp ? packageName : className; 17059 int packageUid = -1; 17060 ArrayList<String> components; 17061 17062 // writer 17063 synchronized (mPackages) { 17064 pkgSetting = mSettings.mPackages.get(packageName); 17065 if (pkgSetting == null) { 17066 if (className == null) { 17067 throw new IllegalArgumentException("Unknown package: " + packageName); 17068 } 17069 throw new IllegalArgumentException( 17070 "Unknown component: " + packageName + "/" + className); 17071 } 17072 // Allow root and verify that userId is not being specified by a different user 17073 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17074 throw new SecurityException( 17075 "Permission Denial: attempt to change component state from pid=" 17076 + Binder.getCallingPid() 17077 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17078 } 17079 if (className == null) { 17080 // We're dealing with an application/package level state change 17081 if (pkgSetting.getEnabled(userId) == newState) { 17082 // Nothing to do 17083 return; 17084 } 17085 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17086 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17087 // Don't care about who enables an app. 17088 callingPackage = null; 17089 } 17090 pkgSetting.setEnabled(newState, userId, callingPackage); 17091 // pkgSetting.pkg.mSetEnabled = newState; 17092 } else { 17093 // We're dealing with a component level state change 17094 // First, verify that this is a valid class name. 17095 PackageParser.Package pkg = pkgSetting.pkg; 17096 if (pkg == null || !pkg.hasComponentClassName(className)) { 17097 if (pkg != null && 17098 pkg.applicationInfo.targetSdkVersion >= 17099 Build.VERSION_CODES.JELLY_BEAN) { 17100 throw new IllegalArgumentException("Component class " + className 17101 + " does not exist in " + packageName); 17102 } else { 17103 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17104 + className + " does not exist in " + packageName); 17105 } 17106 } 17107 switch (newState) { 17108 case COMPONENT_ENABLED_STATE_ENABLED: 17109 if (!pkgSetting.enableComponentLPw(className, userId)) { 17110 return; 17111 } 17112 break; 17113 case COMPONENT_ENABLED_STATE_DISABLED: 17114 if (!pkgSetting.disableComponentLPw(className, userId)) { 17115 return; 17116 } 17117 break; 17118 case COMPONENT_ENABLED_STATE_DEFAULT: 17119 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17120 return; 17121 } 17122 break; 17123 default: 17124 Slog.e(TAG, "Invalid new component state: " + newState); 17125 return; 17126 } 17127 } 17128 scheduleWritePackageRestrictionsLocked(userId); 17129 components = mPendingBroadcasts.get(userId, packageName); 17130 final boolean newPackage = components == null; 17131 if (newPackage) { 17132 components = new ArrayList<String>(); 17133 } 17134 if (!components.contains(componentName)) { 17135 components.add(componentName); 17136 } 17137 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17138 sendNow = true; 17139 // Purge entry from pending broadcast list if another one exists already 17140 // since we are sending one right away. 17141 mPendingBroadcasts.remove(userId, packageName); 17142 } else { 17143 if (newPackage) { 17144 mPendingBroadcasts.put(userId, packageName, components); 17145 } 17146 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17147 // Schedule a message 17148 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17149 } 17150 } 17151 } 17152 17153 long callingId = Binder.clearCallingIdentity(); 17154 try { 17155 if (sendNow) { 17156 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17157 sendPackageChangedBroadcast(packageName, 17158 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17159 } 17160 } finally { 17161 Binder.restoreCallingIdentity(callingId); 17162 } 17163 } 17164 17165 @Override 17166 public void flushPackageRestrictionsAsUser(int userId) { 17167 if (!sUserManager.exists(userId)) { 17168 return; 17169 } 17170 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17171 false /* checkShell */, "flushPackageRestrictions"); 17172 synchronized (mPackages) { 17173 mSettings.writePackageRestrictionsLPr(userId); 17174 mDirtyUsers.remove(userId); 17175 if (mDirtyUsers.isEmpty()) { 17176 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17177 } 17178 } 17179 } 17180 17181 private void sendPackageChangedBroadcast(String packageName, 17182 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17183 if (DEBUG_INSTALL) 17184 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17185 + componentNames); 17186 Bundle extras = new Bundle(4); 17187 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17188 String nameList[] = new String[componentNames.size()]; 17189 componentNames.toArray(nameList); 17190 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17191 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17192 extras.putInt(Intent.EXTRA_UID, packageUid); 17193 // If this is not reporting a change of the overall package, then only send it 17194 // to registered receivers. We don't want to launch a swath of apps for every 17195 // little component state change. 17196 final int flags = !componentNames.contains(packageName) 17197 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17198 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17199 new int[] {UserHandle.getUserId(packageUid)}); 17200 } 17201 17202 @Override 17203 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17204 if (!sUserManager.exists(userId)) return; 17205 final int uid = Binder.getCallingUid(); 17206 final int permission = mContext.checkCallingOrSelfPermission( 17207 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17208 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17209 enforceCrossUserPermission(uid, userId, 17210 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17211 // writer 17212 synchronized (mPackages) { 17213 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17214 allowedByPermission, uid, userId)) { 17215 scheduleWritePackageRestrictionsLocked(userId); 17216 } 17217 } 17218 } 17219 17220 @Override 17221 public String getInstallerPackageName(String packageName) { 17222 // reader 17223 synchronized (mPackages) { 17224 return mSettings.getInstallerPackageNameLPr(packageName); 17225 } 17226 } 17227 17228 @Override 17229 public int getApplicationEnabledSetting(String packageName, int userId) { 17230 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17231 int uid = Binder.getCallingUid(); 17232 enforceCrossUserPermission(uid, userId, 17233 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17234 // reader 17235 synchronized (mPackages) { 17236 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17237 } 17238 } 17239 17240 @Override 17241 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17242 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17243 int uid = Binder.getCallingUid(); 17244 enforceCrossUserPermission(uid, userId, 17245 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17246 // reader 17247 synchronized (mPackages) { 17248 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17249 } 17250 } 17251 17252 @Override 17253 public void enterSafeMode() { 17254 enforceSystemOrRoot("Only the system can request entering safe mode"); 17255 17256 if (!mSystemReady) { 17257 mSafeMode = true; 17258 } 17259 } 17260 17261 @Override 17262 public void systemReady() { 17263 mSystemReady = true; 17264 17265 // Read the compatibilty setting when the system is ready. 17266 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17267 mContext.getContentResolver(), 17268 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17269 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17270 if (DEBUG_SETTINGS) { 17271 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17272 } 17273 17274 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17275 17276 synchronized (mPackages) { 17277 // Verify that all of the preferred activity components actually 17278 // exist. It is possible for applications to be updated and at 17279 // that point remove a previously declared activity component that 17280 // had been set as a preferred activity. We try to clean this up 17281 // the next time we encounter that preferred activity, but it is 17282 // possible for the user flow to never be able to return to that 17283 // situation so here we do a sanity check to make sure we haven't 17284 // left any junk around. 17285 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17286 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17287 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17288 removed.clear(); 17289 for (PreferredActivity pa : pir.filterSet()) { 17290 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17291 removed.add(pa); 17292 } 17293 } 17294 if (removed.size() > 0) { 17295 for (int r=0; r<removed.size(); r++) { 17296 PreferredActivity pa = removed.get(r); 17297 Slog.w(TAG, "Removing dangling preferred activity: " 17298 + pa.mPref.mComponent); 17299 pir.removeFilter(pa); 17300 } 17301 mSettings.writePackageRestrictionsLPr( 17302 mSettings.mPreferredActivities.keyAt(i)); 17303 } 17304 } 17305 17306 for (int userId : UserManagerService.getInstance().getUserIds()) { 17307 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17308 grantPermissionsUserIds = ArrayUtils.appendInt( 17309 grantPermissionsUserIds, userId); 17310 } 17311 } 17312 } 17313 sUserManager.systemReady(); 17314 17315 // If we upgraded grant all default permissions before kicking off. 17316 for (int userId : grantPermissionsUserIds) { 17317 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17318 } 17319 17320 // Kick off any messages waiting for system ready 17321 if (mPostSystemReadyMessages != null) { 17322 for (Message msg : mPostSystemReadyMessages) { 17323 msg.sendToTarget(); 17324 } 17325 mPostSystemReadyMessages = null; 17326 } 17327 17328 // Watch for external volumes that come and go over time 17329 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17330 storage.registerListener(mStorageListener); 17331 17332 mInstallerService.systemReady(); 17333 mPackageDexOptimizer.systemReady(); 17334 17335 MountServiceInternal mountServiceInternal = LocalServices.getService( 17336 MountServiceInternal.class); 17337 mountServiceInternal.addExternalStoragePolicy( 17338 new MountServiceInternal.ExternalStorageMountPolicy() { 17339 @Override 17340 public int getMountMode(int uid, String packageName) { 17341 if (Process.isIsolated(uid)) { 17342 return Zygote.MOUNT_EXTERNAL_NONE; 17343 } 17344 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17345 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17346 } 17347 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17348 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17349 } 17350 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17351 return Zygote.MOUNT_EXTERNAL_READ; 17352 } 17353 return Zygote.MOUNT_EXTERNAL_WRITE; 17354 } 17355 17356 @Override 17357 public boolean hasExternalStorage(int uid, String packageName) { 17358 return true; 17359 } 17360 }); 17361 } 17362 17363 @Override 17364 public boolean isSafeMode() { 17365 return mSafeMode; 17366 } 17367 17368 @Override 17369 public boolean hasSystemUidErrors() { 17370 return mHasSystemUidErrors; 17371 } 17372 17373 static String arrayToString(int[] array) { 17374 StringBuffer buf = new StringBuffer(128); 17375 buf.append('['); 17376 if (array != null) { 17377 for (int i=0; i<array.length; i++) { 17378 if (i > 0) buf.append(", "); 17379 buf.append(array[i]); 17380 } 17381 } 17382 buf.append(']'); 17383 return buf.toString(); 17384 } 17385 17386 static class DumpState { 17387 public static final int DUMP_LIBS = 1 << 0; 17388 public static final int DUMP_FEATURES = 1 << 1; 17389 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17390 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17391 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17392 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17393 public static final int DUMP_PERMISSIONS = 1 << 6; 17394 public static final int DUMP_PACKAGES = 1 << 7; 17395 public static final int DUMP_SHARED_USERS = 1 << 8; 17396 public static final int DUMP_MESSAGES = 1 << 9; 17397 public static final int DUMP_PROVIDERS = 1 << 10; 17398 public static final int DUMP_VERIFIERS = 1 << 11; 17399 public static final int DUMP_PREFERRED = 1 << 12; 17400 public static final int DUMP_PREFERRED_XML = 1 << 13; 17401 public static final int DUMP_KEYSETS = 1 << 14; 17402 public static final int DUMP_VERSION = 1 << 15; 17403 public static final int DUMP_INSTALLS = 1 << 16; 17404 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17405 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17406 17407 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17408 17409 private int mTypes; 17410 17411 private int mOptions; 17412 17413 private boolean mTitlePrinted; 17414 17415 private SharedUserSetting mSharedUser; 17416 17417 public boolean isDumping(int type) { 17418 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17419 return true; 17420 } 17421 17422 return (mTypes & type) != 0; 17423 } 17424 17425 public void setDump(int type) { 17426 mTypes |= type; 17427 } 17428 17429 public boolean isOptionEnabled(int option) { 17430 return (mOptions & option) != 0; 17431 } 17432 17433 public void setOptionEnabled(int option) { 17434 mOptions |= option; 17435 } 17436 17437 public boolean onTitlePrinted() { 17438 final boolean printed = mTitlePrinted; 17439 mTitlePrinted = true; 17440 return printed; 17441 } 17442 17443 public boolean getTitlePrinted() { 17444 return mTitlePrinted; 17445 } 17446 17447 public void setTitlePrinted(boolean enabled) { 17448 mTitlePrinted = enabled; 17449 } 17450 17451 public SharedUserSetting getSharedUser() { 17452 return mSharedUser; 17453 } 17454 17455 public void setSharedUser(SharedUserSetting user) { 17456 mSharedUser = user; 17457 } 17458 } 17459 17460 @Override 17461 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17462 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17463 (new PackageManagerShellCommand(this)).exec( 17464 this, in, out, err, args, resultReceiver); 17465 } 17466 17467 @Override 17468 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17469 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17470 != PackageManager.PERMISSION_GRANTED) { 17471 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17472 + Binder.getCallingPid() 17473 + ", uid=" + Binder.getCallingUid() 17474 + " without permission " 17475 + android.Manifest.permission.DUMP); 17476 return; 17477 } 17478 17479 DumpState dumpState = new DumpState(); 17480 boolean fullPreferred = false; 17481 boolean checkin = false; 17482 17483 String packageName = null; 17484 ArraySet<String> permissionNames = null; 17485 17486 int opti = 0; 17487 while (opti < args.length) { 17488 String opt = args[opti]; 17489 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17490 break; 17491 } 17492 opti++; 17493 17494 if ("-a".equals(opt)) { 17495 // Right now we only know how to print all. 17496 } else if ("-h".equals(opt)) { 17497 pw.println("Package manager dump options:"); 17498 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17499 pw.println(" --checkin: dump for a checkin"); 17500 pw.println(" -f: print details of intent filters"); 17501 pw.println(" -h: print this help"); 17502 pw.println(" cmd may be one of:"); 17503 pw.println(" l[ibraries]: list known shared libraries"); 17504 pw.println(" f[eatures]: list device features"); 17505 pw.println(" k[eysets]: print known keysets"); 17506 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17507 pw.println(" perm[issions]: dump permissions"); 17508 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17509 pw.println(" pref[erred]: print preferred package settings"); 17510 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17511 pw.println(" prov[iders]: dump content providers"); 17512 pw.println(" p[ackages]: dump installed packages"); 17513 pw.println(" s[hared-users]: dump shared user IDs"); 17514 pw.println(" m[essages]: print collected runtime messages"); 17515 pw.println(" v[erifiers]: print package verifier info"); 17516 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17517 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17518 pw.println(" version: print database version info"); 17519 pw.println(" write: write current settings now"); 17520 pw.println(" installs: details about install sessions"); 17521 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17522 pw.println(" <package.name>: info about given package"); 17523 return; 17524 } else if ("--checkin".equals(opt)) { 17525 checkin = true; 17526 } else if ("-f".equals(opt)) { 17527 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17528 } else { 17529 pw.println("Unknown argument: " + opt + "; use -h for help"); 17530 } 17531 } 17532 17533 // Is the caller requesting to dump a particular piece of data? 17534 if (opti < args.length) { 17535 String cmd = args[opti]; 17536 opti++; 17537 // Is this a package name? 17538 if ("android".equals(cmd) || cmd.contains(".")) { 17539 packageName = cmd; 17540 // When dumping a single package, we always dump all of its 17541 // filter information since the amount of data will be reasonable. 17542 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17543 } else if ("check-permission".equals(cmd)) { 17544 if (opti >= args.length) { 17545 pw.println("Error: check-permission missing permission argument"); 17546 return; 17547 } 17548 String perm = args[opti]; 17549 opti++; 17550 if (opti >= args.length) { 17551 pw.println("Error: check-permission missing package argument"); 17552 return; 17553 } 17554 String pkg = args[opti]; 17555 opti++; 17556 int user = UserHandle.getUserId(Binder.getCallingUid()); 17557 if (opti < args.length) { 17558 try { 17559 user = Integer.parseInt(args[opti]); 17560 } catch (NumberFormatException e) { 17561 pw.println("Error: check-permission user argument is not a number: " 17562 + args[opti]); 17563 return; 17564 } 17565 } 17566 pw.println(checkPermission(perm, pkg, user)); 17567 return; 17568 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17569 dumpState.setDump(DumpState.DUMP_LIBS); 17570 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17571 dumpState.setDump(DumpState.DUMP_FEATURES); 17572 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17573 if (opti >= args.length) { 17574 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17575 | DumpState.DUMP_SERVICE_RESOLVERS 17576 | DumpState.DUMP_RECEIVER_RESOLVERS 17577 | DumpState.DUMP_CONTENT_RESOLVERS); 17578 } else { 17579 while (opti < args.length) { 17580 String name = args[opti]; 17581 if ("a".equals(name) || "activity".equals(name)) { 17582 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17583 } else if ("s".equals(name) || "service".equals(name)) { 17584 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17585 } else if ("r".equals(name) || "receiver".equals(name)) { 17586 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17587 } else if ("c".equals(name) || "content".equals(name)) { 17588 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17589 } else { 17590 pw.println("Error: unknown resolver table type: " + name); 17591 return; 17592 } 17593 opti++; 17594 } 17595 } 17596 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17597 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17598 } else if ("permission".equals(cmd)) { 17599 if (opti >= args.length) { 17600 pw.println("Error: permission requires permission name"); 17601 return; 17602 } 17603 permissionNames = new ArraySet<>(); 17604 while (opti < args.length) { 17605 permissionNames.add(args[opti]); 17606 opti++; 17607 } 17608 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17609 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17610 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17611 dumpState.setDump(DumpState.DUMP_PREFERRED); 17612 } else if ("preferred-xml".equals(cmd)) { 17613 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17614 if (opti < args.length && "--full".equals(args[opti])) { 17615 fullPreferred = true; 17616 opti++; 17617 } 17618 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17619 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17620 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17621 dumpState.setDump(DumpState.DUMP_PACKAGES); 17622 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17623 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17624 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17625 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17626 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17627 dumpState.setDump(DumpState.DUMP_MESSAGES); 17628 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17629 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17630 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17631 || "intent-filter-verifiers".equals(cmd)) { 17632 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17633 } else if ("version".equals(cmd)) { 17634 dumpState.setDump(DumpState.DUMP_VERSION); 17635 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17636 dumpState.setDump(DumpState.DUMP_KEYSETS); 17637 } else if ("installs".equals(cmd)) { 17638 dumpState.setDump(DumpState.DUMP_INSTALLS); 17639 } else if ("write".equals(cmd)) { 17640 synchronized (mPackages) { 17641 mSettings.writeLPr(); 17642 pw.println("Settings written."); 17643 return; 17644 } 17645 } 17646 } 17647 17648 if (checkin) { 17649 pw.println("vers,1"); 17650 } 17651 17652 // reader 17653 synchronized (mPackages) { 17654 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17655 if (!checkin) { 17656 if (dumpState.onTitlePrinted()) 17657 pw.println(); 17658 pw.println("Database versions:"); 17659 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17660 } 17661 } 17662 17663 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17664 if (!checkin) { 17665 if (dumpState.onTitlePrinted()) 17666 pw.println(); 17667 pw.println("Verifiers:"); 17668 pw.print(" Required: "); 17669 pw.print(mRequiredVerifierPackage); 17670 pw.print(" (uid="); 17671 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17672 UserHandle.USER_SYSTEM)); 17673 pw.println(")"); 17674 } else if (mRequiredVerifierPackage != null) { 17675 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17676 pw.print(","); 17677 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17678 UserHandle.USER_SYSTEM)); 17679 } 17680 } 17681 17682 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17683 packageName == null) { 17684 if (mIntentFilterVerifierComponent != null) { 17685 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17686 if (!checkin) { 17687 if (dumpState.onTitlePrinted()) 17688 pw.println(); 17689 pw.println("Intent Filter Verifier:"); 17690 pw.print(" Using: "); 17691 pw.print(verifierPackageName); 17692 pw.print(" (uid="); 17693 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17694 UserHandle.USER_SYSTEM)); 17695 pw.println(")"); 17696 } else if (verifierPackageName != null) { 17697 pw.print("ifv,"); pw.print(verifierPackageName); 17698 pw.print(","); 17699 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17700 UserHandle.USER_SYSTEM)); 17701 } 17702 } else { 17703 pw.println(); 17704 pw.println("No Intent Filter Verifier available!"); 17705 } 17706 } 17707 17708 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17709 boolean printedHeader = false; 17710 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17711 while (it.hasNext()) { 17712 String name = it.next(); 17713 SharedLibraryEntry ent = mSharedLibraries.get(name); 17714 if (!checkin) { 17715 if (!printedHeader) { 17716 if (dumpState.onTitlePrinted()) 17717 pw.println(); 17718 pw.println("Libraries:"); 17719 printedHeader = true; 17720 } 17721 pw.print(" "); 17722 } else { 17723 pw.print("lib,"); 17724 } 17725 pw.print(name); 17726 if (!checkin) { 17727 pw.print(" -> "); 17728 } 17729 if (ent.path != null) { 17730 if (!checkin) { 17731 pw.print("(jar) "); 17732 pw.print(ent.path); 17733 } else { 17734 pw.print(",jar,"); 17735 pw.print(ent.path); 17736 } 17737 } else { 17738 if (!checkin) { 17739 pw.print("(apk) "); 17740 pw.print(ent.apk); 17741 } else { 17742 pw.print(",apk,"); 17743 pw.print(ent.apk); 17744 } 17745 } 17746 pw.println(); 17747 } 17748 } 17749 17750 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17751 if (dumpState.onTitlePrinted()) 17752 pw.println(); 17753 if (!checkin) { 17754 pw.println("Features:"); 17755 } 17756 17757 for (FeatureInfo feat : mAvailableFeatures.values()) { 17758 if (checkin) { 17759 pw.print("feat,"); 17760 pw.print(feat.name); 17761 pw.print(","); 17762 pw.println(feat.version); 17763 } else { 17764 pw.print(" "); 17765 pw.print(feat.name); 17766 if (feat.version > 0) { 17767 pw.print(" version="); 17768 pw.print(feat.version); 17769 } 17770 pw.println(); 17771 } 17772 } 17773 } 17774 17775 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17776 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17777 : "Activity Resolver Table:", " ", packageName, 17778 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17779 dumpState.setTitlePrinted(true); 17780 } 17781 } 17782 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17783 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17784 : "Receiver Resolver Table:", " ", packageName, 17785 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17786 dumpState.setTitlePrinted(true); 17787 } 17788 } 17789 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17790 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17791 : "Service Resolver Table:", " ", packageName, 17792 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17793 dumpState.setTitlePrinted(true); 17794 } 17795 } 17796 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17797 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17798 : "Provider Resolver Table:", " ", packageName, 17799 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17800 dumpState.setTitlePrinted(true); 17801 } 17802 } 17803 17804 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17805 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17806 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17807 int user = mSettings.mPreferredActivities.keyAt(i); 17808 if (pir.dump(pw, 17809 dumpState.getTitlePrinted() 17810 ? "\nPreferred Activities User " + user + ":" 17811 : "Preferred Activities User " + user + ":", " ", 17812 packageName, true, false)) { 17813 dumpState.setTitlePrinted(true); 17814 } 17815 } 17816 } 17817 17818 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17819 pw.flush(); 17820 FileOutputStream fout = new FileOutputStream(fd); 17821 BufferedOutputStream str = new BufferedOutputStream(fout); 17822 XmlSerializer serializer = new FastXmlSerializer(); 17823 try { 17824 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17825 serializer.startDocument(null, true); 17826 serializer.setFeature( 17827 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17828 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17829 serializer.endDocument(); 17830 serializer.flush(); 17831 } catch (IllegalArgumentException e) { 17832 pw.println("Failed writing: " + e); 17833 } catch (IllegalStateException e) { 17834 pw.println("Failed writing: " + e); 17835 } catch (IOException e) { 17836 pw.println("Failed writing: " + e); 17837 } 17838 } 17839 17840 if (!checkin 17841 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17842 && packageName == null) { 17843 pw.println(); 17844 int count = mSettings.mPackages.size(); 17845 if (count == 0) { 17846 pw.println("No applications!"); 17847 pw.println(); 17848 } else { 17849 final String prefix = " "; 17850 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17851 if (allPackageSettings.size() == 0) { 17852 pw.println("No domain preferred apps!"); 17853 pw.println(); 17854 } else { 17855 pw.println("App verification status:"); 17856 pw.println(); 17857 count = 0; 17858 for (PackageSetting ps : allPackageSettings) { 17859 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17860 if (ivi == null || ivi.getPackageName() == null) continue; 17861 pw.println(prefix + "Package: " + ivi.getPackageName()); 17862 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17863 pw.println(prefix + "Status: " + ivi.getStatusString()); 17864 pw.println(); 17865 count++; 17866 } 17867 if (count == 0) { 17868 pw.println(prefix + "No app verification established."); 17869 pw.println(); 17870 } 17871 for (int userId : sUserManager.getUserIds()) { 17872 pw.println("App linkages for user " + userId + ":"); 17873 pw.println(); 17874 count = 0; 17875 for (PackageSetting ps : allPackageSettings) { 17876 final long status = ps.getDomainVerificationStatusForUser(userId); 17877 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17878 continue; 17879 } 17880 pw.println(prefix + "Package: " + ps.name); 17881 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17882 String statusStr = IntentFilterVerificationInfo. 17883 getStatusStringFromValue(status); 17884 pw.println(prefix + "Status: " + statusStr); 17885 pw.println(); 17886 count++; 17887 } 17888 if (count == 0) { 17889 pw.println(prefix + "No configured app linkages."); 17890 pw.println(); 17891 } 17892 } 17893 } 17894 } 17895 } 17896 17897 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17898 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17899 if (packageName == null && permissionNames == null) { 17900 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17901 if (iperm == 0) { 17902 if (dumpState.onTitlePrinted()) 17903 pw.println(); 17904 pw.println("AppOp Permissions:"); 17905 } 17906 pw.print(" AppOp Permission "); 17907 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17908 pw.println(":"); 17909 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17910 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17911 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17912 } 17913 } 17914 } 17915 } 17916 17917 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17918 boolean printedSomething = false; 17919 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17920 if (packageName != null && !packageName.equals(p.info.packageName)) { 17921 continue; 17922 } 17923 if (!printedSomething) { 17924 if (dumpState.onTitlePrinted()) 17925 pw.println(); 17926 pw.println("Registered ContentProviders:"); 17927 printedSomething = true; 17928 } 17929 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17930 pw.print(" "); pw.println(p.toString()); 17931 } 17932 printedSomething = false; 17933 for (Map.Entry<String, PackageParser.Provider> entry : 17934 mProvidersByAuthority.entrySet()) { 17935 PackageParser.Provider p = entry.getValue(); 17936 if (packageName != null && !packageName.equals(p.info.packageName)) { 17937 continue; 17938 } 17939 if (!printedSomething) { 17940 if (dumpState.onTitlePrinted()) 17941 pw.println(); 17942 pw.println("ContentProvider Authorities:"); 17943 printedSomething = true; 17944 } 17945 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17946 pw.print(" "); pw.println(p.toString()); 17947 if (p.info != null && p.info.applicationInfo != null) { 17948 final String appInfo = p.info.applicationInfo.toString(); 17949 pw.print(" applicationInfo="); pw.println(appInfo); 17950 } 17951 } 17952 } 17953 17954 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17955 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17956 } 17957 17958 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17959 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17960 } 17961 17962 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17963 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17964 } 17965 17966 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17967 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17968 } 17969 17970 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17971 // XXX should handle packageName != null by dumping only install data that 17972 // the given package is involved with. 17973 if (dumpState.onTitlePrinted()) pw.println(); 17974 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17975 } 17976 17977 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17978 if (dumpState.onTitlePrinted()) pw.println(); 17979 mSettings.dumpReadMessagesLPr(pw, dumpState); 17980 17981 pw.println(); 17982 pw.println("Package warning messages:"); 17983 BufferedReader in = null; 17984 String line = null; 17985 try { 17986 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17987 while ((line = in.readLine()) != null) { 17988 if (line.contains("ignored: updated version")) continue; 17989 pw.println(line); 17990 } 17991 } catch (IOException ignored) { 17992 } finally { 17993 IoUtils.closeQuietly(in); 17994 } 17995 } 17996 17997 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17998 BufferedReader in = null; 17999 String line = null; 18000 try { 18001 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18002 while ((line = in.readLine()) != null) { 18003 if (line.contains("ignored: updated version")) continue; 18004 pw.print("msg,"); 18005 pw.println(line); 18006 } 18007 } catch (IOException ignored) { 18008 } finally { 18009 IoUtils.closeQuietly(in); 18010 } 18011 } 18012 } 18013 } 18014 18015 private String dumpDomainString(String packageName) { 18016 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18017 .getList(); 18018 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18019 18020 ArraySet<String> result = new ArraySet<>(); 18021 if (iviList.size() > 0) { 18022 for (IntentFilterVerificationInfo ivi : iviList) { 18023 for (String host : ivi.getDomains()) { 18024 result.add(host); 18025 } 18026 } 18027 } 18028 if (filters != null && filters.size() > 0) { 18029 for (IntentFilter filter : filters) { 18030 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18031 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18032 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18033 result.addAll(filter.getHostsList()); 18034 } 18035 } 18036 } 18037 18038 StringBuilder sb = new StringBuilder(result.size() * 16); 18039 for (String domain : result) { 18040 if (sb.length() > 0) sb.append(" "); 18041 sb.append(domain); 18042 } 18043 return sb.toString(); 18044 } 18045 18046 // ------- apps on sdcard specific code ------- 18047 static final boolean DEBUG_SD_INSTALL = false; 18048 18049 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18050 18051 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18052 18053 private boolean mMediaMounted = false; 18054 18055 static String getEncryptKey() { 18056 try { 18057 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18058 SD_ENCRYPTION_KEYSTORE_NAME); 18059 if (sdEncKey == null) { 18060 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18061 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18062 if (sdEncKey == null) { 18063 Slog.e(TAG, "Failed to create encryption keys"); 18064 return null; 18065 } 18066 } 18067 return sdEncKey; 18068 } catch (NoSuchAlgorithmException nsae) { 18069 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18070 return null; 18071 } catch (IOException ioe) { 18072 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18073 return null; 18074 } 18075 } 18076 18077 /* 18078 * Update media status on PackageManager. 18079 */ 18080 @Override 18081 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18082 int callingUid = Binder.getCallingUid(); 18083 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18084 throw new SecurityException("Media status can only be updated by the system"); 18085 } 18086 // reader; this apparently protects mMediaMounted, but should probably 18087 // be a different lock in that case. 18088 synchronized (mPackages) { 18089 Log.i(TAG, "Updating external media status from " 18090 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18091 + (mediaStatus ? "mounted" : "unmounted")); 18092 if (DEBUG_SD_INSTALL) 18093 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18094 + ", mMediaMounted=" + mMediaMounted); 18095 if (mediaStatus == mMediaMounted) { 18096 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18097 : 0, -1); 18098 mHandler.sendMessage(msg); 18099 return; 18100 } 18101 mMediaMounted = mediaStatus; 18102 } 18103 // Queue up an async operation since the package installation may take a 18104 // little while. 18105 mHandler.post(new Runnable() { 18106 public void run() { 18107 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18108 } 18109 }); 18110 } 18111 18112 /** 18113 * Called by MountService when the initial ASECs to scan are available. 18114 * Should block until all the ASEC containers are finished being scanned. 18115 */ 18116 public void scanAvailableAsecs() { 18117 updateExternalMediaStatusInner(true, false, false); 18118 } 18119 18120 /* 18121 * Collect information of applications on external media, map them against 18122 * existing containers and update information based on current mount status. 18123 * Please note that we always have to report status if reportStatus has been 18124 * set to true especially when unloading packages. 18125 */ 18126 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18127 boolean externalStorage) { 18128 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18129 int[] uidArr = EmptyArray.INT; 18130 18131 final String[] list = PackageHelper.getSecureContainerList(); 18132 if (ArrayUtils.isEmpty(list)) { 18133 Log.i(TAG, "No secure containers found"); 18134 } else { 18135 // Process list of secure containers and categorize them 18136 // as active or stale based on their package internal state. 18137 18138 // reader 18139 synchronized (mPackages) { 18140 for (String cid : list) { 18141 // Leave stages untouched for now; installer service owns them 18142 if (PackageInstallerService.isStageName(cid)) continue; 18143 18144 if (DEBUG_SD_INSTALL) 18145 Log.i(TAG, "Processing container " + cid); 18146 String pkgName = getAsecPackageName(cid); 18147 if (pkgName == null) { 18148 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18149 continue; 18150 } 18151 if (DEBUG_SD_INSTALL) 18152 Log.i(TAG, "Looking for pkg : " + pkgName); 18153 18154 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18155 if (ps == null) { 18156 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18157 continue; 18158 } 18159 18160 /* 18161 * Skip packages that are not external if we're unmounting 18162 * external storage. 18163 */ 18164 if (externalStorage && !isMounted && !isExternal(ps)) { 18165 continue; 18166 } 18167 18168 final AsecInstallArgs args = new AsecInstallArgs(cid, 18169 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18170 // The package status is changed only if the code path 18171 // matches between settings and the container id. 18172 if (ps.codePathString != null 18173 && ps.codePathString.startsWith(args.getCodePath())) { 18174 if (DEBUG_SD_INSTALL) { 18175 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18176 + " at code path: " + ps.codePathString); 18177 } 18178 18179 // We do have a valid package installed on sdcard 18180 processCids.put(args, ps.codePathString); 18181 final int uid = ps.appId; 18182 if (uid != -1) { 18183 uidArr = ArrayUtils.appendInt(uidArr, uid); 18184 } 18185 } else { 18186 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18187 + ps.codePathString); 18188 } 18189 } 18190 } 18191 18192 Arrays.sort(uidArr); 18193 } 18194 18195 // Process packages with valid entries. 18196 if (isMounted) { 18197 if (DEBUG_SD_INSTALL) 18198 Log.i(TAG, "Loading packages"); 18199 loadMediaPackages(processCids, uidArr, externalStorage); 18200 startCleaningPackages(); 18201 mInstallerService.onSecureContainersAvailable(); 18202 } else { 18203 if (DEBUG_SD_INSTALL) 18204 Log.i(TAG, "Unloading packages"); 18205 unloadMediaPackages(processCids, uidArr, reportStatus); 18206 } 18207 } 18208 18209 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18210 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18211 final int size = infos.size(); 18212 final String[] packageNames = new String[size]; 18213 final int[] packageUids = new int[size]; 18214 for (int i = 0; i < size; i++) { 18215 final ApplicationInfo info = infos.get(i); 18216 packageNames[i] = info.packageName; 18217 packageUids[i] = info.uid; 18218 } 18219 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18220 finishedReceiver); 18221 } 18222 18223 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18224 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18225 sendResourcesChangedBroadcast(mediaStatus, replacing, 18226 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18227 } 18228 18229 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18230 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18231 int size = pkgList.length; 18232 if (size > 0) { 18233 // Send broadcasts here 18234 Bundle extras = new Bundle(); 18235 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18236 if (uidArr != null) { 18237 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18238 } 18239 if (replacing) { 18240 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18241 } 18242 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18243 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18244 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18245 } 18246 } 18247 18248 /* 18249 * Look at potentially valid container ids from processCids If package 18250 * information doesn't match the one on record or package scanning fails, 18251 * the cid is added to list of removeCids. We currently don't delete stale 18252 * containers. 18253 */ 18254 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18255 boolean externalStorage) { 18256 ArrayList<String> pkgList = new ArrayList<String>(); 18257 Set<AsecInstallArgs> keys = processCids.keySet(); 18258 18259 for (AsecInstallArgs args : keys) { 18260 String codePath = processCids.get(args); 18261 if (DEBUG_SD_INSTALL) 18262 Log.i(TAG, "Loading container : " + args.cid); 18263 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18264 try { 18265 // Make sure there are no container errors first. 18266 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18267 Slog.e(TAG, "Failed to mount cid : " + args.cid 18268 + " when installing from sdcard"); 18269 continue; 18270 } 18271 // Check code path here. 18272 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18273 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18274 + " does not match one in settings " + codePath); 18275 continue; 18276 } 18277 // Parse package 18278 int parseFlags = mDefParseFlags; 18279 if (args.isExternalAsec()) { 18280 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18281 } 18282 if (args.isFwdLocked()) { 18283 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18284 } 18285 18286 synchronized (mInstallLock) { 18287 PackageParser.Package pkg = null; 18288 try { 18289 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18290 } catch (PackageManagerException e) { 18291 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18292 } 18293 // Scan the package 18294 if (pkg != null) { 18295 /* 18296 * TODO why is the lock being held? doPostInstall is 18297 * called in other places without the lock. This needs 18298 * to be straightened out. 18299 */ 18300 // writer 18301 synchronized (mPackages) { 18302 retCode = PackageManager.INSTALL_SUCCEEDED; 18303 pkgList.add(pkg.packageName); 18304 // Post process args 18305 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18306 pkg.applicationInfo.uid); 18307 } 18308 } else { 18309 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18310 } 18311 } 18312 18313 } finally { 18314 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18315 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18316 } 18317 } 18318 } 18319 // writer 18320 synchronized (mPackages) { 18321 // If the platform SDK has changed since the last time we booted, 18322 // we need to re-grant app permission to catch any new ones that 18323 // appear. This is really a hack, and means that apps can in some 18324 // cases get permissions that the user didn't initially explicitly 18325 // allow... it would be nice to have some better way to handle 18326 // this situation. 18327 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18328 : mSettings.getInternalVersion(); 18329 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18330 : StorageManager.UUID_PRIVATE_INTERNAL; 18331 18332 int updateFlags = UPDATE_PERMISSIONS_ALL; 18333 if (ver.sdkVersion != mSdkVersion) { 18334 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18335 + mSdkVersion + "; regranting permissions for external"); 18336 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18337 } 18338 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18339 18340 // Yay, everything is now upgraded 18341 ver.forceCurrent(); 18342 18343 // can downgrade to reader 18344 // Persist settings 18345 mSettings.writeLPr(); 18346 } 18347 // Send a broadcast to let everyone know we are done processing 18348 if (pkgList.size() > 0) { 18349 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18350 } 18351 } 18352 18353 /* 18354 * Utility method to unload a list of specified containers 18355 */ 18356 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18357 // Just unmount all valid containers. 18358 for (AsecInstallArgs arg : cidArgs) { 18359 synchronized (mInstallLock) { 18360 arg.doPostDeleteLI(false); 18361 } 18362 } 18363 } 18364 18365 /* 18366 * Unload packages mounted on external media. This involves deleting package 18367 * data from internal structures, sending broadcasts about disabled packages, 18368 * gc'ing to free up references, unmounting all secure containers 18369 * corresponding to packages on external media, and posting a 18370 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18371 * that we always have to post this message if status has been requested no 18372 * matter what. 18373 */ 18374 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18375 final boolean reportStatus) { 18376 if (DEBUG_SD_INSTALL) 18377 Log.i(TAG, "unloading media packages"); 18378 ArrayList<String> pkgList = new ArrayList<String>(); 18379 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18380 final Set<AsecInstallArgs> keys = processCids.keySet(); 18381 for (AsecInstallArgs args : keys) { 18382 String pkgName = args.getPackageName(); 18383 if (DEBUG_SD_INSTALL) 18384 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18385 // Delete package internally 18386 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18387 synchronized (mInstallLock) { 18388 boolean res = deletePackageLI(pkgName, null, false, null, 18389 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18390 if (res) { 18391 pkgList.add(pkgName); 18392 } else { 18393 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18394 failedList.add(args); 18395 } 18396 } 18397 } 18398 18399 // reader 18400 synchronized (mPackages) { 18401 // We didn't update the settings after removing each package; 18402 // write them now for all packages. 18403 mSettings.writeLPr(); 18404 } 18405 18406 // We have to absolutely send UPDATED_MEDIA_STATUS only 18407 // after confirming that all the receivers processed the ordered 18408 // broadcast when packages get disabled, force a gc to clean things up. 18409 // and unload all the containers. 18410 if (pkgList.size() > 0) { 18411 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18412 new IIntentReceiver.Stub() { 18413 public void performReceive(Intent intent, int resultCode, String data, 18414 Bundle extras, boolean ordered, boolean sticky, 18415 int sendingUser) throws RemoteException { 18416 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18417 reportStatus ? 1 : 0, 1, keys); 18418 mHandler.sendMessage(msg); 18419 } 18420 }); 18421 } else { 18422 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18423 keys); 18424 mHandler.sendMessage(msg); 18425 } 18426 } 18427 18428 private void loadPrivatePackages(final VolumeInfo vol) { 18429 mHandler.post(new Runnable() { 18430 @Override 18431 public void run() { 18432 loadPrivatePackagesInner(vol); 18433 } 18434 }); 18435 } 18436 18437 private void loadPrivatePackagesInner(VolumeInfo vol) { 18438 final String volumeUuid = vol.fsUuid; 18439 if (TextUtils.isEmpty(volumeUuid)) { 18440 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18441 return; 18442 } 18443 18444 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18445 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18446 18447 final VersionInfo ver; 18448 final List<PackageSetting> packages; 18449 synchronized (mPackages) { 18450 ver = mSettings.findOrCreateVersion(volumeUuid); 18451 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18452 } 18453 18454 // TODO: introduce a new concept similar to "frozen" to prevent these 18455 // apps from being launched until after data has been fully reconciled 18456 for (PackageSetting ps : packages) { 18457 synchronized (mInstallLock) { 18458 final PackageParser.Package pkg; 18459 try { 18460 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18461 loaded.add(pkg.applicationInfo); 18462 18463 } catch (PackageManagerException e) { 18464 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18465 } 18466 18467 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18468 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18469 } 18470 } 18471 } 18472 18473 // Reconcile app data for all started/unlocked users 18474 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18475 final UserManager um = mContext.getSystemService(UserManager.class); 18476 for (UserInfo user : um.getUsers()) { 18477 final int flags; 18478 if (um.isUserUnlocked(user.id)) { 18479 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18480 } else if (um.isUserRunning(user.id)) { 18481 flags = StorageManager.FLAG_STORAGE_DE; 18482 } else { 18483 continue; 18484 } 18485 18486 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18487 reconcileAppsData(volumeUuid, user.id, flags); 18488 } 18489 18490 synchronized (mPackages) { 18491 int updateFlags = UPDATE_PERMISSIONS_ALL; 18492 if (ver.sdkVersion != mSdkVersion) { 18493 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18494 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18495 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18496 } 18497 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18498 18499 // Yay, everything is now upgraded 18500 ver.forceCurrent(); 18501 18502 mSettings.writeLPr(); 18503 } 18504 18505 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18506 sendResourcesChangedBroadcast(true, false, loaded, null); 18507 } 18508 18509 private void unloadPrivatePackages(final VolumeInfo vol) { 18510 mHandler.post(new Runnable() { 18511 @Override 18512 public void run() { 18513 unloadPrivatePackagesInner(vol); 18514 } 18515 }); 18516 } 18517 18518 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18519 final String volumeUuid = vol.fsUuid; 18520 if (TextUtils.isEmpty(volumeUuid)) { 18521 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18522 return; 18523 } 18524 18525 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18526 synchronized (mInstallLock) { 18527 synchronized (mPackages) { 18528 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18529 for (PackageSetting ps : packages) { 18530 if (ps.pkg == null) continue; 18531 18532 final ApplicationInfo info = ps.pkg.applicationInfo; 18533 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18534 if (deletePackageLI(ps.name, null, false, null, 18535 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18536 unloaded.add(info); 18537 } else { 18538 Slog.w(TAG, "Failed to unload " + ps.codePath); 18539 } 18540 } 18541 18542 mSettings.writeLPr(); 18543 } 18544 } 18545 18546 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18547 sendResourcesChangedBroadcast(false, false, unloaded, null); 18548 } 18549 18550 /** 18551 * Examine all users present on given mounted volume, and destroy data 18552 * belonging to users that are no longer valid, or whose user ID has been 18553 * recycled. 18554 */ 18555 private void reconcileUsers(String volumeUuid) { 18556 // TODO: also reconcile DE directories 18557 final File[] files = FileUtils 18558 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18559 for (File file : files) { 18560 if (!file.isDirectory()) continue; 18561 18562 final int userId; 18563 final UserInfo info; 18564 try { 18565 userId = Integer.parseInt(file.getName()); 18566 info = sUserManager.getUserInfo(userId); 18567 } catch (NumberFormatException e) { 18568 Slog.w(TAG, "Invalid user directory " + file); 18569 continue; 18570 } 18571 18572 boolean destroyUser = false; 18573 if (info == null) { 18574 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18575 + " because no matching user was found"); 18576 destroyUser = true; 18577 } else { 18578 try { 18579 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18580 } catch (IOException e) { 18581 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18582 + " because we failed to enforce serial number: " + e); 18583 destroyUser = true; 18584 } 18585 } 18586 18587 if (destroyUser) { 18588 synchronized (mInstallLock) { 18589 try { 18590 mInstaller.removeUserDataDirs(volumeUuid, userId); 18591 } catch (InstallerException e) { 18592 Slog.w(TAG, "Failed to clean up user dirs", e); 18593 } 18594 } 18595 } 18596 } 18597 } 18598 18599 private void assertPackageKnown(String volumeUuid, String packageName) 18600 throws PackageManagerException { 18601 synchronized (mPackages) { 18602 final PackageSetting ps = mSettings.mPackages.get(packageName); 18603 if (ps == null) { 18604 throw new PackageManagerException("Package " + packageName + " is unknown"); 18605 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18606 throw new PackageManagerException( 18607 "Package " + packageName + " found on unknown volume " + volumeUuid 18608 + "; expected volume " + ps.volumeUuid); 18609 } 18610 } 18611 } 18612 18613 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18614 throws PackageManagerException { 18615 synchronized (mPackages) { 18616 final PackageSetting ps = mSettings.mPackages.get(packageName); 18617 if (ps == null) { 18618 throw new PackageManagerException("Package " + packageName + " is unknown"); 18619 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18620 throw new PackageManagerException( 18621 "Package " + packageName + " found on unknown volume " + volumeUuid 18622 + "; expected volume " + ps.volumeUuid); 18623 } else if (!ps.getInstalled(userId)) { 18624 throw new PackageManagerException( 18625 "Package " + packageName + " not installed for user " + userId); 18626 } 18627 } 18628 } 18629 18630 /** 18631 * Examine all apps present on given mounted volume, and destroy apps that 18632 * aren't expected, either due to uninstallation or reinstallation on 18633 * another volume. 18634 */ 18635 private void reconcileApps(String volumeUuid) { 18636 final File[] files = FileUtils 18637 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18638 for (File file : files) { 18639 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18640 && !PackageInstallerService.isStageName(file.getName()); 18641 if (!isPackage) { 18642 // Ignore entries which are not packages 18643 continue; 18644 } 18645 18646 try { 18647 final PackageLite pkg = PackageParser.parsePackageLite(file, 18648 PackageParser.PARSE_MUST_BE_APK); 18649 assertPackageKnown(volumeUuid, pkg.packageName); 18650 18651 } catch (PackageParserException | PackageManagerException e) { 18652 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18653 synchronized (mInstallLock) { 18654 removeCodePathLI(file); 18655 } 18656 } 18657 } 18658 } 18659 18660 /** 18661 * Reconcile all app data for the given user. 18662 * <p> 18663 * Verifies that directories exist and that ownership and labeling is 18664 * correct for all installed apps on all mounted volumes. 18665 */ 18666 void reconcileAppsData(int userId, int flags) { 18667 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18668 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18669 final String volumeUuid = vol.getFsUuid(); 18670 reconcileAppsData(volumeUuid, userId, flags); 18671 } 18672 } 18673 18674 /** 18675 * Reconcile all app data on given mounted volume. 18676 * <p> 18677 * Destroys app data that isn't expected, either due to uninstallation or 18678 * reinstallation on another volume. 18679 * <p> 18680 * Verifies that directories exist and that ownership and labeling is 18681 * correct for all installed apps. 18682 */ 18683 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18684 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18685 + Integer.toHexString(flags)); 18686 18687 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18688 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18689 18690 boolean restoreconNeeded = false; 18691 18692 // First look for stale data that doesn't belong, and check if things 18693 // have changed since we did our last restorecon 18694 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18695 if (!isUserKeyUnlocked(userId)) { 18696 throw new RuntimeException( 18697 "Yikes, someone asked us to reconcile CE storage while " + userId 18698 + " was still locked; this would have caused massive data loss!"); 18699 } 18700 18701 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18702 18703 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18704 for (File file : files) { 18705 final String packageName = file.getName(); 18706 try { 18707 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18708 } catch (PackageManagerException e) { 18709 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18710 synchronized (mInstallLock) { 18711 destroyAppDataLI(volumeUuid, packageName, userId, 18712 StorageManager.FLAG_STORAGE_CE); 18713 } 18714 } 18715 } 18716 } 18717 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18718 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18719 18720 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18721 for (File file : files) { 18722 final String packageName = file.getName(); 18723 try { 18724 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18725 } catch (PackageManagerException e) { 18726 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18727 synchronized (mInstallLock) { 18728 destroyAppDataLI(volumeUuid, packageName, userId, 18729 StorageManager.FLAG_STORAGE_DE); 18730 } 18731 } 18732 } 18733 } 18734 18735 // Ensure that data directories are ready to roll for all packages 18736 // installed for this volume and user 18737 final List<PackageSetting> packages; 18738 synchronized (mPackages) { 18739 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18740 } 18741 int preparedCount = 0; 18742 for (PackageSetting ps : packages) { 18743 final String packageName = ps.name; 18744 if (ps.pkg == null) { 18745 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18746 // TODO: might be due to legacy ASEC apps; we should circle back 18747 // and reconcile again once they're scanned 18748 continue; 18749 } 18750 18751 if (ps.getInstalled(userId)) { 18752 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18753 18754 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18755 // We may have just shuffled around app data directories, so 18756 // prepare them one more time 18757 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18758 } 18759 18760 preparedCount++; 18761 } 18762 } 18763 18764 if (restoreconNeeded) { 18765 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18766 SELinuxMMAC.setRestoreconDone(ceDir); 18767 } 18768 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18769 SELinuxMMAC.setRestoreconDone(deDir); 18770 } 18771 } 18772 18773 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18774 + " packages; restoreconNeeded was " + restoreconNeeded); 18775 } 18776 18777 /** 18778 * Prepare app data for the given app just after it was installed or 18779 * upgraded. This method carefully only touches users that it's installed 18780 * for, and it forces a restorecon to handle any seinfo changes. 18781 * <p> 18782 * Verifies that directories exist and that ownership and labeling is 18783 * correct for all installed apps. If there is an ownership mismatch, it 18784 * will try recovering system apps by wiping data; third-party app data is 18785 * left intact. 18786 * <p> 18787 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18788 */ 18789 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18790 prepareAppDataAfterInstallInternal(pkg); 18791 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18792 for (int i = 0; i < childCount; i++) { 18793 PackageParser.Package childPackage = pkg.childPackages.get(i); 18794 prepareAppDataAfterInstallInternal(childPackage); 18795 } 18796 } 18797 18798 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18799 final PackageSetting ps; 18800 synchronized (mPackages) { 18801 ps = mSettings.mPackages.get(pkg.packageName); 18802 mSettings.writeKernelMappingLPr(ps); 18803 } 18804 18805 final UserManager um = mContext.getSystemService(UserManager.class); 18806 for (UserInfo user : um.getUsers()) { 18807 final int flags; 18808 if (um.isUserUnlocked(user.id)) { 18809 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18810 } else if (um.isUserRunning(user.id)) { 18811 flags = StorageManager.FLAG_STORAGE_DE; 18812 } else { 18813 continue; 18814 } 18815 18816 if (ps.getInstalled(user.id)) { 18817 // Whenever an app changes, force a restorecon of its data 18818 // TODO: when user data is locked, mark that we're still dirty 18819 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18820 } 18821 } 18822 } 18823 18824 /** 18825 * Prepare app data for the given app. 18826 * <p> 18827 * Verifies that directories exist and that ownership and labeling is 18828 * correct for all installed apps. If there is an ownership mismatch, this 18829 * will try recovering system apps by wiping data; third-party app data is 18830 * left intact. 18831 */ 18832 private void prepareAppData(String volumeUuid, int userId, int flags, 18833 PackageParser.Package pkg, boolean restoreconNeeded) { 18834 if (DEBUG_APP_DATA) { 18835 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18836 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18837 } 18838 18839 final String packageName = pkg.packageName; 18840 final ApplicationInfo app = pkg.applicationInfo; 18841 final int appId = UserHandle.getAppId(app.uid); 18842 18843 Preconditions.checkNotNull(app.seinfo); 18844 18845 synchronized (mInstallLock) { 18846 try { 18847 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18848 appId, app.seinfo, app.targetSdkVersion); 18849 } catch (InstallerException e) { 18850 if (app.isSystemApp()) { 18851 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18852 + ", but trying to recover: " + e); 18853 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18854 try { 18855 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18856 appId, app.seinfo, app.targetSdkVersion); 18857 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18858 } catch (InstallerException e2) { 18859 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18860 } 18861 } else { 18862 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18863 } 18864 } 18865 18866 if (restoreconNeeded) { 18867 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18868 } 18869 18870 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18871 // Create a native library symlink only if we have native libraries 18872 // and if the native libraries are 32 bit libraries. We do not provide 18873 // this symlink for 64 bit libraries. 18874 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18875 final String nativeLibPath = app.nativeLibraryDir; 18876 try { 18877 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18878 nativeLibPath, userId); 18879 } catch (InstallerException e) { 18880 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18881 } 18882 } 18883 } 18884 } 18885 } 18886 18887 /** 18888 * For system apps on non-FBE devices, this method migrates any existing 18889 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18890 * requested by the app. 18891 */ 18892 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18893 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18894 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18895 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18896 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18897 synchronized (mInstallLock) { 18898 try { 18899 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18900 } catch (InstallerException e) { 18901 logCriticalInfo(Log.WARN, 18902 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18903 } 18904 } 18905 return true; 18906 } else { 18907 return false; 18908 } 18909 } 18910 18911 private void unfreezePackage(String packageName) { 18912 synchronized (mPackages) { 18913 final PackageSetting ps = mSettings.mPackages.get(packageName); 18914 if (ps != null) { 18915 ps.frozen = false; 18916 } 18917 } 18918 } 18919 18920 @Override 18921 public int movePackage(final String packageName, final String volumeUuid) { 18922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18923 18924 final int moveId = mNextMoveId.getAndIncrement(); 18925 mHandler.post(new Runnable() { 18926 @Override 18927 public void run() { 18928 try { 18929 movePackageInternal(packageName, volumeUuid, moveId); 18930 } catch (PackageManagerException e) { 18931 Slog.w(TAG, "Failed to move " + packageName, e); 18932 mMoveCallbacks.notifyStatusChanged(moveId, 18933 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18934 } 18935 } 18936 }); 18937 return moveId; 18938 } 18939 18940 private void movePackageInternal(final String packageName, final String volumeUuid, 18941 final int moveId) throws PackageManagerException { 18942 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18944 final PackageManager pm = mContext.getPackageManager(); 18945 18946 final boolean currentAsec; 18947 final String currentVolumeUuid; 18948 final File codeFile; 18949 final String installerPackageName; 18950 final String packageAbiOverride; 18951 final int appId; 18952 final String seinfo; 18953 final String label; 18954 final int targetSdkVersion; 18955 18956 // reader 18957 synchronized (mPackages) { 18958 final PackageParser.Package pkg = mPackages.get(packageName); 18959 final PackageSetting ps = mSettings.mPackages.get(packageName); 18960 if (pkg == null || ps == null) { 18961 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18962 } 18963 18964 if (pkg.applicationInfo.isSystemApp()) { 18965 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18966 "Cannot move system application"); 18967 } 18968 18969 if (pkg.applicationInfo.isExternalAsec()) { 18970 currentAsec = true; 18971 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18972 } else if (pkg.applicationInfo.isForwardLocked()) { 18973 currentAsec = true; 18974 currentVolumeUuid = "forward_locked"; 18975 } else { 18976 currentAsec = false; 18977 currentVolumeUuid = ps.volumeUuid; 18978 18979 final File probe = new File(pkg.codePath); 18980 final File probeOat = new File(probe, "oat"); 18981 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18982 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18983 "Move only supported for modern cluster style installs"); 18984 } 18985 } 18986 18987 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18988 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18989 "Package already moved to " + volumeUuid); 18990 } 18991 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18992 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18993 "Device admin cannot be moved"); 18994 } 18995 18996 if (ps.frozen) { 18997 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18998 "Failed to move already frozen package"); 18999 } 19000 ps.frozen = true; 19001 19002 codeFile = new File(pkg.codePath); 19003 installerPackageName = ps.installerPackageName; 19004 packageAbiOverride = ps.cpuAbiOverrideString; 19005 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19006 seinfo = pkg.applicationInfo.seinfo; 19007 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19008 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19009 } 19010 19011 // Now that we're guarded by frozen state, kill app during move 19012 final long token = Binder.clearCallingIdentity(); 19013 try { 19014 killApplication(packageName, appId, "move pkg"); 19015 } finally { 19016 Binder.restoreCallingIdentity(token); 19017 } 19018 19019 final Bundle extras = new Bundle(); 19020 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19021 extras.putString(Intent.EXTRA_TITLE, label); 19022 mMoveCallbacks.notifyCreated(moveId, extras); 19023 19024 int installFlags; 19025 final boolean moveCompleteApp; 19026 final File measurePath; 19027 19028 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19029 installFlags = INSTALL_INTERNAL; 19030 moveCompleteApp = !currentAsec; 19031 measurePath = Environment.getDataAppDirectory(volumeUuid); 19032 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19033 installFlags = INSTALL_EXTERNAL; 19034 moveCompleteApp = false; 19035 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19036 } else { 19037 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19038 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19039 || !volume.isMountedWritable()) { 19040 unfreezePackage(packageName); 19041 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19042 "Move location not mounted private volume"); 19043 } 19044 19045 Preconditions.checkState(!currentAsec); 19046 19047 installFlags = INSTALL_INTERNAL; 19048 moveCompleteApp = true; 19049 measurePath = Environment.getDataAppDirectory(volumeUuid); 19050 } 19051 19052 final PackageStats stats = new PackageStats(null, -1); 19053 synchronized (mInstaller) { 19054 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19055 unfreezePackage(packageName); 19056 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19057 "Failed to measure package size"); 19058 } 19059 } 19060 19061 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19062 + stats.dataSize); 19063 19064 final long startFreeBytes = measurePath.getFreeSpace(); 19065 final long sizeBytes; 19066 if (moveCompleteApp) { 19067 sizeBytes = stats.codeSize + stats.dataSize; 19068 } else { 19069 sizeBytes = stats.codeSize; 19070 } 19071 19072 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19073 unfreezePackage(packageName); 19074 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19075 "Not enough free space to move"); 19076 } 19077 19078 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19079 19080 final CountDownLatch installedLatch = new CountDownLatch(1); 19081 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19082 @Override 19083 public void onUserActionRequired(Intent intent) throws RemoteException { 19084 throw new IllegalStateException(); 19085 } 19086 19087 @Override 19088 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19089 Bundle extras) throws RemoteException { 19090 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19091 + PackageManager.installStatusToString(returnCode, msg)); 19092 19093 installedLatch.countDown(); 19094 19095 // Regardless of success or failure of the move operation, 19096 // always unfreeze the package 19097 unfreezePackage(packageName); 19098 19099 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19100 switch (status) { 19101 case PackageInstaller.STATUS_SUCCESS: 19102 mMoveCallbacks.notifyStatusChanged(moveId, 19103 PackageManager.MOVE_SUCCEEDED); 19104 break; 19105 case PackageInstaller.STATUS_FAILURE_STORAGE: 19106 mMoveCallbacks.notifyStatusChanged(moveId, 19107 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19108 break; 19109 default: 19110 mMoveCallbacks.notifyStatusChanged(moveId, 19111 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19112 break; 19113 } 19114 } 19115 }; 19116 19117 final MoveInfo move; 19118 if (moveCompleteApp) { 19119 // Kick off a thread to report progress estimates 19120 new Thread() { 19121 @Override 19122 public void run() { 19123 while (true) { 19124 try { 19125 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19126 break; 19127 } 19128 } catch (InterruptedException ignored) { 19129 } 19130 19131 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19132 final int progress = 10 + (int) MathUtils.constrain( 19133 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19134 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19135 } 19136 } 19137 }.start(); 19138 19139 final String dataAppName = codeFile.getName(); 19140 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19141 dataAppName, appId, seinfo, targetSdkVersion); 19142 } else { 19143 move = null; 19144 } 19145 19146 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19147 19148 final Message msg = mHandler.obtainMessage(INIT_COPY); 19149 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19150 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19151 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19152 packageAbiOverride, null); 19153 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19154 msg.obj = params; 19155 19156 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19157 System.identityHashCode(msg.obj)); 19158 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19159 System.identityHashCode(msg.obj)); 19160 19161 mHandler.sendMessage(msg); 19162 } 19163 19164 @Override 19165 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19167 19168 final int realMoveId = mNextMoveId.getAndIncrement(); 19169 final Bundle extras = new Bundle(); 19170 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19171 mMoveCallbacks.notifyCreated(realMoveId, extras); 19172 19173 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19174 @Override 19175 public void onCreated(int moveId, Bundle extras) { 19176 // Ignored 19177 } 19178 19179 @Override 19180 public void onStatusChanged(int moveId, int status, long estMillis) { 19181 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19182 } 19183 }; 19184 19185 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19186 storage.setPrimaryStorageUuid(volumeUuid, callback); 19187 return realMoveId; 19188 } 19189 19190 @Override 19191 public int getMoveStatus(int moveId) { 19192 mContext.enforceCallingOrSelfPermission( 19193 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19194 return mMoveCallbacks.mLastStatus.get(moveId); 19195 } 19196 19197 @Override 19198 public void registerMoveCallback(IPackageMoveObserver callback) { 19199 mContext.enforceCallingOrSelfPermission( 19200 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19201 mMoveCallbacks.register(callback); 19202 } 19203 19204 @Override 19205 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19206 mContext.enforceCallingOrSelfPermission( 19207 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19208 mMoveCallbacks.unregister(callback); 19209 } 19210 19211 @Override 19212 public boolean setInstallLocation(int loc) { 19213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19214 null); 19215 if (getInstallLocation() == loc) { 19216 return true; 19217 } 19218 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19219 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19220 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19221 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19222 return true; 19223 } 19224 return false; 19225 } 19226 19227 @Override 19228 public int getInstallLocation() { 19229 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19230 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19231 PackageHelper.APP_INSTALL_AUTO); 19232 } 19233 19234 /** Called by UserManagerService */ 19235 void cleanUpUser(UserManagerService userManager, int userHandle) { 19236 synchronized (mPackages) { 19237 mDirtyUsers.remove(userHandle); 19238 mUserNeedsBadging.delete(userHandle); 19239 mSettings.removeUserLPw(userHandle); 19240 mPendingBroadcasts.remove(userHandle); 19241 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19242 } 19243 synchronized (mInstallLock) { 19244 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19245 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19246 final String volumeUuid = vol.getFsUuid(); 19247 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19248 try { 19249 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19250 } catch (InstallerException e) { 19251 Slog.w(TAG, "Failed to remove user data", e); 19252 } 19253 } 19254 synchronized (mPackages) { 19255 removeUnusedPackagesLILPw(userManager, userHandle); 19256 } 19257 } 19258 } 19259 19260 /** 19261 * We're removing userHandle and would like to remove any downloaded packages 19262 * that are no longer in use by any other user. 19263 * @param userHandle the user being removed 19264 */ 19265 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19266 final boolean DEBUG_CLEAN_APKS = false; 19267 int [] users = userManager.getUserIds(); 19268 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19269 while (psit.hasNext()) { 19270 PackageSetting ps = psit.next(); 19271 if (ps.pkg == null) { 19272 continue; 19273 } 19274 final String packageName = ps.pkg.packageName; 19275 // Skip over if system app 19276 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19277 continue; 19278 } 19279 if (DEBUG_CLEAN_APKS) { 19280 Slog.i(TAG, "Checking package " + packageName); 19281 } 19282 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19283 if (keep) { 19284 if (DEBUG_CLEAN_APKS) { 19285 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19286 } 19287 } else { 19288 for (int i = 0; i < users.length; i++) { 19289 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19290 keep = true; 19291 if (DEBUG_CLEAN_APKS) { 19292 Slog.i(TAG, " Keeping package " + packageName + " for user " 19293 + users[i]); 19294 } 19295 break; 19296 } 19297 } 19298 } 19299 if (!keep) { 19300 if (DEBUG_CLEAN_APKS) { 19301 Slog.i(TAG, " Removing package " + packageName); 19302 } 19303 mHandler.post(new Runnable() { 19304 public void run() { 19305 deletePackageX(packageName, userHandle, 0); 19306 } //end run 19307 }); 19308 } 19309 } 19310 } 19311 19312 /** Called by UserManagerService */ 19313 void createNewUser(int userHandle) { 19314 synchronized (mInstallLock) { 19315 try { 19316 mInstaller.createUserConfig(userHandle); 19317 } catch (InstallerException e) { 19318 Slog.w(TAG, "Failed to create user config", e); 19319 } 19320 mSettings.createNewUserLI(this, mInstaller, userHandle); 19321 } 19322 synchronized (mPackages) { 19323 applyFactoryDefaultBrowserLPw(userHandle); 19324 primeDomainVerificationsLPw(userHandle); 19325 } 19326 } 19327 19328 void newUserCreated(final int userHandle) { 19329 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19330 // If permission review for legacy apps is required, we represent 19331 // dagerous permissions for such apps as always granted runtime 19332 // permissions to keep per user flag state whether review is needed. 19333 // Hence, if a new user is added we have to propagate dangerous 19334 // permission grants for these legacy apps. 19335 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19336 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19337 | UPDATE_PERMISSIONS_REPLACE_ALL); 19338 } 19339 } 19340 19341 @Override 19342 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19343 mContext.enforceCallingOrSelfPermission( 19344 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19345 "Only package verification agents can read the verifier device identity"); 19346 19347 synchronized (mPackages) { 19348 return mSettings.getVerifierDeviceIdentityLPw(); 19349 } 19350 } 19351 19352 @Override 19353 public void setPermissionEnforced(String permission, boolean enforced) { 19354 // TODO: Now that we no longer change GID for storage, this should to away. 19355 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19356 "setPermissionEnforced"); 19357 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19358 synchronized (mPackages) { 19359 if (mSettings.mReadExternalStorageEnforced == null 19360 || mSettings.mReadExternalStorageEnforced != enforced) { 19361 mSettings.mReadExternalStorageEnforced = enforced; 19362 mSettings.writeLPr(); 19363 } 19364 } 19365 // kill any non-foreground processes so we restart them and 19366 // grant/revoke the GID. 19367 final IActivityManager am = ActivityManagerNative.getDefault(); 19368 if (am != null) { 19369 final long token = Binder.clearCallingIdentity(); 19370 try { 19371 am.killProcessesBelowForeground("setPermissionEnforcement"); 19372 } catch (RemoteException e) { 19373 } finally { 19374 Binder.restoreCallingIdentity(token); 19375 } 19376 } 19377 } else { 19378 throw new IllegalArgumentException("No selective enforcement for " + permission); 19379 } 19380 } 19381 19382 @Override 19383 @Deprecated 19384 public boolean isPermissionEnforced(String permission) { 19385 return true; 19386 } 19387 19388 @Override 19389 public boolean isStorageLow() { 19390 final long token = Binder.clearCallingIdentity(); 19391 try { 19392 final DeviceStorageMonitorInternal 19393 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19394 if (dsm != null) { 19395 return dsm.isMemoryLow(); 19396 } else { 19397 return false; 19398 } 19399 } finally { 19400 Binder.restoreCallingIdentity(token); 19401 } 19402 } 19403 19404 @Override 19405 public IPackageInstaller getPackageInstaller() { 19406 return mInstallerService; 19407 } 19408 19409 private boolean userNeedsBadging(int userId) { 19410 int index = mUserNeedsBadging.indexOfKey(userId); 19411 if (index < 0) { 19412 final UserInfo userInfo; 19413 final long token = Binder.clearCallingIdentity(); 19414 try { 19415 userInfo = sUserManager.getUserInfo(userId); 19416 } finally { 19417 Binder.restoreCallingIdentity(token); 19418 } 19419 final boolean b; 19420 if (userInfo != null && userInfo.isManagedProfile()) { 19421 b = true; 19422 } else { 19423 b = false; 19424 } 19425 mUserNeedsBadging.put(userId, b); 19426 return b; 19427 } 19428 return mUserNeedsBadging.valueAt(index); 19429 } 19430 19431 @Override 19432 public KeySet getKeySetByAlias(String packageName, String alias) { 19433 if (packageName == null || alias == null) { 19434 return null; 19435 } 19436 synchronized(mPackages) { 19437 final PackageParser.Package pkg = mPackages.get(packageName); 19438 if (pkg == null) { 19439 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19440 throw new IllegalArgumentException("Unknown package: " + packageName); 19441 } 19442 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19443 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19444 } 19445 } 19446 19447 @Override 19448 public KeySet getSigningKeySet(String packageName) { 19449 if (packageName == null) { 19450 return null; 19451 } 19452 synchronized(mPackages) { 19453 final PackageParser.Package pkg = mPackages.get(packageName); 19454 if (pkg == null) { 19455 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19456 throw new IllegalArgumentException("Unknown package: " + packageName); 19457 } 19458 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19459 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19460 throw new SecurityException("May not access signing KeySet of other apps."); 19461 } 19462 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19463 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19464 } 19465 } 19466 19467 @Override 19468 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19469 if (packageName == null || ks == null) { 19470 return false; 19471 } 19472 synchronized(mPackages) { 19473 final PackageParser.Package pkg = mPackages.get(packageName); 19474 if (pkg == null) { 19475 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19476 throw new IllegalArgumentException("Unknown package: " + packageName); 19477 } 19478 IBinder ksh = ks.getToken(); 19479 if (ksh instanceof KeySetHandle) { 19480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19481 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19482 } 19483 return false; 19484 } 19485 } 19486 19487 @Override 19488 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19489 if (packageName == null || ks == null) { 19490 return false; 19491 } 19492 synchronized(mPackages) { 19493 final PackageParser.Package pkg = mPackages.get(packageName); 19494 if (pkg == null) { 19495 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19496 throw new IllegalArgumentException("Unknown package: " + packageName); 19497 } 19498 IBinder ksh = ks.getToken(); 19499 if (ksh instanceof KeySetHandle) { 19500 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19501 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19502 } 19503 return false; 19504 } 19505 } 19506 19507 private void deletePackageIfUnusedLPr(final String packageName) { 19508 PackageSetting ps = mSettings.mPackages.get(packageName); 19509 if (ps == null) { 19510 return; 19511 } 19512 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19513 // TODO Implement atomic delete if package is unused 19514 // It is currently possible that the package will be deleted even if it is installed 19515 // after this method returns. 19516 mHandler.post(new Runnable() { 19517 public void run() { 19518 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19519 } 19520 }); 19521 } 19522 } 19523 19524 /** 19525 * Check and throw if the given before/after packages would be considered a 19526 * downgrade. 19527 */ 19528 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19529 throws PackageManagerException { 19530 if (after.versionCode < before.mVersionCode) { 19531 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19532 "Update version code " + after.versionCode + " is older than current " 19533 + before.mVersionCode); 19534 } else if (after.versionCode == before.mVersionCode) { 19535 if (after.baseRevisionCode < before.baseRevisionCode) { 19536 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19537 "Update base revision code " + after.baseRevisionCode 19538 + " is older than current " + before.baseRevisionCode); 19539 } 19540 19541 if (!ArrayUtils.isEmpty(after.splitNames)) { 19542 for (int i = 0; i < after.splitNames.length; i++) { 19543 final String splitName = after.splitNames[i]; 19544 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19545 if (j != -1) { 19546 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19547 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19548 "Update split " + splitName + " revision code " 19549 + after.splitRevisionCodes[i] + " is older than current " 19550 + before.splitRevisionCodes[j]); 19551 } 19552 } 19553 } 19554 } 19555 } 19556 } 19557 19558 private static class MoveCallbacks extends Handler { 19559 private static final int MSG_CREATED = 1; 19560 private static final int MSG_STATUS_CHANGED = 2; 19561 19562 private final RemoteCallbackList<IPackageMoveObserver> 19563 mCallbacks = new RemoteCallbackList<>(); 19564 19565 private final SparseIntArray mLastStatus = new SparseIntArray(); 19566 19567 public MoveCallbacks(Looper looper) { 19568 super(looper); 19569 } 19570 19571 public void register(IPackageMoveObserver callback) { 19572 mCallbacks.register(callback); 19573 } 19574 19575 public void unregister(IPackageMoveObserver callback) { 19576 mCallbacks.unregister(callback); 19577 } 19578 19579 @Override 19580 public void handleMessage(Message msg) { 19581 final SomeArgs args = (SomeArgs) msg.obj; 19582 final int n = mCallbacks.beginBroadcast(); 19583 for (int i = 0; i < n; i++) { 19584 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19585 try { 19586 invokeCallback(callback, msg.what, args); 19587 } catch (RemoteException ignored) { 19588 } 19589 } 19590 mCallbacks.finishBroadcast(); 19591 args.recycle(); 19592 } 19593 19594 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19595 throws RemoteException { 19596 switch (what) { 19597 case MSG_CREATED: { 19598 callback.onCreated(args.argi1, (Bundle) args.arg2); 19599 break; 19600 } 19601 case MSG_STATUS_CHANGED: { 19602 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19603 break; 19604 } 19605 } 19606 } 19607 19608 private void notifyCreated(int moveId, Bundle extras) { 19609 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19610 19611 final SomeArgs args = SomeArgs.obtain(); 19612 args.argi1 = moveId; 19613 args.arg2 = extras; 19614 obtainMessage(MSG_CREATED, args).sendToTarget(); 19615 } 19616 19617 private void notifyStatusChanged(int moveId, int status) { 19618 notifyStatusChanged(moveId, status, -1); 19619 } 19620 19621 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19622 Slog.v(TAG, "Move " + moveId + " status " + status); 19623 19624 final SomeArgs args = SomeArgs.obtain(); 19625 args.argi1 = moveId; 19626 args.argi2 = status; 19627 args.arg3 = estMillis; 19628 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19629 19630 synchronized (mLastStatus) { 19631 mLastStatus.put(moveId, status); 19632 } 19633 } 19634 } 19635 19636 private final static class OnPermissionChangeListeners extends Handler { 19637 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19638 19639 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19640 new RemoteCallbackList<>(); 19641 19642 public OnPermissionChangeListeners(Looper looper) { 19643 super(looper); 19644 } 19645 19646 @Override 19647 public void handleMessage(Message msg) { 19648 switch (msg.what) { 19649 case MSG_ON_PERMISSIONS_CHANGED: { 19650 final int uid = msg.arg1; 19651 handleOnPermissionsChanged(uid); 19652 } break; 19653 } 19654 } 19655 19656 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19657 mPermissionListeners.register(listener); 19658 19659 } 19660 19661 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19662 mPermissionListeners.unregister(listener); 19663 } 19664 19665 public void onPermissionsChanged(int uid) { 19666 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19667 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19668 } 19669 } 19670 19671 private void handleOnPermissionsChanged(int uid) { 19672 final int count = mPermissionListeners.beginBroadcast(); 19673 try { 19674 for (int i = 0; i < count; i++) { 19675 IOnPermissionsChangeListener callback = mPermissionListeners 19676 .getBroadcastItem(i); 19677 try { 19678 callback.onPermissionsChanged(uid); 19679 } catch (RemoteException e) { 19680 Log.e(TAG, "Permission listener is dead", e); 19681 } 19682 } 19683 } finally { 19684 mPermissionListeners.finishBroadcast(); 19685 } 19686 } 19687 } 19688 19689 private class PackageManagerInternalImpl extends PackageManagerInternal { 19690 @Override 19691 public void setLocationPackagesProvider(PackagesProvider provider) { 19692 synchronized (mPackages) { 19693 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19694 } 19695 } 19696 19697 @Override 19698 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19699 synchronized (mPackages) { 19700 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19701 } 19702 } 19703 19704 @Override 19705 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19706 synchronized (mPackages) { 19707 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19708 } 19709 } 19710 19711 @Override 19712 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19713 synchronized (mPackages) { 19714 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19715 } 19716 } 19717 19718 @Override 19719 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19720 synchronized (mPackages) { 19721 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19722 } 19723 } 19724 19725 @Override 19726 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19727 synchronized (mPackages) { 19728 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19729 } 19730 } 19731 19732 @Override 19733 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19734 synchronized (mPackages) { 19735 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19736 packageName, userId); 19737 } 19738 } 19739 19740 @Override 19741 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19742 synchronized (mPackages) { 19743 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19744 packageName, userId); 19745 } 19746 } 19747 19748 @Override 19749 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19750 synchronized (mPackages) { 19751 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19752 packageName, userId); 19753 } 19754 } 19755 19756 @Override 19757 public void setKeepUninstalledPackages(final List<String> packageList) { 19758 Preconditions.checkNotNull(packageList); 19759 List<String> removedFromList = null; 19760 synchronized (mPackages) { 19761 if (mKeepUninstalledPackages != null) { 19762 final int packagesCount = mKeepUninstalledPackages.size(); 19763 for (int i = 0; i < packagesCount; i++) { 19764 String oldPackage = mKeepUninstalledPackages.get(i); 19765 if (packageList != null && packageList.contains(oldPackage)) { 19766 continue; 19767 } 19768 if (removedFromList == null) { 19769 removedFromList = new ArrayList<>(); 19770 } 19771 removedFromList.add(oldPackage); 19772 } 19773 } 19774 mKeepUninstalledPackages = new ArrayList<>(packageList); 19775 if (removedFromList != null) { 19776 final int removedCount = removedFromList.size(); 19777 for (int i = 0; i < removedCount; i++) { 19778 deletePackageIfUnusedLPr(removedFromList.get(i)); 19779 } 19780 } 19781 } 19782 } 19783 19784 @Override 19785 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19786 synchronized (mPackages) { 19787 // If we do not support permission review, done. 19788 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19789 return false; 19790 } 19791 19792 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19793 if (packageSetting == null) { 19794 return false; 19795 } 19796 19797 // Permission review applies only to apps not supporting the new permission model. 19798 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19799 return false; 19800 } 19801 19802 // Legacy apps have the permission and get user consent on launch. 19803 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19804 return permissionsState.isPermissionReviewRequired(userId); 19805 } 19806 } 19807 19808 @Override 19809 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19810 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19811 } 19812 19813 @Override 19814 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19815 int userId) { 19816 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19817 } 19818 } 19819 19820 @Override 19821 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19822 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19823 synchronized (mPackages) { 19824 final long identity = Binder.clearCallingIdentity(); 19825 try { 19826 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19827 packageNames, userId); 19828 } finally { 19829 Binder.restoreCallingIdentity(identity); 19830 } 19831 } 19832 } 19833 19834 private static void enforceSystemOrPhoneCaller(String tag) { 19835 int callingUid = Binder.getCallingUid(); 19836 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19837 throw new SecurityException( 19838 "Cannot call " + tag + " from UID " + callingUid); 19839 } 19840 } 19841 19842 boolean isHistoricalPackageUsageAvailable() { 19843 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19844 } 19845 19846 /** 19847 * Return a <b>copy</b> of the collection of packages known to the package manager. 19848 * @return A copy of the values of mPackages. 19849 */ 19850 Collection<PackageParser.Package> getPackages() { 19851 synchronized (mPackages) { 19852 return new ArrayList<>(mPackages.values()); 19853 } 19854 } 19855 19856 /** 19857 * Logs process start information (including base APK hash) to the security log. 19858 * @hide 19859 */ 19860 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19861 String apkFile, int pid) { 19862 if (!SecurityLog.isLoggingEnabled()) { 19863 return; 19864 } 19865 Bundle data = new Bundle(); 19866 data.putLong("startTimestamp", System.currentTimeMillis()); 19867 data.putString("processName", processName); 19868 data.putInt("uid", uid); 19869 data.putString("seinfo", seinfo); 19870 data.putString("apkFile", apkFile); 19871 data.putInt("pid", pid); 19872 Message msg = mProcessLoggingHandler.obtainMessage( 19873 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19874 msg.setData(data); 19875 mProcessLoggingHandler.sendMessage(msg); 19876 } 19877} 19878