PackageManagerService.java revision 6dffdf82857e4016c6fb953039b0508cb1fd0f71
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 (PackageDexOptimizer.canOptimizePackage(pkg)) { 7018 // If the cache was pruned, any compiled odex files will likely be out of date 7019 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 7020 // Instead, force the extraction in this case. 7021 performDexOpt(pkg.packageName, 7022 null /* instructionSet */, 7023 false /* checkProfiles */, 7024 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7025 false /* force */); 7026 } 7027 } 7028 } 7029 7030 @Override 7031 public void notifyPackageUse(String packageName) { 7032 synchronized (mPackages) { 7033 PackageParser.Package p = mPackages.get(packageName); 7034 if (p == null) { 7035 return; 7036 } 7037 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7038 } 7039 } 7040 7041 // TODO: this is not used nor needed. Delete it. 7042 @Override 7043 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7044 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7045 getFullCompilerFilter(), false /* force */); 7046 } 7047 7048 @Override 7049 public boolean performDexOpt(String packageName, String instructionSet, 7050 boolean checkProfiles, int compileReason, boolean force) { 7051 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7052 getCompilerFilterForReason(compileReason), force); 7053 } 7054 7055 @Override 7056 public boolean performDexOptMode(String packageName, String instructionSet, 7057 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7058 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7059 targetCompilerFilter, force); 7060 } 7061 7062 private boolean performDexOptTraced(String packageName, String instructionSet, 7063 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7064 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7065 try { 7066 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7067 targetCompilerFilter, force); 7068 } finally { 7069 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7070 } 7071 } 7072 7073 private boolean performDexOptInternal(String packageName, String instructionSet, 7074 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7075 PackageParser.Package p; 7076 final String targetInstructionSet; 7077 synchronized (mPackages) { 7078 p = mPackages.get(packageName); 7079 if (p == null) { 7080 return false; 7081 } 7082 mPackageUsage.write(false); 7083 7084 targetInstructionSet = instructionSet != null ? instructionSet : 7085 getPrimaryInstructionSet(p.applicationInfo); 7086 } 7087 long callingId = Binder.clearCallingIdentity(); 7088 try { 7089 synchronized (mInstallLock) { 7090 final String[] instructionSets = new String[] { targetInstructionSet }; 7091 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7092 checkProfiles, targetCompilerFilter, force); 7093 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7094 } 7095 } finally { 7096 Binder.restoreCallingIdentity(callingId); 7097 } 7098 } 7099 7100 public ArraySet<String> getOptimizablePackages() { 7101 ArraySet<String> pkgs = new ArraySet<String>(); 7102 synchronized (mPackages) { 7103 for (PackageParser.Package p : mPackages.values()) { 7104 if (PackageDexOptimizer.canOptimizePackage(p)) { 7105 pkgs.add(p.packageName); 7106 } 7107 } 7108 } 7109 return pkgs; 7110 } 7111 7112 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7113 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7114 boolean force) { 7115 // Select the dex optimizer based on the force parameter. 7116 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7117 // allocate an object here. 7118 PackageDexOptimizer pdo = force 7119 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7120 : mPackageDexOptimizer; 7121 7122 // Optimize all dependencies first. Note: we ignore the return value and march on 7123 // on errors. 7124 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7125 if (!deps.isEmpty()) { 7126 for (PackageParser.Package depPackage : deps) { 7127 // TODO: Analyze and investigate if we (should) profile libraries. 7128 // Currently this will do a full compilation of the library by default. 7129 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7130 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7131 } 7132 } 7133 7134 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7135 } 7136 7137 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7138 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7139 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7140 Set<String> collectedNames = new HashSet<>(); 7141 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7142 7143 retValue.remove(p); 7144 7145 return retValue; 7146 } else { 7147 return Collections.emptyList(); 7148 } 7149 } 7150 7151 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7152 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7153 if (!collectedNames.contains(p.packageName)) { 7154 collectedNames.add(p.packageName); 7155 collected.add(p); 7156 7157 if (p.usesLibraries != null) { 7158 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7159 } 7160 if (p.usesOptionalLibraries != null) { 7161 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7162 collectedNames); 7163 } 7164 } 7165 } 7166 7167 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7168 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7169 for (String libName : libs) { 7170 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7171 if (libPkg != null) { 7172 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7173 } 7174 } 7175 } 7176 7177 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7178 synchronized (mPackages) { 7179 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7180 if (lib != null && lib.apk != null) { 7181 return mPackages.get(lib.apk); 7182 } 7183 } 7184 return null; 7185 } 7186 7187 public void shutdown() { 7188 mPackageUsage.write(true); 7189 } 7190 7191 @Override 7192 public void forceDexOpt(String packageName) { 7193 enforceSystemOrRoot("forceDexOpt"); 7194 7195 PackageParser.Package pkg; 7196 synchronized (mPackages) { 7197 pkg = mPackages.get(packageName); 7198 if (pkg == null) { 7199 throw new IllegalArgumentException("Unknown package: " + packageName); 7200 } 7201 } 7202 7203 synchronized (mInstallLock) { 7204 final String[] instructionSets = new String[] { 7205 getPrimaryInstructionSet(pkg.applicationInfo) }; 7206 7207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7208 7209 // Whoever is calling forceDexOpt wants a fully compiled package. 7210 // Don't use profiles since that may cause compilation to be skipped. 7211 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7212 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7213 true /* force */); 7214 7215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7216 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7217 throw new IllegalStateException("Failed to dexopt: " + res); 7218 } 7219 } 7220 } 7221 7222 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7223 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7224 Slog.w(TAG, "Unable to update from " + oldPkg.name 7225 + " to " + newPkg.packageName 7226 + ": old package not in system partition"); 7227 return false; 7228 } else if (mPackages.get(oldPkg.name) != null) { 7229 Slog.w(TAG, "Unable to update from " + oldPkg.name 7230 + " to " + newPkg.packageName 7231 + ": old package still exists"); 7232 return false; 7233 } 7234 return true; 7235 } 7236 7237 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7238 // TODO: triage flags as part of 26466827 7239 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7240 7241 boolean res = true; 7242 final int[] users = sUserManager.getUserIds(); 7243 for (int user : users) { 7244 try { 7245 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7246 } catch (InstallerException e) { 7247 Slog.w(TAG, "Failed to delete data directory", e); 7248 res = false; 7249 } 7250 } 7251 return res; 7252 } 7253 7254 void removeCodePathLI(File codePath) { 7255 if (codePath.isDirectory()) { 7256 try { 7257 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7258 } catch (InstallerException e) { 7259 Slog.w(TAG, "Failed to remove code path", e); 7260 } 7261 } else { 7262 codePath.delete(); 7263 } 7264 } 7265 7266 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7267 try { 7268 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7269 } catch (InstallerException e) { 7270 Slog.w(TAG, "Failed to destroy app data", e); 7271 } 7272 } 7273 7274 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7275 int appId, String seinfo) { 7276 try { 7277 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7278 } catch (InstallerException e) { 7279 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7280 } 7281 } 7282 7283 private void deleteProfilesLI(String packageName, boolean destroy) { 7284 final PackageParser.Package pkg; 7285 synchronized (mPackages) { 7286 pkg = mPackages.get(packageName); 7287 } 7288 if (pkg == null) { 7289 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7290 return; 7291 } 7292 deleteProfilesLI(pkg, destroy); 7293 } 7294 7295 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7296 try { 7297 if (destroy) { 7298 mInstaller.destroyAppProfiles(pkg.packageName); 7299 } else { 7300 mInstaller.clearAppProfiles(pkg.packageName); 7301 } 7302 } catch (InstallerException ex) { 7303 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7304 } 7305 } 7306 7307 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7308 final PackageParser.Package pkg; 7309 synchronized (mPackages) { 7310 pkg = mPackages.get(packageName); 7311 } 7312 if (pkg == null) { 7313 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7314 return; 7315 } 7316 deleteCodeCacheDirsLI(pkg); 7317 } 7318 7319 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7320 // TODO: triage flags as part of 26466827 7321 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7322 7323 int[] users = sUserManager.getUserIds(); 7324 int res = 0; 7325 for (int user : users) { 7326 // Remove the parent code cache 7327 try { 7328 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7329 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7330 } catch (InstallerException e) { 7331 Slog.w(TAG, "Failed to delete code cache directory", e); 7332 } 7333 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7334 for (int i = 0; i < childCount; i++) { 7335 PackageParser.Package childPkg = pkg.childPackages.get(i); 7336 // Remove the child code cache 7337 try { 7338 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7339 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7340 } catch (InstallerException e) { 7341 Slog.w(TAG, "Failed to delete code cache directory", e); 7342 } 7343 } 7344 } 7345 } 7346 7347 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7348 long lastUpdateTime) { 7349 // Set parent install/update time 7350 PackageSetting ps = (PackageSetting) pkg.mExtras; 7351 if (ps != null) { 7352 ps.firstInstallTime = firstInstallTime; 7353 ps.lastUpdateTime = lastUpdateTime; 7354 } 7355 // Set children install/update time 7356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7357 for (int i = 0; i < childCount; i++) { 7358 PackageParser.Package childPkg = pkg.childPackages.get(i); 7359 ps = (PackageSetting) childPkg.mExtras; 7360 if (ps != null) { 7361 ps.firstInstallTime = firstInstallTime; 7362 ps.lastUpdateTime = lastUpdateTime; 7363 } 7364 } 7365 } 7366 7367 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7368 PackageParser.Package changingLib) { 7369 if (file.path != null) { 7370 usesLibraryFiles.add(file.path); 7371 return; 7372 } 7373 PackageParser.Package p = mPackages.get(file.apk); 7374 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7375 // If we are doing this while in the middle of updating a library apk, 7376 // then we need to make sure to use that new apk for determining the 7377 // dependencies here. (We haven't yet finished committing the new apk 7378 // to the package manager state.) 7379 if (p == null || p.packageName.equals(changingLib.packageName)) { 7380 p = changingLib; 7381 } 7382 } 7383 if (p != null) { 7384 usesLibraryFiles.addAll(p.getAllCodePaths()); 7385 } 7386 } 7387 7388 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7389 PackageParser.Package changingLib) throws PackageManagerException { 7390 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7391 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7392 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7393 for (int i=0; i<N; i++) { 7394 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7395 if (file == null) { 7396 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7397 "Package " + pkg.packageName + " requires unavailable shared library " 7398 + pkg.usesLibraries.get(i) + "; failing!"); 7399 } 7400 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7401 } 7402 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7403 for (int i=0; i<N; i++) { 7404 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7405 if (file == null) { 7406 Slog.w(TAG, "Package " + pkg.packageName 7407 + " desires unavailable shared library " 7408 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7409 } else { 7410 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7411 } 7412 } 7413 N = usesLibraryFiles.size(); 7414 if (N > 0) { 7415 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7416 } else { 7417 pkg.usesLibraryFiles = null; 7418 } 7419 } 7420 } 7421 7422 private static boolean hasString(List<String> list, List<String> which) { 7423 if (list == null) { 7424 return false; 7425 } 7426 for (int i=list.size()-1; i>=0; i--) { 7427 for (int j=which.size()-1; j>=0; j--) { 7428 if (which.get(j).equals(list.get(i))) { 7429 return true; 7430 } 7431 } 7432 } 7433 return false; 7434 } 7435 7436 private void updateAllSharedLibrariesLPw() { 7437 for (PackageParser.Package pkg : mPackages.values()) { 7438 try { 7439 updateSharedLibrariesLPw(pkg, null); 7440 } catch (PackageManagerException e) { 7441 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7442 } 7443 } 7444 } 7445 7446 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7447 PackageParser.Package changingPkg) { 7448 ArrayList<PackageParser.Package> res = null; 7449 for (PackageParser.Package pkg : mPackages.values()) { 7450 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7451 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7452 if (res == null) { 7453 res = new ArrayList<PackageParser.Package>(); 7454 } 7455 res.add(pkg); 7456 try { 7457 updateSharedLibrariesLPw(pkg, changingPkg); 7458 } catch (PackageManagerException e) { 7459 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7460 } 7461 } 7462 } 7463 return res; 7464 } 7465 7466 /** 7467 * Derive the value of the {@code cpuAbiOverride} based on the provided 7468 * value and an optional stored value from the package settings. 7469 */ 7470 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7471 String cpuAbiOverride = null; 7472 7473 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7474 cpuAbiOverride = null; 7475 } else if (abiOverride != null) { 7476 cpuAbiOverride = abiOverride; 7477 } else if (settings != null) { 7478 cpuAbiOverride = settings.cpuAbiOverrideString; 7479 } 7480 7481 return cpuAbiOverride; 7482 } 7483 7484 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7485 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7487 // If the package has children and this is the first dive in the function 7488 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7489 // whether all packages (parent and children) would be successfully scanned 7490 // before the actual scan since scanning mutates internal state and we want 7491 // to atomically install the package and its children. 7492 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7493 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7494 scanFlags |= SCAN_CHECK_ONLY; 7495 } 7496 } else { 7497 scanFlags &= ~SCAN_CHECK_ONLY; 7498 } 7499 7500 final PackageParser.Package scannedPkg; 7501 try { 7502 // Scan the parent 7503 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7504 // Scan the children 7505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7506 for (int i = 0; i < childCount; i++) { 7507 PackageParser.Package childPkg = pkg.childPackages.get(i); 7508 scanPackageLI(childPkg, parseFlags, 7509 scanFlags, currentTime, user); 7510 } 7511 } finally { 7512 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7513 } 7514 7515 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7516 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7517 } 7518 7519 return scannedPkg; 7520 } 7521 7522 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7523 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7524 boolean success = false; 7525 try { 7526 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7527 currentTime, user); 7528 success = true; 7529 return res; 7530 } finally { 7531 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7532 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7533 } 7534 } 7535 } 7536 7537 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7538 int scanFlags, long currentTime, UserHandle user) 7539 throws PackageManagerException { 7540 final File scanFile = new File(pkg.codePath); 7541 if (pkg.applicationInfo.getCodePath() == null || 7542 pkg.applicationInfo.getResourcePath() == null) { 7543 // Bail out. The resource and code paths haven't been set. 7544 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7545 "Code and resource paths haven't been set correctly"); 7546 } 7547 7548 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7549 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7550 } else { 7551 // Only allow system apps to be flagged as core apps. 7552 pkg.coreApp = false; 7553 } 7554 7555 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7556 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7557 } 7558 7559 if (mCustomResolverComponentName != null && 7560 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7561 setUpCustomResolverActivity(pkg); 7562 } 7563 7564 if (pkg.packageName.equals("android")) { 7565 synchronized (mPackages) { 7566 if (mAndroidApplication != null) { 7567 Slog.w(TAG, "*************************************************"); 7568 Slog.w(TAG, "Core android package being redefined. Skipping."); 7569 Slog.w(TAG, " file=" + scanFile); 7570 Slog.w(TAG, "*************************************************"); 7571 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7572 "Core android package being redefined. Skipping."); 7573 } 7574 7575 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7576 // Set up information for our fall-back user intent resolution activity. 7577 mPlatformPackage = pkg; 7578 pkg.mVersionCode = mSdkVersion; 7579 mAndroidApplication = pkg.applicationInfo; 7580 7581 if (!mResolverReplaced) { 7582 mResolveActivity.applicationInfo = mAndroidApplication; 7583 mResolveActivity.name = ResolverActivity.class.getName(); 7584 mResolveActivity.packageName = mAndroidApplication.packageName; 7585 mResolveActivity.processName = "system:ui"; 7586 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7587 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7588 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7589 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7590 mResolveActivity.exported = true; 7591 mResolveActivity.enabled = true; 7592 mResolveInfo.activityInfo = mResolveActivity; 7593 mResolveInfo.priority = 0; 7594 mResolveInfo.preferredOrder = 0; 7595 mResolveInfo.match = 0; 7596 mResolveComponentName = new ComponentName( 7597 mAndroidApplication.packageName, mResolveActivity.name); 7598 } 7599 } 7600 } 7601 } 7602 7603 if (DEBUG_PACKAGE_SCANNING) { 7604 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7605 Log.d(TAG, "Scanning package " + pkg.packageName); 7606 } 7607 7608 synchronized (mPackages) { 7609 if (mPackages.containsKey(pkg.packageName) 7610 || mSharedLibraries.containsKey(pkg.packageName)) { 7611 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7612 "Application package " + pkg.packageName 7613 + " already installed. Skipping duplicate."); 7614 } 7615 7616 // If we're only installing presumed-existing packages, require that the 7617 // scanned APK is both already known and at the path previously established 7618 // for it. Previously unknown packages we pick up normally, but if we have an 7619 // a priori expectation about this package's install presence, enforce it. 7620 // With a singular exception for new system packages. When an OTA contains 7621 // a new system package, we allow the codepath to change from a system location 7622 // to the user-installed location. If we don't allow this change, any newer, 7623 // user-installed version of the application will be ignored. 7624 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7625 if (mExpectingBetter.containsKey(pkg.packageName)) { 7626 logCriticalInfo(Log.WARN, 7627 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7628 } else { 7629 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7630 if (known != null) { 7631 if (DEBUG_PACKAGE_SCANNING) { 7632 Log.d(TAG, "Examining " + pkg.codePath 7633 + " and requiring known paths " + known.codePathString 7634 + " & " + known.resourcePathString); 7635 } 7636 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7637 || !pkg.applicationInfo.getResourcePath().equals( 7638 known.resourcePathString)) { 7639 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7640 "Application package " + pkg.packageName 7641 + " found at " + pkg.applicationInfo.getCodePath() 7642 + " but expected at " + known.codePathString 7643 + "; ignoring."); 7644 } 7645 } 7646 } 7647 } 7648 } 7649 7650 // Initialize package source and resource directories 7651 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7652 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7653 7654 SharedUserSetting suid = null; 7655 PackageSetting pkgSetting = null; 7656 7657 if (!isSystemApp(pkg)) { 7658 // Only system apps can use these features. 7659 pkg.mOriginalPackages = null; 7660 pkg.mRealPackage = null; 7661 pkg.mAdoptPermissions = null; 7662 } 7663 7664 // Getting the package setting may have a side-effect, so if we 7665 // are only checking if scan would succeed, stash a copy of the 7666 // old setting to restore at the end. 7667 PackageSetting nonMutatedPs = null; 7668 7669 // writer 7670 synchronized (mPackages) { 7671 if (pkg.mSharedUserId != null) { 7672 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7673 if (suid == null) { 7674 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7675 "Creating application package " + pkg.packageName 7676 + " for shared user failed"); 7677 } 7678 if (DEBUG_PACKAGE_SCANNING) { 7679 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7680 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7681 + "): packages=" + suid.packages); 7682 } 7683 } 7684 7685 // Check if we are renaming from an original package name. 7686 PackageSetting origPackage = null; 7687 String realName = null; 7688 if (pkg.mOriginalPackages != null) { 7689 // This package may need to be renamed to a previously 7690 // installed name. Let's check on that... 7691 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7692 if (pkg.mOriginalPackages.contains(renamed)) { 7693 // This package had originally been installed as the 7694 // original name, and we have already taken care of 7695 // transitioning to the new one. Just update the new 7696 // one to continue using the old name. 7697 realName = pkg.mRealPackage; 7698 if (!pkg.packageName.equals(renamed)) { 7699 // Callers into this function may have already taken 7700 // care of renaming the package; only do it here if 7701 // it is not already done. 7702 pkg.setPackageName(renamed); 7703 } 7704 7705 } else { 7706 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7707 if ((origPackage = mSettings.peekPackageLPr( 7708 pkg.mOriginalPackages.get(i))) != null) { 7709 // We do have the package already installed under its 7710 // original name... should we use it? 7711 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7712 // New package is not compatible with original. 7713 origPackage = null; 7714 continue; 7715 } else if (origPackage.sharedUser != null) { 7716 // Make sure uid is compatible between packages. 7717 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7718 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7719 + " to " + pkg.packageName + ": old uid " 7720 + origPackage.sharedUser.name 7721 + " differs from " + pkg.mSharedUserId); 7722 origPackage = null; 7723 continue; 7724 } 7725 } else { 7726 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7727 + pkg.packageName + " to old name " + origPackage.name); 7728 } 7729 break; 7730 } 7731 } 7732 } 7733 } 7734 7735 if (mTransferedPackages.contains(pkg.packageName)) { 7736 Slog.w(TAG, "Package " + pkg.packageName 7737 + " was transferred to another, but its .apk remains"); 7738 } 7739 7740 // See comments in nonMutatedPs declaration 7741 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7742 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7743 if (foundPs != null) { 7744 nonMutatedPs = new PackageSetting(foundPs); 7745 } 7746 } 7747 7748 // Just create the setting, don't add it yet. For already existing packages 7749 // the PkgSetting exists already and doesn't have to be created. 7750 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7751 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7752 pkg.applicationInfo.primaryCpuAbi, 7753 pkg.applicationInfo.secondaryCpuAbi, 7754 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7755 user, false); 7756 if (pkgSetting == null) { 7757 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7758 "Creating application package " + pkg.packageName + " failed"); 7759 } 7760 7761 if (pkgSetting.origPackage != null) { 7762 // If we are first transitioning from an original package, 7763 // fix up the new package's name now. We need to do this after 7764 // looking up the package under its new name, so getPackageLP 7765 // can take care of fiddling things correctly. 7766 pkg.setPackageName(origPackage.name); 7767 7768 // File a report about this. 7769 String msg = "New package " + pkgSetting.realName 7770 + " renamed to replace old package " + pkgSetting.name; 7771 reportSettingsProblem(Log.WARN, msg); 7772 7773 // Make a note of it. 7774 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7775 mTransferedPackages.add(origPackage.name); 7776 } 7777 7778 // No longer need to retain this. 7779 pkgSetting.origPackage = null; 7780 } 7781 7782 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7783 // Make a note of it. 7784 mTransferedPackages.add(pkg.packageName); 7785 } 7786 7787 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7788 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7789 } 7790 7791 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7792 // Check all shared libraries and map to their actual file path. 7793 // We only do this here for apps not on a system dir, because those 7794 // are the only ones that can fail an install due to this. We 7795 // will take care of the system apps by updating all of their 7796 // library paths after the scan is done. 7797 updateSharedLibrariesLPw(pkg, null); 7798 } 7799 7800 if (mFoundPolicyFile) { 7801 SELinuxMMAC.assignSeinfoValue(pkg); 7802 } 7803 7804 pkg.applicationInfo.uid = pkgSetting.appId; 7805 pkg.mExtras = pkgSetting; 7806 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7807 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7808 // We just determined the app is signed correctly, so bring 7809 // over the latest parsed certs. 7810 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7811 } else { 7812 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7813 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7814 "Package " + pkg.packageName + " upgrade keys do not match the " 7815 + "previously installed version"); 7816 } else { 7817 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7818 String msg = "System package " + pkg.packageName 7819 + " signature changed; retaining data."; 7820 reportSettingsProblem(Log.WARN, msg); 7821 } 7822 } 7823 } else { 7824 try { 7825 verifySignaturesLP(pkgSetting, pkg); 7826 // We just determined the app is signed correctly, so bring 7827 // over the latest parsed certs. 7828 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7829 } catch (PackageManagerException e) { 7830 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7831 throw e; 7832 } 7833 // The signature has changed, but this package is in the system 7834 // image... let's recover! 7835 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7836 // However... if this package is part of a shared user, but it 7837 // doesn't match the signature of the shared user, let's fail. 7838 // What this means is that you can't change the signatures 7839 // associated with an overall shared user, which doesn't seem all 7840 // that unreasonable. 7841 if (pkgSetting.sharedUser != null) { 7842 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7843 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7844 throw new PackageManagerException( 7845 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7846 "Signature mismatch for shared user: " 7847 + pkgSetting.sharedUser); 7848 } 7849 } 7850 // File a report about this. 7851 String msg = "System package " + pkg.packageName 7852 + " signature changed; retaining data."; 7853 reportSettingsProblem(Log.WARN, msg); 7854 } 7855 } 7856 // Verify that this new package doesn't have any content providers 7857 // that conflict with existing packages. Only do this if the 7858 // package isn't already installed, since we don't want to break 7859 // things that are installed. 7860 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7861 final int N = pkg.providers.size(); 7862 int i; 7863 for (i=0; i<N; i++) { 7864 PackageParser.Provider p = pkg.providers.get(i); 7865 if (p.info.authority != null) { 7866 String names[] = p.info.authority.split(";"); 7867 for (int j = 0; j < names.length; j++) { 7868 if (mProvidersByAuthority.containsKey(names[j])) { 7869 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7870 final String otherPackageName = 7871 ((other != null && other.getComponentName() != null) ? 7872 other.getComponentName().getPackageName() : "?"); 7873 throw new PackageManagerException( 7874 INSTALL_FAILED_CONFLICTING_PROVIDER, 7875 "Can't install because provider name " + names[j] 7876 + " (in package " + pkg.applicationInfo.packageName 7877 + ") is already used by " + otherPackageName); 7878 } 7879 } 7880 } 7881 } 7882 } 7883 7884 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7885 // This package wants to adopt ownership of permissions from 7886 // another package. 7887 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7888 final String origName = pkg.mAdoptPermissions.get(i); 7889 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7890 if (orig != null) { 7891 if (verifyPackageUpdateLPr(orig, pkg)) { 7892 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7893 + pkg.packageName); 7894 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7895 } 7896 } 7897 } 7898 } 7899 } 7900 7901 final String pkgName = pkg.packageName; 7902 7903 final long scanFileTime = scanFile.lastModified(); 7904 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7905 pkg.applicationInfo.processName = fixProcessName( 7906 pkg.applicationInfo.packageName, 7907 pkg.applicationInfo.processName, 7908 pkg.applicationInfo.uid); 7909 7910 if (pkg != mPlatformPackage) { 7911 // Get all of our default paths setup 7912 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7913 } 7914 7915 final String path = scanFile.getPath(); 7916 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7917 7918 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7919 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7920 7921 // Some system apps still use directory structure for native libraries 7922 // in which case we might end up not detecting abi solely based on apk 7923 // structure. Try to detect abi based on directory structure. 7924 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7925 pkg.applicationInfo.primaryCpuAbi == null) { 7926 setBundledAppAbisAndRoots(pkg, pkgSetting); 7927 setNativeLibraryPaths(pkg); 7928 } 7929 7930 } else { 7931 if ((scanFlags & SCAN_MOVE) != 0) { 7932 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7933 // but we already have this packages package info in the PackageSetting. We just 7934 // use that and derive the native library path based on the new codepath. 7935 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7936 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7937 } 7938 7939 // Set native library paths again. For moves, the path will be updated based on the 7940 // ABIs we've determined above. For non-moves, the path will be updated based on the 7941 // ABIs we determined during compilation, but the path will depend on the final 7942 // package path (after the rename away from the stage path). 7943 setNativeLibraryPaths(pkg); 7944 } 7945 7946 // This is a special case for the "system" package, where the ABI is 7947 // dictated by the zygote configuration (and init.rc). We should keep track 7948 // of this ABI so that we can deal with "normal" applications that run under 7949 // the same UID correctly. 7950 if (mPlatformPackage == pkg) { 7951 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7952 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7953 } 7954 7955 // If there's a mismatch between the abi-override in the package setting 7956 // and the abiOverride specified for the install. Warn about this because we 7957 // would've already compiled the app without taking the package setting into 7958 // account. 7959 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7960 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7961 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7962 " for package " + pkg.packageName); 7963 } 7964 } 7965 7966 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7967 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7968 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7969 7970 // Copy the derived override back to the parsed package, so that we can 7971 // update the package settings accordingly. 7972 pkg.cpuAbiOverride = cpuAbiOverride; 7973 7974 if (DEBUG_ABI_SELECTION) { 7975 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7976 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7977 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7978 } 7979 7980 // Push the derived path down into PackageSettings so we know what to 7981 // clean up at uninstall time. 7982 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7983 7984 if (DEBUG_ABI_SELECTION) { 7985 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7986 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7987 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7988 } 7989 7990 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7991 // We don't do this here during boot because we can do it all 7992 // at once after scanning all existing packages. 7993 // 7994 // We also do this *before* we perform dexopt on this package, so that 7995 // we can avoid redundant dexopts, and also to make sure we've got the 7996 // code and package path correct. 7997 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7998 pkg, true /* boot complete */); 7999 } 8000 8001 if (mFactoryTest && pkg.requestedPermissions.contains( 8002 android.Manifest.permission.FACTORY_TEST)) { 8003 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8004 } 8005 8006 ArrayList<PackageParser.Package> clientLibPkgs = null; 8007 8008 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8009 if (nonMutatedPs != null) { 8010 synchronized (mPackages) { 8011 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8012 } 8013 } 8014 return pkg; 8015 } 8016 8017 // Only privileged apps and updated privileged apps can add child packages. 8018 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8019 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8020 throw new PackageManagerException("Only privileged apps and updated " 8021 + "privileged apps can add child packages. Ignoring package " 8022 + pkg.packageName); 8023 } 8024 final int childCount = pkg.childPackages.size(); 8025 for (int i = 0; i < childCount; i++) { 8026 PackageParser.Package childPkg = pkg.childPackages.get(i); 8027 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8028 childPkg.packageName)) { 8029 throw new PackageManagerException("Cannot override a child package of " 8030 + "another disabled system app. Ignoring package " + pkg.packageName); 8031 } 8032 } 8033 } 8034 8035 // writer 8036 synchronized (mPackages) { 8037 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8038 // Only system apps can add new shared libraries. 8039 if (pkg.libraryNames != null) { 8040 for (int i=0; i<pkg.libraryNames.size(); i++) { 8041 String name = pkg.libraryNames.get(i); 8042 boolean allowed = false; 8043 if (pkg.isUpdatedSystemApp()) { 8044 // New library entries can only be added through the 8045 // system image. This is important to get rid of a lot 8046 // of nasty edge cases: for example if we allowed a non- 8047 // system update of the app to add a library, then uninstalling 8048 // the update would make the library go away, and assumptions 8049 // we made such as through app install filtering would now 8050 // have allowed apps on the device which aren't compatible 8051 // with it. Better to just have the restriction here, be 8052 // conservative, and create many fewer cases that can negatively 8053 // impact the user experience. 8054 final PackageSetting sysPs = mSettings 8055 .getDisabledSystemPkgLPr(pkg.packageName); 8056 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8057 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8058 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8059 allowed = true; 8060 break; 8061 } 8062 } 8063 } 8064 } else { 8065 allowed = true; 8066 } 8067 if (allowed) { 8068 if (!mSharedLibraries.containsKey(name)) { 8069 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8070 } else if (!name.equals(pkg.packageName)) { 8071 Slog.w(TAG, "Package " + pkg.packageName + " library " 8072 + name + " already exists; skipping"); 8073 } 8074 } else { 8075 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8076 + name + " that is not declared on system image; skipping"); 8077 } 8078 } 8079 if ((scanFlags & SCAN_BOOTING) == 0) { 8080 // If we are not booting, we need to update any applications 8081 // that are clients of our shared library. If we are booting, 8082 // this will all be done once the scan is complete. 8083 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8084 } 8085 } 8086 } 8087 } 8088 8089 // Request the ActivityManager to kill the process(only for existing packages) 8090 // so that we do not end up in a confused state while the user is still using the older 8091 // version of the application while the new one gets installed. 8092 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8093 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8094 if (killApp) { 8095 if (isReplacing) { 8096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8097 8098 killApplication(pkg.applicationInfo.packageName, 8099 pkg.applicationInfo.uid, "replace pkg"); 8100 8101 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8102 } 8103 } 8104 8105 // Also need to kill any apps that are dependent on the library. 8106 if (clientLibPkgs != null) { 8107 for (int i=0; i<clientLibPkgs.size(); i++) { 8108 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8109 killApplication(clientPkg.applicationInfo.packageName, 8110 clientPkg.applicationInfo.uid, "update lib"); 8111 } 8112 } 8113 8114 // Make sure we're not adding any bogus keyset info 8115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8116 ksms.assertScannedPackageValid(pkg); 8117 8118 // writer 8119 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8120 8121 boolean createIdmapFailed = false; 8122 synchronized (mPackages) { 8123 // We don't expect installation to fail beyond this point 8124 8125 // Add the new setting to mSettings 8126 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8127 // Add the new setting to mPackages 8128 mPackages.put(pkg.applicationInfo.packageName, pkg); 8129 // Make sure we don't accidentally delete its data. 8130 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8131 while (iter.hasNext()) { 8132 PackageCleanItem item = iter.next(); 8133 if (pkgName.equals(item.packageName)) { 8134 iter.remove(); 8135 } 8136 } 8137 8138 // Take care of first install / last update times. 8139 if (currentTime != 0) { 8140 if (pkgSetting.firstInstallTime == 0) { 8141 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8142 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8143 pkgSetting.lastUpdateTime = currentTime; 8144 } 8145 } else if (pkgSetting.firstInstallTime == 0) { 8146 // We need *something*. Take time time stamp of the file. 8147 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8148 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8149 if (scanFileTime != pkgSetting.timeStamp) { 8150 // A package on the system image has changed; consider this 8151 // to be an update. 8152 pkgSetting.lastUpdateTime = scanFileTime; 8153 } 8154 } 8155 8156 // Add the package's KeySets to the global KeySetManagerService 8157 ksms.addScannedPackageLPw(pkg); 8158 8159 int N = pkg.providers.size(); 8160 StringBuilder r = null; 8161 int i; 8162 for (i=0; i<N; i++) { 8163 PackageParser.Provider p = pkg.providers.get(i); 8164 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8165 p.info.processName, pkg.applicationInfo.uid); 8166 mProviders.addProvider(p); 8167 p.syncable = p.info.isSyncable; 8168 if (p.info.authority != null) { 8169 String names[] = p.info.authority.split(";"); 8170 p.info.authority = null; 8171 for (int j = 0; j < names.length; j++) { 8172 if (j == 1 && p.syncable) { 8173 // We only want the first authority for a provider to possibly be 8174 // syncable, so if we already added this provider using a different 8175 // authority clear the syncable flag. We copy the provider before 8176 // changing it because the mProviders object contains a reference 8177 // to a provider that we don't want to change. 8178 // Only do this for the second authority since the resulting provider 8179 // object can be the same for all future authorities for this provider. 8180 p = new PackageParser.Provider(p); 8181 p.syncable = false; 8182 } 8183 if (!mProvidersByAuthority.containsKey(names[j])) { 8184 mProvidersByAuthority.put(names[j], p); 8185 if (p.info.authority == null) { 8186 p.info.authority = names[j]; 8187 } else { 8188 p.info.authority = p.info.authority + ";" + names[j]; 8189 } 8190 if (DEBUG_PACKAGE_SCANNING) { 8191 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8192 Log.d(TAG, "Registered content provider: " + names[j] 8193 + ", className = " + p.info.name + ", isSyncable = " 8194 + p.info.isSyncable); 8195 } 8196 } else { 8197 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8198 Slog.w(TAG, "Skipping provider name " + names[j] + 8199 " (in package " + pkg.applicationInfo.packageName + 8200 "): name already used by " 8201 + ((other != null && other.getComponentName() != null) 8202 ? other.getComponentName().getPackageName() : "?")); 8203 } 8204 } 8205 } 8206 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8207 if (r == null) { 8208 r = new StringBuilder(256); 8209 } else { 8210 r.append(' '); 8211 } 8212 r.append(p.info.name); 8213 } 8214 } 8215 if (r != null) { 8216 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8217 } 8218 8219 N = pkg.services.size(); 8220 r = null; 8221 for (i=0; i<N; i++) { 8222 PackageParser.Service s = pkg.services.get(i); 8223 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8224 s.info.processName, pkg.applicationInfo.uid); 8225 mServices.addService(s); 8226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8227 if (r == null) { 8228 r = new StringBuilder(256); 8229 } else { 8230 r.append(' '); 8231 } 8232 r.append(s.info.name); 8233 } 8234 } 8235 if (r != null) { 8236 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8237 } 8238 8239 N = pkg.receivers.size(); 8240 r = null; 8241 for (i=0; i<N; i++) { 8242 PackageParser.Activity a = pkg.receivers.get(i); 8243 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8244 a.info.processName, pkg.applicationInfo.uid); 8245 mReceivers.addActivity(a, "receiver"); 8246 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8247 if (r == null) { 8248 r = new StringBuilder(256); 8249 } else { 8250 r.append(' '); 8251 } 8252 r.append(a.info.name); 8253 } 8254 } 8255 if (r != null) { 8256 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8257 } 8258 8259 N = pkg.activities.size(); 8260 r = null; 8261 for (i=0; i<N; i++) { 8262 PackageParser.Activity a = pkg.activities.get(i); 8263 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8264 a.info.processName, pkg.applicationInfo.uid); 8265 mActivities.addActivity(a, "activity"); 8266 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8267 if (r == null) { 8268 r = new StringBuilder(256); 8269 } else { 8270 r.append(' '); 8271 } 8272 r.append(a.info.name); 8273 } 8274 } 8275 if (r != null) { 8276 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8277 } 8278 8279 N = pkg.permissionGroups.size(); 8280 r = null; 8281 for (i=0; i<N; i++) { 8282 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8283 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8284 if (cur == null) { 8285 mPermissionGroups.put(pg.info.name, pg); 8286 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8287 if (r == null) { 8288 r = new StringBuilder(256); 8289 } else { 8290 r.append(' '); 8291 } 8292 r.append(pg.info.name); 8293 } 8294 } else { 8295 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8296 + pg.info.packageName + " ignored: original from " 8297 + cur.info.packageName); 8298 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8299 if (r == null) { 8300 r = new StringBuilder(256); 8301 } else { 8302 r.append(' '); 8303 } 8304 r.append("DUP:"); 8305 r.append(pg.info.name); 8306 } 8307 } 8308 } 8309 if (r != null) { 8310 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8311 } 8312 8313 N = pkg.permissions.size(); 8314 r = null; 8315 for (i=0; i<N; i++) { 8316 PackageParser.Permission p = pkg.permissions.get(i); 8317 8318 // Assume by default that we did not install this permission into the system. 8319 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8320 8321 // Now that permission groups have a special meaning, we ignore permission 8322 // groups for legacy apps to prevent unexpected behavior. In particular, 8323 // permissions for one app being granted to someone just becase they happen 8324 // to be in a group defined by another app (before this had no implications). 8325 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8326 p.group = mPermissionGroups.get(p.info.group); 8327 // Warn for a permission in an unknown group. 8328 if (p.info.group != null && p.group == null) { 8329 Slog.w(TAG, "Permission " + p.info.name + " from package " 8330 + p.info.packageName + " in an unknown group " + p.info.group); 8331 } 8332 } 8333 8334 ArrayMap<String, BasePermission> permissionMap = 8335 p.tree ? mSettings.mPermissionTrees 8336 : mSettings.mPermissions; 8337 BasePermission bp = permissionMap.get(p.info.name); 8338 8339 // Allow system apps to redefine non-system permissions 8340 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8341 final boolean currentOwnerIsSystem = (bp.perm != null 8342 && isSystemApp(bp.perm.owner)); 8343 if (isSystemApp(p.owner)) { 8344 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8345 // It's a built-in permission and no owner, take ownership now 8346 bp.packageSetting = pkgSetting; 8347 bp.perm = p; 8348 bp.uid = pkg.applicationInfo.uid; 8349 bp.sourcePackage = p.info.packageName; 8350 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8351 } else if (!currentOwnerIsSystem) { 8352 String msg = "New decl " + p.owner + " of permission " 8353 + p.info.name + " is system; overriding " + bp.sourcePackage; 8354 reportSettingsProblem(Log.WARN, msg); 8355 bp = null; 8356 } 8357 } 8358 } 8359 8360 if (bp == null) { 8361 bp = new BasePermission(p.info.name, p.info.packageName, 8362 BasePermission.TYPE_NORMAL); 8363 permissionMap.put(p.info.name, bp); 8364 } 8365 8366 if (bp.perm == null) { 8367 if (bp.sourcePackage == null 8368 || bp.sourcePackage.equals(p.info.packageName)) { 8369 BasePermission tree = findPermissionTreeLP(p.info.name); 8370 if (tree == null 8371 || tree.sourcePackage.equals(p.info.packageName)) { 8372 bp.packageSetting = pkgSetting; 8373 bp.perm = p; 8374 bp.uid = pkg.applicationInfo.uid; 8375 bp.sourcePackage = p.info.packageName; 8376 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8378 if (r == null) { 8379 r = new StringBuilder(256); 8380 } else { 8381 r.append(' '); 8382 } 8383 r.append(p.info.name); 8384 } 8385 } else { 8386 Slog.w(TAG, "Permission " + p.info.name + " from package " 8387 + p.info.packageName + " ignored: base tree " 8388 + tree.name + " is from package " 8389 + tree.sourcePackage); 8390 } 8391 } else { 8392 Slog.w(TAG, "Permission " + p.info.name + " from package " 8393 + p.info.packageName + " ignored: original from " 8394 + bp.sourcePackage); 8395 } 8396 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8397 if (r == null) { 8398 r = new StringBuilder(256); 8399 } else { 8400 r.append(' '); 8401 } 8402 r.append("DUP:"); 8403 r.append(p.info.name); 8404 } 8405 if (bp.perm == p) { 8406 bp.protectionLevel = p.info.protectionLevel; 8407 } 8408 } 8409 8410 if (r != null) { 8411 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8412 } 8413 8414 N = pkg.instrumentation.size(); 8415 r = null; 8416 for (i=0; i<N; i++) { 8417 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8418 a.info.packageName = pkg.applicationInfo.packageName; 8419 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8420 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8421 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8422 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8423 a.info.dataDir = pkg.applicationInfo.dataDir; 8424 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8425 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8426 8427 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8428 // need other information about the application, like the ABI and what not ? 8429 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8430 mInstrumentation.put(a.getComponentName(), a); 8431 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8432 if (r == null) { 8433 r = new StringBuilder(256); 8434 } else { 8435 r.append(' '); 8436 } 8437 r.append(a.info.name); 8438 } 8439 } 8440 if (r != null) { 8441 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8442 } 8443 8444 if (pkg.protectedBroadcasts != null) { 8445 N = pkg.protectedBroadcasts.size(); 8446 for (i=0; i<N; i++) { 8447 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8448 } 8449 } 8450 8451 pkgSetting.setTimeStamp(scanFileTime); 8452 8453 // Create idmap files for pairs of (packages, overlay packages). 8454 // Note: "android", ie framework-res.apk, is handled by native layers. 8455 if (pkg.mOverlayTarget != null) { 8456 // This is an overlay package. 8457 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8458 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8459 mOverlays.put(pkg.mOverlayTarget, 8460 new ArrayMap<String, PackageParser.Package>()); 8461 } 8462 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8463 map.put(pkg.packageName, pkg); 8464 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8465 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8466 createIdmapFailed = true; 8467 } 8468 } 8469 } else if (mOverlays.containsKey(pkg.packageName) && 8470 !pkg.packageName.equals("android")) { 8471 // This is a regular package, with one or more known overlay packages. 8472 createIdmapsForPackageLI(pkg); 8473 } 8474 } 8475 8476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8477 8478 if (createIdmapFailed) { 8479 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8480 "scanPackageLI failed to createIdmap"); 8481 } 8482 return pkg; 8483 } 8484 8485 /** 8486 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8487 * is derived purely on the basis of the contents of {@code scanFile} and 8488 * {@code cpuAbiOverride}. 8489 * 8490 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8491 */ 8492 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8493 String cpuAbiOverride, boolean extractLibs) 8494 throws PackageManagerException { 8495 // TODO: We can probably be smarter about this stuff. For installed apps, 8496 // we can calculate this information at install time once and for all. For 8497 // system apps, we can probably assume that this information doesn't change 8498 // after the first boot scan. As things stand, we do lots of unnecessary work. 8499 8500 // Give ourselves some initial paths; we'll come back for another 8501 // pass once we've determined ABI below. 8502 setNativeLibraryPaths(pkg); 8503 8504 // We would never need to extract libs for forward-locked and external packages, 8505 // since the container service will do it for us. We shouldn't attempt to 8506 // extract libs from system app when it was not updated. 8507 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8508 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8509 extractLibs = false; 8510 } 8511 8512 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8513 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8514 8515 NativeLibraryHelper.Handle handle = null; 8516 try { 8517 handle = NativeLibraryHelper.Handle.create(pkg); 8518 // TODO(multiArch): This can be null for apps that didn't go through the 8519 // usual installation process. We can calculate it again, like we 8520 // do during install time. 8521 // 8522 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8523 // unnecessary. 8524 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8525 8526 // Null out the abis so that they can be recalculated. 8527 pkg.applicationInfo.primaryCpuAbi = null; 8528 pkg.applicationInfo.secondaryCpuAbi = null; 8529 if (isMultiArch(pkg.applicationInfo)) { 8530 // Warn if we've set an abiOverride for multi-lib packages.. 8531 // By definition, we need to copy both 32 and 64 bit libraries for 8532 // such packages. 8533 if (pkg.cpuAbiOverride != null 8534 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8535 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8536 } 8537 8538 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8539 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8540 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8541 if (extractLibs) { 8542 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8543 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8544 useIsaSpecificSubdirs); 8545 } else { 8546 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8547 } 8548 } 8549 8550 maybeThrowExceptionForMultiArchCopy( 8551 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8552 8553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8554 if (extractLibs) { 8555 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8556 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8557 useIsaSpecificSubdirs); 8558 } else { 8559 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8560 } 8561 } 8562 8563 maybeThrowExceptionForMultiArchCopy( 8564 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8565 8566 if (abi64 >= 0) { 8567 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8568 } 8569 8570 if (abi32 >= 0) { 8571 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8572 if (abi64 >= 0) { 8573 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8574 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8575 pkg.applicationInfo.primaryCpuAbi = abi; 8576 } else { 8577 pkg.applicationInfo.secondaryCpuAbi = abi; 8578 } 8579 } else { 8580 pkg.applicationInfo.primaryCpuAbi = abi; 8581 } 8582 } 8583 8584 } else { 8585 String[] abiList = (cpuAbiOverride != null) ? 8586 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8587 8588 // Enable gross and lame hacks for apps that are built with old 8589 // SDK tools. We must scan their APKs for renderscript bitcode and 8590 // not launch them if it's present. Don't bother checking on devices 8591 // that don't have 64 bit support. 8592 boolean needsRenderScriptOverride = false; 8593 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8594 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8595 abiList = Build.SUPPORTED_32_BIT_ABIS; 8596 needsRenderScriptOverride = true; 8597 } 8598 8599 final int copyRet; 8600 if (extractLibs) { 8601 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8602 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8603 } else { 8604 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8605 } 8606 8607 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8608 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8609 "Error unpackaging native libs for app, errorCode=" + copyRet); 8610 } 8611 8612 if (copyRet >= 0) { 8613 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8614 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8615 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8616 } else if (needsRenderScriptOverride) { 8617 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8618 } 8619 } 8620 } catch (IOException ioe) { 8621 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8622 } finally { 8623 IoUtils.closeQuietly(handle); 8624 } 8625 8626 // Now that we've calculated the ABIs and determined if it's an internal app, 8627 // we will go ahead and populate the nativeLibraryPath. 8628 setNativeLibraryPaths(pkg); 8629 } 8630 8631 /** 8632 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8633 * i.e, so that all packages can be run inside a single process if required. 8634 * 8635 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8636 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8637 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8638 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8639 * updating a package that belongs to a shared user. 8640 * 8641 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8642 * adds unnecessary complexity. 8643 */ 8644 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8645 PackageParser.Package scannedPackage, boolean bootComplete) { 8646 String requiredInstructionSet = null; 8647 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8648 requiredInstructionSet = VMRuntime.getInstructionSet( 8649 scannedPackage.applicationInfo.primaryCpuAbi); 8650 } 8651 8652 PackageSetting requirer = null; 8653 for (PackageSetting ps : packagesForUser) { 8654 // If packagesForUser contains scannedPackage, we skip it. This will happen 8655 // when scannedPackage is an update of an existing package. Without this check, 8656 // we will never be able to change the ABI of any package belonging to a shared 8657 // user, even if it's compatible with other packages. 8658 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8659 if (ps.primaryCpuAbiString == null) { 8660 continue; 8661 } 8662 8663 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8664 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8665 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8666 // this but there's not much we can do. 8667 String errorMessage = "Instruction set mismatch, " 8668 + ((requirer == null) ? "[caller]" : requirer) 8669 + " requires " + requiredInstructionSet + " whereas " + ps 8670 + " requires " + instructionSet; 8671 Slog.w(TAG, errorMessage); 8672 } 8673 8674 if (requiredInstructionSet == null) { 8675 requiredInstructionSet = instructionSet; 8676 requirer = ps; 8677 } 8678 } 8679 } 8680 8681 if (requiredInstructionSet != null) { 8682 String adjustedAbi; 8683 if (requirer != null) { 8684 // requirer != null implies that either scannedPackage was null or that scannedPackage 8685 // did not require an ABI, in which case we have to adjust scannedPackage to match 8686 // the ABI of the set (which is the same as requirer's ABI) 8687 adjustedAbi = requirer.primaryCpuAbiString; 8688 if (scannedPackage != null) { 8689 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8690 } 8691 } else { 8692 // requirer == null implies that we're updating all ABIs in the set to 8693 // match scannedPackage. 8694 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8695 } 8696 8697 for (PackageSetting ps : packagesForUser) { 8698 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8699 if (ps.primaryCpuAbiString != null) { 8700 continue; 8701 } 8702 8703 ps.primaryCpuAbiString = adjustedAbi; 8704 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8705 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8706 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8707 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8708 + " (requirer=" 8709 + (requirer == null ? "null" : requirer.pkg.packageName) 8710 + ", scannedPackage=" 8711 + (scannedPackage != null ? scannedPackage.packageName : "null") 8712 + ")"); 8713 try { 8714 mInstaller.rmdex(ps.codePathString, 8715 getDexCodeInstructionSet(getPreferredInstructionSet())); 8716 } catch (InstallerException ignored) { 8717 } 8718 } 8719 } 8720 } 8721 } 8722 } 8723 8724 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8725 synchronized (mPackages) { 8726 mResolverReplaced = true; 8727 // Set up information for custom user intent resolution activity. 8728 mResolveActivity.applicationInfo = pkg.applicationInfo; 8729 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8730 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8731 mResolveActivity.processName = pkg.applicationInfo.packageName; 8732 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8733 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8734 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8735 mResolveActivity.theme = 0; 8736 mResolveActivity.exported = true; 8737 mResolveActivity.enabled = true; 8738 mResolveInfo.activityInfo = mResolveActivity; 8739 mResolveInfo.priority = 0; 8740 mResolveInfo.preferredOrder = 0; 8741 mResolveInfo.match = 0; 8742 mResolveComponentName = mCustomResolverComponentName; 8743 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8744 mResolveComponentName); 8745 } 8746 } 8747 8748 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8749 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8750 8751 // Set up information for ephemeral installer activity 8752 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8753 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8754 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8755 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8756 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8757 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8758 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8759 mEphemeralInstallerActivity.theme = 0; 8760 mEphemeralInstallerActivity.exported = true; 8761 mEphemeralInstallerActivity.enabled = true; 8762 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8763 mEphemeralInstallerInfo.priority = 0; 8764 mEphemeralInstallerInfo.preferredOrder = 0; 8765 mEphemeralInstallerInfo.match = 0; 8766 8767 if (DEBUG_EPHEMERAL) { 8768 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8769 } 8770 } 8771 8772 private static String calculateBundledApkRoot(final String codePathString) { 8773 final File codePath = new File(codePathString); 8774 final File codeRoot; 8775 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8776 codeRoot = Environment.getRootDirectory(); 8777 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8778 codeRoot = Environment.getOemDirectory(); 8779 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8780 codeRoot = Environment.getVendorDirectory(); 8781 } else { 8782 // Unrecognized code path; take its top real segment as the apk root: 8783 // e.g. /something/app/blah.apk => /something 8784 try { 8785 File f = codePath.getCanonicalFile(); 8786 File parent = f.getParentFile(); // non-null because codePath is a file 8787 File tmp; 8788 while ((tmp = parent.getParentFile()) != null) { 8789 f = parent; 8790 parent = tmp; 8791 } 8792 codeRoot = f; 8793 Slog.w(TAG, "Unrecognized code path " 8794 + codePath + " - using " + codeRoot); 8795 } catch (IOException e) { 8796 // Can't canonicalize the code path -- shenanigans? 8797 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8798 return Environment.getRootDirectory().getPath(); 8799 } 8800 } 8801 return codeRoot.getPath(); 8802 } 8803 8804 /** 8805 * Derive and set the location of native libraries for the given package, 8806 * which varies depending on where and how the package was installed. 8807 */ 8808 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8809 final ApplicationInfo info = pkg.applicationInfo; 8810 final String codePath = pkg.codePath; 8811 final File codeFile = new File(codePath); 8812 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8813 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8814 8815 info.nativeLibraryRootDir = null; 8816 info.nativeLibraryRootRequiresIsa = false; 8817 info.nativeLibraryDir = null; 8818 info.secondaryNativeLibraryDir = null; 8819 8820 if (isApkFile(codeFile)) { 8821 // Monolithic install 8822 if (bundledApp) { 8823 // If "/system/lib64/apkname" exists, assume that is the per-package 8824 // native library directory to use; otherwise use "/system/lib/apkname". 8825 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8826 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8827 getPrimaryInstructionSet(info)); 8828 8829 // This is a bundled system app so choose the path based on the ABI. 8830 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8831 // is just the default path. 8832 final String apkName = deriveCodePathName(codePath); 8833 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8834 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8835 apkName).getAbsolutePath(); 8836 8837 if (info.secondaryCpuAbi != null) { 8838 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8839 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8840 secondaryLibDir, apkName).getAbsolutePath(); 8841 } 8842 } else if (asecApp) { 8843 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8844 .getAbsolutePath(); 8845 } else { 8846 final String apkName = deriveCodePathName(codePath); 8847 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8848 .getAbsolutePath(); 8849 } 8850 8851 info.nativeLibraryRootRequiresIsa = false; 8852 info.nativeLibraryDir = info.nativeLibraryRootDir; 8853 } else { 8854 // Cluster install 8855 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8856 info.nativeLibraryRootRequiresIsa = true; 8857 8858 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8859 getPrimaryInstructionSet(info)).getAbsolutePath(); 8860 8861 if (info.secondaryCpuAbi != null) { 8862 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8863 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8864 } 8865 } 8866 } 8867 8868 /** 8869 * Calculate the abis and roots for a bundled app. These can uniquely 8870 * be determined from the contents of the system partition, i.e whether 8871 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8872 * of this information, and instead assume that the system was built 8873 * sensibly. 8874 */ 8875 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8876 PackageSetting pkgSetting) { 8877 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8878 8879 // If "/system/lib64/apkname" exists, assume that is the per-package 8880 // native library directory to use; otherwise use "/system/lib/apkname". 8881 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8882 setBundledAppAbi(pkg, apkRoot, apkName); 8883 // pkgSetting might be null during rescan following uninstall of updates 8884 // to a bundled app, so accommodate that possibility. The settings in 8885 // that case will be established later from the parsed package. 8886 // 8887 // If the settings aren't null, sync them up with what we've just derived. 8888 // note that apkRoot isn't stored in the package settings. 8889 if (pkgSetting != null) { 8890 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8891 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8892 } 8893 } 8894 8895 /** 8896 * Deduces the ABI of a bundled app and sets the relevant fields on the 8897 * parsed pkg object. 8898 * 8899 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8900 * under which system libraries are installed. 8901 * @param apkName the name of the installed package. 8902 */ 8903 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8904 final File codeFile = new File(pkg.codePath); 8905 8906 final boolean has64BitLibs; 8907 final boolean has32BitLibs; 8908 if (isApkFile(codeFile)) { 8909 // Monolithic install 8910 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8911 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8912 } else { 8913 // Cluster install 8914 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8915 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8916 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8917 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8918 has64BitLibs = (new File(rootDir, isa)).exists(); 8919 } else { 8920 has64BitLibs = false; 8921 } 8922 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8923 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8924 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8925 has32BitLibs = (new File(rootDir, isa)).exists(); 8926 } else { 8927 has32BitLibs = false; 8928 } 8929 } 8930 8931 if (has64BitLibs && !has32BitLibs) { 8932 // The package has 64 bit libs, but not 32 bit libs. Its primary 8933 // ABI should be 64 bit. We can safely assume here that the bundled 8934 // native libraries correspond to the most preferred ABI in the list. 8935 8936 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8937 pkg.applicationInfo.secondaryCpuAbi = null; 8938 } else if (has32BitLibs && !has64BitLibs) { 8939 // The package has 32 bit libs but not 64 bit libs. Its primary 8940 // ABI should be 32 bit. 8941 8942 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8943 pkg.applicationInfo.secondaryCpuAbi = null; 8944 } else if (has32BitLibs && has64BitLibs) { 8945 // The application has both 64 and 32 bit bundled libraries. We check 8946 // here that the app declares multiArch support, and warn if it doesn't. 8947 // 8948 // We will be lenient here and record both ABIs. The primary will be the 8949 // ABI that's higher on the list, i.e, a device that's configured to prefer 8950 // 64 bit apps will see a 64 bit primary ABI, 8951 8952 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8953 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8954 } 8955 8956 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8959 } else { 8960 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8961 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8962 } 8963 } else { 8964 pkg.applicationInfo.primaryCpuAbi = null; 8965 pkg.applicationInfo.secondaryCpuAbi = null; 8966 } 8967 } 8968 8969 private void killPackage(PackageParser.Package pkg, String reason) { 8970 // Kill the parent package 8971 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8972 // Kill the child packages 8973 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8974 for (int i = 0; i < childCount; i++) { 8975 PackageParser.Package childPkg = pkg.childPackages.get(i); 8976 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8977 } 8978 } 8979 8980 private void killApplication(String pkgName, int appId, String reason) { 8981 // Request the ActivityManager to kill the process(only for existing packages) 8982 // so that we do not end up in a confused state while the user is still using the older 8983 // version of the application while the new one gets installed. 8984 IActivityManager am = ActivityManagerNative.getDefault(); 8985 if (am != null) { 8986 try { 8987 am.killApplicationWithAppId(pkgName, appId, reason); 8988 } catch (RemoteException e) { 8989 } 8990 } 8991 } 8992 8993 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8994 // Remove the parent package setting 8995 PackageSetting ps = (PackageSetting) pkg.mExtras; 8996 if (ps != null) { 8997 removePackageLI(ps, chatty); 8998 } 8999 // Remove the child package setting 9000 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9001 for (int i = 0; i < childCount; i++) { 9002 PackageParser.Package childPkg = pkg.childPackages.get(i); 9003 ps = (PackageSetting) childPkg.mExtras; 9004 if (ps != null) { 9005 removePackageLI(ps, chatty); 9006 } 9007 } 9008 } 9009 9010 void removePackageLI(PackageSetting ps, boolean chatty) { 9011 if (DEBUG_INSTALL) { 9012 if (chatty) 9013 Log.d(TAG, "Removing package " + ps.name); 9014 } 9015 9016 // writer 9017 synchronized (mPackages) { 9018 mPackages.remove(ps.name); 9019 final PackageParser.Package pkg = ps.pkg; 9020 if (pkg != null) { 9021 cleanPackageDataStructuresLILPw(pkg, chatty); 9022 } 9023 } 9024 } 9025 9026 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9027 if (DEBUG_INSTALL) { 9028 if (chatty) 9029 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9030 } 9031 9032 // writer 9033 synchronized (mPackages) { 9034 // Remove the parent package 9035 mPackages.remove(pkg.applicationInfo.packageName); 9036 cleanPackageDataStructuresLILPw(pkg, chatty); 9037 9038 // Remove the child packages 9039 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9040 for (int i = 0; i < childCount; i++) { 9041 PackageParser.Package childPkg = pkg.childPackages.get(i); 9042 mPackages.remove(childPkg.applicationInfo.packageName); 9043 cleanPackageDataStructuresLILPw(childPkg, chatty); 9044 } 9045 } 9046 } 9047 9048 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9049 int N = pkg.providers.size(); 9050 StringBuilder r = null; 9051 int i; 9052 for (i=0; i<N; i++) { 9053 PackageParser.Provider p = pkg.providers.get(i); 9054 mProviders.removeProvider(p); 9055 if (p.info.authority == null) { 9056 9057 /* There was another ContentProvider with this authority when 9058 * this app was installed so this authority is null, 9059 * Ignore it as we don't have to unregister the provider. 9060 */ 9061 continue; 9062 } 9063 String names[] = p.info.authority.split(";"); 9064 for (int j = 0; j < names.length; j++) { 9065 if (mProvidersByAuthority.get(names[j]) == p) { 9066 mProvidersByAuthority.remove(names[j]); 9067 if (DEBUG_REMOVE) { 9068 if (chatty) 9069 Log.d(TAG, "Unregistered content provider: " + names[j] 9070 + ", className = " + p.info.name + ", isSyncable = " 9071 + p.info.isSyncable); 9072 } 9073 } 9074 } 9075 if (DEBUG_REMOVE && chatty) { 9076 if (r == null) { 9077 r = new StringBuilder(256); 9078 } else { 9079 r.append(' '); 9080 } 9081 r.append(p.info.name); 9082 } 9083 } 9084 if (r != null) { 9085 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9086 } 9087 9088 N = pkg.services.size(); 9089 r = null; 9090 for (i=0; i<N; i++) { 9091 PackageParser.Service s = pkg.services.get(i); 9092 mServices.removeService(s); 9093 if (chatty) { 9094 if (r == null) { 9095 r = new StringBuilder(256); 9096 } else { 9097 r.append(' '); 9098 } 9099 r.append(s.info.name); 9100 } 9101 } 9102 if (r != null) { 9103 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9104 } 9105 9106 N = pkg.receivers.size(); 9107 r = null; 9108 for (i=0; i<N; i++) { 9109 PackageParser.Activity a = pkg.receivers.get(i); 9110 mReceivers.removeActivity(a, "receiver"); 9111 if (DEBUG_REMOVE && chatty) { 9112 if (r == null) { 9113 r = new StringBuilder(256); 9114 } else { 9115 r.append(' '); 9116 } 9117 r.append(a.info.name); 9118 } 9119 } 9120 if (r != null) { 9121 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9122 } 9123 9124 N = pkg.activities.size(); 9125 r = null; 9126 for (i=0; i<N; i++) { 9127 PackageParser.Activity a = pkg.activities.get(i); 9128 mActivities.removeActivity(a, "activity"); 9129 if (DEBUG_REMOVE && chatty) { 9130 if (r == null) { 9131 r = new StringBuilder(256); 9132 } else { 9133 r.append(' '); 9134 } 9135 r.append(a.info.name); 9136 } 9137 } 9138 if (r != null) { 9139 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9140 } 9141 9142 N = pkg.permissions.size(); 9143 r = null; 9144 for (i=0; i<N; i++) { 9145 PackageParser.Permission p = pkg.permissions.get(i); 9146 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9147 if (bp == null) { 9148 bp = mSettings.mPermissionTrees.get(p.info.name); 9149 } 9150 if (bp != null && bp.perm == p) { 9151 bp.perm = null; 9152 if (DEBUG_REMOVE && chatty) { 9153 if (r == null) { 9154 r = new StringBuilder(256); 9155 } else { 9156 r.append(' '); 9157 } 9158 r.append(p.info.name); 9159 } 9160 } 9161 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9162 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9163 if (appOpPkgs != null) { 9164 appOpPkgs.remove(pkg.packageName); 9165 } 9166 } 9167 } 9168 if (r != null) { 9169 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9170 } 9171 9172 N = pkg.requestedPermissions.size(); 9173 r = null; 9174 for (i=0; i<N; i++) { 9175 String perm = pkg.requestedPermissions.get(i); 9176 BasePermission bp = mSettings.mPermissions.get(perm); 9177 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9178 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9179 if (appOpPkgs != null) { 9180 appOpPkgs.remove(pkg.packageName); 9181 if (appOpPkgs.isEmpty()) { 9182 mAppOpPermissionPackages.remove(perm); 9183 } 9184 } 9185 } 9186 } 9187 if (r != null) { 9188 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9189 } 9190 9191 N = pkg.instrumentation.size(); 9192 r = null; 9193 for (i=0; i<N; i++) { 9194 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9195 mInstrumentation.remove(a.getComponentName()); 9196 if (DEBUG_REMOVE && chatty) { 9197 if (r == null) { 9198 r = new StringBuilder(256); 9199 } else { 9200 r.append(' '); 9201 } 9202 r.append(a.info.name); 9203 } 9204 } 9205 if (r != null) { 9206 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9207 } 9208 9209 r = null; 9210 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9211 // Only system apps can hold shared libraries. 9212 if (pkg.libraryNames != null) { 9213 for (i=0; i<pkg.libraryNames.size(); i++) { 9214 String name = pkg.libraryNames.get(i); 9215 SharedLibraryEntry cur = mSharedLibraries.get(name); 9216 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9217 mSharedLibraries.remove(name); 9218 if (DEBUG_REMOVE && chatty) { 9219 if (r == null) { 9220 r = new StringBuilder(256); 9221 } else { 9222 r.append(' '); 9223 } 9224 r.append(name); 9225 } 9226 } 9227 } 9228 } 9229 } 9230 if (r != null) { 9231 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9232 } 9233 } 9234 9235 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9236 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9237 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9238 return true; 9239 } 9240 } 9241 return false; 9242 } 9243 9244 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9245 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9246 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9247 9248 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9249 // Update the parent permissions 9250 updatePermissionsLPw(pkg.packageName, pkg, flags); 9251 // Update the child permissions 9252 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9253 for (int i = 0; i < childCount; i++) { 9254 PackageParser.Package childPkg = pkg.childPackages.get(i); 9255 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9256 } 9257 } 9258 9259 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9260 int flags) { 9261 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9262 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9263 } 9264 9265 private void updatePermissionsLPw(String changingPkg, 9266 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9267 // Make sure there are no dangling permission trees. 9268 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9269 while (it.hasNext()) { 9270 final BasePermission bp = it.next(); 9271 if (bp.packageSetting == null) { 9272 // We may not yet have parsed the package, so just see if 9273 // we still know about its settings. 9274 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9275 } 9276 if (bp.packageSetting == null) { 9277 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9278 + " from package " + bp.sourcePackage); 9279 it.remove(); 9280 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9281 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9282 Slog.i(TAG, "Removing old permission tree: " + bp.name 9283 + " from package " + bp.sourcePackage); 9284 flags |= UPDATE_PERMISSIONS_ALL; 9285 it.remove(); 9286 } 9287 } 9288 } 9289 9290 // Make sure all dynamic permissions have been assigned to a package, 9291 // and make sure there are no dangling permissions. 9292 it = mSettings.mPermissions.values().iterator(); 9293 while (it.hasNext()) { 9294 final BasePermission bp = it.next(); 9295 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9296 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9297 + bp.name + " pkg=" + bp.sourcePackage 9298 + " info=" + bp.pendingInfo); 9299 if (bp.packageSetting == null && bp.pendingInfo != null) { 9300 final BasePermission tree = findPermissionTreeLP(bp.name); 9301 if (tree != null && tree.perm != null) { 9302 bp.packageSetting = tree.packageSetting; 9303 bp.perm = new PackageParser.Permission(tree.perm.owner, 9304 new PermissionInfo(bp.pendingInfo)); 9305 bp.perm.info.packageName = tree.perm.info.packageName; 9306 bp.perm.info.name = bp.name; 9307 bp.uid = tree.uid; 9308 } 9309 } 9310 } 9311 if (bp.packageSetting == null) { 9312 // We may not yet have parsed the package, so just see if 9313 // we still know about its settings. 9314 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9315 } 9316 if (bp.packageSetting == null) { 9317 Slog.w(TAG, "Removing dangling permission: " + bp.name 9318 + " from package " + bp.sourcePackage); 9319 it.remove(); 9320 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9321 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9322 Slog.i(TAG, "Removing old permission: " + bp.name 9323 + " from package " + bp.sourcePackage); 9324 flags |= UPDATE_PERMISSIONS_ALL; 9325 it.remove(); 9326 } 9327 } 9328 } 9329 9330 // Now update the permissions for all packages, in particular 9331 // replace the granted permissions of the system packages. 9332 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9333 for (PackageParser.Package pkg : mPackages.values()) { 9334 if (pkg != pkgInfo) { 9335 // Only replace for packages on requested volume 9336 final String volumeUuid = getVolumeUuidForPackage(pkg); 9337 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9338 && Objects.equals(replaceVolumeUuid, volumeUuid); 9339 grantPermissionsLPw(pkg, replace, changingPkg); 9340 } 9341 } 9342 } 9343 9344 if (pkgInfo != null) { 9345 // Only replace for packages on requested volume 9346 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9347 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9348 && Objects.equals(replaceVolumeUuid, volumeUuid); 9349 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9350 } 9351 } 9352 9353 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9354 String packageOfInterest) { 9355 // IMPORTANT: There are two types of permissions: install and runtime. 9356 // Install time permissions are granted when the app is installed to 9357 // all device users and users added in the future. Runtime permissions 9358 // are granted at runtime explicitly to specific users. Normal and signature 9359 // protected permissions are install time permissions. Dangerous permissions 9360 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9361 // otherwise they are runtime permissions. This function does not manage 9362 // runtime permissions except for the case an app targeting Lollipop MR1 9363 // being upgraded to target a newer SDK, in which case dangerous permissions 9364 // are transformed from install time to runtime ones. 9365 9366 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9367 if (ps == null) { 9368 return; 9369 } 9370 9371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9372 9373 PermissionsState permissionsState = ps.getPermissionsState(); 9374 PermissionsState origPermissions = permissionsState; 9375 9376 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9377 9378 boolean runtimePermissionsRevoked = false; 9379 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9380 9381 boolean changedInstallPermission = false; 9382 9383 if (replace) { 9384 ps.installPermissionsFixed = false; 9385 if (!ps.isSharedUser()) { 9386 origPermissions = new PermissionsState(permissionsState); 9387 permissionsState.reset(); 9388 } else { 9389 // We need to know only about runtime permission changes since the 9390 // calling code always writes the install permissions state but 9391 // the runtime ones are written only if changed. The only cases of 9392 // changed runtime permissions here are promotion of an install to 9393 // runtime and revocation of a runtime from a shared user. 9394 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9395 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9396 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9397 runtimePermissionsRevoked = true; 9398 } 9399 } 9400 } 9401 9402 permissionsState.setGlobalGids(mGlobalGids); 9403 9404 final int N = pkg.requestedPermissions.size(); 9405 for (int i=0; i<N; i++) { 9406 final String name = pkg.requestedPermissions.get(i); 9407 final BasePermission bp = mSettings.mPermissions.get(name); 9408 9409 if (DEBUG_INSTALL) { 9410 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9411 } 9412 9413 if (bp == null || bp.packageSetting == null) { 9414 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9415 Slog.w(TAG, "Unknown permission " + name 9416 + " in package " + pkg.packageName); 9417 } 9418 continue; 9419 } 9420 9421 final String perm = bp.name; 9422 boolean allowedSig = false; 9423 int grant = GRANT_DENIED; 9424 9425 // Keep track of app op permissions. 9426 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9427 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9428 if (pkgs == null) { 9429 pkgs = new ArraySet<>(); 9430 mAppOpPermissionPackages.put(bp.name, pkgs); 9431 } 9432 pkgs.add(pkg.packageName); 9433 } 9434 9435 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9436 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9437 >= Build.VERSION_CODES.M; 9438 switch (level) { 9439 case PermissionInfo.PROTECTION_NORMAL: { 9440 // For all apps normal permissions are install time ones. 9441 grant = GRANT_INSTALL; 9442 } break; 9443 9444 case PermissionInfo.PROTECTION_DANGEROUS: { 9445 // If a permission review is required for legacy apps we represent 9446 // their permissions as always granted runtime ones since we need 9447 // to keep the review required permission flag per user while an 9448 // install permission's state is shared across all users. 9449 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9450 // For legacy apps dangerous permissions are install time ones. 9451 grant = GRANT_INSTALL; 9452 } else if (origPermissions.hasInstallPermission(bp.name)) { 9453 // For legacy apps that became modern, install becomes runtime. 9454 grant = GRANT_UPGRADE; 9455 } else if (mPromoteSystemApps 9456 && isSystemApp(ps) 9457 && mExistingSystemPackages.contains(ps.name)) { 9458 // For legacy system apps, install becomes runtime. 9459 // We cannot check hasInstallPermission() for system apps since those 9460 // permissions were granted implicitly and not persisted pre-M. 9461 grant = GRANT_UPGRADE; 9462 } else { 9463 // For modern apps keep runtime permissions unchanged. 9464 grant = GRANT_RUNTIME; 9465 } 9466 } break; 9467 9468 case PermissionInfo.PROTECTION_SIGNATURE: { 9469 // For all apps signature permissions are install time ones. 9470 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9471 if (allowedSig) { 9472 grant = GRANT_INSTALL; 9473 } 9474 } break; 9475 } 9476 9477 if (DEBUG_INSTALL) { 9478 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9479 } 9480 9481 if (grant != GRANT_DENIED) { 9482 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9483 // If this is an existing, non-system package, then 9484 // we can't add any new permissions to it. 9485 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9486 // Except... if this is a permission that was added 9487 // to the platform (note: need to only do this when 9488 // updating the platform). 9489 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9490 grant = GRANT_DENIED; 9491 } 9492 } 9493 } 9494 9495 switch (grant) { 9496 case GRANT_INSTALL: { 9497 // Revoke this as runtime permission to handle the case of 9498 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9499 for (int userId : UserManagerService.getInstance().getUserIds()) { 9500 if (origPermissions.getRuntimePermissionState( 9501 bp.name, userId) != null) { 9502 // Revoke the runtime permission and clear the flags. 9503 origPermissions.revokeRuntimePermission(bp, userId); 9504 origPermissions.updatePermissionFlags(bp, userId, 9505 PackageManager.MASK_PERMISSION_FLAGS, 0); 9506 // If we revoked a permission permission, we have to write. 9507 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9508 changedRuntimePermissionUserIds, userId); 9509 } 9510 } 9511 // Grant an install permission. 9512 if (permissionsState.grantInstallPermission(bp) != 9513 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9514 changedInstallPermission = true; 9515 } 9516 } break; 9517 9518 case GRANT_RUNTIME: { 9519 // Grant previously granted runtime permissions. 9520 for (int userId : UserManagerService.getInstance().getUserIds()) { 9521 PermissionState permissionState = origPermissions 9522 .getRuntimePermissionState(bp.name, userId); 9523 int flags = permissionState != null 9524 ? permissionState.getFlags() : 0; 9525 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9526 if (permissionsState.grantRuntimePermission(bp, userId) == 9527 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9528 // If we cannot put the permission as it was, we have to write. 9529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9530 changedRuntimePermissionUserIds, userId); 9531 } 9532 // If the app supports runtime permissions no need for a review. 9533 if (Build.PERMISSIONS_REVIEW_REQUIRED 9534 && appSupportsRuntimePermissions 9535 && (flags & PackageManager 9536 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9537 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9538 // Since we changed the flags, we have to write. 9539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9540 changedRuntimePermissionUserIds, userId); 9541 } 9542 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9543 && !appSupportsRuntimePermissions) { 9544 // For legacy apps that need a permission review, every new 9545 // runtime permission is granted but it is pending a review. 9546 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9547 permissionsState.grantRuntimePermission(bp, userId); 9548 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9549 // We changed the permission and flags, hence have to write. 9550 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9551 changedRuntimePermissionUserIds, userId); 9552 } 9553 } 9554 // Propagate the permission flags. 9555 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9556 } 9557 } break; 9558 9559 case GRANT_UPGRADE: { 9560 // Grant runtime permissions for a previously held install permission. 9561 PermissionState permissionState = origPermissions 9562 .getInstallPermissionState(bp.name); 9563 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9564 9565 if (origPermissions.revokeInstallPermission(bp) 9566 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9567 // We will be transferring the permission flags, so clear them. 9568 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9569 PackageManager.MASK_PERMISSION_FLAGS, 0); 9570 changedInstallPermission = true; 9571 } 9572 9573 // If the permission is not to be promoted to runtime we ignore it and 9574 // also its other flags as they are not applicable to install permissions. 9575 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9576 for (int userId : currentUserIds) { 9577 if (permissionsState.grantRuntimePermission(bp, userId) != 9578 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9579 // Transfer the permission flags. 9580 permissionsState.updatePermissionFlags(bp, userId, 9581 flags, flags); 9582 // If we granted the permission, we have to write. 9583 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9584 changedRuntimePermissionUserIds, userId); 9585 } 9586 } 9587 } 9588 } break; 9589 9590 default: { 9591 if (packageOfInterest == null 9592 || packageOfInterest.equals(pkg.packageName)) { 9593 Slog.w(TAG, "Not granting permission " + perm 9594 + " to package " + pkg.packageName 9595 + " because it was previously installed without"); 9596 } 9597 } break; 9598 } 9599 } else { 9600 if (permissionsState.revokeInstallPermission(bp) != 9601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9602 // Also drop the permission flags. 9603 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9604 PackageManager.MASK_PERMISSION_FLAGS, 0); 9605 changedInstallPermission = true; 9606 Slog.i(TAG, "Un-granting permission " + perm 9607 + " from package " + pkg.packageName 9608 + " (protectionLevel=" + bp.protectionLevel 9609 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9610 + ")"); 9611 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9612 // Don't print warning for app op permissions, since it is fine for them 9613 // not to be granted, there is a UI for the user to decide. 9614 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9615 Slog.w(TAG, "Not granting permission " + perm 9616 + " to package " + pkg.packageName 9617 + " (protectionLevel=" + bp.protectionLevel 9618 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9619 + ")"); 9620 } 9621 } 9622 } 9623 } 9624 9625 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9626 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9627 // This is the first that we have heard about this package, so the 9628 // permissions we have now selected are fixed until explicitly 9629 // changed. 9630 ps.installPermissionsFixed = true; 9631 } 9632 9633 // Persist the runtime permissions state for users with changes. If permissions 9634 // were revoked because no app in the shared user declares them we have to 9635 // write synchronously to avoid losing runtime permissions state. 9636 for (int userId : changedRuntimePermissionUserIds) { 9637 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9638 } 9639 9640 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9641 } 9642 9643 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9644 boolean allowed = false; 9645 final int NP = PackageParser.NEW_PERMISSIONS.length; 9646 for (int ip=0; ip<NP; ip++) { 9647 final PackageParser.NewPermissionInfo npi 9648 = PackageParser.NEW_PERMISSIONS[ip]; 9649 if (npi.name.equals(perm) 9650 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9651 allowed = true; 9652 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9653 + pkg.packageName); 9654 break; 9655 } 9656 } 9657 return allowed; 9658 } 9659 9660 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9661 BasePermission bp, PermissionsState origPermissions) { 9662 boolean allowed; 9663 allowed = (compareSignatures( 9664 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9665 == PackageManager.SIGNATURE_MATCH) 9666 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9667 == PackageManager.SIGNATURE_MATCH); 9668 if (!allowed && (bp.protectionLevel 9669 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9670 if (isSystemApp(pkg)) { 9671 // For updated system applications, a system permission 9672 // is granted only if it had been defined by the original application. 9673 if (pkg.isUpdatedSystemApp()) { 9674 final PackageSetting sysPs = mSettings 9675 .getDisabledSystemPkgLPr(pkg.packageName); 9676 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9677 // If the original was granted this permission, we take 9678 // that grant decision as read and propagate it to the 9679 // update. 9680 if (sysPs.isPrivileged()) { 9681 allowed = true; 9682 } 9683 } else { 9684 // The system apk may have been updated with an older 9685 // version of the one on the data partition, but which 9686 // granted a new system permission that it didn't have 9687 // before. In this case we do want to allow the app to 9688 // now get the new permission if the ancestral apk is 9689 // privileged to get it. 9690 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9691 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9692 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9693 allowed = true; 9694 break; 9695 } 9696 } 9697 } 9698 // Also if a privileged parent package on the system image or any of 9699 // its children requested a privileged permission, the updated child 9700 // packages can also get the permission. 9701 if (pkg.parentPackage != null) { 9702 final PackageSetting disabledSysParentPs = mSettings 9703 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9704 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9705 && disabledSysParentPs.isPrivileged()) { 9706 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9707 allowed = true; 9708 } else if (disabledSysParentPs.pkg.childPackages != null) { 9709 final int count = disabledSysParentPs.pkg.childPackages.size(); 9710 for (int i = 0; i < count; i++) { 9711 PackageParser.Package disabledSysChildPkg = 9712 disabledSysParentPs.pkg.childPackages.get(i); 9713 if (isPackageRequestingPermission(disabledSysChildPkg, 9714 perm)) { 9715 allowed = true; 9716 break; 9717 } 9718 } 9719 } 9720 } 9721 } 9722 } 9723 } else { 9724 allowed = isPrivilegedApp(pkg); 9725 } 9726 } 9727 } 9728 if (!allowed) { 9729 if (!allowed && (bp.protectionLevel 9730 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9731 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9732 // If this was a previously normal/dangerous permission that got moved 9733 // to a system permission as part of the runtime permission redesign, then 9734 // we still want to blindly grant it to old apps. 9735 allowed = true; 9736 } 9737 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9738 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9739 // If this permission is to be granted to the system installer and 9740 // this app is an installer, then it gets the permission. 9741 allowed = true; 9742 } 9743 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9744 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9745 // If this permission is to be granted to the system verifier and 9746 // this app is a verifier, then it gets the permission. 9747 allowed = true; 9748 } 9749 if (!allowed && (bp.protectionLevel 9750 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9751 && isSystemApp(pkg)) { 9752 // Any pre-installed system app is allowed to get this permission. 9753 allowed = true; 9754 } 9755 if (!allowed && (bp.protectionLevel 9756 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9757 // For development permissions, a development permission 9758 // is granted only if it was already granted. 9759 allowed = origPermissions.hasInstallPermission(perm); 9760 } 9761 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9762 && pkg.packageName.equals(mSetupWizardPackage)) { 9763 // If this permission is to be granted to the system setup wizard and 9764 // this app is a setup wizard, then it gets the permission. 9765 allowed = true; 9766 } 9767 } 9768 return allowed; 9769 } 9770 9771 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9772 final int permCount = pkg.requestedPermissions.size(); 9773 for (int j = 0; j < permCount; j++) { 9774 String requestedPermission = pkg.requestedPermissions.get(j); 9775 if (permission.equals(requestedPermission)) { 9776 return true; 9777 } 9778 } 9779 return false; 9780 } 9781 9782 final class ActivityIntentResolver 9783 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9784 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9785 boolean defaultOnly, int userId) { 9786 if (!sUserManager.exists(userId)) return null; 9787 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9788 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9789 } 9790 9791 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9792 int userId) { 9793 if (!sUserManager.exists(userId)) return null; 9794 mFlags = flags; 9795 return super.queryIntent(intent, resolvedType, 9796 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9797 } 9798 9799 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9800 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9801 if (!sUserManager.exists(userId)) return null; 9802 if (packageActivities == null) { 9803 return null; 9804 } 9805 mFlags = flags; 9806 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9807 final int N = packageActivities.size(); 9808 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9809 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9810 9811 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9812 for (int i = 0; i < N; ++i) { 9813 intentFilters = packageActivities.get(i).intents; 9814 if (intentFilters != null && intentFilters.size() > 0) { 9815 PackageParser.ActivityIntentInfo[] array = 9816 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9817 intentFilters.toArray(array); 9818 listCut.add(array); 9819 } 9820 } 9821 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9822 } 9823 9824 /** 9825 * Finds a privileged activity that matches the specified activity names. 9826 */ 9827 private PackageParser.Activity findMatchingActivity( 9828 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9829 for (PackageParser.Activity sysActivity : activityList) { 9830 if (sysActivity.info.name.equals(activityInfo.name)) { 9831 return sysActivity; 9832 } 9833 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9834 return sysActivity; 9835 } 9836 if (sysActivity.info.targetActivity != null) { 9837 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9838 return sysActivity; 9839 } 9840 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9841 return sysActivity; 9842 } 9843 } 9844 } 9845 return null; 9846 } 9847 9848 public class IterGenerator<E> { 9849 public Iterator<E> generate(ActivityIntentInfo info) { 9850 return null; 9851 } 9852 } 9853 9854 public class ActionIterGenerator extends IterGenerator<String> { 9855 @Override 9856 public Iterator<String> generate(ActivityIntentInfo info) { 9857 return info.actionsIterator(); 9858 } 9859 } 9860 9861 public class CategoriesIterGenerator extends IterGenerator<String> { 9862 @Override 9863 public Iterator<String> generate(ActivityIntentInfo info) { 9864 return info.categoriesIterator(); 9865 } 9866 } 9867 9868 public class SchemesIterGenerator extends IterGenerator<String> { 9869 @Override 9870 public Iterator<String> generate(ActivityIntentInfo info) { 9871 return info.schemesIterator(); 9872 } 9873 } 9874 9875 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9876 @Override 9877 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9878 return info.authoritiesIterator(); 9879 } 9880 } 9881 9882 /** 9883 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9884 * MODIFIED. Do not pass in a list that should not be changed. 9885 */ 9886 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9887 IterGenerator<T> generator, Iterator<T> searchIterator) { 9888 // loop through the set of actions; every one must be found in the intent filter 9889 while (searchIterator.hasNext()) { 9890 // we must have at least one filter in the list to consider a match 9891 if (intentList.size() == 0) { 9892 break; 9893 } 9894 9895 final T searchAction = searchIterator.next(); 9896 9897 // loop through the set of intent filters 9898 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9899 while (intentIter.hasNext()) { 9900 final ActivityIntentInfo intentInfo = intentIter.next(); 9901 boolean selectionFound = false; 9902 9903 // loop through the intent filter's selection criteria; at least one 9904 // of them must match the searched criteria 9905 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9906 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9907 final T intentSelection = intentSelectionIter.next(); 9908 if (intentSelection != null && intentSelection.equals(searchAction)) { 9909 selectionFound = true; 9910 break; 9911 } 9912 } 9913 9914 // the selection criteria wasn't found in this filter's set; this filter 9915 // is not a potential match 9916 if (!selectionFound) { 9917 intentIter.remove(); 9918 } 9919 } 9920 } 9921 } 9922 9923 private boolean isProtectedAction(ActivityIntentInfo filter) { 9924 final Iterator<String> actionsIter = filter.actionsIterator(); 9925 while (actionsIter != null && actionsIter.hasNext()) { 9926 final String filterAction = actionsIter.next(); 9927 if (PROTECTED_ACTIONS.contains(filterAction)) { 9928 return true; 9929 } 9930 } 9931 return false; 9932 } 9933 9934 /** 9935 * Adjusts the priority of the given intent filter according to policy. 9936 * <p> 9937 * <ul> 9938 * <li>The priority for non privileged applications is capped to '0'</li> 9939 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9940 * <li>The priority for unbundled updates to privileged applications is capped to the 9941 * priority defined on the system partition</li> 9942 * </ul> 9943 * <p> 9944 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9945 * allowed to obtain any priority on any action. 9946 */ 9947 private void adjustPriority( 9948 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9949 // nothing to do; priority is fine as-is 9950 if (intent.getPriority() <= 0) { 9951 return; 9952 } 9953 9954 final ActivityInfo activityInfo = intent.activity.info; 9955 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9956 9957 final boolean privilegedApp = 9958 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9959 if (!privilegedApp) { 9960 // non-privileged applications can never define a priority >0 9961 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9962 + " package: " + applicationInfo.packageName 9963 + " activity: " + intent.activity.className 9964 + " origPrio: " + intent.getPriority()); 9965 intent.setPriority(0); 9966 return; 9967 } 9968 9969 if (systemActivities == null) { 9970 // the system package is not disabled; we're parsing the system partition 9971 if (isProtectedAction(intent)) { 9972 if (mDeferProtectedFilters) { 9973 // We can't deal with these just yet. No component should ever obtain a 9974 // >0 priority for a protected actions, with ONE exception -- the setup 9975 // wizard. The setup wizard, however, cannot be known until we're able to 9976 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 9977 // until all intent filters have been processed. Chicken, meet egg. 9978 // Let the filter temporarily have a high priority and rectify the 9979 // priorities after all system packages have been scanned. 9980 mProtectedFilters.add(intent); 9981 if (DEBUG_FILTERS) { 9982 Slog.i(TAG, "Protected action; save for later;" 9983 + " package: " + applicationInfo.packageName 9984 + " activity: " + intent.activity.className 9985 + " origPrio: " + intent.getPriority()); 9986 } 9987 return; 9988 } else { 9989 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 9990 Slog.i(TAG, "No setup wizard;" 9991 + " All protected intents capped to priority 0"); 9992 } 9993 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 9994 if (DEBUG_FILTERS) { 9995 Slog.i(TAG, "Found setup wizard;" 9996 + " allow priority " + intent.getPriority() + ";" 9997 + " package: " + intent.activity.info.packageName 9998 + " activity: " + intent.activity.className 9999 + " priority: " + intent.getPriority()); 10000 } 10001 // setup wizard gets whatever it wants 10002 return; 10003 } 10004 Slog.w(TAG, "Protected action; cap priority to 0;" 10005 + " package: " + intent.activity.info.packageName 10006 + " activity: " + intent.activity.className 10007 + " origPrio: " + intent.getPriority()); 10008 intent.setPriority(0); 10009 return; 10010 } 10011 } 10012 // privileged apps on the system image get whatever priority they request 10013 return; 10014 } 10015 10016 // privileged app unbundled update ... try to find the same activity 10017 final PackageParser.Activity foundActivity = 10018 findMatchingActivity(systemActivities, activityInfo); 10019 if (foundActivity == null) { 10020 // this is a new activity; it cannot obtain >0 priority 10021 if (DEBUG_FILTERS) { 10022 Slog.i(TAG, "New activity; cap priority to 0;" 10023 + " package: " + applicationInfo.packageName 10024 + " activity: " + intent.activity.className 10025 + " origPrio: " + intent.getPriority()); 10026 } 10027 intent.setPriority(0); 10028 return; 10029 } 10030 10031 // found activity, now check for filter equivalence 10032 10033 // a shallow copy is enough; we modify the list, not its contents 10034 final List<ActivityIntentInfo> intentListCopy = 10035 new ArrayList<>(foundActivity.intents); 10036 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10037 10038 // find matching action subsets 10039 final Iterator<String> actionsIterator = intent.actionsIterator(); 10040 if (actionsIterator != null) { 10041 getIntentListSubset( 10042 intentListCopy, new ActionIterGenerator(), actionsIterator); 10043 if (intentListCopy.size() == 0) { 10044 // no more intents to match; we're not equivalent 10045 if (DEBUG_FILTERS) { 10046 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10047 + " package: " + applicationInfo.packageName 10048 + " activity: " + intent.activity.className 10049 + " origPrio: " + intent.getPriority()); 10050 } 10051 intent.setPriority(0); 10052 return; 10053 } 10054 } 10055 10056 // find matching category subsets 10057 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10058 if (categoriesIterator != null) { 10059 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10060 categoriesIterator); 10061 if (intentListCopy.size() == 0) { 10062 // no more intents to match; we're not equivalent 10063 if (DEBUG_FILTERS) { 10064 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10065 + " package: " + applicationInfo.packageName 10066 + " activity: " + intent.activity.className 10067 + " origPrio: " + intent.getPriority()); 10068 } 10069 intent.setPriority(0); 10070 return; 10071 } 10072 } 10073 10074 // find matching schemes subsets 10075 final Iterator<String> schemesIterator = intent.schemesIterator(); 10076 if (schemesIterator != null) { 10077 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10078 schemesIterator); 10079 if (intentListCopy.size() == 0) { 10080 // no more intents to match; we're not equivalent 10081 if (DEBUG_FILTERS) { 10082 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10083 + " package: " + applicationInfo.packageName 10084 + " activity: " + intent.activity.className 10085 + " origPrio: " + intent.getPriority()); 10086 } 10087 intent.setPriority(0); 10088 return; 10089 } 10090 } 10091 10092 // find matching authorities subsets 10093 final Iterator<IntentFilter.AuthorityEntry> 10094 authoritiesIterator = intent.authoritiesIterator(); 10095 if (authoritiesIterator != null) { 10096 getIntentListSubset(intentListCopy, 10097 new AuthoritiesIterGenerator(), 10098 authoritiesIterator); 10099 if (intentListCopy.size() == 0) { 10100 // no more intents to match; we're not equivalent 10101 if (DEBUG_FILTERS) { 10102 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10103 + " package: " + applicationInfo.packageName 10104 + " activity: " + intent.activity.className 10105 + " origPrio: " + intent.getPriority()); 10106 } 10107 intent.setPriority(0); 10108 return; 10109 } 10110 } 10111 10112 // we found matching filter(s); app gets the max priority of all intents 10113 int cappedPriority = 0; 10114 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10115 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10116 } 10117 if (intent.getPriority() > cappedPriority) { 10118 if (DEBUG_FILTERS) { 10119 Slog.i(TAG, "Found matching filter(s);" 10120 + " cap priority to " + cappedPriority + ";" 10121 + " package: " + applicationInfo.packageName 10122 + " activity: " + intent.activity.className 10123 + " origPrio: " + intent.getPriority()); 10124 } 10125 intent.setPriority(cappedPriority); 10126 return; 10127 } 10128 // all this for nothing; the requested priority was <= what was on the system 10129 } 10130 10131 public final void addActivity(PackageParser.Activity a, String type) { 10132 mActivities.put(a.getComponentName(), a); 10133 if (DEBUG_SHOW_INFO) 10134 Log.v( 10135 TAG, " " + type + " " + 10136 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10137 if (DEBUG_SHOW_INFO) 10138 Log.v(TAG, " Class=" + a.info.name); 10139 final int NI = a.intents.size(); 10140 for (int j=0; j<NI; j++) { 10141 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10142 if ("activity".equals(type)) { 10143 final PackageSetting ps = 10144 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10145 final List<PackageParser.Activity> systemActivities = 10146 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10147 adjustPriority(systemActivities, intent); 10148 } 10149 if (DEBUG_SHOW_INFO) { 10150 Log.v(TAG, " IntentFilter:"); 10151 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10152 } 10153 if (!intent.debugCheck()) { 10154 Log.w(TAG, "==> For Activity " + a.info.name); 10155 } 10156 addFilter(intent); 10157 } 10158 } 10159 10160 public final void removeActivity(PackageParser.Activity a, String type) { 10161 mActivities.remove(a.getComponentName()); 10162 if (DEBUG_SHOW_INFO) { 10163 Log.v(TAG, " " + type + " " 10164 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10165 : a.info.name) + ":"); 10166 Log.v(TAG, " Class=" + a.info.name); 10167 } 10168 final int NI = a.intents.size(); 10169 for (int j=0; j<NI; j++) { 10170 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10171 if (DEBUG_SHOW_INFO) { 10172 Log.v(TAG, " IntentFilter:"); 10173 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10174 } 10175 removeFilter(intent); 10176 } 10177 } 10178 10179 @Override 10180 protected boolean allowFilterResult( 10181 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10182 ActivityInfo filterAi = filter.activity.info; 10183 for (int i=dest.size()-1; i>=0; i--) { 10184 ActivityInfo destAi = dest.get(i).activityInfo; 10185 if (destAi.name == filterAi.name 10186 && destAi.packageName == filterAi.packageName) { 10187 return false; 10188 } 10189 } 10190 return true; 10191 } 10192 10193 @Override 10194 protected ActivityIntentInfo[] newArray(int size) { 10195 return new ActivityIntentInfo[size]; 10196 } 10197 10198 @Override 10199 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10200 if (!sUserManager.exists(userId)) return true; 10201 PackageParser.Package p = filter.activity.owner; 10202 if (p != null) { 10203 PackageSetting ps = (PackageSetting)p.mExtras; 10204 if (ps != null) { 10205 // System apps are never considered stopped for purposes of 10206 // filtering, because there may be no way for the user to 10207 // actually re-launch them. 10208 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10209 && ps.getStopped(userId); 10210 } 10211 } 10212 return false; 10213 } 10214 10215 @Override 10216 protected boolean isPackageForFilter(String packageName, 10217 PackageParser.ActivityIntentInfo info) { 10218 return packageName.equals(info.activity.owner.packageName); 10219 } 10220 10221 @Override 10222 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10223 int match, int userId) { 10224 if (!sUserManager.exists(userId)) return null; 10225 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10226 return null; 10227 } 10228 final PackageParser.Activity activity = info.activity; 10229 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10230 if (ps == null) { 10231 return null; 10232 } 10233 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10234 ps.readUserState(userId), userId); 10235 if (ai == null) { 10236 return null; 10237 } 10238 final ResolveInfo res = new ResolveInfo(); 10239 res.activityInfo = ai; 10240 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10241 res.filter = info; 10242 } 10243 if (info != null) { 10244 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10245 } 10246 res.priority = info.getPriority(); 10247 res.preferredOrder = activity.owner.mPreferredOrder; 10248 //System.out.println("Result: " + res.activityInfo.className + 10249 // " = " + res.priority); 10250 res.match = match; 10251 res.isDefault = info.hasDefault; 10252 res.labelRes = info.labelRes; 10253 res.nonLocalizedLabel = info.nonLocalizedLabel; 10254 if (userNeedsBadging(userId)) { 10255 res.noResourceId = true; 10256 } else { 10257 res.icon = info.icon; 10258 } 10259 res.iconResourceId = info.icon; 10260 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10261 return res; 10262 } 10263 10264 @Override 10265 protected void sortResults(List<ResolveInfo> results) { 10266 Collections.sort(results, mResolvePrioritySorter); 10267 } 10268 10269 @Override 10270 protected void dumpFilter(PrintWriter out, String prefix, 10271 PackageParser.ActivityIntentInfo filter) { 10272 out.print(prefix); out.print( 10273 Integer.toHexString(System.identityHashCode(filter.activity))); 10274 out.print(' '); 10275 filter.activity.printComponentShortName(out); 10276 out.print(" filter "); 10277 out.println(Integer.toHexString(System.identityHashCode(filter))); 10278 } 10279 10280 @Override 10281 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10282 return filter.activity; 10283 } 10284 10285 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10286 PackageParser.Activity activity = (PackageParser.Activity)label; 10287 out.print(prefix); out.print( 10288 Integer.toHexString(System.identityHashCode(activity))); 10289 out.print(' '); 10290 activity.printComponentShortName(out); 10291 if (count > 1) { 10292 out.print(" ("); out.print(count); out.print(" filters)"); 10293 } 10294 out.println(); 10295 } 10296 10297 // Keys are String (activity class name), values are Activity. 10298 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10299 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10300 private int mFlags; 10301 } 10302 10303 private final class ServiceIntentResolver 10304 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10305 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10306 boolean defaultOnly, int userId) { 10307 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10308 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10309 } 10310 10311 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10312 int userId) { 10313 if (!sUserManager.exists(userId)) return null; 10314 mFlags = flags; 10315 return super.queryIntent(intent, resolvedType, 10316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10317 } 10318 10319 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10320 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10321 if (!sUserManager.exists(userId)) return null; 10322 if (packageServices == null) { 10323 return null; 10324 } 10325 mFlags = flags; 10326 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10327 final int N = packageServices.size(); 10328 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10329 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10330 10331 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10332 for (int i = 0; i < N; ++i) { 10333 intentFilters = packageServices.get(i).intents; 10334 if (intentFilters != null && intentFilters.size() > 0) { 10335 PackageParser.ServiceIntentInfo[] array = 10336 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10337 intentFilters.toArray(array); 10338 listCut.add(array); 10339 } 10340 } 10341 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10342 } 10343 10344 public final void addService(PackageParser.Service s) { 10345 mServices.put(s.getComponentName(), s); 10346 if (DEBUG_SHOW_INFO) { 10347 Log.v(TAG, " " 10348 + (s.info.nonLocalizedLabel != null 10349 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10350 Log.v(TAG, " Class=" + s.info.name); 10351 } 10352 final int NI = s.intents.size(); 10353 int j; 10354 for (j=0; j<NI; j++) { 10355 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10356 if (DEBUG_SHOW_INFO) { 10357 Log.v(TAG, " IntentFilter:"); 10358 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10359 } 10360 if (!intent.debugCheck()) { 10361 Log.w(TAG, "==> For Service " + s.info.name); 10362 } 10363 addFilter(intent); 10364 } 10365 } 10366 10367 public final void removeService(PackageParser.Service s) { 10368 mServices.remove(s.getComponentName()); 10369 if (DEBUG_SHOW_INFO) { 10370 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10371 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10372 Log.v(TAG, " Class=" + s.info.name); 10373 } 10374 final int NI = s.intents.size(); 10375 int j; 10376 for (j=0; j<NI; j++) { 10377 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10378 if (DEBUG_SHOW_INFO) { 10379 Log.v(TAG, " IntentFilter:"); 10380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10381 } 10382 removeFilter(intent); 10383 } 10384 } 10385 10386 @Override 10387 protected boolean allowFilterResult( 10388 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10389 ServiceInfo filterSi = filter.service.info; 10390 for (int i=dest.size()-1; i>=0; i--) { 10391 ServiceInfo destAi = dest.get(i).serviceInfo; 10392 if (destAi.name == filterSi.name 10393 && destAi.packageName == filterSi.packageName) { 10394 return false; 10395 } 10396 } 10397 return true; 10398 } 10399 10400 @Override 10401 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10402 return new PackageParser.ServiceIntentInfo[size]; 10403 } 10404 10405 @Override 10406 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10407 if (!sUserManager.exists(userId)) return true; 10408 PackageParser.Package p = filter.service.owner; 10409 if (p != null) { 10410 PackageSetting ps = (PackageSetting)p.mExtras; 10411 if (ps != null) { 10412 // System apps are never considered stopped for purposes of 10413 // filtering, because there may be no way for the user to 10414 // actually re-launch them. 10415 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10416 && ps.getStopped(userId); 10417 } 10418 } 10419 return false; 10420 } 10421 10422 @Override 10423 protected boolean isPackageForFilter(String packageName, 10424 PackageParser.ServiceIntentInfo info) { 10425 return packageName.equals(info.service.owner.packageName); 10426 } 10427 10428 @Override 10429 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10430 int match, int userId) { 10431 if (!sUserManager.exists(userId)) return null; 10432 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10433 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10434 return null; 10435 } 10436 final PackageParser.Service service = info.service; 10437 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10438 if (ps == null) { 10439 return null; 10440 } 10441 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10442 ps.readUserState(userId), userId); 10443 if (si == null) { 10444 return null; 10445 } 10446 final ResolveInfo res = new ResolveInfo(); 10447 res.serviceInfo = si; 10448 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10449 res.filter = filter; 10450 } 10451 res.priority = info.getPriority(); 10452 res.preferredOrder = service.owner.mPreferredOrder; 10453 res.match = match; 10454 res.isDefault = info.hasDefault; 10455 res.labelRes = info.labelRes; 10456 res.nonLocalizedLabel = info.nonLocalizedLabel; 10457 res.icon = info.icon; 10458 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10459 return res; 10460 } 10461 10462 @Override 10463 protected void sortResults(List<ResolveInfo> results) { 10464 Collections.sort(results, mResolvePrioritySorter); 10465 } 10466 10467 @Override 10468 protected void dumpFilter(PrintWriter out, String prefix, 10469 PackageParser.ServiceIntentInfo filter) { 10470 out.print(prefix); out.print( 10471 Integer.toHexString(System.identityHashCode(filter.service))); 10472 out.print(' '); 10473 filter.service.printComponentShortName(out); 10474 out.print(" filter "); 10475 out.println(Integer.toHexString(System.identityHashCode(filter))); 10476 } 10477 10478 @Override 10479 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10480 return filter.service; 10481 } 10482 10483 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10484 PackageParser.Service service = (PackageParser.Service)label; 10485 out.print(prefix); out.print( 10486 Integer.toHexString(System.identityHashCode(service))); 10487 out.print(' '); 10488 service.printComponentShortName(out); 10489 if (count > 1) { 10490 out.print(" ("); out.print(count); out.print(" filters)"); 10491 } 10492 out.println(); 10493 } 10494 10495// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10496// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10497// final List<ResolveInfo> retList = Lists.newArrayList(); 10498// while (i.hasNext()) { 10499// final ResolveInfo resolveInfo = (ResolveInfo) i; 10500// if (isEnabledLP(resolveInfo.serviceInfo)) { 10501// retList.add(resolveInfo); 10502// } 10503// } 10504// return retList; 10505// } 10506 10507 // Keys are String (activity class name), values are Activity. 10508 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10509 = new ArrayMap<ComponentName, PackageParser.Service>(); 10510 private int mFlags; 10511 }; 10512 10513 private final class ProviderIntentResolver 10514 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10515 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10516 boolean defaultOnly, int userId) { 10517 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10518 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10519 } 10520 10521 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10522 int userId) { 10523 if (!sUserManager.exists(userId)) 10524 return null; 10525 mFlags = flags; 10526 return super.queryIntent(intent, resolvedType, 10527 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10528 } 10529 10530 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10531 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10532 if (!sUserManager.exists(userId)) 10533 return null; 10534 if (packageProviders == null) { 10535 return null; 10536 } 10537 mFlags = flags; 10538 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10539 final int N = packageProviders.size(); 10540 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10541 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10542 10543 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10544 for (int i = 0; i < N; ++i) { 10545 intentFilters = packageProviders.get(i).intents; 10546 if (intentFilters != null && intentFilters.size() > 0) { 10547 PackageParser.ProviderIntentInfo[] array = 10548 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10549 intentFilters.toArray(array); 10550 listCut.add(array); 10551 } 10552 } 10553 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10554 } 10555 10556 public final void addProvider(PackageParser.Provider p) { 10557 if (mProviders.containsKey(p.getComponentName())) { 10558 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10559 return; 10560 } 10561 10562 mProviders.put(p.getComponentName(), p); 10563 if (DEBUG_SHOW_INFO) { 10564 Log.v(TAG, " " 10565 + (p.info.nonLocalizedLabel != null 10566 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10567 Log.v(TAG, " Class=" + p.info.name); 10568 } 10569 final int NI = p.intents.size(); 10570 int j; 10571 for (j = 0; j < NI; j++) { 10572 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10573 if (DEBUG_SHOW_INFO) { 10574 Log.v(TAG, " IntentFilter:"); 10575 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10576 } 10577 if (!intent.debugCheck()) { 10578 Log.w(TAG, "==> For Provider " + p.info.name); 10579 } 10580 addFilter(intent); 10581 } 10582 } 10583 10584 public final void removeProvider(PackageParser.Provider p) { 10585 mProviders.remove(p.getComponentName()); 10586 if (DEBUG_SHOW_INFO) { 10587 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10588 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10589 Log.v(TAG, " Class=" + p.info.name); 10590 } 10591 final int NI = p.intents.size(); 10592 int j; 10593 for (j = 0; j < NI; j++) { 10594 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " IntentFilter:"); 10597 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10598 } 10599 removeFilter(intent); 10600 } 10601 } 10602 10603 @Override 10604 protected boolean allowFilterResult( 10605 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10606 ProviderInfo filterPi = filter.provider.info; 10607 for (int i = dest.size() - 1; i >= 0; i--) { 10608 ProviderInfo destPi = dest.get(i).providerInfo; 10609 if (destPi.name == filterPi.name 10610 && destPi.packageName == filterPi.packageName) { 10611 return false; 10612 } 10613 } 10614 return true; 10615 } 10616 10617 @Override 10618 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10619 return new PackageParser.ProviderIntentInfo[size]; 10620 } 10621 10622 @Override 10623 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10624 if (!sUserManager.exists(userId)) 10625 return true; 10626 PackageParser.Package p = filter.provider.owner; 10627 if (p != null) { 10628 PackageSetting ps = (PackageSetting) p.mExtras; 10629 if (ps != null) { 10630 // System apps are never considered stopped for purposes of 10631 // filtering, because there may be no way for the user to 10632 // actually re-launch them. 10633 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10634 && ps.getStopped(userId); 10635 } 10636 } 10637 return false; 10638 } 10639 10640 @Override 10641 protected boolean isPackageForFilter(String packageName, 10642 PackageParser.ProviderIntentInfo info) { 10643 return packageName.equals(info.provider.owner.packageName); 10644 } 10645 10646 @Override 10647 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10648 int match, int userId) { 10649 if (!sUserManager.exists(userId)) 10650 return null; 10651 final PackageParser.ProviderIntentInfo info = filter; 10652 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10653 return null; 10654 } 10655 final PackageParser.Provider provider = info.provider; 10656 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10657 if (ps == null) { 10658 return null; 10659 } 10660 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10661 ps.readUserState(userId), userId); 10662 if (pi == null) { 10663 return null; 10664 } 10665 final ResolveInfo res = new ResolveInfo(); 10666 res.providerInfo = pi; 10667 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10668 res.filter = filter; 10669 } 10670 res.priority = info.getPriority(); 10671 res.preferredOrder = provider.owner.mPreferredOrder; 10672 res.match = match; 10673 res.isDefault = info.hasDefault; 10674 res.labelRes = info.labelRes; 10675 res.nonLocalizedLabel = info.nonLocalizedLabel; 10676 res.icon = info.icon; 10677 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10678 return res; 10679 } 10680 10681 @Override 10682 protected void sortResults(List<ResolveInfo> results) { 10683 Collections.sort(results, mResolvePrioritySorter); 10684 } 10685 10686 @Override 10687 protected void dumpFilter(PrintWriter out, String prefix, 10688 PackageParser.ProviderIntentInfo filter) { 10689 out.print(prefix); 10690 out.print( 10691 Integer.toHexString(System.identityHashCode(filter.provider))); 10692 out.print(' '); 10693 filter.provider.printComponentShortName(out); 10694 out.print(" filter "); 10695 out.println(Integer.toHexString(System.identityHashCode(filter))); 10696 } 10697 10698 @Override 10699 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10700 return filter.provider; 10701 } 10702 10703 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10704 PackageParser.Provider provider = (PackageParser.Provider)label; 10705 out.print(prefix); out.print( 10706 Integer.toHexString(System.identityHashCode(provider))); 10707 out.print(' '); 10708 provider.printComponentShortName(out); 10709 if (count > 1) { 10710 out.print(" ("); out.print(count); out.print(" filters)"); 10711 } 10712 out.println(); 10713 } 10714 10715 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10716 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10717 private int mFlags; 10718 } 10719 10720 private static final class EphemeralIntentResolver 10721 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10722 @Override 10723 protected EphemeralResolveIntentInfo[] newArray(int size) { 10724 return new EphemeralResolveIntentInfo[size]; 10725 } 10726 10727 @Override 10728 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10729 return true; 10730 } 10731 10732 @Override 10733 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10734 int userId) { 10735 if (!sUserManager.exists(userId)) { 10736 return null; 10737 } 10738 return info.getEphemeralResolveInfo(); 10739 } 10740 } 10741 10742 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10743 new Comparator<ResolveInfo>() { 10744 public int compare(ResolveInfo r1, ResolveInfo r2) { 10745 int v1 = r1.priority; 10746 int v2 = r2.priority; 10747 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10748 if (v1 != v2) { 10749 return (v1 > v2) ? -1 : 1; 10750 } 10751 v1 = r1.preferredOrder; 10752 v2 = r2.preferredOrder; 10753 if (v1 != v2) { 10754 return (v1 > v2) ? -1 : 1; 10755 } 10756 if (r1.isDefault != r2.isDefault) { 10757 return r1.isDefault ? -1 : 1; 10758 } 10759 v1 = r1.match; 10760 v2 = r2.match; 10761 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10762 if (v1 != v2) { 10763 return (v1 > v2) ? -1 : 1; 10764 } 10765 if (r1.system != r2.system) { 10766 return r1.system ? -1 : 1; 10767 } 10768 if (r1.activityInfo != null) { 10769 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10770 } 10771 if (r1.serviceInfo != null) { 10772 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10773 } 10774 if (r1.providerInfo != null) { 10775 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10776 } 10777 return 0; 10778 } 10779 }; 10780 10781 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10782 new Comparator<ProviderInfo>() { 10783 public int compare(ProviderInfo p1, ProviderInfo p2) { 10784 final int v1 = p1.initOrder; 10785 final int v2 = p2.initOrder; 10786 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10787 } 10788 }; 10789 10790 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10791 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10792 final int[] userIds) { 10793 mHandler.post(new Runnable() { 10794 @Override 10795 public void run() { 10796 try { 10797 final IActivityManager am = ActivityManagerNative.getDefault(); 10798 if (am == null) return; 10799 final int[] resolvedUserIds; 10800 if (userIds == null) { 10801 resolvedUserIds = am.getRunningUserIds(); 10802 } else { 10803 resolvedUserIds = userIds; 10804 } 10805 for (int id : resolvedUserIds) { 10806 final Intent intent = new Intent(action, 10807 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10808 if (extras != null) { 10809 intent.putExtras(extras); 10810 } 10811 if (targetPkg != null) { 10812 intent.setPackage(targetPkg); 10813 } 10814 // Modify the UID when posting to other users 10815 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10816 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10817 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10818 intent.putExtra(Intent.EXTRA_UID, uid); 10819 } 10820 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10821 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10822 if (DEBUG_BROADCASTS) { 10823 RuntimeException here = new RuntimeException("here"); 10824 here.fillInStackTrace(); 10825 Slog.d(TAG, "Sending to user " + id + ": " 10826 + intent.toShortString(false, true, false, false) 10827 + " " + intent.getExtras(), here); 10828 } 10829 am.broadcastIntent(null, intent, null, finishedReceiver, 10830 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10831 null, finishedReceiver != null, false, id); 10832 } 10833 } catch (RemoteException ex) { 10834 } 10835 } 10836 }); 10837 } 10838 10839 /** 10840 * Check if the external storage media is available. This is true if there 10841 * is a mounted external storage medium or if the external storage is 10842 * emulated. 10843 */ 10844 private boolean isExternalMediaAvailable() { 10845 return mMediaMounted || Environment.isExternalStorageEmulated(); 10846 } 10847 10848 @Override 10849 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10850 // writer 10851 synchronized (mPackages) { 10852 if (!isExternalMediaAvailable()) { 10853 // If the external storage is no longer mounted at this point, 10854 // the caller may not have been able to delete all of this 10855 // packages files and can not delete any more. Bail. 10856 return null; 10857 } 10858 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10859 if (lastPackage != null) { 10860 pkgs.remove(lastPackage); 10861 } 10862 if (pkgs.size() > 0) { 10863 return pkgs.get(0); 10864 } 10865 } 10866 return null; 10867 } 10868 10869 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10870 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10871 userId, andCode ? 1 : 0, packageName); 10872 if (mSystemReady) { 10873 msg.sendToTarget(); 10874 } else { 10875 if (mPostSystemReadyMessages == null) { 10876 mPostSystemReadyMessages = new ArrayList<>(); 10877 } 10878 mPostSystemReadyMessages.add(msg); 10879 } 10880 } 10881 10882 void startCleaningPackages() { 10883 // reader 10884 if (!isExternalMediaAvailable()) { 10885 return; 10886 } 10887 synchronized (mPackages) { 10888 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10889 return; 10890 } 10891 } 10892 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10893 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10894 IActivityManager am = ActivityManagerNative.getDefault(); 10895 if (am != null) { 10896 try { 10897 am.startService(null, intent, null, mContext.getOpPackageName(), 10898 UserHandle.USER_SYSTEM); 10899 } catch (RemoteException e) { 10900 } 10901 } 10902 } 10903 10904 @Override 10905 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10906 int installFlags, String installerPackageName, int userId) { 10907 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10908 10909 final int callingUid = Binder.getCallingUid(); 10910 enforceCrossUserPermission(callingUid, userId, 10911 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10912 10913 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10914 try { 10915 if (observer != null) { 10916 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10917 } 10918 } catch (RemoteException re) { 10919 } 10920 return; 10921 } 10922 10923 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10924 installFlags |= PackageManager.INSTALL_FROM_ADB; 10925 10926 } else { 10927 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10928 // about installerPackageName. 10929 10930 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10931 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10932 } 10933 10934 UserHandle user; 10935 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10936 user = UserHandle.ALL; 10937 } else { 10938 user = new UserHandle(userId); 10939 } 10940 10941 // Only system components can circumvent runtime permissions when installing. 10942 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10943 && mContext.checkCallingOrSelfPermission(Manifest.permission 10944 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10945 throw new SecurityException("You need the " 10946 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10947 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10948 } 10949 10950 final File originFile = new File(originPath); 10951 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10952 10953 final Message msg = mHandler.obtainMessage(INIT_COPY); 10954 final VerificationInfo verificationInfo = new VerificationInfo( 10955 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10956 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10957 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10958 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10959 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10960 msg.obj = params; 10961 10962 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10963 System.identityHashCode(msg.obj)); 10964 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10965 System.identityHashCode(msg.obj)); 10966 10967 mHandler.sendMessage(msg); 10968 } 10969 10970 void installStage(String packageName, File stagedDir, String stagedCid, 10971 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10972 String installerPackageName, int installerUid, UserHandle user) { 10973 if (DEBUG_EPHEMERAL) { 10974 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10975 Slog.d(TAG, "Ephemeral install of " + packageName); 10976 } 10977 } 10978 final VerificationInfo verificationInfo = new VerificationInfo( 10979 sessionParams.originatingUri, sessionParams.referrerUri, 10980 sessionParams.originatingUid, installerUid); 10981 10982 final OriginInfo origin; 10983 if (stagedDir != null) { 10984 origin = OriginInfo.fromStagedFile(stagedDir); 10985 } else { 10986 origin = OriginInfo.fromStagedContainer(stagedCid); 10987 } 10988 10989 final Message msg = mHandler.obtainMessage(INIT_COPY); 10990 final InstallParams params = new InstallParams(origin, null, observer, 10991 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10992 verificationInfo, user, sessionParams.abiOverride, 10993 sessionParams.grantedRuntimePermissions); 10994 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10995 msg.obj = params; 10996 10997 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10998 System.identityHashCode(msg.obj)); 10999 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11000 System.identityHashCode(msg.obj)); 11001 11002 mHandler.sendMessage(msg); 11003 } 11004 11005 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11006 int userId) { 11007 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11008 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11009 } 11010 11011 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11012 int appId, int userId) { 11013 Bundle extras = new Bundle(1); 11014 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11015 11016 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11017 packageName, extras, 0, null, null, new int[] {userId}); 11018 try { 11019 IActivityManager am = ActivityManagerNative.getDefault(); 11020 if (isSystem && am.isUserRunning(userId, 0)) { 11021 // The just-installed/enabled app is bundled on the system, so presumed 11022 // to be able to run automatically without needing an explicit launch. 11023 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11024 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11025 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11026 .setPackage(packageName); 11027 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11028 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11029 } 11030 } catch (RemoteException e) { 11031 // shouldn't happen 11032 Slog.w(TAG, "Unable to bootstrap installed package", e); 11033 } 11034 } 11035 11036 @Override 11037 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11038 int userId) { 11039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11040 PackageSetting pkgSetting; 11041 final int uid = Binder.getCallingUid(); 11042 enforceCrossUserPermission(uid, userId, 11043 true /* requireFullPermission */, true /* checkShell */, 11044 "setApplicationHiddenSetting for user " + userId); 11045 11046 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11047 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11048 return false; 11049 } 11050 11051 long callingId = Binder.clearCallingIdentity(); 11052 try { 11053 boolean sendAdded = false; 11054 boolean sendRemoved = false; 11055 // writer 11056 synchronized (mPackages) { 11057 pkgSetting = mSettings.mPackages.get(packageName); 11058 if (pkgSetting == null) { 11059 return false; 11060 } 11061 if (pkgSetting.getHidden(userId) != hidden) { 11062 pkgSetting.setHidden(hidden, userId); 11063 mSettings.writePackageRestrictionsLPr(userId); 11064 if (hidden) { 11065 sendRemoved = true; 11066 } else { 11067 sendAdded = true; 11068 } 11069 } 11070 } 11071 if (sendAdded) { 11072 sendPackageAddedForUser(packageName, pkgSetting, userId); 11073 return true; 11074 } 11075 if (sendRemoved) { 11076 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11077 "hiding pkg"); 11078 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11079 return true; 11080 } 11081 } finally { 11082 Binder.restoreCallingIdentity(callingId); 11083 } 11084 return false; 11085 } 11086 11087 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11088 int userId) { 11089 final PackageRemovedInfo info = new PackageRemovedInfo(); 11090 info.removedPackage = packageName; 11091 info.removedUsers = new int[] {userId}; 11092 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11093 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11094 } 11095 11096 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11097 if (pkgList.length > 0) { 11098 Bundle extras = new Bundle(1); 11099 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11100 11101 sendPackageBroadcast( 11102 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11103 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11104 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11105 new int[] {userId}); 11106 } 11107 } 11108 11109 /** 11110 * Returns true if application is not found or there was an error. Otherwise it returns 11111 * the hidden state of the package for the given user. 11112 */ 11113 @Override 11114 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11117 true /* requireFullPermission */, false /* checkShell */, 11118 "getApplicationHidden for user " + userId); 11119 PackageSetting pkgSetting; 11120 long callingId = Binder.clearCallingIdentity(); 11121 try { 11122 // writer 11123 synchronized (mPackages) { 11124 pkgSetting = mSettings.mPackages.get(packageName); 11125 if (pkgSetting == null) { 11126 return true; 11127 } 11128 return pkgSetting.getHidden(userId); 11129 } 11130 } finally { 11131 Binder.restoreCallingIdentity(callingId); 11132 } 11133 } 11134 11135 /** 11136 * @hide 11137 */ 11138 @Override 11139 public int installExistingPackageAsUser(String packageName, int userId) { 11140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11141 null); 11142 PackageSetting pkgSetting; 11143 final int uid = Binder.getCallingUid(); 11144 enforceCrossUserPermission(uid, userId, 11145 true /* requireFullPermission */, true /* checkShell */, 11146 "installExistingPackage for user " + userId); 11147 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11148 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11149 } 11150 11151 long callingId = Binder.clearCallingIdentity(); 11152 try { 11153 boolean installed = false; 11154 11155 // writer 11156 synchronized (mPackages) { 11157 pkgSetting = mSettings.mPackages.get(packageName); 11158 if (pkgSetting == null) { 11159 return PackageManager.INSTALL_FAILED_INVALID_URI; 11160 } 11161 if (!pkgSetting.getInstalled(userId)) { 11162 pkgSetting.setInstalled(true, userId); 11163 pkgSetting.setHidden(false, userId); 11164 mSettings.writePackageRestrictionsLPr(userId); 11165 installed = true; 11166 } 11167 } 11168 11169 if (installed) { 11170 if (pkgSetting.pkg != null) { 11171 prepareAppDataAfterInstall(pkgSetting.pkg); 11172 } 11173 sendPackageAddedForUser(packageName, pkgSetting, userId); 11174 } 11175 } finally { 11176 Binder.restoreCallingIdentity(callingId); 11177 } 11178 11179 return PackageManager.INSTALL_SUCCEEDED; 11180 } 11181 11182 boolean isUserRestricted(int userId, String restrictionKey) { 11183 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11184 if (restrictions.getBoolean(restrictionKey, false)) { 11185 Log.w(TAG, "User is restricted: " + restrictionKey); 11186 return true; 11187 } 11188 return false; 11189 } 11190 11191 @Override 11192 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11193 int userId) { 11194 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11195 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11196 true /* requireFullPermission */, true /* checkShell */, 11197 "setPackagesSuspended for user " + userId); 11198 11199 if (ArrayUtils.isEmpty(packageNames)) { 11200 return packageNames; 11201 } 11202 11203 // List of package names for whom the suspended state has changed. 11204 List<String> changedPackages = new ArrayList<>(packageNames.length); 11205 // List of package names for whom the suspended state is not set as requested in this 11206 // method. 11207 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11208 for (int i = 0; i < packageNames.length; i++) { 11209 String packageName = packageNames[i]; 11210 long callingId = Binder.clearCallingIdentity(); 11211 try { 11212 boolean changed = false; 11213 final int appId; 11214 synchronized (mPackages) { 11215 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11216 if (pkgSetting == null) { 11217 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11218 + "\". Skipping suspending/un-suspending."); 11219 unactionedPackages.add(packageName); 11220 continue; 11221 } 11222 appId = pkgSetting.appId; 11223 if (pkgSetting.getSuspended(userId) != suspended) { 11224 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11225 unactionedPackages.add(packageName); 11226 continue; 11227 } 11228 pkgSetting.setSuspended(suspended, userId); 11229 mSettings.writePackageRestrictionsLPr(userId); 11230 changed = true; 11231 changedPackages.add(packageName); 11232 } 11233 } 11234 11235 if (changed && suspended) { 11236 killApplication(packageName, UserHandle.getUid(userId, appId), 11237 "suspending package"); 11238 } 11239 } finally { 11240 Binder.restoreCallingIdentity(callingId); 11241 } 11242 } 11243 11244 if (!changedPackages.isEmpty()) { 11245 sendPackagesSuspendedForUser(changedPackages.toArray( 11246 new String[changedPackages.size()]), userId, suspended); 11247 } 11248 11249 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11250 } 11251 11252 @Override 11253 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11255 true /* requireFullPermission */, false /* checkShell */, 11256 "isPackageSuspendedForUser for user " + userId); 11257 synchronized (mPackages) { 11258 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11259 if (pkgSetting == null) { 11260 throw new IllegalArgumentException("Unknown target package: " + packageName); 11261 } 11262 return pkgSetting.getSuspended(userId); 11263 } 11264 } 11265 11266 /** 11267 * TODO: cache and disallow blocking the active dialer. 11268 * 11269 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11270 */ 11271 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11272 if (isPackageDeviceAdmin(packageName, userId)) { 11273 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11274 + "\": has an active device admin"); 11275 return false; 11276 } 11277 11278 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11279 if (packageName.equals(activeLauncherPackageName)) { 11280 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11281 + "\": contains the active launcher"); 11282 return false; 11283 } 11284 11285 if (packageName.equals(mRequiredInstallerPackage)) { 11286 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11287 + "\": required for package installation"); 11288 return false; 11289 } 11290 11291 if (packageName.equals(mRequiredVerifierPackage)) { 11292 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11293 + "\": required for package verification"); 11294 return false; 11295 } 11296 11297 final PackageParser.Package pkg = mPackages.get(packageName); 11298 if (pkg != null && isPrivilegedApp(pkg)) { 11299 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11300 + "\": is a privileged app"); 11301 return false; 11302 } 11303 11304 return true; 11305 } 11306 11307 private String getActiveLauncherPackageName(int userId) { 11308 Intent intent = new Intent(Intent.ACTION_MAIN); 11309 intent.addCategory(Intent.CATEGORY_HOME); 11310 ResolveInfo resolveInfo = resolveIntent( 11311 intent, 11312 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11313 PackageManager.MATCH_DEFAULT_ONLY, 11314 userId); 11315 11316 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11317 } 11318 11319 @Override 11320 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11321 mContext.enforceCallingOrSelfPermission( 11322 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11323 "Only package verification agents can verify applications"); 11324 11325 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11326 final PackageVerificationResponse response = new PackageVerificationResponse( 11327 verificationCode, Binder.getCallingUid()); 11328 msg.arg1 = id; 11329 msg.obj = response; 11330 mHandler.sendMessage(msg); 11331 } 11332 11333 @Override 11334 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11335 long millisecondsToDelay) { 11336 mContext.enforceCallingOrSelfPermission( 11337 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11338 "Only package verification agents can extend verification timeouts"); 11339 11340 final PackageVerificationState state = mPendingVerification.get(id); 11341 final PackageVerificationResponse response = new PackageVerificationResponse( 11342 verificationCodeAtTimeout, Binder.getCallingUid()); 11343 11344 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11345 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11346 } 11347 if (millisecondsToDelay < 0) { 11348 millisecondsToDelay = 0; 11349 } 11350 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11351 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11352 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11353 } 11354 11355 if ((state != null) && !state.timeoutExtended()) { 11356 state.extendTimeout(); 11357 11358 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11359 msg.arg1 = id; 11360 msg.obj = response; 11361 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11362 } 11363 } 11364 11365 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11366 int verificationCode, UserHandle user) { 11367 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11368 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11369 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11370 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11371 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11372 11373 mContext.sendBroadcastAsUser(intent, user, 11374 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11375 } 11376 11377 private ComponentName matchComponentForVerifier(String packageName, 11378 List<ResolveInfo> receivers) { 11379 ActivityInfo targetReceiver = null; 11380 11381 final int NR = receivers.size(); 11382 for (int i = 0; i < NR; i++) { 11383 final ResolveInfo info = receivers.get(i); 11384 if (info.activityInfo == null) { 11385 continue; 11386 } 11387 11388 if (packageName.equals(info.activityInfo.packageName)) { 11389 targetReceiver = info.activityInfo; 11390 break; 11391 } 11392 } 11393 11394 if (targetReceiver == null) { 11395 return null; 11396 } 11397 11398 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11399 } 11400 11401 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11402 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11403 if (pkgInfo.verifiers.length == 0) { 11404 return null; 11405 } 11406 11407 final int N = pkgInfo.verifiers.length; 11408 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11409 for (int i = 0; i < N; i++) { 11410 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11411 11412 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11413 receivers); 11414 if (comp == null) { 11415 continue; 11416 } 11417 11418 final int verifierUid = getUidForVerifier(verifierInfo); 11419 if (verifierUid == -1) { 11420 continue; 11421 } 11422 11423 if (DEBUG_VERIFY) { 11424 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11425 + " with the correct signature"); 11426 } 11427 sufficientVerifiers.add(comp); 11428 verificationState.addSufficientVerifier(verifierUid); 11429 } 11430 11431 return sufficientVerifiers; 11432 } 11433 11434 private int getUidForVerifier(VerifierInfo verifierInfo) { 11435 synchronized (mPackages) { 11436 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11437 if (pkg == null) { 11438 return -1; 11439 } else if (pkg.mSignatures.length != 1) { 11440 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11441 + " has more than one signature; ignoring"); 11442 return -1; 11443 } 11444 11445 /* 11446 * If the public key of the package's signature does not match 11447 * our expected public key, then this is a different package and 11448 * we should skip. 11449 */ 11450 11451 final byte[] expectedPublicKey; 11452 try { 11453 final Signature verifierSig = pkg.mSignatures[0]; 11454 final PublicKey publicKey = verifierSig.getPublicKey(); 11455 expectedPublicKey = publicKey.getEncoded(); 11456 } catch (CertificateException e) { 11457 return -1; 11458 } 11459 11460 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11461 11462 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11463 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11464 + " does not have the expected public key; ignoring"); 11465 return -1; 11466 } 11467 11468 return pkg.applicationInfo.uid; 11469 } 11470 } 11471 11472 @Override 11473 public void finishPackageInstall(int token) { 11474 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11475 11476 if (DEBUG_INSTALL) { 11477 Slog.v(TAG, "BM finishing package install for " + token); 11478 } 11479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11480 11481 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11482 mHandler.sendMessage(msg); 11483 } 11484 11485 /** 11486 * Get the verification agent timeout. 11487 * 11488 * @return verification timeout in milliseconds 11489 */ 11490 private long getVerificationTimeout() { 11491 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11492 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11493 DEFAULT_VERIFICATION_TIMEOUT); 11494 } 11495 11496 /** 11497 * Get the default verification agent response code. 11498 * 11499 * @return default verification response code 11500 */ 11501 private int getDefaultVerificationResponse() { 11502 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11503 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11504 DEFAULT_VERIFICATION_RESPONSE); 11505 } 11506 11507 /** 11508 * Check whether or not package verification has been enabled. 11509 * 11510 * @return true if verification should be performed 11511 */ 11512 private boolean isVerificationEnabled(int userId, int installFlags) { 11513 if (!DEFAULT_VERIFY_ENABLE) { 11514 return false; 11515 } 11516 // Ephemeral apps don't get the full verification treatment 11517 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11518 if (DEBUG_EPHEMERAL) { 11519 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11520 } 11521 return false; 11522 } 11523 11524 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11525 11526 // Check if installing from ADB 11527 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11528 // Do not run verification in a test harness environment 11529 if (ActivityManager.isRunningInTestHarness()) { 11530 return false; 11531 } 11532 if (ensureVerifyAppsEnabled) { 11533 return true; 11534 } 11535 // Check if the developer does not want package verification for ADB installs 11536 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11537 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11538 return false; 11539 } 11540 } 11541 11542 if (ensureVerifyAppsEnabled) { 11543 return true; 11544 } 11545 11546 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11547 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11548 } 11549 11550 @Override 11551 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11552 throws RemoteException { 11553 mContext.enforceCallingOrSelfPermission( 11554 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11555 "Only intentfilter verification agents can verify applications"); 11556 11557 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11558 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11559 Binder.getCallingUid(), verificationCode, failedDomains); 11560 msg.arg1 = id; 11561 msg.obj = response; 11562 mHandler.sendMessage(msg); 11563 } 11564 11565 @Override 11566 public int getIntentVerificationStatus(String packageName, int userId) { 11567 synchronized (mPackages) { 11568 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11569 } 11570 } 11571 11572 @Override 11573 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11576 11577 boolean result = false; 11578 synchronized (mPackages) { 11579 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11580 } 11581 if (result) { 11582 scheduleWritePackageRestrictionsLocked(userId); 11583 } 11584 return result; 11585 } 11586 11587 @Override 11588 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11589 String packageName) { 11590 synchronized (mPackages) { 11591 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11592 } 11593 } 11594 11595 @Override 11596 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11597 if (TextUtils.isEmpty(packageName)) { 11598 return ParceledListSlice.emptyList(); 11599 } 11600 synchronized (mPackages) { 11601 PackageParser.Package pkg = mPackages.get(packageName); 11602 if (pkg == null || pkg.activities == null) { 11603 return ParceledListSlice.emptyList(); 11604 } 11605 final int count = pkg.activities.size(); 11606 ArrayList<IntentFilter> result = new ArrayList<>(); 11607 for (int n=0; n<count; n++) { 11608 PackageParser.Activity activity = pkg.activities.get(n); 11609 if (activity.intents != null && activity.intents.size() > 0) { 11610 result.addAll(activity.intents); 11611 } 11612 } 11613 return new ParceledListSlice<>(result); 11614 } 11615 } 11616 11617 @Override 11618 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11619 mContext.enforceCallingOrSelfPermission( 11620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11621 11622 synchronized (mPackages) { 11623 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11624 if (packageName != null) { 11625 result |= updateIntentVerificationStatus(packageName, 11626 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11627 userId); 11628 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11629 packageName, userId); 11630 } 11631 return result; 11632 } 11633 } 11634 11635 @Override 11636 public String getDefaultBrowserPackageName(int userId) { 11637 synchronized (mPackages) { 11638 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11639 } 11640 } 11641 11642 /** 11643 * Get the "allow unknown sources" setting. 11644 * 11645 * @return the current "allow unknown sources" setting 11646 */ 11647 private int getUnknownSourcesSettings() { 11648 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11649 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11650 -1); 11651 } 11652 11653 @Override 11654 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11655 final int uid = Binder.getCallingUid(); 11656 // writer 11657 synchronized (mPackages) { 11658 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11659 if (targetPackageSetting == null) { 11660 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11661 } 11662 11663 PackageSetting installerPackageSetting; 11664 if (installerPackageName != null) { 11665 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11666 if (installerPackageSetting == null) { 11667 throw new IllegalArgumentException("Unknown installer package: " 11668 + installerPackageName); 11669 } 11670 } else { 11671 installerPackageSetting = null; 11672 } 11673 11674 Signature[] callerSignature; 11675 Object obj = mSettings.getUserIdLPr(uid); 11676 if (obj != null) { 11677 if (obj instanceof SharedUserSetting) { 11678 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11679 } else if (obj instanceof PackageSetting) { 11680 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11681 } else { 11682 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11683 } 11684 } else { 11685 throw new SecurityException("Unknown calling UID: " + uid); 11686 } 11687 11688 // Verify: can't set installerPackageName to a package that is 11689 // not signed with the same cert as the caller. 11690 if (installerPackageSetting != null) { 11691 if (compareSignatures(callerSignature, 11692 installerPackageSetting.signatures.mSignatures) 11693 != PackageManager.SIGNATURE_MATCH) { 11694 throw new SecurityException( 11695 "Caller does not have same cert as new installer package " 11696 + installerPackageName); 11697 } 11698 } 11699 11700 // Verify: if target already has an installer package, it must 11701 // be signed with the same cert as the caller. 11702 if (targetPackageSetting.installerPackageName != null) { 11703 PackageSetting setting = mSettings.mPackages.get( 11704 targetPackageSetting.installerPackageName); 11705 // If the currently set package isn't valid, then it's always 11706 // okay to change it. 11707 if (setting != null) { 11708 if (compareSignatures(callerSignature, 11709 setting.signatures.mSignatures) 11710 != PackageManager.SIGNATURE_MATCH) { 11711 throw new SecurityException( 11712 "Caller does not have same cert as old installer package " 11713 + targetPackageSetting.installerPackageName); 11714 } 11715 } 11716 } 11717 11718 // Okay! 11719 targetPackageSetting.installerPackageName = installerPackageName; 11720 scheduleWriteSettingsLocked(); 11721 } 11722 } 11723 11724 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11725 // Queue up an async operation since the package installation may take a little while. 11726 mHandler.post(new Runnable() { 11727 public void run() { 11728 mHandler.removeCallbacks(this); 11729 // Result object to be returned 11730 PackageInstalledInfo res = new PackageInstalledInfo(); 11731 res.setReturnCode(currentStatus); 11732 res.uid = -1; 11733 res.pkg = null; 11734 res.removedInfo = null; 11735 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11736 args.doPreInstall(res.returnCode); 11737 synchronized (mInstallLock) { 11738 installPackageTracedLI(args, res); 11739 } 11740 args.doPostInstall(res.returnCode, res.uid); 11741 } 11742 11743 // A restore should be performed at this point if (a) the install 11744 // succeeded, (b) the operation is not an update, and (c) the new 11745 // package has not opted out of backup participation. 11746 final boolean update = res.removedInfo != null 11747 && res.removedInfo.removedPackage != null; 11748 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11749 boolean doRestore = !update 11750 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11751 11752 // Set up the post-install work request bookkeeping. This will be used 11753 // and cleaned up by the post-install event handling regardless of whether 11754 // there's a restore pass performed. Token values are >= 1. 11755 int token; 11756 if (mNextInstallToken < 0) mNextInstallToken = 1; 11757 token = mNextInstallToken++; 11758 11759 PostInstallData data = new PostInstallData(args, res); 11760 mRunningInstalls.put(token, data); 11761 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11762 11763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11764 // Pass responsibility to the Backup Manager. It will perform a 11765 // restore if appropriate, then pass responsibility back to the 11766 // Package Manager to run the post-install observer callbacks 11767 // and broadcasts. 11768 IBackupManager bm = IBackupManager.Stub.asInterface( 11769 ServiceManager.getService(Context.BACKUP_SERVICE)); 11770 if (bm != null) { 11771 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11772 + " to BM for possible restore"); 11773 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11774 try { 11775 // TODO: http://b/22388012 11776 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11777 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11778 } else { 11779 doRestore = false; 11780 } 11781 } catch (RemoteException e) { 11782 // can't happen; the backup manager is local 11783 } catch (Exception e) { 11784 Slog.e(TAG, "Exception trying to enqueue restore", e); 11785 doRestore = false; 11786 } 11787 } else { 11788 Slog.e(TAG, "Backup Manager not found!"); 11789 doRestore = false; 11790 } 11791 } 11792 11793 if (!doRestore) { 11794 // No restore possible, or the Backup Manager was mysteriously not 11795 // available -- just fire the post-install work request directly. 11796 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11797 11798 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11799 11800 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11801 mHandler.sendMessage(msg); 11802 } 11803 } 11804 }); 11805 } 11806 11807 private abstract class HandlerParams { 11808 private static final int MAX_RETRIES = 4; 11809 11810 /** 11811 * Number of times startCopy() has been attempted and had a non-fatal 11812 * error. 11813 */ 11814 private int mRetries = 0; 11815 11816 /** User handle for the user requesting the information or installation. */ 11817 private final UserHandle mUser; 11818 String traceMethod; 11819 int traceCookie; 11820 11821 HandlerParams(UserHandle user) { 11822 mUser = user; 11823 } 11824 11825 UserHandle getUser() { 11826 return mUser; 11827 } 11828 11829 HandlerParams setTraceMethod(String traceMethod) { 11830 this.traceMethod = traceMethod; 11831 return this; 11832 } 11833 11834 HandlerParams setTraceCookie(int traceCookie) { 11835 this.traceCookie = traceCookie; 11836 return this; 11837 } 11838 11839 final boolean startCopy() { 11840 boolean res; 11841 try { 11842 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11843 11844 if (++mRetries > MAX_RETRIES) { 11845 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11846 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11847 handleServiceError(); 11848 return false; 11849 } else { 11850 handleStartCopy(); 11851 res = true; 11852 } 11853 } catch (RemoteException e) { 11854 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11855 mHandler.sendEmptyMessage(MCS_RECONNECT); 11856 res = false; 11857 } 11858 handleReturnCode(); 11859 return res; 11860 } 11861 11862 final void serviceError() { 11863 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11864 handleServiceError(); 11865 handleReturnCode(); 11866 } 11867 11868 abstract void handleStartCopy() throws RemoteException; 11869 abstract void handleServiceError(); 11870 abstract void handleReturnCode(); 11871 } 11872 11873 class MeasureParams extends HandlerParams { 11874 private final PackageStats mStats; 11875 private boolean mSuccess; 11876 11877 private final IPackageStatsObserver mObserver; 11878 11879 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11880 super(new UserHandle(stats.userHandle)); 11881 mObserver = observer; 11882 mStats = stats; 11883 } 11884 11885 @Override 11886 public String toString() { 11887 return "MeasureParams{" 11888 + Integer.toHexString(System.identityHashCode(this)) 11889 + " " + mStats.packageName + "}"; 11890 } 11891 11892 @Override 11893 void handleStartCopy() throws RemoteException { 11894 synchronized (mInstallLock) { 11895 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11896 } 11897 11898 if (mSuccess) { 11899 final boolean mounted; 11900 if (Environment.isExternalStorageEmulated()) { 11901 mounted = true; 11902 } else { 11903 final String status = Environment.getExternalStorageState(); 11904 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11905 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11906 } 11907 11908 if (mounted) { 11909 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11910 11911 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11912 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11913 11914 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11915 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11916 11917 // Always subtract cache size, since it's a subdirectory 11918 mStats.externalDataSize -= mStats.externalCacheSize; 11919 11920 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11921 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11922 11923 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11924 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11925 } 11926 } 11927 } 11928 11929 @Override 11930 void handleReturnCode() { 11931 if (mObserver != null) { 11932 try { 11933 mObserver.onGetStatsCompleted(mStats, mSuccess); 11934 } catch (RemoteException e) { 11935 Slog.i(TAG, "Observer no longer exists."); 11936 } 11937 } 11938 } 11939 11940 @Override 11941 void handleServiceError() { 11942 Slog.e(TAG, "Could not measure application " + mStats.packageName 11943 + " external storage"); 11944 } 11945 } 11946 11947 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11948 throws RemoteException { 11949 long result = 0; 11950 for (File path : paths) { 11951 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11952 } 11953 return result; 11954 } 11955 11956 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11957 for (File path : paths) { 11958 try { 11959 mcs.clearDirectory(path.getAbsolutePath()); 11960 } catch (RemoteException e) { 11961 } 11962 } 11963 } 11964 11965 static class OriginInfo { 11966 /** 11967 * Location where install is coming from, before it has been 11968 * copied/renamed into place. This could be a single monolithic APK 11969 * file, or a cluster directory. This location may be untrusted. 11970 */ 11971 final File file; 11972 final String cid; 11973 11974 /** 11975 * Flag indicating that {@link #file} or {@link #cid} has already been 11976 * staged, meaning downstream users don't need to defensively copy the 11977 * contents. 11978 */ 11979 final boolean staged; 11980 11981 /** 11982 * Flag indicating that {@link #file} or {@link #cid} is an already 11983 * installed app that is being moved. 11984 */ 11985 final boolean existing; 11986 11987 final String resolvedPath; 11988 final File resolvedFile; 11989 11990 static OriginInfo fromNothing() { 11991 return new OriginInfo(null, null, false, false); 11992 } 11993 11994 static OriginInfo fromUntrustedFile(File file) { 11995 return new OriginInfo(file, null, false, false); 11996 } 11997 11998 static OriginInfo fromExistingFile(File file) { 11999 return new OriginInfo(file, null, false, true); 12000 } 12001 12002 static OriginInfo fromStagedFile(File file) { 12003 return new OriginInfo(file, null, true, false); 12004 } 12005 12006 static OriginInfo fromStagedContainer(String cid) { 12007 return new OriginInfo(null, cid, true, false); 12008 } 12009 12010 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12011 this.file = file; 12012 this.cid = cid; 12013 this.staged = staged; 12014 this.existing = existing; 12015 12016 if (cid != null) { 12017 resolvedPath = PackageHelper.getSdDir(cid); 12018 resolvedFile = new File(resolvedPath); 12019 } else if (file != null) { 12020 resolvedPath = file.getAbsolutePath(); 12021 resolvedFile = file; 12022 } else { 12023 resolvedPath = null; 12024 resolvedFile = null; 12025 } 12026 } 12027 } 12028 12029 static class MoveInfo { 12030 final int moveId; 12031 final String fromUuid; 12032 final String toUuid; 12033 final String packageName; 12034 final String dataAppName; 12035 final int appId; 12036 final String seinfo; 12037 final int targetSdkVersion; 12038 12039 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12040 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12041 this.moveId = moveId; 12042 this.fromUuid = fromUuid; 12043 this.toUuid = toUuid; 12044 this.packageName = packageName; 12045 this.dataAppName = dataAppName; 12046 this.appId = appId; 12047 this.seinfo = seinfo; 12048 this.targetSdkVersion = targetSdkVersion; 12049 } 12050 } 12051 12052 static class VerificationInfo { 12053 /** A constant used to indicate that a uid value is not present. */ 12054 public static final int NO_UID = -1; 12055 12056 /** URI referencing where the package was downloaded from. */ 12057 final Uri originatingUri; 12058 12059 /** HTTP referrer URI associated with the originatingURI. */ 12060 final Uri referrer; 12061 12062 /** UID of the application that the install request originated from. */ 12063 final int originatingUid; 12064 12065 /** UID of application requesting the install */ 12066 final int installerUid; 12067 12068 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12069 this.originatingUri = originatingUri; 12070 this.referrer = referrer; 12071 this.originatingUid = originatingUid; 12072 this.installerUid = installerUid; 12073 } 12074 } 12075 12076 class InstallParams extends HandlerParams { 12077 final OriginInfo origin; 12078 final MoveInfo move; 12079 final IPackageInstallObserver2 observer; 12080 int installFlags; 12081 final String installerPackageName; 12082 final String volumeUuid; 12083 private InstallArgs mArgs; 12084 private int mRet; 12085 final String packageAbiOverride; 12086 final String[] grantedRuntimePermissions; 12087 final VerificationInfo verificationInfo; 12088 12089 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12090 int installFlags, String installerPackageName, String volumeUuid, 12091 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12092 String[] grantedPermissions) { 12093 super(user); 12094 this.origin = origin; 12095 this.move = move; 12096 this.observer = observer; 12097 this.installFlags = installFlags; 12098 this.installerPackageName = installerPackageName; 12099 this.volumeUuid = volumeUuid; 12100 this.verificationInfo = verificationInfo; 12101 this.packageAbiOverride = packageAbiOverride; 12102 this.grantedRuntimePermissions = grantedPermissions; 12103 } 12104 12105 @Override 12106 public String toString() { 12107 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12108 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12109 } 12110 12111 private int installLocationPolicy(PackageInfoLite pkgLite) { 12112 String packageName = pkgLite.packageName; 12113 int installLocation = pkgLite.installLocation; 12114 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12115 // reader 12116 synchronized (mPackages) { 12117 // Currently installed package which the new package is attempting to replace or 12118 // null if no such package is installed. 12119 PackageParser.Package installedPkg = mPackages.get(packageName); 12120 // Package which currently owns the data which the new package will own if installed. 12121 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12122 // will be null whereas dataOwnerPkg will contain information about the package 12123 // which was uninstalled while keeping its data. 12124 PackageParser.Package dataOwnerPkg = installedPkg; 12125 if (dataOwnerPkg == null) { 12126 PackageSetting ps = mSettings.mPackages.get(packageName); 12127 if (ps != null) { 12128 dataOwnerPkg = ps.pkg; 12129 } 12130 } 12131 12132 if (dataOwnerPkg != null) { 12133 // If installed, the package will get access to data left on the device by its 12134 // predecessor. As a security measure, this is permited only if this is not a 12135 // version downgrade or if the predecessor package is marked as debuggable and 12136 // a downgrade is explicitly requested. 12137 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 12138 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 12139 try { 12140 checkDowngrade(dataOwnerPkg, pkgLite); 12141 } catch (PackageManagerException e) { 12142 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12143 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12144 } 12145 } 12146 } 12147 12148 if (installedPkg != null) { 12149 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12150 // Check for updated system application. 12151 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12152 if (onSd) { 12153 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12154 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12155 } 12156 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12157 } else { 12158 if (onSd) { 12159 // Install flag overrides everything. 12160 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12161 } 12162 // If current upgrade specifies particular preference 12163 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12164 // Application explicitly specified internal. 12165 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12166 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12167 // App explictly prefers external. Let policy decide 12168 } else { 12169 // Prefer previous location 12170 if (isExternal(installedPkg)) { 12171 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12172 } 12173 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12174 } 12175 } 12176 } else { 12177 // Invalid install. Return error code 12178 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12179 } 12180 } 12181 } 12182 // All the special cases have been taken care of. 12183 // Return result based on recommended install location. 12184 if (onSd) { 12185 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12186 } 12187 return pkgLite.recommendedInstallLocation; 12188 } 12189 12190 /* 12191 * Invoke remote method to get package information and install 12192 * location values. Override install location based on default 12193 * policy if needed and then create install arguments based 12194 * on the install location. 12195 */ 12196 public void handleStartCopy() throws RemoteException { 12197 int ret = PackageManager.INSTALL_SUCCEEDED; 12198 12199 // If we're already staged, we've firmly committed to an install location 12200 if (origin.staged) { 12201 if (origin.file != null) { 12202 installFlags |= PackageManager.INSTALL_INTERNAL; 12203 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12204 } else if (origin.cid != null) { 12205 installFlags |= PackageManager.INSTALL_EXTERNAL; 12206 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12207 } else { 12208 throw new IllegalStateException("Invalid stage location"); 12209 } 12210 } 12211 12212 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12213 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12214 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12215 PackageInfoLite pkgLite = null; 12216 12217 if (onInt && onSd) { 12218 // Check if both bits are set. 12219 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12220 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12221 } else if (onSd && ephemeral) { 12222 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12223 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12224 } else { 12225 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12226 packageAbiOverride); 12227 12228 if (DEBUG_EPHEMERAL && ephemeral) { 12229 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12230 } 12231 12232 /* 12233 * If we have too little free space, try to free cache 12234 * before giving up. 12235 */ 12236 if (!origin.staged && pkgLite.recommendedInstallLocation 12237 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12238 // TODO: focus freeing disk space on the target device 12239 final StorageManager storage = StorageManager.from(mContext); 12240 final long lowThreshold = storage.getStorageLowBytes( 12241 Environment.getDataDirectory()); 12242 12243 final long sizeBytes = mContainerService.calculateInstalledSize( 12244 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12245 12246 try { 12247 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12248 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12249 installFlags, packageAbiOverride); 12250 } catch (InstallerException e) { 12251 Slog.w(TAG, "Failed to free cache", e); 12252 } 12253 12254 /* 12255 * The cache free must have deleted the file we 12256 * downloaded to install. 12257 * 12258 * TODO: fix the "freeCache" call to not delete 12259 * the file we care about. 12260 */ 12261 if (pkgLite.recommendedInstallLocation 12262 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12263 pkgLite.recommendedInstallLocation 12264 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12265 } 12266 } 12267 } 12268 12269 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12270 int loc = pkgLite.recommendedInstallLocation; 12271 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12272 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12273 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12274 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12275 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12276 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12277 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12278 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12279 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12280 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12281 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12282 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12283 } else { 12284 // Override with defaults if needed. 12285 loc = installLocationPolicy(pkgLite); 12286 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12287 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12288 } else if (!onSd && !onInt) { 12289 // Override install location with flags 12290 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12291 // Set the flag to install on external media. 12292 installFlags |= PackageManager.INSTALL_EXTERNAL; 12293 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12294 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12295 if (DEBUG_EPHEMERAL) { 12296 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12297 } 12298 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12299 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12300 |PackageManager.INSTALL_INTERNAL); 12301 } else { 12302 // Make sure the flag for installing on external 12303 // media is unset 12304 installFlags |= PackageManager.INSTALL_INTERNAL; 12305 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12306 } 12307 } 12308 } 12309 } 12310 12311 final InstallArgs args = createInstallArgs(this); 12312 mArgs = args; 12313 12314 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12315 // TODO: http://b/22976637 12316 // Apps installed for "all" users use the device owner to verify the app 12317 UserHandle verifierUser = getUser(); 12318 if (verifierUser == UserHandle.ALL) { 12319 verifierUser = UserHandle.SYSTEM; 12320 } 12321 12322 /* 12323 * Determine if we have any installed package verifiers. If we 12324 * do, then we'll defer to them to verify the packages. 12325 */ 12326 final int requiredUid = mRequiredVerifierPackage == null ? -1 12327 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12328 verifierUser.getIdentifier()); 12329 if (!origin.existing && requiredUid != -1 12330 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12331 final Intent verification = new Intent( 12332 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12333 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12334 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12335 PACKAGE_MIME_TYPE); 12336 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12337 12338 // Query all live verifiers based on current user state 12339 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12340 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12341 12342 if (DEBUG_VERIFY) { 12343 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12344 + verification.toString() + " with " + pkgLite.verifiers.length 12345 + " optional verifiers"); 12346 } 12347 12348 final int verificationId = mPendingVerificationToken++; 12349 12350 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12351 12352 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12353 installerPackageName); 12354 12355 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12356 installFlags); 12357 12358 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12359 pkgLite.packageName); 12360 12361 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12362 pkgLite.versionCode); 12363 12364 if (verificationInfo != null) { 12365 if (verificationInfo.originatingUri != null) { 12366 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12367 verificationInfo.originatingUri); 12368 } 12369 if (verificationInfo.referrer != null) { 12370 verification.putExtra(Intent.EXTRA_REFERRER, 12371 verificationInfo.referrer); 12372 } 12373 if (verificationInfo.originatingUid >= 0) { 12374 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12375 verificationInfo.originatingUid); 12376 } 12377 if (verificationInfo.installerUid >= 0) { 12378 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12379 verificationInfo.installerUid); 12380 } 12381 } 12382 12383 final PackageVerificationState verificationState = new PackageVerificationState( 12384 requiredUid, args); 12385 12386 mPendingVerification.append(verificationId, verificationState); 12387 12388 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12389 receivers, verificationState); 12390 12391 /* 12392 * If any sufficient verifiers were listed in the package 12393 * manifest, attempt to ask them. 12394 */ 12395 if (sufficientVerifiers != null) { 12396 final int N = sufficientVerifiers.size(); 12397 if (N == 0) { 12398 Slog.i(TAG, "Additional verifiers required, but none installed."); 12399 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12400 } else { 12401 for (int i = 0; i < N; i++) { 12402 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12403 12404 final Intent sufficientIntent = new Intent(verification); 12405 sufficientIntent.setComponent(verifierComponent); 12406 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12407 } 12408 } 12409 } 12410 12411 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12412 mRequiredVerifierPackage, receivers); 12413 if (ret == PackageManager.INSTALL_SUCCEEDED 12414 && mRequiredVerifierPackage != null) { 12415 Trace.asyncTraceBegin( 12416 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12417 /* 12418 * Send the intent to the required verification agent, 12419 * but only start the verification timeout after the 12420 * target BroadcastReceivers have run. 12421 */ 12422 verification.setComponent(requiredVerifierComponent); 12423 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12424 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12425 new BroadcastReceiver() { 12426 @Override 12427 public void onReceive(Context context, Intent intent) { 12428 final Message msg = mHandler 12429 .obtainMessage(CHECK_PENDING_VERIFICATION); 12430 msg.arg1 = verificationId; 12431 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12432 } 12433 }, null, 0, null, null); 12434 12435 /* 12436 * We don't want the copy to proceed until verification 12437 * succeeds, so null out this field. 12438 */ 12439 mArgs = null; 12440 } 12441 } else { 12442 /* 12443 * No package verification is enabled, so immediately start 12444 * the remote call to initiate copy using temporary file. 12445 */ 12446 ret = args.copyApk(mContainerService, true); 12447 } 12448 } 12449 12450 mRet = ret; 12451 } 12452 12453 @Override 12454 void handleReturnCode() { 12455 // If mArgs is null, then MCS couldn't be reached. When it 12456 // reconnects, it will try again to install. At that point, this 12457 // will succeed. 12458 if (mArgs != null) { 12459 processPendingInstall(mArgs, mRet); 12460 } 12461 } 12462 12463 @Override 12464 void handleServiceError() { 12465 mArgs = createInstallArgs(this); 12466 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12467 } 12468 12469 public boolean isForwardLocked() { 12470 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12471 } 12472 } 12473 12474 /** 12475 * Used during creation of InstallArgs 12476 * 12477 * @param installFlags package installation flags 12478 * @return true if should be installed on external storage 12479 */ 12480 private static boolean installOnExternalAsec(int installFlags) { 12481 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12482 return false; 12483 } 12484 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12485 return true; 12486 } 12487 return false; 12488 } 12489 12490 /** 12491 * Used during creation of InstallArgs 12492 * 12493 * @param installFlags package installation flags 12494 * @return true if should be installed as forward locked 12495 */ 12496 private static boolean installForwardLocked(int installFlags) { 12497 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12498 } 12499 12500 private InstallArgs createInstallArgs(InstallParams params) { 12501 if (params.move != null) { 12502 return new MoveInstallArgs(params); 12503 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12504 return new AsecInstallArgs(params); 12505 } else { 12506 return new FileInstallArgs(params); 12507 } 12508 } 12509 12510 /** 12511 * Create args that describe an existing installed package. Typically used 12512 * when cleaning up old installs, or used as a move source. 12513 */ 12514 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12515 String resourcePath, String[] instructionSets) { 12516 final boolean isInAsec; 12517 if (installOnExternalAsec(installFlags)) { 12518 /* Apps on SD card are always in ASEC containers. */ 12519 isInAsec = true; 12520 } else if (installForwardLocked(installFlags) 12521 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12522 /* 12523 * Forward-locked apps are only in ASEC containers if they're the 12524 * new style 12525 */ 12526 isInAsec = true; 12527 } else { 12528 isInAsec = false; 12529 } 12530 12531 if (isInAsec) { 12532 return new AsecInstallArgs(codePath, instructionSets, 12533 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12534 } else { 12535 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12536 } 12537 } 12538 12539 static abstract class InstallArgs { 12540 /** @see InstallParams#origin */ 12541 final OriginInfo origin; 12542 /** @see InstallParams#move */ 12543 final MoveInfo move; 12544 12545 final IPackageInstallObserver2 observer; 12546 // Always refers to PackageManager flags only 12547 final int installFlags; 12548 final String installerPackageName; 12549 final String volumeUuid; 12550 final UserHandle user; 12551 final String abiOverride; 12552 final String[] installGrantPermissions; 12553 /** If non-null, drop an async trace when the install completes */ 12554 final String traceMethod; 12555 final int traceCookie; 12556 12557 // The list of instruction sets supported by this app. This is currently 12558 // only used during the rmdex() phase to clean up resources. We can get rid of this 12559 // if we move dex files under the common app path. 12560 /* nullable */ String[] instructionSets; 12561 12562 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12563 int installFlags, String installerPackageName, String volumeUuid, 12564 UserHandle user, String[] instructionSets, 12565 String abiOverride, String[] installGrantPermissions, 12566 String traceMethod, int traceCookie) { 12567 this.origin = origin; 12568 this.move = move; 12569 this.installFlags = installFlags; 12570 this.observer = observer; 12571 this.installerPackageName = installerPackageName; 12572 this.volumeUuid = volumeUuid; 12573 this.user = user; 12574 this.instructionSets = instructionSets; 12575 this.abiOverride = abiOverride; 12576 this.installGrantPermissions = installGrantPermissions; 12577 this.traceMethod = traceMethod; 12578 this.traceCookie = traceCookie; 12579 } 12580 12581 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12582 abstract int doPreInstall(int status); 12583 12584 /** 12585 * Rename package into final resting place. All paths on the given 12586 * scanned package should be updated to reflect the rename. 12587 */ 12588 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12589 abstract int doPostInstall(int status, int uid); 12590 12591 /** @see PackageSettingBase#codePathString */ 12592 abstract String getCodePath(); 12593 /** @see PackageSettingBase#resourcePathString */ 12594 abstract String getResourcePath(); 12595 12596 // Need installer lock especially for dex file removal. 12597 abstract void cleanUpResourcesLI(); 12598 abstract boolean doPostDeleteLI(boolean delete); 12599 12600 /** 12601 * Called before the source arguments are copied. This is used mostly 12602 * for MoveParams when it needs to read the source file to put it in the 12603 * destination. 12604 */ 12605 int doPreCopy() { 12606 return PackageManager.INSTALL_SUCCEEDED; 12607 } 12608 12609 /** 12610 * Called after the source arguments are copied. This is used mostly for 12611 * MoveParams when it needs to read the source file to put it in the 12612 * destination. 12613 */ 12614 int doPostCopy(int uid) { 12615 return PackageManager.INSTALL_SUCCEEDED; 12616 } 12617 12618 protected boolean isFwdLocked() { 12619 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12620 } 12621 12622 protected boolean isExternalAsec() { 12623 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12624 } 12625 12626 protected boolean isEphemeral() { 12627 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12628 } 12629 12630 UserHandle getUser() { 12631 return user; 12632 } 12633 } 12634 12635 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12636 if (!allCodePaths.isEmpty()) { 12637 if (instructionSets == null) { 12638 throw new IllegalStateException("instructionSet == null"); 12639 } 12640 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12641 for (String codePath : allCodePaths) { 12642 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12643 try { 12644 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12645 } catch (InstallerException ignored) { 12646 } 12647 } 12648 } 12649 } 12650 } 12651 12652 /** 12653 * Logic to handle installation of non-ASEC applications, including copying 12654 * and renaming logic. 12655 */ 12656 class FileInstallArgs extends InstallArgs { 12657 private File codeFile; 12658 private File resourceFile; 12659 12660 // Example topology: 12661 // /data/app/com.example/base.apk 12662 // /data/app/com.example/split_foo.apk 12663 // /data/app/com.example/lib/arm/libfoo.so 12664 // /data/app/com.example/lib/arm64/libfoo.so 12665 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12666 12667 /** New install */ 12668 FileInstallArgs(InstallParams params) { 12669 super(params.origin, params.move, params.observer, params.installFlags, 12670 params.installerPackageName, params.volumeUuid, 12671 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12672 params.grantedRuntimePermissions, 12673 params.traceMethod, params.traceCookie); 12674 if (isFwdLocked()) { 12675 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12676 } 12677 } 12678 12679 /** Existing install */ 12680 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12681 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12682 null, null, null, 0); 12683 this.codeFile = (codePath != null) ? new File(codePath) : null; 12684 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12685 } 12686 12687 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12688 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12689 try { 12690 return doCopyApk(imcs, temp); 12691 } finally { 12692 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12693 } 12694 } 12695 12696 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12697 if (origin.staged) { 12698 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12699 codeFile = origin.file; 12700 resourceFile = origin.file; 12701 return PackageManager.INSTALL_SUCCEEDED; 12702 } 12703 12704 try { 12705 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12706 final File tempDir = 12707 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12708 codeFile = tempDir; 12709 resourceFile = tempDir; 12710 } catch (IOException e) { 12711 Slog.w(TAG, "Failed to create copy file: " + e); 12712 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12713 } 12714 12715 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12716 @Override 12717 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12718 if (!FileUtils.isValidExtFilename(name)) { 12719 throw new IllegalArgumentException("Invalid filename: " + name); 12720 } 12721 try { 12722 final File file = new File(codeFile, name); 12723 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12724 O_RDWR | O_CREAT, 0644); 12725 Os.chmod(file.getAbsolutePath(), 0644); 12726 return new ParcelFileDescriptor(fd); 12727 } catch (ErrnoException e) { 12728 throw new RemoteException("Failed to open: " + e.getMessage()); 12729 } 12730 } 12731 }; 12732 12733 int ret = PackageManager.INSTALL_SUCCEEDED; 12734 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12735 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12736 Slog.e(TAG, "Failed to copy package"); 12737 return ret; 12738 } 12739 12740 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12741 NativeLibraryHelper.Handle handle = null; 12742 try { 12743 handle = NativeLibraryHelper.Handle.create(codeFile); 12744 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12745 abiOverride); 12746 } catch (IOException e) { 12747 Slog.e(TAG, "Copying native libraries failed", e); 12748 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12749 } finally { 12750 IoUtils.closeQuietly(handle); 12751 } 12752 12753 return ret; 12754 } 12755 12756 int doPreInstall(int status) { 12757 if (status != PackageManager.INSTALL_SUCCEEDED) { 12758 cleanUp(); 12759 } 12760 return status; 12761 } 12762 12763 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12764 if (status != PackageManager.INSTALL_SUCCEEDED) { 12765 cleanUp(); 12766 return false; 12767 } 12768 12769 final File targetDir = codeFile.getParentFile(); 12770 final File beforeCodeFile = codeFile; 12771 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12772 12773 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12774 try { 12775 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12776 } catch (ErrnoException e) { 12777 Slog.w(TAG, "Failed to rename", e); 12778 return false; 12779 } 12780 12781 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12782 Slog.w(TAG, "Failed to restorecon"); 12783 return false; 12784 } 12785 12786 // Reflect the rename internally 12787 codeFile = afterCodeFile; 12788 resourceFile = afterCodeFile; 12789 12790 // Reflect the rename in scanned details 12791 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12792 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12793 afterCodeFile, pkg.baseCodePath)); 12794 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12795 afterCodeFile, pkg.splitCodePaths)); 12796 12797 // Reflect the rename in app info 12798 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12799 pkg.setApplicationInfoCodePath(pkg.codePath); 12800 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12801 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12802 pkg.setApplicationInfoResourcePath(pkg.codePath); 12803 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12804 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12805 12806 return true; 12807 } 12808 12809 int doPostInstall(int status, int uid) { 12810 if (status != PackageManager.INSTALL_SUCCEEDED) { 12811 cleanUp(); 12812 } 12813 return status; 12814 } 12815 12816 @Override 12817 String getCodePath() { 12818 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12819 } 12820 12821 @Override 12822 String getResourcePath() { 12823 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12824 } 12825 12826 private boolean cleanUp() { 12827 if (codeFile == null || !codeFile.exists()) { 12828 return false; 12829 } 12830 12831 removeCodePathLI(codeFile); 12832 12833 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12834 resourceFile.delete(); 12835 } 12836 12837 return true; 12838 } 12839 12840 void cleanUpResourcesLI() { 12841 // Try enumerating all code paths before deleting 12842 List<String> allCodePaths = Collections.EMPTY_LIST; 12843 if (codeFile != null && codeFile.exists()) { 12844 try { 12845 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12846 allCodePaths = pkg.getAllCodePaths(); 12847 } catch (PackageParserException e) { 12848 // Ignored; we tried our best 12849 } 12850 } 12851 12852 cleanUp(); 12853 removeDexFiles(allCodePaths, instructionSets); 12854 } 12855 12856 boolean doPostDeleteLI(boolean delete) { 12857 // XXX err, shouldn't we respect the delete flag? 12858 cleanUpResourcesLI(); 12859 return true; 12860 } 12861 } 12862 12863 private boolean isAsecExternal(String cid) { 12864 final String asecPath = PackageHelper.getSdFilesystem(cid); 12865 return !asecPath.startsWith(mAsecInternalPath); 12866 } 12867 12868 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12869 PackageManagerException { 12870 if (copyRet < 0) { 12871 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12872 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12873 throw new PackageManagerException(copyRet, message); 12874 } 12875 } 12876 } 12877 12878 /** 12879 * Extract the MountService "container ID" from the full code path of an 12880 * .apk. 12881 */ 12882 static String cidFromCodePath(String fullCodePath) { 12883 int eidx = fullCodePath.lastIndexOf("/"); 12884 String subStr1 = fullCodePath.substring(0, eidx); 12885 int sidx = subStr1.lastIndexOf("/"); 12886 return subStr1.substring(sidx+1, eidx); 12887 } 12888 12889 /** 12890 * Logic to handle installation of ASEC applications, including copying and 12891 * renaming logic. 12892 */ 12893 class AsecInstallArgs extends InstallArgs { 12894 static final String RES_FILE_NAME = "pkg.apk"; 12895 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12896 12897 String cid; 12898 String packagePath; 12899 String resourcePath; 12900 12901 /** New install */ 12902 AsecInstallArgs(InstallParams params) { 12903 super(params.origin, params.move, params.observer, params.installFlags, 12904 params.installerPackageName, params.volumeUuid, 12905 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12906 params.grantedRuntimePermissions, 12907 params.traceMethod, params.traceCookie); 12908 } 12909 12910 /** Existing install */ 12911 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12912 boolean isExternal, boolean isForwardLocked) { 12913 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12914 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12915 instructionSets, null, null, null, 0); 12916 // Hackily pretend we're still looking at a full code path 12917 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12918 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12919 } 12920 12921 // Extract cid from fullCodePath 12922 int eidx = fullCodePath.lastIndexOf("/"); 12923 String subStr1 = fullCodePath.substring(0, eidx); 12924 int sidx = subStr1.lastIndexOf("/"); 12925 cid = subStr1.substring(sidx+1, eidx); 12926 setMountPath(subStr1); 12927 } 12928 12929 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12930 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12931 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12932 instructionSets, null, null, null, 0); 12933 this.cid = cid; 12934 setMountPath(PackageHelper.getSdDir(cid)); 12935 } 12936 12937 void createCopyFile() { 12938 cid = mInstallerService.allocateExternalStageCidLegacy(); 12939 } 12940 12941 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12942 if (origin.staged && origin.cid != null) { 12943 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12944 cid = origin.cid; 12945 setMountPath(PackageHelper.getSdDir(cid)); 12946 return PackageManager.INSTALL_SUCCEEDED; 12947 } 12948 12949 if (temp) { 12950 createCopyFile(); 12951 } else { 12952 /* 12953 * Pre-emptively destroy the container since it's destroyed if 12954 * copying fails due to it existing anyway. 12955 */ 12956 PackageHelper.destroySdDir(cid); 12957 } 12958 12959 final String newMountPath = imcs.copyPackageToContainer( 12960 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12961 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12962 12963 if (newMountPath != null) { 12964 setMountPath(newMountPath); 12965 return PackageManager.INSTALL_SUCCEEDED; 12966 } else { 12967 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12968 } 12969 } 12970 12971 @Override 12972 String getCodePath() { 12973 return packagePath; 12974 } 12975 12976 @Override 12977 String getResourcePath() { 12978 return resourcePath; 12979 } 12980 12981 int doPreInstall(int status) { 12982 if (status != PackageManager.INSTALL_SUCCEEDED) { 12983 // Destroy container 12984 PackageHelper.destroySdDir(cid); 12985 } else { 12986 boolean mounted = PackageHelper.isContainerMounted(cid); 12987 if (!mounted) { 12988 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12989 Process.SYSTEM_UID); 12990 if (newMountPath != null) { 12991 setMountPath(newMountPath); 12992 } else { 12993 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12994 } 12995 } 12996 } 12997 return status; 12998 } 12999 13000 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13001 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13002 String newMountPath = null; 13003 if (PackageHelper.isContainerMounted(cid)) { 13004 // Unmount the container 13005 if (!PackageHelper.unMountSdDir(cid)) { 13006 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13007 return false; 13008 } 13009 } 13010 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13011 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13012 " which might be stale. Will try to clean up."); 13013 // Clean up the stale container and proceed to recreate. 13014 if (!PackageHelper.destroySdDir(newCacheId)) { 13015 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13016 return false; 13017 } 13018 // Successfully cleaned up stale container. Try to rename again. 13019 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13020 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13021 + " inspite of cleaning it up."); 13022 return false; 13023 } 13024 } 13025 if (!PackageHelper.isContainerMounted(newCacheId)) { 13026 Slog.w(TAG, "Mounting container " + newCacheId); 13027 newMountPath = PackageHelper.mountSdDir(newCacheId, 13028 getEncryptKey(), Process.SYSTEM_UID); 13029 } else { 13030 newMountPath = PackageHelper.getSdDir(newCacheId); 13031 } 13032 if (newMountPath == null) { 13033 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13034 return false; 13035 } 13036 Log.i(TAG, "Succesfully renamed " + cid + 13037 " to " + newCacheId + 13038 " at new path: " + newMountPath); 13039 cid = newCacheId; 13040 13041 final File beforeCodeFile = new File(packagePath); 13042 setMountPath(newMountPath); 13043 final File afterCodeFile = new File(packagePath); 13044 13045 // Reflect the rename in scanned details 13046 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13047 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13048 afterCodeFile, pkg.baseCodePath)); 13049 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13050 afterCodeFile, pkg.splitCodePaths)); 13051 13052 // Reflect the rename in app info 13053 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13054 pkg.setApplicationInfoCodePath(pkg.codePath); 13055 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13056 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13057 pkg.setApplicationInfoResourcePath(pkg.codePath); 13058 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13059 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13060 13061 return true; 13062 } 13063 13064 private void setMountPath(String mountPath) { 13065 final File mountFile = new File(mountPath); 13066 13067 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13068 if (monolithicFile.exists()) { 13069 packagePath = monolithicFile.getAbsolutePath(); 13070 if (isFwdLocked()) { 13071 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13072 } else { 13073 resourcePath = packagePath; 13074 } 13075 } else { 13076 packagePath = mountFile.getAbsolutePath(); 13077 resourcePath = packagePath; 13078 } 13079 } 13080 13081 int doPostInstall(int status, int uid) { 13082 if (status != PackageManager.INSTALL_SUCCEEDED) { 13083 cleanUp(); 13084 } else { 13085 final int groupOwner; 13086 final String protectedFile; 13087 if (isFwdLocked()) { 13088 groupOwner = UserHandle.getSharedAppGid(uid); 13089 protectedFile = RES_FILE_NAME; 13090 } else { 13091 groupOwner = -1; 13092 protectedFile = null; 13093 } 13094 13095 if (uid < Process.FIRST_APPLICATION_UID 13096 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13097 Slog.e(TAG, "Failed to finalize " + cid); 13098 PackageHelper.destroySdDir(cid); 13099 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13100 } 13101 13102 boolean mounted = PackageHelper.isContainerMounted(cid); 13103 if (!mounted) { 13104 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13105 } 13106 } 13107 return status; 13108 } 13109 13110 private void cleanUp() { 13111 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13112 13113 // Destroy secure container 13114 PackageHelper.destroySdDir(cid); 13115 } 13116 13117 private List<String> getAllCodePaths() { 13118 final File codeFile = new File(getCodePath()); 13119 if (codeFile != null && codeFile.exists()) { 13120 try { 13121 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13122 return pkg.getAllCodePaths(); 13123 } catch (PackageParserException e) { 13124 // Ignored; we tried our best 13125 } 13126 } 13127 return Collections.EMPTY_LIST; 13128 } 13129 13130 void cleanUpResourcesLI() { 13131 // Enumerate all code paths before deleting 13132 cleanUpResourcesLI(getAllCodePaths()); 13133 } 13134 13135 private void cleanUpResourcesLI(List<String> allCodePaths) { 13136 cleanUp(); 13137 removeDexFiles(allCodePaths, instructionSets); 13138 } 13139 13140 String getPackageName() { 13141 return getAsecPackageName(cid); 13142 } 13143 13144 boolean doPostDeleteLI(boolean delete) { 13145 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13146 final List<String> allCodePaths = getAllCodePaths(); 13147 boolean mounted = PackageHelper.isContainerMounted(cid); 13148 if (mounted) { 13149 // Unmount first 13150 if (PackageHelper.unMountSdDir(cid)) { 13151 mounted = false; 13152 } 13153 } 13154 if (!mounted && delete) { 13155 cleanUpResourcesLI(allCodePaths); 13156 } 13157 return !mounted; 13158 } 13159 13160 @Override 13161 int doPreCopy() { 13162 if (isFwdLocked()) { 13163 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13164 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13165 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13166 } 13167 } 13168 13169 return PackageManager.INSTALL_SUCCEEDED; 13170 } 13171 13172 @Override 13173 int doPostCopy(int uid) { 13174 if (isFwdLocked()) { 13175 if (uid < Process.FIRST_APPLICATION_UID 13176 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13177 RES_FILE_NAME)) { 13178 Slog.e(TAG, "Failed to finalize " + cid); 13179 PackageHelper.destroySdDir(cid); 13180 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13181 } 13182 } 13183 13184 return PackageManager.INSTALL_SUCCEEDED; 13185 } 13186 } 13187 13188 /** 13189 * Logic to handle movement of existing installed applications. 13190 */ 13191 class MoveInstallArgs extends InstallArgs { 13192 private File codeFile; 13193 private File resourceFile; 13194 13195 /** New install */ 13196 MoveInstallArgs(InstallParams params) { 13197 super(params.origin, params.move, params.observer, params.installFlags, 13198 params.installerPackageName, params.volumeUuid, 13199 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13200 params.grantedRuntimePermissions, 13201 params.traceMethod, params.traceCookie); 13202 } 13203 13204 int copyApk(IMediaContainerService imcs, boolean temp) { 13205 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13206 + move.fromUuid + " to " + move.toUuid); 13207 synchronized (mInstaller) { 13208 try { 13209 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13210 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13211 } catch (InstallerException e) { 13212 Slog.w(TAG, "Failed to move app", e); 13213 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13214 } 13215 } 13216 13217 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13218 resourceFile = codeFile; 13219 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13220 13221 return PackageManager.INSTALL_SUCCEEDED; 13222 } 13223 13224 int doPreInstall(int status) { 13225 if (status != PackageManager.INSTALL_SUCCEEDED) { 13226 cleanUp(move.toUuid); 13227 } 13228 return status; 13229 } 13230 13231 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13232 if (status != PackageManager.INSTALL_SUCCEEDED) { 13233 cleanUp(move.toUuid); 13234 return false; 13235 } 13236 13237 // Reflect the move in app info 13238 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13239 pkg.setApplicationInfoCodePath(pkg.codePath); 13240 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13241 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13242 pkg.setApplicationInfoResourcePath(pkg.codePath); 13243 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13244 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13245 13246 return true; 13247 } 13248 13249 int doPostInstall(int status, int uid) { 13250 if (status == PackageManager.INSTALL_SUCCEEDED) { 13251 cleanUp(move.fromUuid); 13252 } else { 13253 cleanUp(move.toUuid); 13254 } 13255 return status; 13256 } 13257 13258 @Override 13259 String getCodePath() { 13260 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13261 } 13262 13263 @Override 13264 String getResourcePath() { 13265 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13266 } 13267 13268 private boolean cleanUp(String volumeUuid) { 13269 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13270 move.dataAppName); 13271 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13272 synchronized (mInstallLock) { 13273 // Clean up both app data and code 13274 removeDataDirsLI(volumeUuid, move.packageName); 13275 removeCodePathLI(codeFile); 13276 } 13277 return true; 13278 } 13279 13280 void cleanUpResourcesLI() { 13281 throw new UnsupportedOperationException(); 13282 } 13283 13284 boolean doPostDeleteLI(boolean delete) { 13285 throw new UnsupportedOperationException(); 13286 } 13287 } 13288 13289 static String getAsecPackageName(String packageCid) { 13290 int idx = packageCid.lastIndexOf("-"); 13291 if (idx == -1) { 13292 return packageCid; 13293 } 13294 return packageCid.substring(0, idx); 13295 } 13296 13297 // Utility method used to create code paths based on package name and available index. 13298 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13299 String idxStr = ""; 13300 int idx = 1; 13301 // Fall back to default value of idx=1 if prefix is not 13302 // part of oldCodePath 13303 if (oldCodePath != null) { 13304 String subStr = oldCodePath; 13305 // Drop the suffix right away 13306 if (suffix != null && subStr.endsWith(suffix)) { 13307 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13308 } 13309 // If oldCodePath already contains prefix find out the 13310 // ending index to either increment or decrement. 13311 int sidx = subStr.lastIndexOf(prefix); 13312 if (sidx != -1) { 13313 subStr = subStr.substring(sidx + prefix.length()); 13314 if (subStr != null) { 13315 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13316 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13317 } 13318 try { 13319 idx = Integer.parseInt(subStr); 13320 if (idx <= 1) { 13321 idx++; 13322 } else { 13323 idx--; 13324 } 13325 } catch(NumberFormatException e) { 13326 } 13327 } 13328 } 13329 } 13330 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13331 return prefix + idxStr; 13332 } 13333 13334 private File getNextCodePath(File targetDir, String packageName) { 13335 int suffix = 1; 13336 File result; 13337 do { 13338 result = new File(targetDir, packageName + "-" + suffix); 13339 suffix++; 13340 } while (result.exists()); 13341 return result; 13342 } 13343 13344 // Utility method that returns the relative package path with respect 13345 // to the installation directory. Like say for /data/data/com.test-1.apk 13346 // string com.test-1 is returned. 13347 static String deriveCodePathName(String codePath) { 13348 if (codePath == null) { 13349 return null; 13350 } 13351 final File codeFile = new File(codePath); 13352 final String name = codeFile.getName(); 13353 if (codeFile.isDirectory()) { 13354 return name; 13355 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13356 final int lastDot = name.lastIndexOf('.'); 13357 return name.substring(0, lastDot); 13358 } else { 13359 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13360 return null; 13361 } 13362 } 13363 13364 static class PackageInstalledInfo { 13365 String name; 13366 int uid; 13367 // The set of users that originally had this package installed. 13368 int[] origUsers; 13369 // The set of users that now have this package installed. 13370 int[] newUsers; 13371 PackageParser.Package pkg; 13372 int returnCode; 13373 String returnMsg; 13374 PackageRemovedInfo removedInfo; 13375 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13376 13377 public void setError(int code, String msg) { 13378 setReturnCode(code); 13379 setReturnMessage(msg); 13380 Slog.w(TAG, msg); 13381 } 13382 13383 public void setError(String msg, PackageParserException e) { 13384 setReturnCode(e.error); 13385 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13386 Slog.w(TAG, msg, e); 13387 } 13388 13389 public void setError(String msg, PackageManagerException e) { 13390 returnCode = e.error; 13391 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13392 Slog.w(TAG, msg, e); 13393 } 13394 13395 public void setReturnCode(int returnCode) { 13396 this.returnCode = returnCode; 13397 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13398 for (int i = 0; i < childCount; i++) { 13399 addedChildPackages.valueAt(i).returnCode = returnCode; 13400 } 13401 } 13402 13403 private void setReturnMessage(String returnMsg) { 13404 this.returnMsg = returnMsg; 13405 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13406 for (int i = 0; i < childCount; i++) { 13407 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13408 } 13409 } 13410 13411 // In some error cases we want to convey more info back to the observer 13412 String origPackage; 13413 String origPermission; 13414 } 13415 13416 /* 13417 * Install a non-existing package. 13418 */ 13419 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13420 UserHandle user, String installerPackageName, String volumeUuid, 13421 PackageInstalledInfo res) { 13422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13423 13424 // Remember this for later, in case we need to rollback this install 13425 String pkgName = pkg.packageName; 13426 13427 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13428 13429 synchronized(mPackages) { 13430 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13431 // A package with the same name is already installed, though 13432 // it has been renamed to an older name. The package we 13433 // are trying to install should be installed as an update to 13434 // the existing one, but that has not been requested, so bail. 13435 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13436 + " without first uninstalling package running as " 13437 + mSettings.mRenamedPackages.get(pkgName)); 13438 return; 13439 } 13440 if (mPackages.containsKey(pkgName)) { 13441 // Don't allow installation over an existing package with the same name. 13442 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13443 + " without first uninstalling."); 13444 return; 13445 } 13446 } 13447 13448 try { 13449 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13450 System.currentTimeMillis(), user); 13451 13452 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13453 13454 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13455 prepareAppDataAfterInstall(newPackage); 13456 13457 } else { 13458 // Remove package from internal structures, but keep around any 13459 // data that might have already existed 13460 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13461 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13462 } 13463 } catch (PackageManagerException e) { 13464 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13465 } 13466 13467 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13468 } 13469 13470 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13471 // Can't rotate keys during boot or if sharedUser. 13472 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13473 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13474 return false; 13475 } 13476 // app is using upgradeKeySets; make sure all are valid 13477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13478 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13479 for (int i = 0; i < upgradeKeySets.length; i++) { 13480 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13481 Slog.wtf(TAG, "Package " 13482 + (oldPs.name != null ? oldPs.name : "<null>") 13483 + " contains upgrade-key-set reference to unknown key-set: " 13484 + upgradeKeySets[i] 13485 + " reverting to signatures check."); 13486 return false; 13487 } 13488 } 13489 return true; 13490 } 13491 13492 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13493 // Upgrade keysets are being used. Determine if new package has a superset of the 13494 // required keys. 13495 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13496 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13497 for (int i = 0; i < upgradeKeySets.length; i++) { 13498 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13499 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13500 return true; 13501 } 13502 } 13503 return false; 13504 } 13505 13506 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13507 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13508 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13509 13510 final PackageParser.Package oldPackage; 13511 final String pkgName = pkg.packageName; 13512 final int[] allUsers; 13513 final boolean weFroze; 13514 13515 // First find the old package info and check signatures 13516 synchronized(mPackages) { 13517 oldPackage = mPackages.get(pkgName); 13518 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13519 if (isEphemeral && !oldIsEphemeral) { 13520 // can't downgrade from full to ephemeral 13521 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13522 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13523 return; 13524 } 13525 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13526 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13527 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13528 if (!checkUpgradeKeySetLP(ps, pkg)) { 13529 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13530 "New package not signed by keys specified by upgrade-keysets: " 13531 + pkgName); 13532 return; 13533 } 13534 } else { 13535 // default to original signature matching 13536 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13537 != PackageManager.SIGNATURE_MATCH) { 13538 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13539 "New package has a different signature: " + pkgName); 13540 return; 13541 } 13542 } 13543 13544 // In case of rollback, remember per-user/profile install state 13545 allUsers = sUserManager.getUserIds(); 13546 13547 // Mark the app as frozen to prevent launching during the upgrade 13548 // process, and then kill all running instances 13549 if (!ps.frozen) { 13550 ps.frozen = true; 13551 weFroze = true; 13552 } else { 13553 weFroze = false; 13554 } 13555 } 13556 13557 try { 13558 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13559 installerPackageName, res); 13560 } finally { 13561 // Regardless of success or failure of upgrade steps above, always 13562 // unfreeze the package if we froze it 13563 if (weFroze) { 13564 unfreezePackage(pkgName); 13565 } 13566 } 13567 } 13568 13569 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13570 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13571 String installerPackageName, PackageInstalledInfo res) { 13572 // Update what is removed 13573 res.removedInfo = new PackageRemovedInfo(); 13574 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13575 res.removedInfo.removedPackage = oldPackage.packageName; 13576 res.removedInfo.isUpdate = true; 13577 final int childCount = (oldPackage.childPackages != null) 13578 ? oldPackage.childPackages.size() : 0; 13579 for (int i = 0; i < childCount; i++) { 13580 boolean childPackageUpdated = false; 13581 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13582 if (res.addedChildPackages != null) { 13583 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13584 if (childRes != null) { 13585 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13586 childRes.removedInfo.removedPackage = childPkg.packageName; 13587 childRes.removedInfo.isUpdate = true; 13588 childPackageUpdated = true; 13589 } 13590 } 13591 if (!childPackageUpdated) { 13592 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13593 childRemovedRes.removedPackage = childPkg.packageName; 13594 childRemovedRes.isUpdate = false; 13595 childRemovedRes.dataRemoved = true; 13596 synchronized (mPackages) { 13597 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13598 if (childPs != null) { 13599 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13600 } 13601 } 13602 if (res.removedInfo.removedChildPackages == null) { 13603 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13604 } 13605 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13606 } 13607 } 13608 13609 boolean sysPkg = (isSystemApp(oldPackage)); 13610 if (sysPkg) { 13611 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13612 user, allUsers, installerPackageName, res); 13613 } else { 13614 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13615 user, allUsers, installerPackageName, res); 13616 } 13617 } 13618 13619 public List<String> getPreviousCodePaths(String packageName) { 13620 final PackageSetting ps = mSettings.mPackages.get(packageName); 13621 final List<String> result = new ArrayList<String>(); 13622 if (ps != null && ps.oldCodePaths != null) { 13623 result.addAll(ps.oldCodePaths); 13624 } 13625 return result; 13626 } 13627 13628 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13629 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13630 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13631 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13632 + deletedPackage); 13633 13634 String pkgName = deletedPackage.packageName; 13635 boolean deletedPkg = true; 13636 boolean addedPkg = false; 13637 boolean updatedSettings = false; 13638 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13639 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13640 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13641 13642 final long origUpdateTime = (pkg.mExtras != null) 13643 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13644 13645 // First delete the existing package while retaining the data directory 13646 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13647 res.removedInfo, true, pkg)) { 13648 // If the existing package wasn't successfully deleted 13649 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13650 deletedPkg = false; 13651 } else { 13652 // Successfully deleted the old package; proceed with replace. 13653 13654 // If deleted package lived in a container, give users a chance to 13655 // relinquish resources before killing. 13656 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13657 if (DEBUG_INSTALL) { 13658 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13659 } 13660 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13661 final ArrayList<String> pkgList = new ArrayList<String>(1); 13662 pkgList.add(deletedPackage.applicationInfo.packageName); 13663 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13664 } 13665 13666 deleteCodeCacheDirsLI(pkg); 13667 deleteProfilesLI(pkg, /*destroy*/ false); 13668 13669 try { 13670 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13671 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13672 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13673 13674 // Update the in-memory copy of the previous code paths. 13675 PackageSetting ps = mSettings.mPackages.get(pkgName); 13676 if (!killApp) { 13677 if (ps.oldCodePaths == null) { 13678 ps.oldCodePaths = new ArraySet<>(); 13679 } 13680 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13681 if (deletedPackage.splitCodePaths != null) { 13682 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13683 } 13684 } else { 13685 ps.oldCodePaths = null; 13686 } 13687 if (ps.childPackageNames != null) { 13688 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13689 final String childPkgName = ps.childPackageNames.get(i); 13690 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13691 childPs.oldCodePaths = ps.oldCodePaths; 13692 } 13693 } 13694 prepareAppDataAfterInstall(newPackage); 13695 addedPkg = true; 13696 } catch (PackageManagerException e) { 13697 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13698 } 13699 } 13700 13701 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13702 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13703 13704 // Revert all internal state mutations and added folders for the failed install 13705 if (addedPkg) { 13706 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13707 res.removedInfo, true, null); 13708 } 13709 13710 // Restore the old package 13711 if (deletedPkg) { 13712 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13713 File restoreFile = new File(deletedPackage.codePath); 13714 // Parse old package 13715 boolean oldExternal = isExternal(deletedPackage); 13716 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13717 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13718 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13719 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13720 try { 13721 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13722 null); 13723 } catch (PackageManagerException e) { 13724 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13725 + e.getMessage()); 13726 return; 13727 } 13728 13729 synchronized (mPackages) { 13730 // Ensure the installer package name up to date 13731 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13732 13733 // Update permissions for restored package 13734 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13735 13736 mSettings.writeLPr(); 13737 } 13738 13739 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13740 } 13741 } else { 13742 synchronized (mPackages) { 13743 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13744 if (ps != null) { 13745 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13746 if (res.removedInfo.removedChildPackages != null) { 13747 final int childCount = res.removedInfo.removedChildPackages.size(); 13748 // Iterate in reverse as we may modify the collection 13749 for (int i = childCount - 1; i >= 0; i--) { 13750 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13751 if (res.addedChildPackages.containsKey(childPackageName)) { 13752 res.removedInfo.removedChildPackages.removeAt(i); 13753 } else { 13754 PackageRemovedInfo childInfo = res.removedInfo 13755 .removedChildPackages.valueAt(i); 13756 childInfo.removedForAllUsers = mPackages.get( 13757 childInfo.removedPackage) == null; 13758 } 13759 } 13760 } 13761 } 13762 } 13763 } 13764 } 13765 13766 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13767 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13768 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13769 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13770 + ", old=" + deletedPackage); 13771 13772 final boolean disabledSystem; 13773 13774 // Set the system/privileged flags as needed 13775 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13776 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13777 != 0) { 13778 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13779 } 13780 13781 // Kill package processes including services, providers, etc. 13782 killPackage(deletedPackage, "replace sys pkg"); 13783 13784 // Remove existing system package 13785 removePackageLI(deletedPackage, true); 13786 13787 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13788 if (!disabledSystem) { 13789 // We didn't need to disable the .apk as a current system package, 13790 // which means we are replacing another update that is already 13791 // installed. We need to make sure to delete the older one's .apk. 13792 res.removedInfo.args = createInstallArgsForExisting(0, 13793 deletedPackage.applicationInfo.getCodePath(), 13794 deletedPackage.applicationInfo.getResourcePath(), 13795 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13796 } else { 13797 res.removedInfo.args = null; 13798 } 13799 13800 // Successfully disabled the old package. Now proceed with re-installation 13801 deleteCodeCacheDirsLI(pkg); 13802 deleteProfilesLI(pkg, /*destroy*/ false); 13803 13804 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13805 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13806 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13807 13808 PackageParser.Package newPackage = null; 13809 try { 13810 // Add the package to the internal data structures 13811 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13812 13813 // Set the update and install times 13814 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13815 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13816 System.currentTimeMillis()); 13817 13818 // Check for shared user id changes 13819 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13820 deletedPackage, newPackage); 13821 if (invalidPackageName != null) { 13822 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13823 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13824 + " to " + invalidPackageName); 13825 } 13826 13827 // Update the package dynamic state if succeeded 13828 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13829 // Now that the install succeeded make sure we remove data 13830 // directories for any child package the update removed. 13831 final int deletedChildCount = (deletedPackage.childPackages != null) 13832 ? deletedPackage.childPackages.size() : 0; 13833 final int newChildCount = (newPackage.childPackages != null) 13834 ? newPackage.childPackages.size() : 0; 13835 for (int i = 0; i < deletedChildCount; i++) { 13836 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13837 boolean childPackageDeleted = true; 13838 for (int j = 0; j < newChildCount; j++) { 13839 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13840 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13841 childPackageDeleted = false; 13842 break; 13843 } 13844 } 13845 if (childPackageDeleted) { 13846 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13847 deletedChildPkg.packageName); 13848 if (ps != null && res.removedInfo.removedChildPackages != null) { 13849 PackageRemovedInfo removedChildRes = res.removedInfo 13850 .removedChildPackages.get(deletedChildPkg.packageName); 13851 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13852 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13853 } 13854 } 13855 } 13856 13857 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13858 prepareAppDataAfterInstall(newPackage); 13859 } 13860 } catch (PackageManagerException e) { 13861 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13862 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13863 } 13864 13865 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13866 // Re installation failed. Restore old information 13867 // Remove new pkg information 13868 if (newPackage != null) { 13869 removeInstalledPackageLI(newPackage, true); 13870 } 13871 // Add back the old system package 13872 try { 13873 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13874 } catch (PackageManagerException e) { 13875 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13876 } 13877 13878 synchronized (mPackages) { 13879 if (disabledSystem) { 13880 enableSystemPackageLPw(deletedPackage); 13881 } 13882 13883 // Ensure the installer package name up to date 13884 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13885 13886 // Update permissions for restored package 13887 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13888 13889 mSettings.writeLPr(); 13890 } 13891 13892 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13893 + " after failed upgrade"); 13894 } 13895 } 13896 13897 /** 13898 * Checks whether the parent or any of the child packages have a change shared 13899 * user. For a package to be a valid update the shred users of the parent and 13900 * the children should match. We may later support changing child shared users. 13901 * @param oldPkg The updated package. 13902 * @param newPkg The update package. 13903 * @return The shared user that change between the versions. 13904 */ 13905 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13906 PackageParser.Package newPkg) { 13907 // Check parent shared user 13908 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13909 return newPkg.packageName; 13910 } 13911 // Check child shared users 13912 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13913 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13914 for (int i = 0; i < newChildCount; i++) { 13915 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13916 // If this child was present, did it have the same shared user? 13917 for (int j = 0; j < oldChildCount; j++) { 13918 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13919 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13920 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13921 return newChildPkg.packageName; 13922 } 13923 } 13924 } 13925 return null; 13926 } 13927 13928 private void removeNativeBinariesLI(PackageSetting ps) { 13929 // Remove the lib path for the parent package 13930 if (ps != null) { 13931 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13932 // Remove the lib path for the child packages 13933 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13934 for (int i = 0; i < childCount; i++) { 13935 PackageSetting childPs = null; 13936 synchronized (mPackages) { 13937 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13938 } 13939 if (childPs != null) { 13940 NativeLibraryHelper.removeNativeBinariesLI(childPs 13941 .legacyNativeLibraryPathString); 13942 } 13943 } 13944 } 13945 } 13946 13947 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13948 // Enable the parent package 13949 mSettings.enableSystemPackageLPw(pkg.packageName); 13950 // Enable the child packages 13951 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13952 for (int i = 0; i < childCount; i++) { 13953 PackageParser.Package childPkg = pkg.childPackages.get(i); 13954 mSettings.enableSystemPackageLPw(childPkg.packageName); 13955 } 13956 } 13957 13958 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13959 PackageParser.Package newPkg) { 13960 // Disable the parent package (parent always replaced) 13961 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13962 // Disable the child packages 13963 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13964 for (int i = 0; i < childCount; i++) { 13965 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13966 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13967 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13968 } 13969 return disabled; 13970 } 13971 13972 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13973 String installerPackageName) { 13974 // Enable the parent package 13975 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13976 // Enable the child packages 13977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13978 for (int i = 0; i < childCount; i++) { 13979 PackageParser.Package childPkg = pkg.childPackages.get(i); 13980 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13981 } 13982 } 13983 13984 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13985 // Collect all used permissions in the UID 13986 ArraySet<String> usedPermissions = new ArraySet<>(); 13987 final int packageCount = su.packages.size(); 13988 for (int i = 0; i < packageCount; i++) { 13989 PackageSetting ps = su.packages.valueAt(i); 13990 if (ps.pkg == null) { 13991 continue; 13992 } 13993 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13994 for (int j = 0; j < requestedPermCount; j++) { 13995 String permission = ps.pkg.requestedPermissions.get(j); 13996 BasePermission bp = mSettings.mPermissions.get(permission); 13997 if (bp != null) { 13998 usedPermissions.add(permission); 13999 } 14000 } 14001 } 14002 14003 PermissionsState permissionsState = su.getPermissionsState(); 14004 // Prune install permissions 14005 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14006 final int installPermCount = installPermStates.size(); 14007 for (int i = installPermCount - 1; i >= 0; i--) { 14008 PermissionState permissionState = installPermStates.get(i); 14009 if (!usedPermissions.contains(permissionState.getName())) { 14010 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14011 if (bp != null) { 14012 permissionsState.revokeInstallPermission(bp); 14013 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14014 PackageManager.MASK_PERMISSION_FLAGS, 0); 14015 } 14016 } 14017 } 14018 14019 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14020 14021 // Prune runtime permissions 14022 for (int userId : allUserIds) { 14023 List<PermissionState> runtimePermStates = permissionsState 14024 .getRuntimePermissionStates(userId); 14025 final int runtimePermCount = runtimePermStates.size(); 14026 for (int i = runtimePermCount - 1; i >= 0; i--) { 14027 PermissionState permissionState = runtimePermStates.get(i); 14028 if (!usedPermissions.contains(permissionState.getName())) { 14029 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14030 if (bp != null) { 14031 permissionsState.revokeRuntimePermission(bp, userId); 14032 permissionsState.updatePermissionFlags(bp, userId, 14033 PackageManager.MASK_PERMISSION_FLAGS, 0); 14034 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14035 runtimePermissionChangedUserIds, userId); 14036 } 14037 } 14038 } 14039 } 14040 14041 return runtimePermissionChangedUserIds; 14042 } 14043 14044 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14045 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14046 // Update the parent package setting 14047 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14048 res, user); 14049 // Update the child packages setting 14050 final int childCount = (newPackage.childPackages != null) 14051 ? newPackage.childPackages.size() : 0; 14052 for (int i = 0; i < childCount; i++) { 14053 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14054 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14055 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14056 childRes.origUsers, childRes, user); 14057 } 14058 } 14059 14060 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14061 String installerPackageName, int[] allUsers, int[] installedForUsers, 14062 PackageInstalledInfo res, UserHandle user) { 14063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14064 14065 String pkgName = newPackage.packageName; 14066 synchronized (mPackages) { 14067 //write settings. the installStatus will be incomplete at this stage. 14068 //note that the new package setting would have already been 14069 //added to mPackages. It hasn't been persisted yet. 14070 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14071 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14072 mSettings.writeLPr(); 14073 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14074 } 14075 14076 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14077 synchronized (mPackages) { 14078 updatePermissionsLPw(newPackage.packageName, newPackage, 14079 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14080 ? UPDATE_PERMISSIONS_ALL : 0)); 14081 // For system-bundled packages, we assume that installing an upgraded version 14082 // of the package implies that the user actually wants to run that new code, 14083 // so we enable the package. 14084 PackageSetting ps = mSettings.mPackages.get(pkgName); 14085 final int userId = user.getIdentifier(); 14086 if (ps != null) { 14087 if (isSystemApp(newPackage)) { 14088 if (DEBUG_INSTALL) { 14089 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14090 } 14091 // Enable system package for requested users 14092 if (res.origUsers != null) { 14093 for (int origUserId : res.origUsers) { 14094 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14095 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14096 origUserId, installerPackageName); 14097 } 14098 } 14099 } 14100 // Also convey the prior install/uninstall state 14101 if (allUsers != null && installedForUsers != null) { 14102 for (int currentUserId : allUsers) { 14103 final boolean installed = ArrayUtils.contains( 14104 installedForUsers, currentUserId); 14105 if (DEBUG_INSTALL) { 14106 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14107 } 14108 ps.setInstalled(installed, currentUserId); 14109 } 14110 // these install state changes will be persisted in the 14111 // upcoming call to mSettings.writeLPr(). 14112 } 14113 } 14114 // It's implied that when a user requests installation, they want the app to be 14115 // installed and enabled. 14116 if (userId != UserHandle.USER_ALL) { 14117 ps.setInstalled(true, userId); 14118 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14119 } 14120 } 14121 res.name = pkgName; 14122 res.uid = newPackage.applicationInfo.uid; 14123 res.pkg = newPackage; 14124 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14125 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14126 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14127 //to update install status 14128 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14129 mSettings.writeLPr(); 14130 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14131 } 14132 14133 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14134 } 14135 14136 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14137 try { 14138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14139 installPackageLI(args, res); 14140 } finally { 14141 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14142 } 14143 } 14144 14145 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14146 final int installFlags = args.installFlags; 14147 final String installerPackageName = args.installerPackageName; 14148 final String volumeUuid = args.volumeUuid; 14149 final File tmpPackageFile = new File(args.getCodePath()); 14150 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14151 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14152 || (args.volumeUuid != null)); 14153 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14154 boolean replace = false; 14155 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14156 if (args.move != null) { 14157 // moving a complete application; perform an initial scan on the new install location 14158 scanFlags |= SCAN_INITIAL; 14159 } 14160 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14161 scanFlags |= SCAN_DONT_KILL_APP; 14162 } 14163 14164 // Result object to be returned 14165 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14166 14167 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14168 14169 // Sanity check 14170 if (ephemeral && (forwardLocked || onExternal)) { 14171 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14172 + " external=" + onExternal); 14173 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14174 return; 14175 } 14176 14177 // Retrieve PackageSettings and parse package 14178 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14179 | PackageParser.PARSE_ENFORCE_CODE 14180 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14181 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14182 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14183 PackageParser pp = new PackageParser(); 14184 pp.setSeparateProcesses(mSeparateProcesses); 14185 pp.setDisplayMetrics(mMetrics); 14186 14187 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14188 final PackageParser.Package pkg; 14189 try { 14190 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14191 } catch (PackageParserException e) { 14192 res.setError("Failed parse during installPackageLI", e); 14193 return; 14194 } finally { 14195 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14196 } 14197 14198 // If we are installing a clustered package add results for the children 14199 if (pkg.childPackages != null) { 14200 synchronized (mPackages) { 14201 final int childCount = pkg.childPackages.size(); 14202 for (int i = 0; i < childCount; i++) { 14203 PackageParser.Package childPkg = pkg.childPackages.get(i); 14204 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14205 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14206 childRes.pkg = childPkg; 14207 childRes.name = childPkg.packageName; 14208 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14209 if (childPs != null) { 14210 childRes.origUsers = childPs.queryInstalledUsers( 14211 sUserManager.getUserIds(), true); 14212 } 14213 if ((mPackages.containsKey(childPkg.packageName))) { 14214 childRes.removedInfo = new PackageRemovedInfo(); 14215 childRes.removedInfo.removedPackage = childPkg.packageName; 14216 } 14217 if (res.addedChildPackages == null) { 14218 res.addedChildPackages = new ArrayMap<>(); 14219 } 14220 res.addedChildPackages.put(childPkg.packageName, childRes); 14221 } 14222 } 14223 } 14224 14225 // If package doesn't declare API override, mark that we have an install 14226 // time CPU ABI override. 14227 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14228 pkg.cpuAbiOverride = args.abiOverride; 14229 } 14230 14231 String pkgName = res.name = pkg.packageName; 14232 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14233 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14234 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14235 return; 14236 } 14237 } 14238 14239 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 14240 try { 14241 PackageParser.collectCertificates(pkg, parseFlags); 14242 } catch (PackageParserException e) { 14243 res.setError("Failed collect during installPackageLI", e); 14244 return; 14245 } finally { 14246 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14247 } 14248 14249 // Get rid of all references to package scan path via parser. 14250 pp = null; 14251 String oldCodePath = null; 14252 boolean systemApp = false; 14253 synchronized (mPackages) { 14254 // Check if installing already existing package 14255 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14256 String oldName = mSettings.mRenamedPackages.get(pkgName); 14257 if (pkg.mOriginalPackages != null 14258 && pkg.mOriginalPackages.contains(oldName) 14259 && mPackages.containsKey(oldName)) { 14260 // This package is derived from an original package, 14261 // and this device has been updating from that original 14262 // name. We must continue using the original name, so 14263 // rename the new package here. 14264 pkg.setPackageName(oldName); 14265 pkgName = pkg.packageName; 14266 replace = true; 14267 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14268 + oldName + " pkgName=" + pkgName); 14269 } else if (mPackages.containsKey(pkgName)) { 14270 // This package, under its official name, already exists 14271 // on the device; we should replace it. 14272 replace = true; 14273 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14274 } 14275 14276 // Child packages are installed through the parent package 14277 if (pkg.parentPackage != null) { 14278 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14279 "Package " + pkg.packageName + " is child of package " 14280 + pkg.parentPackage.parentPackage + ". Child packages " 14281 + "can be updated only through the parent package."); 14282 return; 14283 } 14284 14285 if (replace) { 14286 // Prevent apps opting out from runtime permissions 14287 PackageParser.Package oldPackage = mPackages.get(pkgName); 14288 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14289 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14290 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14291 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14292 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14293 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14294 + " doesn't support runtime permissions but the old" 14295 + " target SDK " + oldTargetSdk + " does."); 14296 return; 14297 } 14298 14299 // Prevent installing of child packages 14300 if (oldPackage.parentPackage != null) { 14301 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14302 "Package " + pkg.packageName + " is child of package " 14303 + oldPackage.parentPackage + ". Child packages " 14304 + "can be updated only through the parent package."); 14305 return; 14306 } 14307 } 14308 } 14309 14310 PackageSetting ps = mSettings.mPackages.get(pkgName); 14311 if (ps != null) { 14312 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14313 14314 // Quick sanity check that we're signed correctly if updating; 14315 // we'll check this again later when scanning, but we want to 14316 // bail early here before tripping over redefined permissions. 14317 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14318 if (!checkUpgradeKeySetLP(ps, pkg)) { 14319 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14320 + pkg.packageName + " upgrade keys do not match the " 14321 + "previously installed version"); 14322 return; 14323 } 14324 } else { 14325 try { 14326 verifySignaturesLP(ps, pkg); 14327 } catch (PackageManagerException e) { 14328 res.setError(e.error, e.getMessage()); 14329 return; 14330 } 14331 } 14332 14333 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14334 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14335 systemApp = (ps.pkg.applicationInfo.flags & 14336 ApplicationInfo.FLAG_SYSTEM) != 0; 14337 } 14338 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14339 } 14340 14341 // Check whether the newly-scanned package wants to define an already-defined perm 14342 int N = pkg.permissions.size(); 14343 for (int i = N-1; i >= 0; i--) { 14344 PackageParser.Permission perm = pkg.permissions.get(i); 14345 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14346 if (bp != null) { 14347 // If the defining package is signed with our cert, it's okay. This 14348 // also includes the "updating the same package" case, of course. 14349 // "updating same package" could also involve key-rotation. 14350 final boolean sigsOk; 14351 if (bp.sourcePackage.equals(pkg.packageName) 14352 && (bp.packageSetting instanceof PackageSetting) 14353 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14354 scanFlags))) { 14355 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14356 } else { 14357 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14358 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14359 } 14360 if (!sigsOk) { 14361 // If the owning package is the system itself, we log but allow 14362 // install to proceed; we fail the install on all other permission 14363 // redefinitions. 14364 if (!bp.sourcePackage.equals("android")) { 14365 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14366 + pkg.packageName + " attempting to redeclare permission " 14367 + perm.info.name + " already owned by " + bp.sourcePackage); 14368 res.origPermission = perm.info.name; 14369 res.origPackage = bp.sourcePackage; 14370 return; 14371 } else { 14372 Slog.w(TAG, "Package " + pkg.packageName 14373 + " attempting to redeclare system permission " 14374 + perm.info.name + "; ignoring new declaration"); 14375 pkg.permissions.remove(i); 14376 } 14377 } 14378 } 14379 } 14380 } 14381 14382 if (systemApp) { 14383 if (onExternal) { 14384 // Abort update; system app can't be replaced with app on sdcard 14385 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14386 "Cannot install updates to system apps on sdcard"); 14387 return; 14388 } else if (ephemeral) { 14389 // Abort update; system app can't be replaced with an ephemeral app 14390 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14391 "Cannot update a system app with an ephemeral app"); 14392 return; 14393 } 14394 } 14395 14396 if (args.move != null) { 14397 // We did an in-place move, so dex is ready to roll 14398 scanFlags |= SCAN_NO_DEX; 14399 scanFlags |= SCAN_MOVE; 14400 14401 synchronized (mPackages) { 14402 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14403 if (ps == null) { 14404 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14405 "Missing settings for moved package " + pkgName); 14406 } 14407 14408 // We moved the entire application as-is, so bring over the 14409 // previously derived ABI information. 14410 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14411 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14412 } 14413 14414 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14415 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14416 scanFlags |= SCAN_NO_DEX; 14417 14418 try { 14419 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14420 args.abiOverride : pkg.cpuAbiOverride); 14421 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14422 true /* extract libs */); 14423 } catch (PackageManagerException pme) { 14424 Slog.e(TAG, "Error deriving application ABI", pme); 14425 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14426 return; 14427 } 14428 14429 14430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14431 // Do not run PackageDexOptimizer through the local performDexOpt 14432 // method because `pkg` is not in `mPackages` yet. 14433 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14434 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14436 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14437 String msg = "Extracking package failed for " + pkgName; 14438 res.setError(INSTALL_FAILED_DEXOPT, msg); 14439 return; 14440 } 14441 } 14442 14443 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14444 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14445 return; 14446 } 14447 14448 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14449 14450 if (replace) { 14451 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14452 installerPackageName, res); 14453 } else { 14454 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14455 args.user, installerPackageName, volumeUuid, res); 14456 } 14457 synchronized (mPackages) { 14458 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14459 if (ps != null) { 14460 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14461 } 14462 14463 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14464 for (int i = 0; i < childCount; i++) { 14465 PackageParser.Package childPkg = pkg.childPackages.get(i); 14466 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14467 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14468 if (childPs != null) { 14469 childRes.newUsers = childPs.queryInstalledUsers( 14470 sUserManager.getUserIds(), true); 14471 } 14472 } 14473 } 14474 } 14475 14476 private void startIntentFilterVerifications(int userId, boolean replacing, 14477 PackageParser.Package pkg) { 14478 if (mIntentFilterVerifierComponent == null) { 14479 Slog.w(TAG, "No IntentFilter verification will not be done as " 14480 + "there is no IntentFilterVerifier available!"); 14481 return; 14482 } 14483 14484 final int verifierUid = getPackageUid( 14485 mIntentFilterVerifierComponent.getPackageName(), 14486 MATCH_DEBUG_TRIAGED_MISSING, 14487 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14488 14489 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14490 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14491 mHandler.sendMessage(msg); 14492 14493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14494 for (int i = 0; i < childCount; i++) { 14495 PackageParser.Package childPkg = pkg.childPackages.get(i); 14496 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14497 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14498 mHandler.sendMessage(msg); 14499 } 14500 } 14501 14502 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14503 PackageParser.Package pkg) { 14504 int size = pkg.activities.size(); 14505 if (size == 0) { 14506 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14507 "No activity, so no need to verify any IntentFilter!"); 14508 return; 14509 } 14510 14511 final boolean hasDomainURLs = hasDomainURLs(pkg); 14512 if (!hasDomainURLs) { 14513 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14514 "No domain URLs, so no need to verify any IntentFilter!"); 14515 return; 14516 } 14517 14518 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14519 + " if any IntentFilter from the " + size 14520 + " Activities needs verification ..."); 14521 14522 int count = 0; 14523 final String packageName = pkg.packageName; 14524 14525 synchronized (mPackages) { 14526 // If this is a new install and we see that we've already run verification for this 14527 // package, we have nothing to do: it means the state was restored from backup. 14528 if (!replacing) { 14529 IntentFilterVerificationInfo ivi = 14530 mSettings.getIntentFilterVerificationLPr(packageName); 14531 if (ivi != null) { 14532 if (DEBUG_DOMAIN_VERIFICATION) { 14533 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14534 + ivi.getStatusString()); 14535 } 14536 return; 14537 } 14538 } 14539 14540 // If any filters need to be verified, then all need to be. 14541 boolean needToVerify = false; 14542 for (PackageParser.Activity a : pkg.activities) { 14543 for (ActivityIntentInfo filter : a.intents) { 14544 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14545 if (DEBUG_DOMAIN_VERIFICATION) { 14546 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14547 } 14548 needToVerify = true; 14549 break; 14550 } 14551 } 14552 } 14553 14554 if (needToVerify) { 14555 final int verificationId = mIntentFilterVerificationToken++; 14556 for (PackageParser.Activity a : pkg.activities) { 14557 for (ActivityIntentInfo filter : a.intents) { 14558 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14559 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14560 "Verification needed for IntentFilter:" + filter.toString()); 14561 mIntentFilterVerifier.addOneIntentFilterVerification( 14562 verifierUid, userId, verificationId, filter, packageName); 14563 count++; 14564 } 14565 } 14566 } 14567 } 14568 } 14569 14570 if (count > 0) { 14571 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14572 + " IntentFilter verification" + (count > 1 ? "s" : "") 14573 + " for userId:" + userId); 14574 mIntentFilterVerifier.startVerifications(userId); 14575 } else { 14576 if (DEBUG_DOMAIN_VERIFICATION) { 14577 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14578 } 14579 } 14580 } 14581 14582 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14583 final ComponentName cn = filter.activity.getComponentName(); 14584 final String packageName = cn.getPackageName(); 14585 14586 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14587 packageName); 14588 if (ivi == null) { 14589 return true; 14590 } 14591 int status = ivi.getStatus(); 14592 switch (status) { 14593 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14594 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14595 return true; 14596 14597 default: 14598 // Nothing to do 14599 return false; 14600 } 14601 } 14602 14603 private static boolean isMultiArch(ApplicationInfo info) { 14604 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14605 } 14606 14607 private static boolean isExternal(PackageParser.Package pkg) { 14608 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14609 } 14610 14611 private static boolean isExternal(PackageSetting ps) { 14612 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14613 } 14614 14615 private static boolean isEphemeral(PackageParser.Package pkg) { 14616 return pkg.applicationInfo.isEphemeralApp(); 14617 } 14618 14619 private static boolean isEphemeral(PackageSetting ps) { 14620 return ps.pkg != null && isEphemeral(ps.pkg); 14621 } 14622 14623 private static boolean isSystemApp(PackageParser.Package pkg) { 14624 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14625 } 14626 14627 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14628 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14629 } 14630 14631 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14632 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14633 } 14634 14635 private static boolean isSystemApp(PackageSetting ps) { 14636 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14637 } 14638 14639 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14640 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14641 } 14642 14643 private int packageFlagsToInstallFlags(PackageSetting ps) { 14644 int installFlags = 0; 14645 if (isEphemeral(ps)) { 14646 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14647 } 14648 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14649 // This existing package was an external ASEC install when we have 14650 // the external flag without a UUID 14651 installFlags |= PackageManager.INSTALL_EXTERNAL; 14652 } 14653 if (ps.isForwardLocked()) { 14654 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14655 } 14656 return installFlags; 14657 } 14658 14659 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14660 if (isExternal(pkg)) { 14661 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14662 return StorageManager.UUID_PRIMARY_PHYSICAL; 14663 } else { 14664 return pkg.volumeUuid; 14665 } 14666 } else { 14667 return StorageManager.UUID_PRIVATE_INTERNAL; 14668 } 14669 } 14670 14671 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14672 if (isExternal(pkg)) { 14673 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14674 return mSettings.getExternalVersion(); 14675 } else { 14676 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14677 } 14678 } else { 14679 return mSettings.getInternalVersion(); 14680 } 14681 } 14682 14683 private void deleteTempPackageFiles() { 14684 final FilenameFilter filter = new FilenameFilter() { 14685 public boolean accept(File dir, String name) { 14686 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14687 } 14688 }; 14689 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14690 file.delete(); 14691 } 14692 } 14693 14694 @Override 14695 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14696 int flags) { 14697 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14698 flags); 14699 } 14700 14701 @Override 14702 public void deletePackage(final String packageName, 14703 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14704 mContext.enforceCallingOrSelfPermission( 14705 android.Manifest.permission.DELETE_PACKAGES, null); 14706 Preconditions.checkNotNull(packageName); 14707 Preconditions.checkNotNull(observer); 14708 final int uid = Binder.getCallingUid(); 14709 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14710 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14711 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14712 mContext.enforceCallingOrSelfPermission( 14713 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14714 "deletePackage for user " + userId); 14715 } 14716 14717 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14718 try { 14719 observer.onPackageDeleted(packageName, 14720 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14721 } catch (RemoteException re) { 14722 } 14723 return; 14724 } 14725 14726 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14727 try { 14728 observer.onPackageDeleted(packageName, 14729 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14730 } catch (RemoteException re) { 14731 } 14732 return; 14733 } 14734 14735 if (DEBUG_REMOVE) { 14736 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14737 + " deleteAllUsers: " + deleteAllUsers ); 14738 } 14739 // Queue up an async operation since the package deletion may take a little while. 14740 mHandler.post(new Runnable() { 14741 public void run() { 14742 mHandler.removeCallbacks(this); 14743 int returnCode; 14744 if (!deleteAllUsers) { 14745 returnCode = deletePackageX(packageName, userId, flags); 14746 } else { 14747 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14748 // If nobody is blocking uninstall, proceed with delete for all users 14749 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14750 returnCode = deletePackageX(packageName, userId, flags); 14751 } else { 14752 // Otherwise uninstall individually for users with blockUninstalls=false 14753 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14754 for (int userId : users) { 14755 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14756 returnCode = deletePackageX(packageName, userId, userFlags); 14757 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14758 Slog.w(TAG, "Package delete failed for user " + userId 14759 + ", returnCode " + returnCode); 14760 } 14761 } 14762 } 14763 // The app has only been marked uninstalled for certain users. 14764 // We still need to report that delete was blocked 14765 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14766 } 14767 } 14768 try { 14769 observer.onPackageDeleted(packageName, returnCode, null); 14770 } catch (RemoteException e) { 14771 Log.i(TAG, "Observer no longer exists."); 14772 } //end catch 14773 } //end run 14774 }); 14775 } 14776 14777 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14778 int[] result = EMPTY_INT_ARRAY; 14779 for (int userId : userIds) { 14780 if (getBlockUninstallForUser(packageName, userId)) { 14781 result = ArrayUtils.appendInt(result, userId); 14782 } 14783 } 14784 return result; 14785 } 14786 14787 @Override 14788 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14789 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14790 } 14791 14792 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14793 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14794 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14795 try { 14796 if (dpm != null) { 14797 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14798 /* callingUserOnly =*/ false); 14799 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14800 : deviceOwnerComponentName.getPackageName(); 14801 // Does the package contains the device owner? 14802 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14803 // this check is probably not needed, since DO should be registered as a device 14804 // admin on some user too. (Original bug for this: b/17657954) 14805 if (packageName.equals(deviceOwnerPackageName)) { 14806 return true; 14807 } 14808 // Does it contain a device admin for any user? 14809 int[] users; 14810 if (userId == UserHandle.USER_ALL) { 14811 users = sUserManager.getUserIds(); 14812 } else { 14813 users = new int[]{userId}; 14814 } 14815 for (int i = 0; i < users.length; ++i) { 14816 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14817 return true; 14818 } 14819 } 14820 } 14821 } catch (RemoteException e) { 14822 } 14823 return false; 14824 } 14825 14826 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14827 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14828 } 14829 14830 /** 14831 * This method is an internal method that could be get invoked either 14832 * to delete an installed package or to clean up a failed installation. 14833 * After deleting an installed package, a broadcast is sent to notify any 14834 * listeners that the package has been installed. For cleaning up a failed 14835 * installation, the broadcast is not necessary since the package's 14836 * installation wouldn't have sent the initial broadcast either 14837 * The key steps in deleting a package are 14838 * deleting the package information in internal structures like mPackages, 14839 * deleting the packages base directories through installd 14840 * updating mSettings to reflect current status 14841 * persisting settings for later use 14842 * sending a broadcast if necessary 14843 */ 14844 private int deletePackageX(String packageName, int userId, int flags) { 14845 final PackageRemovedInfo info = new PackageRemovedInfo(); 14846 final boolean res; 14847 14848 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14849 ? UserHandle.ALL : new UserHandle(userId); 14850 14851 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14852 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14853 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14854 } 14855 14856 PackageSetting uninstalledPs = null; 14857 14858 // for the uninstall-updates case and restricted profiles, remember the per- 14859 // user handle installed state 14860 int[] allUsers; 14861 synchronized (mPackages) { 14862 uninstalledPs = mSettings.mPackages.get(packageName); 14863 if (uninstalledPs == null) { 14864 Slog.w(TAG, "Not removing non-existent package " + packageName); 14865 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14866 } 14867 allUsers = sUserManager.getUserIds(); 14868 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14869 } 14870 14871 synchronized (mInstallLock) { 14872 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14873 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14874 flags | REMOVE_CHATTY, info, true, null); 14875 synchronized (mPackages) { 14876 if (res) { 14877 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14878 } 14879 } 14880 } 14881 14882 if (res) { 14883 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14884 info.sendPackageRemovedBroadcasts(killApp); 14885 info.sendSystemPackageUpdatedBroadcasts(); 14886 info.sendSystemPackageAppearedBroadcasts(); 14887 } 14888 // Force a gc here. 14889 Runtime.getRuntime().gc(); 14890 // Delete the resources here after sending the broadcast to let 14891 // other processes clean up before deleting resources. 14892 if (info.args != null) { 14893 synchronized (mInstallLock) { 14894 info.args.doPostDeleteLI(true); 14895 } 14896 } 14897 14898 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14899 } 14900 14901 class PackageRemovedInfo { 14902 String removedPackage; 14903 int uid = -1; 14904 int removedAppId = -1; 14905 int[] origUsers; 14906 int[] removedUsers = null; 14907 boolean isRemovedPackageSystemUpdate = false; 14908 boolean isUpdate; 14909 boolean dataRemoved; 14910 boolean removedForAllUsers; 14911 // Clean up resources deleted packages. 14912 InstallArgs args = null; 14913 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14914 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14915 14916 void sendPackageRemovedBroadcasts(boolean killApp) { 14917 sendPackageRemovedBroadcastInternal(killApp); 14918 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14919 for (int i = 0; i < childCount; i++) { 14920 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14921 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14922 } 14923 } 14924 14925 void sendSystemPackageUpdatedBroadcasts() { 14926 if (isRemovedPackageSystemUpdate) { 14927 sendSystemPackageUpdatedBroadcastsInternal(); 14928 final int childCount = (removedChildPackages != null) 14929 ? removedChildPackages.size() : 0; 14930 for (int i = 0; i < childCount; i++) { 14931 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14932 if (childInfo.isRemovedPackageSystemUpdate) { 14933 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14934 } 14935 } 14936 } 14937 } 14938 14939 void sendSystemPackageAppearedBroadcasts() { 14940 final int packageCount = (appearedChildPackages != null) 14941 ? appearedChildPackages.size() : 0; 14942 for (int i = 0; i < packageCount; i++) { 14943 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14944 for (int userId : installedInfo.newUsers) { 14945 sendPackageAddedForUser(installedInfo.name, true, 14946 UserHandle.getAppId(installedInfo.uid), userId); 14947 } 14948 } 14949 } 14950 14951 private void sendSystemPackageUpdatedBroadcastsInternal() { 14952 Bundle extras = new Bundle(2); 14953 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14954 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14955 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14956 extras, 0, null, null, null); 14957 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14958 extras, 0, null, null, null); 14959 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14960 null, 0, removedPackage, null, null); 14961 } 14962 14963 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14964 Bundle extras = new Bundle(2); 14965 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14966 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14967 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14968 if (isUpdate || isRemovedPackageSystemUpdate) { 14969 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14970 } 14971 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14972 if (removedPackage != null) { 14973 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14974 extras, 0, null, null, removedUsers); 14975 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14976 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14977 removedPackage, extras, 0, null, null, removedUsers); 14978 } 14979 } 14980 if (removedAppId >= 0) { 14981 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14982 removedUsers); 14983 } 14984 } 14985 } 14986 14987 /* 14988 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14989 * flag is not set, the data directory is removed as well. 14990 * make sure this flag is set for partially installed apps. If not its meaningless to 14991 * delete a partially installed application. 14992 */ 14993 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14994 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14995 String packageName = ps.name; 14996 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14997 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14998 // Retrieve object to delete permissions for shared user later on 14999 final PackageSetting deletedPs; 15000 // reader 15001 synchronized (mPackages) { 15002 deletedPs = mSettings.mPackages.get(packageName); 15003 if (outInfo != null) { 15004 outInfo.removedPackage = packageName; 15005 outInfo.removedUsers = deletedPs != null 15006 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15007 : null; 15008 } 15009 } 15010 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15011 removeDataDirsLI(ps.volumeUuid, packageName); 15012 if (outInfo != null) { 15013 outInfo.dataRemoved = true; 15014 } 15015 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15016 } 15017 // writer 15018 synchronized (mPackages) { 15019 if (deletedPs != null) { 15020 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15021 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15022 clearDefaultBrowserIfNeeded(packageName); 15023 if (outInfo != null) { 15024 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15025 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15026 } 15027 updatePermissionsLPw(deletedPs.name, null, 0); 15028 if (deletedPs.sharedUser != null) { 15029 // Remove permissions associated with package. Since runtime 15030 // permissions are per user we have to kill the removed package 15031 // or packages running under the shared user of the removed 15032 // package if revoking the permissions requested only by the removed 15033 // package is successful and this causes a change in gids. 15034 for (int userId : UserManagerService.getInstance().getUserIds()) { 15035 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15036 userId); 15037 if (userIdToKill == UserHandle.USER_ALL 15038 || userIdToKill >= UserHandle.USER_SYSTEM) { 15039 // If gids changed for this user, kill all affected packages. 15040 mHandler.post(new Runnable() { 15041 @Override 15042 public void run() { 15043 // This has to happen with no lock held. 15044 killApplication(deletedPs.name, deletedPs.appId, 15045 KILL_APP_REASON_GIDS_CHANGED); 15046 } 15047 }); 15048 break; 15049 } 15050 } 15051 } 15052 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15053 } 15054 // make sure to preserve per-user disabled state if this removal was just 15055 // a downgrade of a system app to the factory package 15056 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15057 if (DEBUG_REMOVE) { 15058 Slog.d(TAG, "Propagating install state across downgrade"); 15059 } 15060 for (int userId : allUserHandles) { 15061 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15062 if (DEBUG_REMOVE) { 15063 Slog.d(TAG, " user " + userId + " => " + installed); 15064 } 15065 ps.setInstalled(installed, userId); 15066 } 15067 } 15068 } 15069 // can downgrade to reader 15070 if (writeSettings) { 15071 // Save settings now 15072 mSettings.writeLPr(); 15073 } 15074 } 15075 if (outInfo != null) { 15076 // A user ID was deleted here. Go through all users and remove it 15077 // from KeyStore. 15078 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15079 } 15080 } 15081 15082 static boolean locationIsPrivileged(File path) { 15083 try { 15084 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15085 .getCanonicalPath(); 15086 return path.getCanonicalPath().startsWith(privilegedAppDir); 15087 } catch (IOException e) { 15088 Slog.e(TAG, "Unable to access code path " + path); 15089 } 15090 return false; 15091 } 15092 15093 /* 15094 * Tries to delete system package. 15095 */ 15096 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15097 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15098 boolean writeSettings) { 15099 if (deletedPs.parentPackageName != null) { 15100 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15101 return false; 15102 } 15103 15104 final boolean applyUserRestrictions 15105 = (allUserHandles != null) && (outInfo.origUsers != null); 15106 final PackageSetting disabledPs; 15107 // Confirm if the system package has been updated 15108 // An updated system app can be deleted. This will also have to restore 15109 // the system pkg from system partition 15110 // reader 15111 synchronized (mPackages) { 15112 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15113 } 15114 15115 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15116 + " disabledPs=" + disabledPs); 15117 15118 if (disabledPs == null) { 15119 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15120 return false; 15121 } else if (DEBUG_REMOVE) { 15122 Slog.d(TAG, "Deleting system pkg from data partition"); 15123 } 15124 15125 if (DEBUG_REMOVE) { 15126 if (applyUserRestrictions) { 15127 Slog.d(TAG, "Remembering install states:"); 15128 for (int userId : allUserHandles) { 15129 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15130 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15131 } 15132 } 15133 } 15134 15135 // Delete the updated package 15136 outInfo.isRemovedPackageSystemUpdate = true; 15137 if (outInfo.removedChildPackages != null) { 15138 final int childCount = (deletedPs.childPackageNames != null) 15139 ? deletedPs.childPackageNames.size() : 0; 15140 for (int i = 0; i < childCount; i++) { 15141 String childPackageName = deletedPs.childPackageNames.get(i); 15142 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15143 .contains(childPackageName)) { 15144 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15145 childPackageName); 15146 if (childInfo != null) { 15147 childInfo.isRemovedPackageSystemUpdate = true; 15148 } 15149 } 15150 } 15151 } 15152 15153 if (disabledPs.versionCode < deletedPs.versionCode) { 15154 // Delete data for downgrades 15155 flags &= ~PackageManager.DELETE_KEEP_DATA; 15156 } else { 15157 // Preserve data by setting flag 15158 flags |= PackageManager.DELETE_KEEP_DATA; 15159 } 15160 15161 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15162 outInfo, writeSettings, disabledPs.pkg); 15163 if (!ret) { 15164 return false; 15165 } 15166 15167 // writer 15168 synchronized (mPackages) { 15169 // Reinstate the old system package 15170 enableSystemPackageLPw(disabledPs.pkg); 15171 // Remove any native libraries from the upgraded package. 15172 removeNativeBinariesLI(deletedPs); 15173 } 15174 15175 // Install the system package 15176 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15177 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15178 if (locationIsPrivileged(disabledPs.codePath)) { 15179 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15180 } 15181 15182 final PackageParser.Package newPkg; 15183 try { 15184 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15185 } catch (PackageManagerException e) { 15186 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15187 + e.getMessage()); 15188 return false; 15189 } 15190 15191 prepareAppDataAfterInstall(newPkg); 15192 15193 // writer 15194 synchronized (mPackages) { 15195 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15196 15197 // Propagate the permissions state as we do not want to drop on the floor 15198 // runtime permissions. The update permissions method below will take 15199 // care of removing obsolete permissions and grant install permissions. 15200 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15201 updatePermissionsLPw(newPkg.packageName, newPkg, 15202 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15203 15204 if (applyUserRestrictions) { 15205 if (DEBUG_REMOVE) { 15206 Slog.d(TAG, "Propagating install state across reinstall"); 15207 } 15208 for (int userId : allUserHandles) { 15209 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15210 if (DEBUG_REMOVE) { 15211 Slog.d(TAG, " user " + userId + " => " + installed); 15212 } 15213 ps.setInstalled(installed, userId); 15214 15215 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15216 } 15217 // Regardless of writeSettings we need to ensure that this restriction 15218 // state propagation is persisted 15219 mSettings.writeAllUsersPackageRestrictionsLPr(); 15220 } 15221 // can downgrade to reader here 15222 if (writeSettings) { 15223 mSettings.writeLPr(); 15224 } 15225 } 15226 return true; 15227 } 15228 15229 private boolean deleteInstalledPackageLI(PackageSetting ps, 15230 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15231 PackageRemovedInfo outInfo, boolean writeSettings, 15232 PackageParser.Package replacingPackage) { 15233 synchronized (mPackages) { 15234 if (outInfo != null) { 15235 outInfo.uid = ps.appId; 15236 } 15237 15238 if (outInfo != null && outInfo.removedChildPackages != null) { 15239 final int childCount = (ps.childPackageNames != null) 15240 ? ps.childPackageNames.size() : 0; 15241 for (int i = 0; i < childCount; i++) { 15242 String childPackageName = ps.childPackageNames.get(i); 15243 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15244 if (childPs == null) { 15245 return false; 15246 } 15247 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15248 childPackageName); 15249 if (childInfo != null) { 15250 childInfo.uid = childPs.appId; 15251 } 15252 } 15253 } 15254 } 15255 15256 // Delete package data from internal structures and also remove data if flag is set 15257 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15258 15259 // Delete the child packages data 15260 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15261 for (int i = 0; i < childCount; i++) { 15262 PackageSetting childPs; 15263 synchronized (mPackages) { 15264 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15265 } 15266 if (childPs != null) { 15267 PackageRemovedInfo childOutInfo = (outInfo != null 15268 && outInfo.removedChildPackages != null) 15269 ? outInfo.removedChildPackages.get(childPs.name) : null; 15270 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15271 && (replacingPackage != null 15272 && !replacingPackage.hasChildPackage(childPs.name)) 15273 ? flags & ~DELETE_KEEP_DATA : flags; 15274 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15275 deleteFlags, writeSettings); 15276 } 15277 } 15278 15279 // Delete application code and resources only for parent packages 15280 if (ps.parentPackageName == null) { 15281 if (deleteCodeAndResources && (outInfo != null)) { 15282 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15283 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15284 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15285 } 15286 } 15287 15288 return true; 15289 } 15290 15291 @Override 15292 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15293 int userId) { 15294 mContext.enforceCallingOrSelfPermission( 15295 android.Manifest.permission.DELETE_PACKAGES, null); 15296 synchronized (mPackages) { 15297 PackageSetting ps = mSettings.mPackages.get(packageName); 15298 if (ps == null) { 15299 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15300 return false; 15301 } 15302 if (!ps.getInstalled(userId)) { 15303 // Can't block uninstall for an app that is not installed or enabled. 15304 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15305 return false; 15306 } 15307 ps.setBlockUninstall(blockUninstall, userId); 15308 mSettings.writePackageRestrictionsLPr(userId); 15309 } 15310 return true; 15311 } 15312 15313 @Override 15314 public boolean getBlockUninstallForUser(String packageName, int userId) { 15315 synchronized (mPackages) { 15316 PackageSetting ps = mSettings.mPackages.get(packageName); 15317 if (ps == null) { 15318 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15319 return false; 15320 } 15321 return ps.getBlockUninstall(userId); 15322 } 15323 } 15324 15325 @Override 15326 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15327 int callingUid = Binder.getCallingUid(); 15328 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15329 throw new SecurityException( 15330 "setRequiredForSystemUser can only be run by the system or root"); 15331 } 15332 synchronized (mPackages) { 15333 PackageSetting ps = mSettings.mPackages.get(packageName); 15334 if (ps == null) { 15335 Log.w(TAG, "Package doesn't exist: " + packageName); 15336 return false; 15337 } 15338 if (systemUserApp) { 15339 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15340 } else { 15341 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15342 } 15343 mSettings.writeLPr(); 15344 } 15345 return true; 15346 } 15347 15348 /* 15349 * This method handles package deletion in general 15350 */ 15351 private boolean deletePackageLI(String packageName, UserHandle user, 15352 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15353 PackageRemovedInfo outInfo, boolean writeSettings, 15354 PackageParser.Package replacingPackage) { 15355 if (packageName == null) { 15356 Slog.w(TAG, "Attempt to delete null packageName."); 15357 return false; 15358 } 15359 15360 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15361 15362 PackageSetting ps; 15363 15364 synchronized (mPackages) { 15365 ps = mSettings.mPackages.get(packageName); 15366 if (ps == null) { 15367 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15368 return false; 15369 } 15370 15371 if (ps.parentPackageName != null && (!isSystemApp(ps) 15372 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15373 if (DEBUG_REMOVE) { 15374 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15375 + ((user == null) ? UserHandle.USER_ALL : user)); 15376 } 15377 final int removedUserId = (user != null) ? user.getIdentifier() 15378 : UserHandle.USER_ALL; 15379 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15380 return false; 15381 } 15382 markPackageUninstalledForUserLPw(ps, user); 15383 scheduleWritePackageRestrictionsLocked(user); 15384 return true; 15385 } 15386 } 15387 15388 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15389 && user.getIdentifier() != UserHandle.USER_ALL)) { 15390 // The caller is asking that the package only be deleted for a single 15391 // user. To do this, we just mark its uninstalled state and delete 15392 // its data. If this is a system app, we only allow this to happen if 15393 // they have set the special DELETE_SYSTEM_APP which requests different 15394 // semantics than normal for uninstalling system apps. 15395 markPackageUninstalledForUserLPw(ps, user); 15396 15397 if (!isSystemApp(ps)) { 15398 // Do not uninstall the APK if an app should be cached 15399 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15400 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15401 // Other user still have this package installed, so all 15402 // we need to do is clear this user's data and save that 15403 // it is uninstalled. 15404 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15405 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15406 return false; 15407 } 15408 scheduleWritePackageRestrictionsLocked(user); 15409 return true; 15410 } else { 15411 // We need to set it back to 'installed' so the uninstall 15412 // broadcasts will be sent correctly. 15413 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15414 ps.setInstalled(true, user.getIdentifier()); 15415 } 15416 } else { 15417 // This is a system app, so we assume that the 15418 // other users still have this package installed, so all 15419 // we need to do is clear this user's data and save that 15420 // it is uninstalled. 15421 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15422 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15423 return false; 15424 } 15425 scheduleWritePackageRestrictionsLocked(user); 15426 return true; 15427 } 15428 } 15429 15430 // If we are deleting a composite package for all users, keep track 15431 // of result for each child. 15432 if (ps.childPackageNames != null && outInfo != null) { 15433 synchronized (mPackages) { 15434 final int childCount = ps.childPackageNames.size(); 15435 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15436 for (int i = 0; i < childCount; i++) { 15437 String childPackageName = ps.childPackageNames.get(i); 15438 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15439 childInfo.removedPackage = childPackageName; 15440 outInfo.removedChildPackages.put(childPackageName, childInfo); 15441 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15442 if (childPs != null) { 15443 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15444 } 15445 } 15446 } 15447 } 15448 15449 boolean ret = false; 15450 if (isSystemApp(ps)) { 15451 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15452 // When an updated system application is deleted we delete the existing resources 15453 // as well and fall back to existing code in system partition 15454 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15455 } else { 15456 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15457 // Kill application pre-emptively especially for apps on sd. 15458 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15459 if (killApp) { 15460 killApplication(packageName, ps.appId, "uninstall pkg"); 15461 } 15462 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15463 outInfo, writeSettings, replacingPackage); 15464 } 15465 15466 // Take a note whether we deleted the package for all users 15467 if (outInfo != null) { 15468 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15469 if (outInfo.removedChildPackages != null) { 15470 synchronized (mPackages) { 15471 final int childCount = outInfo.removedChildPackages.size(); 15472 for (int i = 0; i < childCount; i++) { 15473 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15474 if (childInfo != null) { 15475 childInfo.removedForAllUsers = mPackages.get( 15476 childInfo.removedPackage) == null; 15477 } 15478 } 15479 } 15480 } 15481 // If we uninstalled an update to a system app there may be some 15482 // child packages that appeared as they are declared in the system 15483 // app but were not declared in the update. 15484 if (isSystemApp(ps)) { 15485 synchronized (mPackages) { 15486 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15487 final int childCount = (updatedPs.childPackageNames != null) 15488 ? updatedPs.childPackageNames.size() : 0; 15489 for (int i = 0; i < childCount; i++) { 15490 String childPackageName = updatedPs.childPackageNames.get(i); 15491 if (outInfo.removedChildPackages == null 15492 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15493 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15494 if (childPs == null) { 15495 continue; 15496 } 15497 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15498 installRes.name = childPackageName; 15499 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15500 installRes.pkg = mPackages.get(childPackageName); 15501 installRes.uid = childPs.pkg.applicationInfo.uid; 15502 if (outInfo.appearedChildPackages == null) { 15503 outInfo.appearedChildPackages = new ArrayMap<>(); 15504 } 15505 outInfo.appearedChildPackages.put(childPackageName, installRes); 15506 } 15507 } 15508 } 15509 } 15510 } 15511 15512 return ret; 15513 } 15514 15515 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15516 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15517 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15518 for (int nextUserId : userIds) { 15519 if (DEBUG_REMOVE) { 15520 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15521 } 15522 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15523 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15524 false /*hidden*/, false /*suspended*/, null, null, null, 15525 false /*blockUninstall*/, 15526 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15527 } 15528 } 15529 15530 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15531 PackageRemovedInfo outInfo) { 15532 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15533 : new int[] {userId}; 15534 for (int nextUserId : userIds) { 15535 if (DEBUG_REMOVE) { 15536 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15537 + nextUserId); 15538 } 15539 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15540 try { 15541 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15542 } catch (InstallerException e) { 15543 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15544 return false; 15545 } 15546 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15547 schedulePackageCleaning(ps.name, nextUserId, false); 15548 synchronized (mPackages) { 15549 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15550 scheduleWritePackageRestrictionsLocked(nextUserId); 15551 } 15552 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15553 } 15554 } 15555 15556 if (outInfo != null) { 15557 outInfo.removedPackage = ps.name; 15558 outInfo.removedAppId = ps.appId; 15559 outInfo.removedUsers = userIds; 15560 } 15561 15562 return true; 15563 } 15564 15565 private final class ClearStorageConnection implements ServiceConnection { 15566 IMediaContainerService mContainerService; 15567 15568 @Override 15569 public void onServiceConnected(ComponentName name, IBinder service) { 15570 synchronized (this) { 15571 mContainerService = IMediaContainerService.Stub.asInterface(service); 15572 notifyAll(); 15573 } 15574 } 15575 15576 @Override 15577 public void onServiceDisconnected(ComponentName name) { 15578 } 15579 } 15580 15581 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15582 final boolean mounted; 15583 if (Environment.isExternalStorageEmulated()) { 15584 mounted = true; 15585 } else { 15586 final String status = Environment.getExternalStorageState(); 15587 15588 mounted = status.equals(Environment.MEDIA_MOUNTED) 15589 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15590 } 15591 15592 if (!mounted) { 15593 return; 15594 } 15595 15596 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15597 int[] users; 15598 if (userId == UserHandle.USER_ALL) { 15599 users = sUserManager.getUserIds(); 15600 } else { 15601 users = new int[] { userId }; 15602 } 15603 final ClearStorageConnection conn = new ClearStorageConnection(); 15604 if (mContext.bindServiceAsUser( 15605 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15606 try { 15607 for (int curUser : users) { 15608 long timeout = SystemClock.uptimeMillis() + 5000; 15609 synchronized (conn) { 15610 long now = SystemClock.uptimeMillis(); 15611 while (conn.mContainerService == null && now < timeout) { 15612 try { 15613 conn.wait(timeout - now); 15614 } catch (InterruptedException e) { 15615 } 15616 } 15617 } 15618 if (conn.mContainerService == null) { 15619 return; 15620 } 15621 15622 final UserEnvironment userEnv = new UserEnvironment(curUser); 15623 clearDirectory(conn.mContainerService, 15624 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15625 if (allData) { 15626 clearDirectory(conn.mContainerService, 15627 userEnv.buildExternalStorageAppDataDirs(packageName)); 15628 clearDirectory(conn.mContainerService, 15629 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15630 } 15631 } 15632 } finally { 15633 mContext.unbindService(conn); 15634 } 15635 } 15636 } 15637 15638 @Override 15639 public void clearApplicationProfileData(String packageName) { 15640 enforceSystemOrRoot("Only the system can clear all profile data"); 15641 try { 15642 mInstaller.clearAppProfiles(packageName); 15643 } catch (InstallerException ex) { 15644 Log.e(TAG, "Could not clear profile data of package " + packageName); 15645 } 15646 } 15647 15648 @Override 15649 public void clearApplicationUserData(final String packageName, 15650 final IPackageDataObserver observer, final int userId) { 15651 mContext.enforceCallingOrSelfPermission( 15652 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15653 15654 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15655 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15656 15657 final DevicePolicyManagerInternal dpmi = LocalServices 15658 .getService(DevicePolicyManagerInternal.class); 15659 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15660 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15661 } 15662 // Queue up an async operation since the package deletion may take a little while. 15663 mHandler.post(new Runnable() { 15664 public void run() { 15665 mHandler.removeCallbacks(this); 15666 final boolean succeeded; 15667 synchronized (mInstallLock) { 15668 succeeded = clearApplicationUserDataLI(packageName, userId); 15669 } 15670 clearExternalStorageDataSync(packageName, userId, true); 15671 if (succeeded) { 15672 // invoke DeviceStorageMonitor's update method to clear any notifications 15673 DeviceStorageMonitorInternal dsm = LocalServices 15674 .getService(DeviceStorageMonitorInternal.class); 15675 if (dsm != null) { 15676 dsm.checkMemory(); 15677 } 15678 } 15679 if(observer != null) { 15680 try { 15681 observer.onRemoveCompleted(packageName, succeeded); 15682 } catch (RemoteException e) { 15683 Log.i(TAG, "Observer no longer exists."); 15684 } 15685 } //end if observer 15686 } //end run 15687 }); 15688 } 15689 15690 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15691 if (packageName == null) { 15692 Slog.w(TAG, "Attempt to delete null packageName."); 15693 return false; 15694 } 15695 15696 // Try finding details about the requested package 15697 PackageParser.Package pkg; 15698 synchronized (mPackages) { 15699 pkg = mPackages.get(packageName); 15700 if (pkg == null) { 15701 final PackageSetting ps = mSettings.mPackages.get(packageName); 15702 if (ps != null) { 15703 pkg = ps.pkg; 15704 } 15705 } 15706 15707 if (pkg == null) { 15708 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15709 return false; 15710 } 15711 15712 PackageSetting ps = (PackageSetting) pkg.mExtras; 15713 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15714 } 15715 15716 // Always delete data directories for package, even if we found no other 15717 // record of app. This helps users recover from UID mismatches without 15718 // resorting to a full data wipe. 15719 // TODO: triage flags as part of 26466827 15720 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15721 try { 15722 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15723 } catch (InstallerException e) { 15724 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15725 return false; 15726 } 15727 15728 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15729 removeKeystoreDataIfNeeded(userId, appId); 15730 15731 // Create a native library symlink only if we have native libraries 15732 // and if the native libraries are 32 bit libraries. We do not provide 15733 // this symlink for 64 bit libraries. 15734 if (pkg.applicationInfo.primaryCpuAbi != null && 15735 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15736 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15737 try { 15738 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15739 nativeLibPath, userId); 15740 } catch (InstallerException e) { 15741 Slog.w(TAG, "Failed linking native library dir", e); 15742 return false; 15743 } 15744 } 15745 15746 return true; 15747 } 15748 15749 /** 15750 * Reverts user permission state changes (permissions and flags) in 15751 * all packages for a given user. 15752 * 15753 * @param userId The device user for which to do a reset. 15754 */ 15755 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15756 final int packageCount = mPackages.size(); 15757 for (int i = 0; i < packageCount; i++) { 15758 PackageParser.Package pkg = mPackages.valueAt(i); 15759 PackageSetting ps = (PackageSetting) pkg.mExtras; 15760 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15761 } 15762 } 15763 15764 /** 15765 * Reverts user permission state changes (permissions and flags). 15766 * 15767 * @param ps The package for which to reset. 15768 * @param userId The device user for which to do a reset. 15769 */ 15770 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15771 final PackageSetting ps, final int userId) { 15772 if (ps.pkg == null) { 15773 return; 15774 } 15775 15776 // These are flags that can change base on user actions. 15777 final int userSettableMask = FLAG_PERMISSION_USER_SET 15778 | FLAG_PERMISSION_USER_FIXED 15779 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15780 | FLAG_PERMISSION_REVIEW_REQUIRED; 15781 15782 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15783 | FLAG_PERMISSION_POLICY_FIXED; 15784 15785 boolean writeInstallPermissions = false; 15786 boolean writeRuntimePermissions = false; 15787 15788 final int permissionCount = ps.pkg.requestedPermissions.size(); 15789 for (int i = 0; i < permissionCount; i++) { 15790 String permission = ps.pkg.requestedPermissions.get(i); 15791 15792 BasePermission bp = mSettings.mPermissions.get(permission); 15793 if (bp == null) { 15794 continue; 15795 } 15796 15797 // If shared user we just reset the state to which only this app contributed. 15798 if (ps.sharedUser != null) { 15799 boolean used = false; 15800 final int packageCount = ps.sharedUser.packages.size(); 15801 for (int j = 0; j < packageCount; j++) { 15802 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15803 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15804 && pkg.pkg.requestedPermissions.contains(permission)) { 15805 used = true; 15806 break; 15807 } 15808 } 15809 if (used) { 15810 continue; 15811 } 15812 } 15813 15814 PermissionsState permissionsState = ps.getPermissionsState(); 15815 15816 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15817 15818 // Always clear the user settable flags. 15819 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15820 bp.name) != null; 15821 // If permission review is enabled and this is a legacy app, mark the 15822 // permission as requiring a review as this is the initial state. 15823 int flags = 0; 15824 if (Build.PERMISSIONS_REVIEW_REQUIRED 15825 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15826 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15827 } 15828 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15829 if (hasInstallState) { 15830 writeInstallPermissions = true; 15831 } else { 15832 writeRuntimePermissions = true; 15833 } 15834 } 15835 15836 // Below is only runtime permission handling. 15837 if (!bp.isRuntime()) { 15838 continue; 15839 } 15840 15841 // Never clobber system or policy. 15842 if ((oldFlags & policyOrSystemFlags) != 0) { 15843 continue; 15844 } 15845 15846 // If this permission was granted by default, make sure it is. 15847 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15848 if (permissionsState.grantRuntimePermission(bp, userId) 15849 != PERMISSION_OPERATION_FAILURE) { 15850 writeRuntimePermissions = true; 15851 } 15852 // If permission review is enabled the permissions for a legacy apps 15853 // are represented as constantly granted runtime ones, so don't revoke. 15854 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15855 // Otherwise, reset the permission. 15856 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15857 switch (revokeResult) { 15858 case PERMISSION_OPERATION_SUCCESS: 15859 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15860 writeRuntimePermissions = true; 15861 final int appId = ps.appId; 15862 mHandler.post(new Runnable() { 15863 @Override 15864 public void run() { 15865 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15866 } 15867 }); 15868 } break; 15869 } 15870 } 15871 } 15872 15873 // Synchronously write as we are taking permissions away. 15874 if (writeRuntimePermissions) { 15875 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15876 } 15877 15878 // Synchronously write as we are taking permissions away. 15879 if (writeInstallPermissions) { 15880 mSettings.writeLPr(); 15881 } 15882 } 15883 15884 /** 15885 * Remove entries from the keystore daemon. Will only remove it if the 15886 * {@code appId} is valid. 15887 */ 15888 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15889 if (appId < 0) { 15890 return; 15891 } 15892 15893 final KeyStore keyStore = KeyStore.getInstance(); 15894 if (keyStore != null) { 15895 if (userId == UserHandle.USER_ALL) { 15896 for (final int individual : sUserManager.getUserIds()) { 15897 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15898 } 15899 } else { 15900 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15901 } 15902 } else { 15903 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15904 } 15905 } 15906 15907 @Override 15908 public void deleteApplicationCacheFiles(final String packageName, 15909 final IPackageDataObserver observer) { 15910 mContext.enforceCallingOrSelfPermission( 15911 android.Manifest.permission.DELETE_CACHE_FILES, null); 15912 // Queue up an async operation since the package deletion may take a little while. 15913 final int userId = UserHandle.getCallingUserId(); 15914 mHandler.post(new Runnable() { 15915 public void run() { 15916 mHandler.removeCallbacks(this); 15917 final boolean succeded; 15918 synchronized (mInstallLock) { 15919 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15920 } 15921 clearExternalStorageDataSync(packageName, userId, false); 15922 if (observer != null) { 15923 try { 15924 observer.onRemoveCompleted(packageName, succeded); 15925 } catch (RemoteException e) { 15926 Log.i(TAG, "Observer no longer exists."); 15927 } 15928 } //end if observer 15929 } //end run 15930 }); 15931 } 15932 15933 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15934 if (packageName == null) { 15935 Slog.w(TAG, "Attempt to delete null packageName."); 15936 return false; 15937 } 15938 PackageParser.Package p; 15939 synchronized (mPackages) { 15940 p = mPackages.get(packageName); 15941 } 15942 if (p == null) { 15943 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15944 return false; 15945 } 15946 final ApplicationInfo applicationInfo = p.applicationInfo; 15947 if (applicationInfo == null) { 15948 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15949 return false; 15950 } 15951 // TODO: triage flags as part of 26466827 15952 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15953 try { 15954 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15955 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15956 } catch (InstallerException e) { 15957 Slog.w(TAG, "Couldn't remove cache files for package " 15958 + packageName + " u" + userId, e); 15959 return false; 15960 } 15961 return true; 15962 } 15963 15964 @Override 15965 public void getPackageSizeInfo(final String packageName, int userHandle, 15966 final IPackageStatsObserver observer) { 15967 mContext.enforceCallingOrSelfPermission( 15968 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15969 if (packageName == null) { 15970 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15971 } 15972 15973 PackageStats stats = new PackageStats(packageName, userHandle); 15974 15975 /* 15976 * Queue up an async operation since the package measurement may take a 15977 * little while. 15978 */ 15979 Message msg = mHandler.obtainMessage(INIT_COPY); 15980 msg.obj = new MeasureParams(stats, observer); 15981 mHandler.sendMessage(msg); 15982 } 15983 15984 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15985 PackageStats pStats) { 15986 if (packageName == null) { 15987 Slog.w(TAG, "Attempt to get size of null packageName."); 15988 return false; 15989 } 15990 PackageParser.Package p; 15991 boolean dataOnly = false; 15992 String libDirRoot = null; 15993 String asecPath = null; 15994 PackageSetting ps = null; 15995 synchronized (mPackages) { 15996 p = mPackages.get(packageName); 15997 ps = mSettings.mPackages.get(packageName); 15998 if(p == null) { 15999 dataOnly = true; 16000 if((ps == null) || (ps.pkg == null)) { 16001 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16002 return false; 16003 } 16004 p = ps.pkg; 16005 } 16006 if (ps != null) { 16007 libDirRoot = ps.legacyNativeLibraryPathString; 16008 } 16009 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16010 final long token = Binder.clearCallingIdentity(); 16011 try { 16012 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16013 if (secureContainerId != null) { 16014 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16015 } 16016 } finally { 16017 Binder.restoreCallingIdentity(token); 16018 } 16019 } 16020 } 16021 String publicSrcDir = null; 16022 if(!dataOnly) { 16023 final ApplicationInfo applicationInfo = p.applicationInfo; 16024 if (applicationInfo == null) { 16025 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16026 return false; 16027 } 16028 if (p.isForwardLocked()) { 16029 publicSrcDir = applicationInfo.getBaseResourcePath(); 16030 } 16031 } 16032 // TODO: extend to measure size of split APKs 16033 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16034 // not just the first level. 16035 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16036 // just the primary. 16037 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16038 16039 String apkPath; 16040 File packageDir = new File(p.codePath); 16041 16042 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16043 apkPath = packageDir.getAbsolutePath(); 16044 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16045 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16046 libDirRoot = null; 16047 } 16048 } else { 16049 apkPath = p.baseCodePath; 16050 } 16051 16052 // TODO: triage flags as part of 26466827 16053 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16054 try { 16055 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16056 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16057 } catch (InstallerException e) { 16058 return false; 16059 } 16060 16061 // Fix-up for forward-locked applications in ASEC containers. 16062 if (!isExternal(p)) { 16063 pStats.codeSize += pStats.externalCodeSize; 16064 pStats.externalCodeSize = 0L; 16065 } 16066 16067 return true; 16068 } 16069 16070 private int getUidTargetSdkVersionLockedLPr(int uid) { 16071 Object obj = mSettings.getUserIdLPr(uid); 16072 if (obj instanceof SharedUserSetting) { 16073 final SharedUserSetting sus = (SharedUserSetting) obj; 16074 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16075 final Iterator<PackageSetting> it = sus.packages.iterator(); 16076 while (it.hasNext()) { 16077 final PackageSetting ps = it.next(); 16078 if (ps.pkg != null) { 16079 int v = ps.pkg.applicationInfo.targetSdkVersion; 16080 if (v < vers) vers = v; 16081 } 16082 } 16083 return vers; 16084 } else if (obj instanceof PackageSetting) { 16085 final PackageSetting ps = (PackageSetting) obj; 16086 if (ps.pkg != null) { 16087 return ps.pkg.applicationInfo.targetSdkVersion; 16088 } 16089 } 16090 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16091 } 16092 16093 @Override 16094 public void addPreferredActivity(IntentFilter filter, int match, 16095 ComponentName[] set, ComponentName activity, int userId) { 16096 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16097 "Adding preferred"); 16098 } 16099 16100 private void addPreferredActivityInternal(IntentFilter filter, int match, 16101 ComponentName[] set, ComponentName activity, boolean always, int userId, 16102 String opname) { 16103 // writer 16104 int callingUid = Binder.getCallingUid(); 16105 enforceCrossUserPermission(callingUid, userId, 16106 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16107 if (filter.countActions() == 0) { 16108 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16109 return; 16110 } 16111 synchronized (mPackages) { 16112 if (mContext.checkCallingOrSelfPermission( 16113 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16114 != PackageManager.PERMISSION_GRANTED) { 16115 if (getUidTargetSdkVersionLockedLPr(callingUid) 16116 < Build.VERSION_CODES.FROYO) { 16117 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16118 + callingUid); 16119 return; 16120 } 16121 mContext.enforceCallingOrSelfPermission( 16122 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16123 } 16124 16125 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16126 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16127 + userId + ":"); 16128 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16129 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16130 scheduleWritePackageRestrictionsLocked(userId); 16131 } 16132 } 16133 16134 @Override 16135 public void replacePreferredActivity(IntentFilter filter, int match, 16136 ComponentName[] set, ComponentName activity, int userId) { 16137 if (filter.countActions() != 1) { 16138 throw new IllegalArgumentException( 16139 "replacePreferredActivity expects filter to have only 1 action."); 16140 } 16141 if (filter.countDataAuthorities() != 0 16142 || filter.countDataPaths() != 0 16143 || filter.countDataSchemes() > 1 16144 || filter.countDataTypes() != 0) { 16145 throw new IllegalArgumentException( 16146 "replacePreferredActivity expects filter to have no data authorities, " + 16147 "paths, or types; and at most one scheme."); 16148 } 16149 16150 final int callingUid = Binder.getCallingUid(); 16151 enforceCrossUserPermission(callingUid, userId, 16152 true /* requireFullPermission */, false /* checkShell */, 16153 "replace preferred activity"); 16154 synchronized (mPackages) { 16155 if (mContext.checkCallingOrSelfPermission( 16156 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16157 != PackageManager.PERMISSION_GRANTED) { 16158 if (getUidTargetSdkVersionLockedLPr(callingUid) 16159 < Build.VERSION_CODES.FROYO) { 16160 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16161 + Binder.getCallingUid()); 16162 return; 16163 } 16164 mContext.enforceCallingOrSelfPermission( 16165 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16166 } 16167 16168 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16169 if (pir != null) { 16170 // Get all of the existing entries that exactly match this filter. 16171 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16172 if (existing != null && existing.size() == 1) { 16173 PreferredActivity cur = existing.get(0); 16174 if (DEBUG_PREFERRED) { 16175 Slog.i(TAG, "Checking replace of preferred:"); 16176 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16177 if (!cur.mPref.mAlways) { 16178 Slog.i(TAG, " -- CUR; not mAlways!"); 16179 } else { 16180 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16181 Slog.i(TAG, " -- CUR: mSet=" 16182 + Arrays.toString(cur.mPref.mSetComponents)); 16183 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16184 Slog.i(TAG, " -- NEW: mMatch=" 16185 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16186 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16187 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16188 } 16189 } 16190 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16191 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16192 && cur.mPref.sameSet(set)) { 16193 // Setting the preferred activity to what it happens to be already 16194 if (DEBUG_PREFERRED) { 16195 Slog.i(TAG, "Replacing with same preferred activity " 16196 + cur.mPref.mShortComponent + " for user " 16197 + userId + ":"); 16198 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16199 } 16200 return; 16201 } 16202 } 16203 16204 if (existing != null) { 16205 if (DEBUG_PREFERRED) { 16206 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16207 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16208 } 16209 for (int i = 0; i < existing.size(); i++) { 16210 PreferredActivity pa = existing.get(i); 16211 if (DEBUG_PREFERRED) { 16212 Slog.i(TAG, "Removing existing preferred activity " 16213 + pa.mPref.mComponent + ":"); 16214 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16215 } 16216 pir.removeFilter(pa); 16217 } 16218 } 16219 } 16220 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16221 "Replacing preferred"); 16222 } 16223 } 16224 16225 @Override 16226 public void clearPackagePreferredActivities(String packageName) { 16227 final int uid = Binder.getCallingUid(); 16228 // writer 16229 synchronized (mPackages) { 16230 PackageParser.Package pkg = mPackages.get(packageName); 16231 if (pkg == null || pkg.applicationInfo.uid != uid) { 16232 if (mContext.checkCallingOrSelfPermission( 16233 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16234 != PackageManager.PERMISSION_GRANTED) { 16235 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16236 < Build.VERSION_CODES.FROYO) { 16237 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16238 + Binder.getCallingUid()); 16239 return; 16240 } 16241 mContext.enforceCallingOrSelfPermission( 16242 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16243 } 16244 } 16245 16246 int user = UserHandle.getCallingUserId(); 16247 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16248 scheduleWritePackageRestrictionsLocked(user); 16249 } 16250 } 16251 } 16252 16253 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16254 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16255 ArrayList<PreferredActivity> removed = null; 16256 boolean changed = false; 16257 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16258 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16259 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16260 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16261 continue; 16262 } 16263 Iterator<PreferredActivity> it = pir.filterIterator(); 16264 while (it.hasNext()) { 16265 PreferredActivity pa = it.next(); 16266 // Mark entry for removal only if it matches the package name 16267 // and the entry is of type "always". 16268 if (packageName == null || 16269 (pa.mPref.mComponent.getPackageName().equals(packageName) 16270 && pa.mPref.mAlways)) { 16271 if (removed == null) { 16272 removed = new ArrayList<PreferredActivity>(); 16273 } 16274 removed.add(pa); 16275 } 16276 } 16277 if (removed != null) { 16278 for (int j=0; j<removed.size(); j++) { 16279 PreferredActivity pa = removed.get(j); 16280 pir.removeFilter(pa); 16281 } 16282 changed = true; 16283 } 16284 } 16285 return changed; 16286 } 16287 16288 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16289 private void clearIntentFilterVerificationsLPw(int userId) { 16290 final int packageCount = mPackages.size(); 16291 for (int i = 0; i < packageCount; i++) { 16292 PackageParser.Package pkg = mPackages.valueAt(i); 16293 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16294 } 16295 } 16296 16297 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16298 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16299 if (userId == UserHandle.USER_ALL) { 16300 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16301 sUserManager.getUserIds())) { 16302 for (int oneUserId : sUserManager.getUserIds()) { 16303 scheduleWritePackageRestrictionsLocked(oneUserId); 16304 } 16305 } 16306 } else { 16307 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16308 scheduleWritePackageRestrictionsLocked(userId); 16309 } 16310 } 16311 } 16312 16313 void clearDefaultBrowserIfNeeded(String packageName) { 16314 for (int oneUserId : sUserManager.getUserIds()) { 16315 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16316 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16317 if (packageName.equals(defaultBrowserPackageName)) { 16318 setDefaultBrowserPackageName(null, oneUserId); 16319 } 16320 } 16321 } 16322 16323 @Override 16324 public void resetApplicationPreferences(int userId) { 16325 mContext.enforceCallingOrSelfPermission( 16326 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16327 // writer 16328 synchronized (mPackages) { 16329 final long identity = Binder.clearCallingIdentity(); 16330 try { 16331 clearPackagePreferredActivitiesLPw(null, userId); 16332 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16333 // TODO: We have to reset the default SMS and Phone. This requires 16334 // significant refactoring to keep all default apps in the package 16335 // manager (cleaner but more work) or have the services provide 16336 // callbacks to the package manager to request a default app reset. 16337 applyFactoryDefaultBrowserLPw(userId); 16338 clearIntentFilterVerificationsLPw(userId); 16339 primeDomainVerificationsLPw(userId); 16340 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16341 scheduleWritePackageRestrictionsLocked(userId); 16342 } finally { 16343 Binder.restoreCallingIdentity(identity); 16344 } 16345 } 16346 } 16347 16348 @Override 16349 public int getPreferredActivities(List<IntentFilter> outFilters, 16350 List<ComponentName> outActivities, String packageName) { 16351 16352 int num = 0; 16353 final int userId = UserHandle.getCallingUserId(); 16354 // reader 16355 synchronized (mPackages) { 16356 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16357 if (pir != null) { 16358 final Iterator<PreferredActivity> it = pir.filterIterator(); 16359 while (it.hasNext()) { 16360 final PreferredActivity pa = it.next(); 16361 if (packageName == null 16362 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16363 && pa.mPref.mAlways)) { 16364 if (outFilters != null) { 16365 outFilters.add(new IntentFilter(pa)); 16366 } 16367 if (outActivities != null) { 16368 outActivities.add(pa.mPref.mComponent); 16369 } 16370 } 16371 } 16372 } 16373 } 16374 16375 return num; 16376 } 16377 16378 @Override 16379 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16380 int userId) { 16381 int callingUid = Binder.getCallingUid(); 16382 if (callingUid != Process.SYSTEM_UID) { 16383 throw new SecurityException( 16384 "addPersistentPreferredActivity can only be run by the system"); 16385 } 16386 if (filter.countActions() == 0) { 16387 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16388 return; 16389 } 16390 synchronized (mPackages) { 16391 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16392 ":"); 16393 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16394 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16395 new PersistentPreferredActivity(filter, activity)); 16396 scheduleWritePackageRestrictionsLocked(userId); 16397 } 16398 } 16399 16400 @Override 16401 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16402 int callingUid = Binder.getCallingUid(); 16403 if (callingUid != Process.SYSTEM_UID) { 16404 throw new SecurityException( 16405 "clearPackagePersistentPreferredActivities can only be run by the system"); 16406 } 16407 ArrayList<PersistentPreferredActivity> removed = null; 16408 boolean changed = false; 16409 synchronized (mPackages) { 16410 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16411 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16412 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16413 .valueAt(i); 16414 if (userId != thisUserId) { 16415 continue; 16416 } 16417 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16418 while (it.hasNext()) { 16419 PersistentPreferredActivity ppa = it.next(); 16420 // Mark entry for removal only if it matches the package name. 16421 if (ppa.mComponent.getPackageName().equals(packageName)) { 16422 if (removed == null) { 16423 removed = new ArrayList<PersistentPreferredActivity>(); 16424 } 16425 removed.add(ppa); 16426 } 16427 } 16428 if (removed != null) { 16429 for (int j=0; j<removed.size(); j++) { 16430 PersistentPreferredActivity ppa = removed.get(j); 16431 ppir.removeFilter(ppa); 16432 } 16433 changed = true; 16434 } 16435 } 16436 16437 if (changed) { 16438 scheduleWritePackageRestrictionsLocked(userId); 16439 } 16440 } 16441 } 16442 16443 /** 16444 * Common machinery for picking apart a restored XML blob and passing 16445 * it to a caller-supplied functor to be applied to the running system. 16446 */ 16447 private void restoreFromXml(XmlPullParser parser, int userId, 16448 String expectedStartTag, BlobXmlRestorer functor) 16449 throws IOException, XmlPullParserException { 16450 int type; 16451 while ((type = parser.next()) != XmlPullParser.START_TAG 16452 && type != XmlPullParser.END_DOCUMENT) { 16453 } 16454 if (type != XmlPullParser.START_TAG) { 16455 // oops didn't find a start tag?! 16456 if (DEBUG_BACKUP) { 16457 Slog.e(TAG, "Didn't find start tag during restore"); 16458 } 16459 return; 16460 } 16461Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16462 // this is supposed to be TAG_PREFERRED_BACKUP 16463 if (!expectedStartTag.equals(parser.getName())) { 16464 if (DEBUG_BACKUP) { 16465 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16466 } 16467 return; 16468 } 16469 16470 // skip interfering stuff, then we're aligned with the backing implementation 16471 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16472Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16473 functor.apply(parser, userId); 16474 } 16475 16476 private interface BlobXmlRestorer { 16477 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16478 } 16479 16480 /** 16481 * Non-Binder method, support for the backup/restore mechanism: write the 16482 * full set of preferred activities in its canonical XML format. Returns the 16483 * XML output as a byte array, or null if there is none. 16484 */ 16485 @Override 16486 public byte[] getPreferredActivityBackup(int userId) { 16487 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16488 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16489 } 16490 16491 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16492 try { 16493 final XmlSerializer serializer = new FastXmlSerializer(); 16494 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16495 serializer.startDocument(null, true); 16496 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16497 16498 synchronized (mPackages) { 16499 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16500 } 16501 16502 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16503 serializer.endDocument(); 16504 serializer.flush(); 16505 } catch (Exception e) { 16506 if (DEBUG_BACKUP) { 16507 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16508 } 16509 return null; 16510 } 16511 16512 return dataStream.toByteArray(); 16513 } 16514 16515 @Override 16516 public void restorePreferredActivities(byte[] backup, int userId) { 16517 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16518 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16519 } 16520 16521 try { 16522 final XmlPullParser parser = Xml.newPullParser(); 16523 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16524 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16525 new BlobXmlRestorer() { 16526 @Override 16527 public void apply(XmlPullParser parser, int userId) 16528 throws XmlPullParserException, IOException { 16529 synchronized (mPackages) { 16530 mSettings.readPreferredActivitiesLPw(parser, userId); 16531 } 16532 } 16533 } ); 16534 } catch (Exception e) { 16535 if (DEBUG_BACKUP) { 16536 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16537 } 16538 } 16539 } 16540 16541 /** 16542 * Non-Binder method, support for the backup/restore mechanism: write the 16543 * default browser (etc) settings in its canonical XML format. Returns the default 16544 * browser XML representation as a byte array, or null if there is none. 16545 */ 16546 @Override 16547 public byte[] getDefaultAppsBackup(int userId) { 16548 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16549 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16550 } 16551 16552 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16553 try { 16554 final XmlSerializer serializer = new FastXmlSerializer(); 16555 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16556 serializer.startDocument(null, true); 16557 serializer.startTag(null, TAG_DEFAULT_APPS); 16558 16559 synchronized (mPackages) { 16560 mSettings.writeDefaultAppsLPr(serializer, userId); 16561 } 16562 16563 serializer.endTag(null, TAG_DEFAULT_APPS); 16564 serializer.endDocument(); 16565 serializer.flush(); 16566 } catch (Exception e) { 16567 if (DEBUG_BACKUP) { 16568 Slog.e(TAG, "Unable to write default apps for backup", e); 16569 } 16570 return null; 16571 } 16572 16573 return dataStream.toByteArray(); 16574 } 16575 16576 @Override 16577 public void restoreDefaultApps(byte[] backup, int userId) { 16578 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16579 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16580 } 16581 16582 try { 16583 final XmlPullParser parser = Xml.newPullParser(); 16584 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16585 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16586 new BlobXmlRestorer() { 16587 @Override 16588 public void apply(XmlPullParser parser, int userId) 16589 throws XmlPullParserException, IOException { 16590 synchronized (mPackages) { 16591 mSettings.readDefaultAppsLPw(parser, userId); 16592 } 16593 } 16594 } ); 16595 } catch (Exception e) { 16596 if (DEBUG_BACKUP) { 16597 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16598 } 16599 } 16600 } 16601 16602 @Override 16603 public byte[] getIntentFilterVerificationBackup(int userId) { 16604 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16605 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16606 } 16607 16608 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16609 try { 16610 final XmlSerializer serializer = new FastXmlSerializer(); 16611 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16612 serializer.startDocument(null, true); 16613 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16614 16615 synchronized (mPackages) { 16616 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16617 } 16618 16619 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16620 serializer.endDocument(); 16621 serializer.flush(); 16622 } catch (Exception e) { 16623 if (DEBUG_BACKUP) { 16624 Slog.e(TAG, "Unable to write default apps for backup", e); 16625 } 16626 return null; 16627 } 16628 16629 return dataStream.toByteArray(); 16630 } 16631 16632 @Override 16633 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16634 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16635 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16636 } 16637 16638 try { 16639 final XmlPullParser parser = Xml.newPullParser(); 16640 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16641 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16642 new BlobXmlRestorer() { 16643 @Override 16644 public void apply(XmlPullParser parser, int userId) 16645 throws XmlPullParserException, IOException { 16646 synchronized (mPackages) { 16647 mSettings.readAllDomainVerificationsLPr(parser, userId); 16648 mSettings.writeLPr(); 16649 } 16650 } 16651 } ); 16652 } catch (Exception e) { 16653 if (DEBUG_BACKUP) { 16654 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16655 } 16656 } 16657 } 16658 16659 @Override 16660 public byte[] getPermissionGrantBackup(int userId) { 16661 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16662 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16663 } 16664 16665 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16666 try { 16667 final XmlSerializer serializer = new FastXmlSerializer(); 16668 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16669 serializer.startDocument(null, true); 16670 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16671 16672 synchronized (mPackages) { 16673 serializeRuntimePermissionGrantsLPr(serializer, userId); 16674 } 16675 16676 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16677 serializer.endDocument(); 16678 serializer.flush(); 16679 } catch (Exception e) { 16680 if (DEBUG_BACKUP) { 16681 Slog.e(TAG, "Unable to write default apps for backup", e); 16682 } 16683 return null; 16684 } 16685 16686 return dataStream.toByteArray(); 16687 } 16688 16689 @Override 16690 public void restorePermissionGrants(byte[] backup, int userId) { 16691 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16692 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16693 } 16694 16695 try { 16696 final XmlPullParser parser = Xml.newPullParser(); 16697 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16698 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16699 new BlobXmlRestorer() { 16700 @Override 16701 public void apply(XmlPullParser parser, int userId) 16702 throws XmlPullParserException, IOException { 16703 synchronized (mPackages) { 16704 processRestoredPermissionGrantsLPr(parser, userId); 16705 } 16706 } 16707 } ); 16708 } catch (Exception e) { 16709 if (DEBUG_BACKUP) { 16710 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16711 } 16712 } 16713 } 16714 16715 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16716 throws IOException { 16717 serializer.startTag(null, TAG_ALL_GRANTS); 16718 16719 final int N = mSettings.mPackages.size(); 16720 for (int i = 0; i < N; i++) { 16721 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16722 boolean pkgGrantsKnown = false; 16723 16724 PermissionsState packagePerms = ps.getPermissionsState(); 16725 16726 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16727 final int grantFlags = state.getFlags(); 16728 // only look at grants that are not system/policy fixed 16729 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16730 final boolean isGranted = state.isGranted(); 16731 // And only back up the user-twiddled state bits 16732 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16733 final String packageName = mSettings.mPackages.keyAt(i); 16734 if (!pkgGrantsKnown) { 16735 serializer.startTag(null, TAG_GRANT); 16736 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16737 pkgGrantsKnown = true; 16738 } 16739 16740 final boolean userSet = 16741 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16742 final boolean userFixed = 16743 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16744 final boolean revoke = 16745 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16746 16747 serializer.startTag(null, TAG_PERMISSION); 16748 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16749 if (isGranted) { 16750 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16751 } 16752 if (userSet) { 16753 serializer.attribute(null, ATTR_USER_SET, "true"); 16754 } 16755 if (userFixed) { 16756 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16757 } 16758 if (revoke) { 16759 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16760 } 16761 serializer.endTag(null, TAG_PERMISSION); 16762 } 16763 } 16764 } 16765 16766 if (pkgGrantsKnown) { 16767 serializer.endTag(null, TAG_GRANT); 16768 } 16769 } 16770 16771 serializer.endTag(null, TAG_ALL_GRANTS); 16772 } 16773 16774 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16775 throws XmlPullParserException, IOException { 16776 String pkgName = null; 16777 int outerDepth = parser.getDepth(); 16778 int type; 16779 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16780 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16781 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16782 continue; 16783 } 16784 16785 final String tagName = parser.getName(); 16786 if (tagName.equals(TAG_GRANT)) { 16787 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16788 if (DEBUG_BACKUP) { 16789 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16790 } 16791 } else if (tagName.equals(TAG_PERMISSION)) { 16792 16793 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16794 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16795 16796 int newFlagSet = 0; 16797 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16798 newFlagSet |= FLAG_PERMISSION_USER_SET; 16799 } 16800 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16801 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16802 } 16803 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16804 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16805 } 16806 if (DEBUG_BACKUP) { 16807 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16808 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16809 } 16810 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16811 if (ps != null) { 16812 // Already installed so we apply the grant immediately 16813 if (DEBUG_BACKUP) { 16814 Slog.v(TAG, " + already installed; applying"); 16815 } 16816 PermissionsState perms = ps.getPermissionsState(); 16817 BasePermission bp = mSettings.mPermissions.get(permName); 16818 if (bp != null) { 16819 if (isGranted) { 16820 perms.grantRuntimePermission(bp, userId); 16821 } 16822 if (newFlagSet != 0) { 16823 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16824 } 16825 } 16826 } else { 16827 // Need to wait for post-restore install to apply the grant 16828 if (DEBUG_BACKUP) { 16829 Slog.v(TAG, " - not yet installed; saving for later"); 16830 } 16831 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16832 isGranted, newFlagSet, userId); 16833 } 16834 } else { 16835 PackageManagerService.reportSettingsProblem(Log.WARN, 16836 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16837 XmlUtils.skipCurrentTag(parser); 16838 } 16839 } 16840 16841 scheduleWriteSettingsLocked(); 16842 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16843 } 16844 16845 @Override 16846 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16847 int sourceUserId, int targetUserId, int flags) { 16848 mContext.enforceCallingOrSelfPermission( 16849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16850 int callingUid = Binder.getCallingUid(); 16851 enforceOwnerRights(ownerPackage, callingUid); 16852 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16853 if (intentFilter.countActions() == 0) { 16854 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16855 return; 16856 } 16857 synchronized (mPackages) { 16858 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16859 ownerPackage, targetUserId, flags); 16860 CrossProfileIntentResolver resolver = 16861 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16862 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16863 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16864 if (existing != null) { 16865 int size = existing.size(); 16866 for (int i = 0; i < size; i++) { 16867 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16868 return; 16869 } 16870 } 16871 } 16872 resolver.addFilter(newFilter); 16873 scheduleWritePackageRestrictionsLocked(sourceUserId); 16874 } 16875 } 16876 16877 @Override 16878 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16879 mContext.enforceCallingOrSelfPermission( 16880 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16881 int callingUid = Binder.getCallingUid(); 16882 enforceOwnerRights(ownerPackage, callingUid); 16883 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16884 synchronized (mPackages) { 16885 CrossProfileIntentResolver resolver = 16886 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16887 ArraySet<CrossProfileIntentFilter> set = 16888 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16889 for (CrossProfileIntentFilter filter : set) { 16890 if (filter.getOwnerPackage().equals(ownerPackage)) { 16891 resolver.removeFilter(filter); 16892 } 16893 } 16894 scheduleWritePackageRestrictionsLocked(sourceUserId); 16895 } 16896 } 16897 16898 // Enforcing that callingUid is owning pkg on userId 16899 private void enforceOwnerRights(String pkg, int callingUid) { 16900 // The system owns everything. 16901 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16902 return; 16903 } 16904 int callingUserId = UserHandle.getUserId(callingUid); 16905 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16906 if (pi == null) { 16907 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16908 + callingUserId); 16909 } 16910 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16911 throw new SecurityException("Calling uid " + callingUid 16912 + " does not own package " + pkg); 16913 } 16914 } 16915 16916 @Override 16917 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16918 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16919 } 16920 16921 private Intent getHomeIntent() { 16922 Intent intent = new Intent(Intent.ACTION_MAIN); 16923 intent.addCategory(Intent.CATEGORY_HOME); 16924 return intent; 16925 } 16926 16927 private IntentFilter getHomeFilter() { 16928 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16929 filter.addCategory(Intent.CATEGORY_HOME); 16930 filter.addCategory(Intent.CATEGORY_DEFAULT); 16931 return filter; 16932 } 16933 16934 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16935 int userId) { 16936 Intent intent = getHomeIntent(); 16937 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16938 PackageManager.GET_META_DATA, userId); 16939 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16940 true, false, false, userId); 16941 16942 allHomeCandidates.clear(); 16943 if (list != null) { 16944 for (ResolveInfo ri : list) { 16945 allHomeCandidates.add(ri); 16946 } 16947 } 16948 return (preferred == null || preferred.activityInfo == null) 16949 ? null 16950 : new ComponentName(preferred.activityInfo.packageName, 16951 preferred.activityInfo.name); 16952 } 16953 16954 @Override 16955 public void setHomeActivity(ComponentName comp, int userId) { 16956 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16957 getHomeActivitiesAsUser(homeActivities, userId); 16958 16959 boolean found = false; 16960 16961 final int size = homeActivities.size(); 16962 final ComponentName[] set = new ComponentName[size]; 16963 for (int i = 0; i < size; i++) { 16964 final ResolveInfo candidate = homeActivities.get(i); 16965 final ActivityInfo info = candidate.activityInfo; 16966 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16967 set[i] = activityName; 16968 if (!found && activityName.equals(comp)) { 16969 found = true; 16970 } 16971 } 16972 if (!found) { 16973 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16974 + userId); 16975 } 16976 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16977 set, comp, userId); 16978 } 16979 16980 private @Nullable String getSetupWizardPackageName() { 16981 final Intent intent = new Intent(Intent.ACTION_MAIN); 16982 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 16983 16984 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 16985 MATCH_SYSTEM_ONLY | MATCH_DISABLED_COMPONENTS, UserHandle.myUserId()); 16986 if (matches.size() == 1) { 16987 return matches.get(0).getComponentInfo().packageName; 16988 } else { 16989 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 16990 + ": matches=" + matches); 16991 return null; 16992 } 16993 } 16994 16995 @Override 16996 public void setApplicationEnabledSetting(String appPackageName, 16997 int newState, int flags, int userId, String callingPackage) { 16998 if (!sUserManager.exists(userId)) return; 16999 if (callingPackage == null) { 17000 callingPackage = Integer.toString(Binder.getCallingUid()); 17001 } 17002 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17003 } 17004 17005 @Override 17006 public void setComponentEnabledSetting(ComponentName componentName, 17007 int newState, int flags, int userId) { 17008 if (!sUserManager.exists(userId)) return; 17009 setEnabledSetting(componentName.getPackageName(), 17010 componentName.getClassName(), newState, flags, userId, null); 17011 } 17012 17013 private void setEnabledSetting(final String packageName, String className, int newState, 17014 final int flags, int userId, String callingPackage) { 17015 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17016 || newState == COMPONENT_ENABLED_STATE_ENABLED 17017 || newState == COMPONENT_ENABLED_STATE_DISABLED 17018 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17019 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17020 throw new IllegalArgumentException("Invalid new component state: " 17021 + newState); 17022 } 17023 PackageSetting pkgSetting; 17024 final int uid = Binder.getCallingUid(); 17025 final int permission = mContext.checkCallingOrSelfPermission( 17026 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17027 enforceCrossUserPermission(uid, userId, 17028 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17029 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17030 boolean sendNow = false; 17031 boolean isApp = (className == null); 17032 String componentName = isApp ? packageName : className; 17033 int packageUid = -1; 17034 ArrayList<String> components; 17035 17036 // writer 17037 synchronized (mPackages) { 17038 pkgSetting = mSettings.mPackages.get(packageName); 17039 if (pkgSetting == null) { 17040 if (className == null) { 17041 throw new IllegalArgumentException("Unknown package: " + packageName); 17042 } 17043 throw new IllegalArgumentException( 17044 "Unknown component: " + packageName + "/" + className); 17045 } 17046 // Allow root and verify that userId is not being specified by a different user 17047 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17048 throw new SecurityException( 17049 "Permission Denial: attempt to change component state from pid=" 17050 + Binder.getCallingPid() 17051 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17052 } 17053 if (className == null) { 17054 // We're dealing with an application/package level state change 17055 if (pkgSetting.getEnabled(userId) == newState) { 17056 // Nothing to do 17057 return; 17058 } 17059 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17060 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17061 // Don't care about who enables an app. 17062 callingPackage = null; 17063 } 17064 pkgSetting.setEnabled(newState, userId, callingPackage); 17065 // pkgSetting.pkg.mSetEnabled = newState; 17066 } else { 17067 // We're dealing with a component level state change 17068 // First, verify that this is a valid class name. 17069 PackageParser.Package pkg = pkgSetting.pkg; 17070 if (pkg == null || !pkg.hasComponentClassName(className)) { 17071 if (pkg != null && 17072 pkg.applicationInfo.targetSdkVersion >= 17073 Build.VERSION_CODES.JELLY_BEAN) { 17074 throw new IllegalArgumentException("Component class " + className 17075 + " does not exist in " + packageName); 17076 } else { 17077 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17078 + className + " does not exist in " + packageName); 17079 } 17080 } 17081 switch (newState) { 17082 case COMPONENT_ENABLED_STATE_ENABLED: 17083 if (!pkgSetting.enableComponentLPw(className, userId)) { 17084 return; 17085 } 17086 break; 17087 case COMPONENT_ENABLED_STATE_DISABLED: 17088 if (!pkgSetting.disableComponentLPw(className, userId)) { 17089 return; 17090 } 17091 break; 17092 case COMPONENT_ENABLED_STATE_DEFAULT: 17093 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17094 return; 17095 } 17096 break; 17097 default: 17098 Slog.e(TAG, "Invalid new component state: " + newState); 17099 return; 17100 } 17101 } 17102 scheduleWritePackageRestrictionsLocked(userId); 17103 components = mPendingBroadcasts.get(userId, packageName); 17104 final boolean newPackage = components == null; 17105 if (newPackage) { 17106 components = new ArrayList<String>(); 17107 } 17108 if (!components.contains(componentName)) { 17109 components.add(componentName); 17110 } 17111 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17112 sendNow = true; 17113 // Purge entry from pending broadcast list if another one exists already 17114 // since we are sending one right away. 17115 mPendingBroadcasts.remove(userId, packageName); 17116 } else { 17117 if (newPackage) { 17118 mPendingBroadcasts.put(userId, packageName, components); 17119 } 17120 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17121 // Schedule a message 17122 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17123 } 17124 } 17125 } 17126 17127 long callingId = Binder.clearCallingIdentity(); 17128 try { 17129 if (sendNow) { 17130 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17131 sendPackageChangedBroadcast(packageName, 17132 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17133 } 17134 } finally { 17135 Binder.restoreCallingIdentity(callingId); 17136 } 17137 } 17138 17139 @Override 17140 public void flushPackageRestrictionsAsUser(int userId) { 17141 if (!sUserManager.exists(userId)) { 17142 return; 17143 } 17144 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17145 false /* checkShell */, "flushPackageRestrictions"); 17146 synchronized (mPackages) { 17147 mSettings.writePackageRestrictionsLPr(userId); 17148 mDirtyUsers.remove(userId); 17149 if (mDirtyUsers.isEmpty()) { 17150 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17151 } 17152 } 17153 } 17154 17155 private void sendPackageChangedBroadcast(String packageName, 17156 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17157 if (DEBUG_INSTALL) 17158 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17159 + componentNames); 17160 Bundle extras = new Bundle(4); 17161 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17162 String nameList[] = new String[componentNames.size()]; 17163 componentNames.toArray(nameList); 17164 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17165 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17166 extras.putInt(Intent.EXTRA_UID, packageUid); 17167 // If this is not reporting a change of the overall package, then only send it 17168 // to registered receivers. We don't want to launch a swath of apps for every 17169 // little component state change. 17170 final int flags = !componentNames.contains(packageName) 17171 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17172 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17173 new int[] {UserHandle.getUserId(packageUid)}); 17174 } 17175 17176 @Override 17177 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17178 if (!sUserManager.exists(userId)) return; 17179 final int uid = Binder.getCallingUid(); 17180 final int permission = mContext.checkCallingOrSelfPermission( 17181 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17182 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17183 enforceCrossUserPermission(uid, userId, 17184 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17185 // writer 17186 synchronized (mPackages) { 17187 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17188 allowedByPermission, uid, userId)) { 17189 scheduleWritePackageRestrictionsLocked(userId); 17190 } 17191 } 17192 } 17193 17194 @Override 17195 public String getInstallerPackageName(String packageName) { 17196 // reader 17197 synchronized (mPackages) { 17198 return mSettings.getInstallerPackageNameLPr(packageName); 17199 } 17200 } 17201 17202 @Override 17203 public int getApplicationEnabledSetting(String packageName, int userId) { 17204 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17205 int uid = Binder.getCallingUid(); 17206 enforceCrossUserPermission(uid, userId, 17207 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17208 // reader 17209 synchronized (mPackages) { 17210 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17211 } 17212 } 17213 17214 @Override 17215 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17216 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17217 int uid = Binder.getCallingUid(); 17218 enforceCrossUserPermission(uid, userId, 17219 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17220 // reader 17221 synchronized (mPackages) { 17222 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17223 } 17224 } 17225 17226 @Override 17227 public void enterSafeMode() { 17228 enforceSystemOrRoot("Only the system can request entering safe mode"); 17229 17230 if (!mSystemReady) { 17231 mSafeMode = true; 17232 } 17233 } 17234 17235 @Override 17236 public void systemReady() { 17237 mSystemReady = true; 17238 17239 // Read the compatibilty setting when the system is ready. 17240 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17241 mContext.getContentResolver(), 17242 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17243 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17244 if (DEBUG_SETTINGS) { 17245 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17246 } 17247 17248 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17249 17250 synchronized (mPackages) { 17251 // Verify that all of the preferred activity components actually 17252 // exist. It is possible for applications to be updated and at 17253 // that point remove a previously declared activity component that 17254 // had been set as a preferred activity. We try to clean this up 17255 // the next time we encounter that preferred activity, but it is 17256 // possible for the user flow to never be able to return to that 17257 // situation so here we do a sanity check to make sure we haven't 17258 // left any junk around. 17259 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17260 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17261 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17262 removed.clear(); 17263 for (PreferredActivity pa : pir.filterSet()) { 17264 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17265 removed.add(pa); 17266 } 17267 } 17268 if (removed.size() > 0) { 17269 for (int r=0; r<removed.size(); r++) { 17270 PreferredActivity pa = removed.get(r); 17271 Slog.w(TAG, "Removing dangling preferred activity: " 17272 + pa.mPref.mComponent); 17273 pir.removeFilter(pa); 17274 } 17275 mSettings.writePackageRestrictionsLPr( 17276 mSettings.mPreferredActivities.keyAt(i)); 17277 } 17278 } 17279 17280 for (int userId : UserManagerService.getInstance().getUserIds()) { 17281 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17282 grantPermissionsUserIds = ArrayUtils.appendInt( 17283 grantPermissionsUserIds, userId); 17284 } 17285 } 17286 } 17287 sUserManager.systemReady(); 17288 17289 // If we upgraded grant all default permissions before kicking off. 17290 for (int userId : grantPermissionsUserIds) { 17291 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17292 } 17293 17294 // Kick off any messages waiting for system ready 17295 if (mPostSystemReadyMessages != null) { 17296 for (Message msg : mPostSystemReadyMessages) { 17297 msg.sendToTarget(); 17298 } 17299 mPostSystemReadyMessages = null; 17300 } 17301 17302 // Watch for external volumes that come and go over time 17303 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17304 storage.registerListener(mStorageListener); 17305 17306 mInstallerService.systemReady(); 17307 mPackageDexOptimizer.systemReady(); 17308 17309 MountServiceInternal mountServiceInternal = LocalServices.getService( 17310 MountServiceInternal.class); 17311 mountServiceInternal.addExternalStoragePolicy( 17312 new MountServiceInternal.ExternalStorageMountPolicy() { 17313 @Override 17314 public int getMountMode(int uid, String packageName) { 17315 if (Process.isIsolated(uid)) { 17316 return Zygote.MOUNT_EXTERNAL_NONE; 17317 } 17318 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17319 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17320 } 17321 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17322 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17323 } 17324 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17325 return Zygote.MOUNT_EXTERNAL_READ; 17326 } 17327 return Zygote.MOUNT_EXTERNAL_WRITE; 17328 } 17329 17330 @Override 17331 public boolean hasExternalStorage(int uid, String packageName) { 17332 return true; 17333 } 17334 }); 17335 } 17336 17337 @Override 17338 public boolean isSafeMode() { 17339 return mSafeMode; 17340 } 17341 17342 @Override 17343 public boolean hasSystemUidErrors() { 17344 return mHasSystemUidErrors; 17345 } 17346 17347 static String arrayToString(int[] array) { 17348 StringBuffer buf = new StringBuffer(128); 17349 buf.append('['); 17350 if (array != null) { 17351 for (int i=0; i<array.length; i++) { 17352 if (i > 0) buf.append(", "); 17353 buf.append(array[i]); 17354 } 17355 } 17356 buf.append(']'); 17357 return buf.toString(); 17358 } 17359 17360 static class DumpState { 17361 public static final int DUMP_LIBS = 1 << 0; 17362 public static final int DUMP_FEATURES = 1 << 1; 17363 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17364 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17365 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17366 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17367 public static final int DUMP_PERMISSIONS = 1 << 6; 17368 public static final int DUMP_PACKAGES = 1 << 7; 17369 public static final int DUMP_SHARED_USERS = 1 << 8; 17370 public static final int DUMP_MESSAGES = 1 << 9; 17371 public static final int DUMP_PROVIDERS = 1 << 10; 17372 public static final int DUMP_VERIFIERS = 1 << 11; 17373 public static final int DUMP_PREFERRED = 1 << 12; 17374 public static final int DUMP_PREFERRED_XML = 1 << 13; 17375 public static final int DUMP_KEYSETS = 1 << 14; 17376 public static final int DUMP_VERSION = 1 << 15; 17377 public static final int DUMP_INSTALLS = 1 << 16; 17378 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17379 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17380 17381 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17382 17383 private int mTypes; 17384 17385 private int mOptions; 17386 17387 private boolean mTitlePrinted; 17388 17389 private SharedUserSetting mSharedUser; 17390 17391 public boolean isDumping(int type) { 17392 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17393 return true; 17394 } 17395 17396 return (mTypes & type) != 0; 17397 } 17398 17399 public void setDump(int type) { 17400 mTypes |= type; 17401 } 17402 17403 public boolean isOptionEnabled(int option) { 17404 return (mOptions & option) != 0; 17405 } 17406 17407 public void setOptionEnabled(int option) { 17408 mOptions |= option; 17409 } 17410 17411 public boolean onTitlePrinted() { 17412 final boolean printed = mTitlePrinted; 17413 mTitlePrinted = true; 17414 return printed; 17415 } 17416 17417 public boolean getTitlePrinted() { 17418 return mTitlePrinted; 17419 } 17420 17421 public void setTitlePrinted(boolean enabled) { 17422 mTitlePrinted = enabled; 17423 } 17424 17425 public SharedUserSetting getSharedUser() { 17426 return mSharedUser; 17427 } 17428 17429 public void setSharedUser(SharedUserSetting user) { 17430 mSharedUser = user; 17431 } 17432 } 17433 17434 @Override 17435 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17436 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17437 (new PackageManagerShellCommand(this)).exec( 17438 this, in, out, err, args, resultReceiver); 17439 } 17440 17441 @Override 17442 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17443 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17444 != PackageManager.PERMISSION_GRANTED) { 17445 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17446 + Binder.getCallingPid() 17447 + ", uid=" + Binder.getCallingUid() 17448 + " without permission " 17449 + android.Manifest.permission.DUMP); 17450 return; 17451 } 17452 17453 DumpState dumpState = new DumpState(); 17454 boolean fullPreferred = false; 17455 boolean checkin = false; 17456 17457 String packageName = null; 17458 ArraySet<String> permissionNames = null; 17459 17460 int opti = 0; 17461 while (opti < args.length) { 17462 String opt = args[opti]; 17463 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17464 break; 17465 } 17466 opti++; 17467 17468 if ("-a".equals(opt)) { 17469 // Right now we only know how to print all. 17470 } else if ("-h".equals(opt)) { 17471 pw.println("Package manager dump options:"); 17472 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17473 pw.println(" --checkin: dump for a checkin"); 17474 pw.println(" -f: print details of intent filters"); 17475 pw.println(" -h: print this help"); 17476 pw.println(" cmd may be one of:"); 17477 pw.println(" l[ibraries]: list known shared libraries"); 17478 pw.println(" f[eatures]: list device features"); 17479 pw.println(" k[eysets]: print known keysets"); 17480 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17481 pw.println(" perm[issions]: dump permissions"); 17482 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17483 pw.println(" pref[erred]: print preferred package settings"); 17484 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17485 pw.println(" prov[iders]: dump content providers"); 17486 pw.println(" p[ackages]: dump installed packages"); 17487 pw.println(" s[hared-users]: dump shared user IDs"); 17488 pw.println(" m[essages]: print collected runtime messages"); 17489 pw.println(" v[erifiers]: print package verifier info"); 17490 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17491 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17492 pw.println(" version: print database version info"); 17493 pw.println(" write: write current settings now"); 17494 pw.println(" installs: details about install sessions"); 17495 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17496 pw.println(" <package.name>: info about given package"); 17497 return; 17498 } else if ("--checkin".equals(opt)) { 17499 checkin = true; 17500 } else if ("-f".equals(opt)) { 17501 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17502 } else { 17503 pw.println("Unknown argument: " + opt + "; use -h for help"); 17504 } 17505 } 17506 17507 // Is the caller requesting to dump a particular piece of data? 17508 if (opti < args.length) { 17509 String cmd = args[opti]; 17510 opti++; 17511 // Is this a package name? 17512 if ("android".equals(cmd) || cmd.contains(".")) { 17513 packageName = cmd; 17514 // When dumping a single package, we always dump all of its 17515 // filter information since the amount of data will be reasonable. 17516 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17517 } else if ("check-permission".equals(cmd)) { 17518 if (opti >= args.length) { 17519 pw.println("Error: check-permission missing permission argument"); 17520 return; 17521 } 17522 String perm = args[opti]; 17523 opti++; 17524 if (opti >= args.length) { 17525 pw.println("Error: check-permission missing package argument"); 17526 return; 17527 } 17528 String pkg = args[opti]; 17529 opti++; 17530 int user = UserHandle.getUserId(Binder.getCallingUid()); 17531 if (opti < args.length) { 17532 try { 17533 user = Integer.parseInt(args[opti]); 17534 } catch (NumberFormatException e) { 17535 pw.println("Error: check-permission user argument is not a number: " 17536 + args[opti]); 17537 return; 17538 } 17539 } 17540 pw.println(checkPermission(perm, pkg, user)); 17541 return; 17542 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17543 dumpState.setDump(DumpState.DUMP_LIBS); 17544 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17545 dumpState.setDump(DumpState.DUMP_FEATURES); 17546 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17547 if (opti >= args.length) { 17548 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17549 | DumpState.DUMP_SERVICE_RESOLVERS 17550 | DumpState.DUMP_RECEIVER_RESOLVERS 17551 | DumpState.DUMP_CONTENT_RESOLVERS); 17552 } else { 17553 while (opti < args.length) { 17554 String name = args[opti]; 17555 if ("a".equals(name) || "activity".equals(name)) { 17556 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17557 } else if ("s".equals(name) || "service".equals(name)) { 17558 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17559 } else if ("r".equals(name) || "receiver".equals(name)) { 17560 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17561 } else if ("c".equals(name) || "content".equals(name)) { 17562 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17563 } else { 17564 pw.println("Error: unknown resolver table type: " + name); 17565 return; 17566 } 17567 opti++; 17568 } 17569 } 17570 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17571 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17572 } else if ("permission".equals(cmd)) { 17573 if (opti >= args.length) { 17574 pw.println("Error: permission requires permission name"); 17575 return; 17576 } 17577 permissionNames = new ArraySet<>(); 17578 while (opti < args.length) { 17579 permissionNames.add(args[opti]); 17580 opti++; 17581 } 17582 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17583 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17584 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17585 dumpState.setDump(DumpState.DUMP_PREFERRED); 17586 } else if ("preferred-xml".equals(cmd)) { 17587 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17588 if (opti < args.length && "--full".equals(args[opti])) { 17589 fullPreferred = true; 17590 opti++; 17591 } 17592 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17593 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17594 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17595 dumpState.setDump(DumpState.DUMP_PACKAGES); 17596 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17597 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17598 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17599 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17600 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17601 dumpState.setDump(DumpState.DUMP_MESSAGES); 17602 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17603 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17604 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17605 || "intent-filter-verifiers".equals(cmd)) { 17606 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17607 } else if ("version".equals(cmd)) { 17608 dumpState.setDump(DumpState.DUMP_VERSION); 17609 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17610 dumpState.setDump(DumpState.DUMP_KEYSETS); 17611 } else if ("installs".equals(cmd)) { 17612 dumpState.setDump(DumpState.DUMP_INSTALLS); 17613 } else if ("write".equals(cmd)) { 17614 synchronized (mPackages) { 17615 mSettings.writeLPr(); 17616 pw.println("Settings written."); 17617 return; 17618 } 17619 } 17620 } 17621 17622 if (checkin) { 17623 pw.println("vers,1"); 17624 } 17625 17626 // reader 17627 synchronized (mPackages) { 17628 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17629 if (!checkin) { 17630 if (dumpState.onTitlePrinted()) 17631 pw.println(); 17632 pw.println("Database versions:"); 17633 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17634 } 17635 } 17636 17637 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17638 if (!checkin) { 17639 if (dumpState.onTitlePrinted()) 17640 pw.println(); 17641 pw.println("Verifiers:"); 17642 pw.print(" Required: "); 17643 pw.print(mRequiredVerifierPackage); 17644 pw.print(" (uid="); 17645 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17646 UserHandle.USER_SYSTEM)); 17647 pw.println(")"); 17648 } else if (mRequiredVerifierPackage != null) { 17649 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17650 pw.print(","); 17651 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17652 UserHandle.USER_SYSTEM)); 17653 } 17654 } 17655 17656 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17657 packageName == null) { 17658 if (mIntentFilterVerifierComponent != null) { 17659 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17660 if (!checkin) { 17661 if (dumpState.onTitlePrinted()) 17662 pw.println(); 17663 pw.println("Intent Filter Verifier:"); 17664 pw.print(" Using: "); 17665 pw.print(verifierPackageName); 17666 pw.print(" (uid="); 17667 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17668 UserHandle.USER_SYSTEM)); 17669 pw.println(")"); 17670 } else if (verifierPackageName != null) { 17671 pw.print("ifv,"); pw.print(verifierPackageName); 17672 pw.print(","); 17673 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17674 UserHandle.USER_SYSTEM)); 17675 } 17676 } else { 17677 pw.println(); 17678 pw.println("No Intent Filter Verifier available!"); 17679 } 17680 } 17681 17682 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17683 boolean printedHeader = false; 17684 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17685 while (it.hasNext()) { 17686 String name = it.next(); 17687 SharedLibraryEntry ent = mSharedLibraries.get(name); 17688 if (!checkin) { 17689 if (!printedHeader) { 17690 if (dumpState.onTitlePrinted()) 17691 pw.println(); 17692 pw.println("Libraries:"); 17693 printedHeader = true; 17694 } 17695 pw.print(" "); 17696 } else { 17697 pw.print("lib,"); 17698 } 17699 pw.print(name); 17700 if (!checkin) { 17701 pw.print(" -> "); 17702 } 17703 if (ent.path != null) { 17704 if (!checkin) { 17705 pw.print("(jar) "); 17706 pw.print(ent.path); 17707 } else { 17708 pw.print(",jar,"); 17709 pw.print(ent.path); 17710 } 17711 } else { 17712 if (!checkin) { 17713 pw.print("(apk) "); 17714 pw.print(ent.apk); 17715 } else { 17716 pw.print(",apk,"); 17717 pw.print(ent.apk); 17718 } 17719 } 17720 pw.println(); 17721 } 17722 } 17723 17724 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17725 if (dumpState.onTitlePrinted()) 17726 pw.println(); 17727 if (!checkin) { 17728 pw.println("Features:"); 17729 } 17730 17731 for (FeatureInfo feat : mAvailableFeatures.values()) { 17732 if (checkin) { 17733 pw.print("feat,"); 17734 pw.print(feat.name); 17735 pw.print(","); 17736 pw.println(feat.version); 17737 } else { 17738 pw.print(" "); 17739 pw.print(feat.name); 17740 if (feat.version > 0) { 17741 pw.print(" version="); 17742 pw.print(feat.version); 17743 } 17744 pw.println(); 17745 } 17746 } 17747 } 17748 17749 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17750 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17751 : "Activity Resolver Table:", " ", packageName, 17752 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17753 dumpState.setTitlePrinted(true); 17754 } 17755 } 17756 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17757 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17758 : "Receiver Resolver Table:", " ", packageName, 17759 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17760 dumpState.setTitlePrinted(true); 17761 } 17762 } 17763 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17764 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17765 : "Service Resolver Table:", " ", packageName, 17766 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17767 dumpState.setTitlePrinted(true); 17768 } 17769 } 17770 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17771 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17772 : "Provider Resolver Table:", " ", packageName, 17773 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17774 dumpState.setTitlePrinted(true); 17775 } 17776 } 17777 17778 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17779 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17780 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17781 int user = mSettings.mPreferredActivities.keyAt(i); 17782 if (pir.dump(pw, 17783 dumpState.getTitlePrinted() 17784 ? "\nPreferred Activities User " + user + ":" 17785 : "Preferred Activities User " + user + ":", " ", 17786 packageName, true, false)) { 17787 dumpState.setTitlePrinted(true); 17788 } 17789 } 17790 } 17791 17792 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17793 pw.flush(); 17794 FileOutputStream fout = new FileOutputStream(fd); 17795 BufferedOutputStream str = new BufferedOutputStream(fout); 17796 XmlSerializer serializer = new FastXmlSerializer(); 17797 try { 17798 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17799 serializer.startDocument(null, true); 17800 serializer.setFeature( 17801 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17802 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17803 serializer.endDocument(); 17804 serializer.flush(); 17805 } catch (IllegalArgumentException e) { 17806 pw.println("Failed writing: " + e); 17807 } catch (IllegalStateException e) { 17808 pw.println("Failed writing: " + e); 17809 } catch (IOException e) { 17810 pw.println("Failed writing: " + e); 17811 } 17812 } 17813 17814 if (!checkin 17815 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17816 && packageName == null) { 17817 pw.println(); 17818 int count = mSettings.mPackages.size(); 17819 if (count == 0) { 17820 pw.println("No applications!"); 17821 pw.println(); 17822 } else { 17823 final String prefix = " "; 17824 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17825 if (allPackageSettings.size() == 0) { 17826 pw.println("No domain preferred apps!"); 17827 pw.println(); 17828 } else { 17829 pw.println("App verification status:"); 17830 pw.println(); 17831 count = 0; 17832 for (PackageSetting ps : allPackageSettings) { 17833 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17834 if (ivi == null || ivi.getPackageName() == null) continue; 17835 pw.println(prefix + "Package: " + ivi.getPackageName()); 17836 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17837 pw.println(prefix + "Status: " + ivi.getStatusString()); 17838 pw.println(); 17839 count++; 17840 } 17841 if (count == 0) { 17842 pw.println(prefix + "No app verification established."); 17843 pw.println(); 17844 } 17845 for (int userId : sUserManager.getUserIds()) { 17846 pw.println("App linkages for user " + userId + ":"); 17847 pw.println(); 17848 count = 0; 17849 for (PackageSetting ps : allPackageSettings) { 17850 final long status = ps.getDomainVerificationStatusForUser(userId); 17851 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17852 continue; 17853 } 17854 pw.println(prefix + "Package: " + ps.name); 17855 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17856 String statusStr = IntentFilterVerificationInfo. 17857 getStatusStringFromValue(status); 17858 pw.println(prefix + "Status: " + statusStr); 17859 pw.println(); 17860 count++; 17861 } 17862 if (count == 0) { 17863 pw.println(prefix + "No configured app linkages."); 17864 pw.println(); 17865 } 17866 } 17867 } 17868 } 17869 } 17870 17871 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17872 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17873 if (packageName == null && permissionNames == null) { 17874 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17875 if (iperm == 0) { 17876 if (dumpState.onTitlePrinted()) 17877 pw.println(); 17878 pw.println("AppOp Permissions:"); 17879 } 17880 pw.print(" AppOp Permission "); 17881 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17882 pw.println(":"); 17883 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17884 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17885 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17886 } 17887 } 17888 } 17889 } 17890 17891 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17892 boolean printedSomething = false; 17893 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17894 if (packageName != null && !packageName.equals(p.info.packageName)) { 17895 continue; 17896 } 17897 if (!printedSomething) { 17898 if (dumpState.onTitlePrinted()) 17899 pw.println(); 17900 pw.println("Registered ContentProviders:"); 17901 printedSomething = true; 17902 } 17903 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17904 pw.print(" "); pw.println(p.toString()); 17905 } 17906 printedSomething = false; 17907 for (Map.Entry<String, PackageParser.Provider> entry : 17908 mProvidersByAuthority.entrySet()) { 17909 PackageParser.Provider p = entry.getValue(); 17910 if (packageName != null && !packageName.equals(p.info.packageName)) { 17911 continue; 17912 } 17913 if (!printedSomething) { 17914 if (dumpState.onTitlePrinted()) 17915 pw.println(); 17916 pw.println("ContentProvider Authorities:"); 17917 printedSomething = true; 17918 } 17919 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17920 pw.print(" "); pw.println(p.toString()); 17921 if (p.info != null && p.info.applicationInfo != null) { 17922 final String appInfo = p.info.applicationInfo.toString(); 17923 pw.print(" applicationInfo="); pw.println(appInfo); 17924 } 17925 } 17926 } 17927 17928 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17929 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17930 } 17931 17932 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17933 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17934 } 17935 17936 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17937 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17938 } 17939 17940 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17941 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17942 } 17943 17944 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17945 // XXX should handle packageName != null by dumping only install data that 17946 // the given package is involved with. 17947 if (dumpState.onTitlePrinted()) pw.println(); 17948 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17949 } 17950 17951 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17952 if (dumpState.onTitlePrinted()) pw.println(); 17953 mSettings.dumpReadMessagesLPr(pw, dumpState); 17954 17955 pw.println(); 17956 pw.println("Package warning messages:"); 17957 BufferedReader in = null; 17958 String line = null; 17959 try { 17960 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17961 while ((line = in.readLine()) != null) { 17962 if (line.contains("ignored: updated version")) continue; 17963 pw.println(line); 17964 } 17965 } catch (IOException ignored) { 17966 } finally { 17967 IoUtils.closeQuietly(in); 17968 } 17969 } 17970 17971 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17972 BufferedReader in = null; 17973 String line = null; 17974 try { 17975 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17976 while ((line = in.readLine()) != null) { 17977 if (line.contains("ignored: updated version")) continue; 17978 pw.print("msg,"); 17979 pw.println(line); 17980 } 17981 } catch (IOException ignored) { 17982 } finally { 17983 IoUtils.closeQuietly(in); 17984 } 17985 } 17986 } 17987 } 17988 17989 private String dumpDomainString(String packageName) { 17990 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17991 .getList(); 17992 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17993 17994 ArraySet<String> result = new ArraySet<>(); 17995 if (iviList.size() > 0) { 17996 for (IntentFilterVerificationInfo ivi : iviList) { 17997 for (String host : ivi.getDomains()) { 17998 result.add(host); 17999 } 18000 } 18001 } 18002 if (filters != null && filters.size() > 0) { 18003 for (IntentFilter filter : filters) { 18004 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18005 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18006 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18007 result.addAll(filter.getHostsList()); 18008 } 18009 } 18010 } 18011 18012 StringBuilder sb = new StringBuilder(result.size() * 16); 18013 for (String domain : result) { 18014 if (sb.length() > 0) sb.append(" "); 18015 sb.append(domain); 18016 } 18017 return sb.toString(); 18018 } 18019 18020 // ------- apps on sdcard specific code ------- 18021 static final boolean DEBUG_SD_INSTALL = false; 18022 18023 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18024 18025 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18026 18027 private boolean mMediaMounted = false; 18028 18029 static String getEncryptKey() { 18030 try { 18031 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18032 SD_ENCRYPTION_KEYSTORE_NAME); 18033 if (sdEncKey == null) { 18034 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18035 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18036 if (sdEncKey == null) { 18037 Slog.e(TAG, "Failed to create encryption keys"); 18038 return null; 18039 } 18040 } 18041 return sdEncKey; 18042 } catch (NoSuchAlgorithmException nsae) { 18043 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18044 return null; 18045 } catch (IOException ioe) { 18046 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18047 return null; 18048 } 18049 } 18050 18051 /* 18052 * Update media status on PackageManager. 18053 */ 18054 @Override 18055 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18056 int callingUid = Binder.getCallingUid(); 18057 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18058 throw new SecurityException("Media status can only be updated by the system"); 18059 } 18060 // reader; this apparently protects mMediaMounted, but should probably 18061 // be a different lock in that case. 18062 synchronized (mPackages) { 18063 Log.i(TAG, "Updating external media status from " 18064 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18065 + (mediaStatus ? "mounted" : "unmounted")); 18066 if (DEBUG_SD_INSTALL) 18067 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18068 + ", mMediaMounted=" + mMediaMounted); 18069 if (mediaStatus == mMediaMounted) { 18070 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18071 : 0, -1); 18072 mHandler.sendMessage(msg); 18073 return; 18074 } 18075 mMediaMounted = mediaStatus; 18076 } 18077 // Queue up an async operation since the package installation may take a 18078 // little while. 18079 mHandler.post(new Runnable() { 18080 public void run() { 18081 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18082 } 18083 }); 18084 } 18085 18086 /** 18087 * Called by MountService when the initial ASECs to scan are available. 18088 * Should block until all the ASEC containers are finished being scanned. 18089 */ 18090 public void scanAvailableAsecs() { 18091 updateExternalMediaStatusInner(true, false, false); 18092 } 18093 18094 /* 18095 * Collect information of applications on external media, map them against 18096 * existing containers and update information based on current mount status. 18097 * Please note that we always have to report status if reportStatus has been 18098 * set to true especially when unloading packages. 18099 */ 18100 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18101 boolean externalStorage) { 18102 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18103 int[] uidArr = EmptyArray.INT; 18104 18105 final String[] list = PackageHelper.getSecureContainerList(); 18106 if (ArrayUtils.isEmpty(list)) { 18107 Log.i(TAG, "No secure containers found"); 18108 } else { 18109 // Process list of secure containers and categorize them 18110 // as active or stale based on their package internal state. 18111 18112 // reader 18113 synchronized (mPackages) { 18114 for (String cid : list) { 18115 // Leave stages untouched for now; installer service owns them 18116 if (PackageInstallerService.isStageName(cid)) continue; 18117 18118 if (DEBUG_SD_INSTALL) 18119 Log.i(TAG, "Processing container " + cid); 18120 String pkgName = getAsecPackageName(cid); 18121 if (pkgName == null) { 18122 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18123 continue; 18124 } 18125 if (DEBUG_SD_INSTALL) 18126 Log.i(TAG, "Looking for pkg : " + pkgName); 18127 18128 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18129 if (ps == null) { 18130 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18131 continue; 18132 } 18133 18134 /* 18135 * Skip packages that are not external if we're unmounting 18136 * external storage. 18137 */ 18138 if (externalStorage && !isMounted && !isExternal(ps)) { 18139 continue; 18140 } 18141 18142 final AsecInstallArgs args = new AsecInstallArgs(cid, 18143 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18144 // The package status is changed only if the code path 18145 // matches between settings and the container id. 18146 if (ps.codePathString != null 18147 && ps.codePathString.startsWith(args.getCodePath())) { 18148 if (DEBUG_SD_INSTALL) { 18149 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18150 + " at code path: " + ps.codePathString); 18151 } 18152 18153 // We do have a valid package installed on sdcard 18154 processCids.put(args, ps.codePathString); 18155 final int uid = ps.appId; 18156 if (uid != -1) { 18157 uidArr = ArrayUtils.appendInt(uidArr, uid); 18158 } 18159 } else { 18160 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18161 + ps.codePathString); 18162 } 18163 } 18164 } 18165 18166 Arrays.sort(uidArr); 18167 } 18168 18169 // Process packages with valid entries. 18170 if (isMounted) { 18171 if (DEBUG_SD_INSTALL) 18172 Log.i(TAG, "Loading packages"); 18173 loadMediaPackages(processCids, uidArr, externalStorage); 18174 startCleaningPackages(); 18175 mInstallerService.onSecureContainersAvailable(); 18176 } else { 18177 if (DEBUG_SD_INSTALL) 18178 Log.i(TAG, "Unloading packages"); 18179 unloadMediaPackages(processCids, uidArr, reportStatus); 18180 } 18181 } 18182 18183 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18184 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18185 final int size = infos.size(); 18186 final String[] packageNames = new String[size]; 18187 final int[] packageUids = new int[size]; 18188 for (int i = 0; i < size; i++) { 18189 final ApplicationInfo info = infos.get(i); 18190 packageNames[i] = info.packageName; 18191 packageUids[i] = info.uid; 18192 } 18193 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18194 finishedReceiver); 18195 } 18196 18197 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18198 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18199 sendResourcesChangedBroadcast(mediaStatus, replacing, 18200 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18201 } 18202 18203 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18204 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18205 int size = pkgList.length; 18206 if (size > 0) { 18207 // Send broadcasts here 18208 Bundle extras = new Bundle(); 18209 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18210 if (uidArr != null) { 18211 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18212 } 18213 if (replacing) { 18214 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18215 } 18216 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18217 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18218 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18219 } 18220 } 18221 18222 /* 18223 * Look at potentially valid container ids from processCids If package 18224 * information doesn't match the one on record or package scanning fails, 18225 * the cid is added to list of removeCids. We currently don't delete stale 18226 * containers. 18227 */ 18228 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18229 boolean externalStorage) { 18230 ArrayList<String> pkgList = new ArrayList<String>(); 18231 Set<AsecInstallArgs> keys = processCids.keySet(); 18232 18233 for (AsecInstallArgs args : keys) { 18234 String codePath = processCids.get(args); 18235 if (DEBUG_SD_INSTALL) 18236 Log.i(TAG, "Loading container : " + args.cid); 18237 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18238 try { 18239 // Make sure there are no container errors first. 18240 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18241 Slog.e(TAG, "Failed to mount cid : " + args.cid 18242 + " when installing from sdcard"); 18243 continue; 18244 } 18245 // Check code path here. 18246 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18247 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18248 + " does not match one in settings " + codePath); 18249 continue; 18250 } 18251 // Parse package 18252 int parseFlags = mDefParseFlags; 18253 if (args.isExternalAsec()) { 18254 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18255 } 18256 if (args.isFwdLocked()) { 18257 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18258 } 18259 18260 synchronized (mInstallLock) { 18261 PackageParser.Package pkg = null; 18262 try { 18263 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18264 } catch (PackageManagerException e) { 18265 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18266 } 18267 // Scan the package 18268 if (pkg != null) { 18269 /* 18270 * TODO why is the lock being held? doPostInstall is 18271 * called in other places without the lock. This needs 18272 * to be straightened out. 18273 */ 18274 // writer 18275 synchronized (mPackages) { 18276 retCode = PackageManager.INSTALL_SUCCEEDED; 18277 pkgList.add(pkg.packageName); 18278 // Post process args 18279 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18280 pkg.applicationInfo.uid); 18281 } 18282 } else { 18283 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18284 } 18285 } 18286 18287 } finally { 18288 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18289 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18290 } 18291 } 18292 } 18293 // writer 18294 synchronized (mPackages) { 18295 // If the platform SDK has changed since the last time we booted, 18296 // we need to re-grant app permission to catch any new ones that 18297 // appear. This is really a hack, and means that apps can in some 18298 // cases get permissions that the user didn't initially explicitly 18299 // allow... it would be nice to have some better way to handle 18300 // this situation. 18301 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18302 : mSettings.getInternalVersion(); 18303 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18304 : StorageManager.UUID_PRIVATE_INTERNAL; 18305 18306 int updateFlags = UPDATE_PERMISSIONS_ALL; 18307 if (ver.sdkVersion != mSdkVersion) { 18308 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18309 + mSdkVersion + "; regranting permissions for external"); 18310 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18311 } 18312 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18313 18314 // Yay, everything is now upgraded 18315 ver.forceCurrent(); 18316 18317 // can downgrade to reader 18318 // Persist settings 18319 mSettings.writeLPr(); 18320 } 18321 // Send a broadcast to let everyone know we are done processing 18322 if (pkgList.size() > 0) { 18323 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18324 } 18325 } 18326 18327 /* 18328 * Utility method to unload a list of specified containers 18329 */ 18330 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18331 // Just unmount all valid containers. 18332 for (AsecInstallArgs arg : cidArgs) { 18333 synchronized (mInstallLock) { 18334 arg.doPostDeleteLI(false); 18335 } 18336 } 18337 } 18338 18339 /* 18340 * Unload packages mounted on external media. This involves deleting package 18341 * data from internal structures, sending broadcasts about disabled packages, 18342 * gc'ing to free up references, unmounting all secure containers 18343 * corresponding to packages on external media, and posting a 18344 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18345 * that we always have to post this message if status has been requested no 18346 * matter what. 18347 */ 18348 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18349 final boolean reportStatus) { 18350 if (DEBUG_SD_INSTALL) 18351 Log.i(TAG, "unloading media packages"); 18352 ArrayList<String> pkgList = new ArrayList<String>(); 18353 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18354 final Set<AsecInstallArgs> keys = processCids.keySet(); 18355 for (AsecInstallArgs args : keys) { 18356 String pkgName = args.getPackageName(); 18357 if (DEBUG_SD_INSTALL) 18358 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18359 // Delete package internally 18360 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18361 synchronized (mInstallLock) { 18362 boolean res = deletePackageLI(pkgName, null, false, null, 18363 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18364 if (res) { 18365 pkgList.add(pkgName); 18366 } else { 18367 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18368 failedList.add(args); 18369 } 18370 } 18371 } 18372 18373 // reader 18374 synchronized (mPackages) { 18375 // We didn't update the settings after removing each package; 18376 // write them now for all packages. 18377 mSettings.writeLPr(); 18378 } 18379 18380 // We have to absolutely send UPDATED_MEDIA_STATUS only 18381 // after confirming that all the receivers processed the ordered 18382 // broadcast when packages get disabled, force a gc to clean things up. 18383 // and unload all the containers. 18384 if (pkgList.size() > 0) { 18385 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18386 new IIntentReceiver.Stub() { 18387 public void performReceive(Intent intent, int resultCode, String data, 18388 Bundle extras, boolean ordered, boolean sticky, 18389 int sendingUser) throws RemoteException { 18390 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18391 reportStatus ? 1 : 0, 1, keys); 18392 mHandler.sendMessage(msg); 18393 } 18394 }); 18395 } else { 18396 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18397 keys); 18398 mHandler.sendMessage(msg); 18399 } 18400 } 18401 18402 private void loadPrivatePackages(final VolumeInfo vol) { 18403 mHandler.post(new Runnable() { 18404 @Override 18405 public void run() { 18406 loadPrivatePackagesInner(vol); 18407 } 18408 }); 18409 } 18410 18411 private void loadPrivatePackagesInner(VolumeInfo vol) { 18412 final String volumeUuid = vol.fsUuid; 18413 if (TextUtils.isEmpty(volumeUuid)) { 18414 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18415 return; 18416 } 18417 18418 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18419 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18420 18421 final VersionInfo ver; 18422 final List<PackageSetting> packages; 18423 synchronized (mPackages) { 18424 ver = mSettings.findOrCreateVersion(volumeUuid); 18425 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18426 } 18427 18428 // TODO: introduce a new concept similar to "frozen" to prevent these 18429 // apps from being launched until after data has been fully reconciled 18430 for (PackageSetting ps : packages) { 18431 synchronized (mInstallLock) { 18432 final PackageParser.Package pkg; 18433 try { 18434 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18435 loaded.add(pkg.applicationInfo); 18436 18437 } catch (PackageManagerException e) { 18438 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18439 } 18440 18441 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18442 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18443 } 18444 } 18445 } 18446 18447 // Reconcile app data for all started/unlocked users 18448 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18449 final UserManager um = mContext.getSystemService(UserManager.class); 18450 for (UserInfo user : um.getUsers()) { 18451 final int flags; 18452 if (um.isUserUnlocked(user.id)) { 18453 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18454 } else if (um.isUserRunning(user.id)) { 18455 flags = StorageManager.FLAG_STORAGE_DE; 18456 } else { 18457 continue; 18458 } 18459 18460 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18461 reconcileAppsData(volumeUuid, user.id, flags); 18462 } 18463 18464 synchronized (mPackages) { 18465 int updateFlags = UPDATE_PERMISSIONS_ALL; 18466 if (ver.sdkVersion != mSdkVersion) { 18467 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18468 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18469 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18470 } 18471 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18472 18473 // Yay, everything is now upgraded 18474 ver.forceCurrent(); 18475 18476 mSettings.writeLPr(); 18477 } 18478 18479 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18480 sendResourcesChangedBroadcast(true, false, loaded, null); 18481 } 18482 18483 private void unloadPrivatePackages(final VolumeInfo vol) { 18484 mHandler.post(new Runnable() { 18485 @Override 18486 public void run() { 18487 unloadPrivatePackagesInner(vol); 18488 } 18489 }); 18490 } 18491 18492 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18493 final String volumeUuid = vol.fsUuid; 18494 if (TextUtils.isEmpty(volumeUuid)) { 18495 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18496 return; 18497 } 18498 18499 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18500 synchronized (mInstallLock) { 18501 synchronized (mPackages) { 18502 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18503 for (PackageSetting ps : packages) { 18504 if (ps.pkg == null) continue; 18505 18506 final ApplicationInfo info = ps.pkg.applicationInfo; 18507 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18508 if (deletePackageLI(ps.name, null, false, null, 18509 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18510 unloaded.add(info); 18511 } else { 18512 Slog.w(TAG, "Failed to unload " + ps.codePath); 18513 } 18514 } 18515 18516 mSettings.writeLPr(); 18517 } 18518 } 18519 18520 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18521 sendResourcesChangedBroadcast(false, false, unloaded, null); 18522 } 18523 18524 /** 18525 * Examine all users present on given mounted volume, and destroy data 18526 * belonging to users that are no longer valid, or whose user ID has been 18527 * recycled. 18528 */ 18529 private void reconcileUsers(String volumeUuid) { 18530 // TODO: also reconcile DE directories 18531 final File[] files = FileUtils 18532 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18533 for (File file : files) { 18534 if (!file.isDirectory()) continue; 18535 18536 final int userId; 18537 final UserInfo info; 18538 try { 18539 userId = Integer.parseInt(file.getName()); 18540 info = sUserManager.getUserInfo(userId); 18541 } catch (NumberFormatException e) { 18542 Slog.w(TAG, "Invalid user directory " + file); 18543 continue; 18544 } 18545 18546 boolean destroyUser = false; 18547 if (info == null) { 18548 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18549 + " because no matching user was found"); 18550 destroyUser = true; 18551 } else { 18552 try { 18553 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18554 } catch (IOException e) { 18555 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18556 + " because we failed to enforce serial number: " + e); 18557 destroyUser = true; 18558 } 18559 } 18560 18561 if (destroyUser) { 18562 synchronized (mInstallLock) { 18563 try { 18564 mInstaller.removeUserDataDirs(volumeUuid, userId); 18565 } catch (InstallerException e) { 18566 Slog.w(TAG, "Failed to clean up user dirs", e); 18567 } 18568 } 18569 } 18570 } 18571 } 18572 18573 private void assertPackageKnown(String volumeUuid, String packageName) 18574 throws PackageManagerException { 18575 synchronized (mPackages) { 18576 final PackageSetting ps = mSettings.mPackages.get(packageName); 18577 if (ps == null) { 18578 throw new PackageManagerException("Package " + packageName + " is unknown"); 18579 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18580 throw new PackageManagerException( 18581 "Package " + packageName + " found on unknown volume " + volumeUuid 18582 + "; expected volume " + ps.volumeUuid); 18583 } 18584 } 18585 } 18586 18587 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18588 throws PackageManagerException { 18589 synchronized (mPackages) { 18590 final PackageSetting ps = mSettings.mPackages.get(packageName); 18591 if (ps == null) { 18592 throw new PackageManagerException("Package " + packageName + " is unknown"); 18593 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18594 throw new PackageManagerException( 18595 "Package " + packageName + " found on unknown volume " + volumeUuid 18596 + "; expected volume " + ps.volumeUuid); 18597 } else if (!ps.getInstalled(userId)) { 18598 throw new PackageManagerException( 18599 "Package " + packageName + " not installed for user " + userId); 18600 } 18601 } 18602 } 18603 18604 /** 18605 * Examine all apps present on given mounted volume, and destroy apps that 18606 * aren't expected, either due to uninstallation or reinstallation on 18607 * another volume. 18608 */ 18609 private void reconcileApps(String volumeUuid) { 18610 final File[] files = FileUtils 18611 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18612 for (File file : files) { 18613 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18614 && !PackageInstallerService.isStageName(file.getName()); 18615 if (!isPackage) { 18616 // Ignore entries which are not packages 18617 continue; 18618 } 18619 18620 try { 18621 final PackageLite pkg = PackageParser.parsePackageLite(file, 18622 PackageParser.PARSE_MUST_BE_APK); 18623 assertPackageKnown(volumeUuid, pkg.packageName); 18624 18625 } catch (PackageParserException | PackageManagerException e) { 18626 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18627 synchronized (mInstallLock) { 18628 removeCodePathLI(file); 18629 } 18630 } 18631 } 18632 } 18633 18634 /** 18635 * Reconcile all app data for the given user. 18636 * <p> 18637 * Verifies that directories exist and that ownership and labeling is 18638 * correct for all installed apps on all mounted volumes. 18639 */ 18640 void reconcileAppsData(int userId, int flags) { 18641 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18642 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18643 final String volumeUuid = vol.getFsUuid(); 18644 reconcileAppsData(volumeUuid, userId, flags); 18645 } 18646 } 18647 18648 /** 18649 * Reconcile all app data on given mounted volume. 18650 * <p> 18651 * Destroys app data that isn't expected, either due to uninstallation or 18652 * reinstallation on another volume. 18653 * <p> 18654 * Verifies that directories exist and that ownership and labeling is 18655 * correct for all installed apps. 18656 */ 18657 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18658 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18659 + Integer.toHexString(flags)); 18660 18661 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18662 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18663 18664 boolean restoreconNeeded = false; 18665 18666 // First look for stale data that doesn't belong, and check if things 18667 // have changed since we did our last restorecon 18668 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18669 if (!isUserKeyUnlocked(userId)) { 18670 throw new RuntimeException( 18671 "Yikes, someone asked us to reconcile CE storage while " + userId 18672 + " was still locked; this would have caused massive data loss!"); 18673 } 18674 18675 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18676 18677 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18678 for (File file : files) { 18679 final String packageName = file.getName(); 18680 try { 18681 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18682 } catch (PackageManagerException e) { 18683 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18684 synchronized (mInstallLock) { 18685 destroyAppDataLI(volumeUuid, packageName, userId, 18686 StorageManager.FLAG_STORAGE_CE); 18687 } 18688 } 18689 } 18690 } 18691 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18692 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18693 18694 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18695 for (File file : files) { 18696 final String packageName = file.getName(); 18697 try { 18698 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18699 } catch (PackageManagerException e) { 18700 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18701 synchronized (mInstallLock) { 18702 destroyAppDataLI(volumeUuid, packageName, userId, 18703 StorageManager.FLAG_STORAGE_DE); 18704 } 18705 } 18706 } 18707 } 18708 18709 // Ensure that data directories are ready to roll for all packages 18710 // installed for this volume and user 18711 final List<PackageSetting> packages; 18712 synchronized (mPackages) { 18713 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18714 } 18715 int preparedCount = 0; 18716 for (PackageSetting ps : packages) { 18717 final String packageName = ps.name; 18718 if (ps.pkg == null) { 18719 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18720 // TODO: might be due to legacy ASEC apps; we should circle back 18721 // and reconcile again once they're scanned 18722 continue; 18723 } 18724 18725 if (ps.getInstalled(userId)) { 18726 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18727 18728 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18729 // We may have just shuffled around app data directories, so 18730 // prepare them one more time 18731 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18732 } 18733 18734 preparedCount++; 18735 } 18736 } 18737 18738 if (restoreconNeeded) { 18739 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18740 SELinuxMMAC.setRestoreconDone(ceDir); 18741 } 18742 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18743 SELinuxMMAC.setRestoreconDone(deDir); 18744 } 18745 } 18746 18747 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18748 + " packages; restoreconNeeded was " + restoreconNeeded); 18749 } 18750 18751 /** 18752 * Prepare app data for the given app just after it was installed or 18753 * upgraded. This method carefully only touches users that it's installed 18754 * for, and it forces a restorecon to handle any seinfo changes. 18755 * <p> 18756 * Verifies that directories exist and that ownership and labeling is 18757 * correct for all installed apps. If there is an ownership mismatch, it 18758 * will try recovering system apps by wiping data; third-party app data is 18759 * left intact. 18760 * <p> 18761 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18762 */ 18763 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18764 prepareAppDataAfterInstallInternal(pkg); 18765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18766 for (int i = 0; i < childCount; i++) { 18767 PackageParser.Package childPackage = pkg.childPackages.get(i); 18768 prepareAppDataAfterInstallInternal(childPackage); 18769 } 18770 } 18771 18772 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18773 final PackageSetting ps; 18774 synchronized (mPackages) { 18775 ps = mSettings.mPackages.get(pkg.packageName); 18776 mSettings.writeKernelMappingLPr(ps); 18777 } 18778 18779 final UserManager um = mContext.getSystemService(UserManager.class); 18780 for (UserInfo user : um.getUsers()) { 18781 final int flags; 18782 if (um.isUserUnlocked(user.id)) { 18783 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18784 } else if (um.isUserRunning(user.id)) { 18785 flags = StorageManager.FLAG_STORAGE_DE; 18786 } else { 18787 continue; 18788 } 18789 18790 if (ps.getInstalled(user.id)) { 18791 // Whenever an app changes, force a restorecon of its data 18792 // TODO: when user data is locked, mark that we're still dirty 18793 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18794 } 18795 } 18796 } 18797 18798 /** 18799 * Prepare app data for the given app. 18800 * <p> 18801 * Verifies that directories exist and that ownership and labeling is 18802 * correct for all installed apps. If there is an ownership mismatch, this 18803 * will try recovering system apps by wiping data; third-party app data is 18804 * left intact. 18805 */ 18806 private void prepareAppData(String volumeUuid, int userId, int flags, 18807 PackageParser.Package pkg, boolean restoreconNeeded) { 18808 if (DEBUG_APP_DATA) { 18809 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18810 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18811 } 18812 18813 final String packageName = pkg.packageName; 18814 final ApplicationInfo app = pkg.applicationInfo; 18815 final int appId = UserHandle.getAppId(app.uid); 18816 18817 Preconditions.checkNotNull(app.seinfo); 18818 18819 synchronized (mInstallLock) { 18820 try { 18821 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18822 appId, app.seinfo, app.targetSdkVersion); 18823 } catch (InstallerException e) { 18824 if (app.isSystemApp()) { 18825 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18826 + ", but trying to recover: " + e); 18827 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18828 try { 18829 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18830 appId, app.seinfo, app.targetSdkVersion); 18831 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18832 } catch (InstallerException e2) { 18833 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18834 } 18835 } else { 18836 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18837 } 18838 } 18839 18840 if (restoreconNeeded) { 18841 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18842 } 18843 18844 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18845 // Create a native library symlink only if we have native libraries 18846 // and if the native libraries are 32 bit libraries. We do not provide 18847 // this symlink for 64 bit libraries. 18848 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18849 final String nativeLibPath = app.nativeLibraryDir; 18850 try { 18851 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18852 nativeLibPath, userId); 18853 } catch (InstallerException e) { 18854 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18855 } 18856 } 18857 } 18858 } 18859 } 18860 18861 /** 18862 * For system apps on non-FBE devices, this method migrates any existing 18863 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18864 * requested by the app. 18865 */ 18866 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18867 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18868 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18869 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18870 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18871 synchronized (mInstallLock) { 18872 try { 18873 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18874 } catch (InstallerException e) { 18875 logCriticalInfo(Log.WARN, 18876 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18877 } 18878 } 18879 return true; 18880 } else { 18881 return false; 18882 } 18883 } 18884 18885 private void unfreezePackage(String packageName) { 18886 synchronized (mPackages) { 18887 final PackageSetting ps = mSettings.mPackages.get(packageName); 18888 if (ps != null) { 18889 ps.frozen = false; 18890 } 18891 } 18892 } 18893 18894 @Override 18895 public int movePackage(final String packageName, final String volumeUuid) { 18896 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18897 18898 final int moveId = mNextMoveId.getAndIncrement(); 18899 mHandler.post(new Runnable() { 18900 @Override 18901 public void run() { 18902 try { 18903 movePackageInternal(packageName, volumeUuid, moveId); 18904 } catch (PackageManagerException e) { 18905 Slog.w(TAG, "Failed to move " + packageName, e); 18906 mMoveCallbacks.notifyStatusChanged(moveId, 18907 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18908 } 18909 } 18910 }); 18911 return moveId; 18912 } 18913 18914 private void movePackageInternal(final String packageName, final String volumeUuid, 18915 final int moveId) throws PackageManagerException { 18916 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18917 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18918 final PackageManager pm = mContext.getPackageManager(); 18919 18920 final boolean currentAsec; 18921 final String currentVolumeUuid; 18922 final File codeFile; 18923 final String installerPackageName; 18924 final String packageAbiOverride; 18925 final int appId; 18926 final String seinfo; 18927 final String label; 18928 final int targetSdkVersion; 18929 18930 // reader 18931 synchronized (mPackages) { 18932 final PackageParser.Package pkg = mPackages.get(packageName); 18933 final PackageSetting ps = mSettings.mPackages.get(packageName); 18934 if (pkg == null || ps == null) { 18935 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18936 } 18937 18938 if (pkg.applicationInfo.isSystemApp()) { 18939 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18940 "Cannot move system application"); 18941 } 18942 18943 if (pkg.applicationInfo.isExternalAsec()) { 18944 currentAsec = true; 18945 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18946 } else if (pkg.applicationInfo.isForwardLocked()) { 18947 currentAsec = true; 18948 currentVolumeUuid = "forward_locked"; 18949 } else { 18950 currentAsec = false; 18951 currentVolumeUuid = ps.volumeUuid; 18952 18953 final File probe = new File(pkg.codePath); 18954 final File probeOat = new File(probe, "oat"); 18955 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18956 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18957 "Move only supported for modern cluster style installs"); 18958 } 18959 } 18960 18961 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18962 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18963 "Package already moved to " + volumeUuid); 18964 } 18965 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18966 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18967 "Device admin cannot be moved"); 18968 } 18969 18970 if (ps.frozen) { 18971 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18972 "Failed to move already frozen package"); 18973 } 18974 ps.frozen = true; 18975 18976 codeFile = new File(pkg.codePath); 18977 installerPackageName = ps.installerPackageName; 18978 packageAbiOverride = ps.cpuAbiOverrideString; 18979 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18980 seinfo = pkg.applicationInfo.seinfo; 18981 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18982 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18983 } 18984 18985 // Now that we're guarded by frozen state, kill app during move 18986 final long token = Binder.clearCallingIdentity(); 18987 try { 18988 killApplication(packageName, appId, "move pkg"); 18989 } finally { 18990 Binder.restoreCallingIdentity(token); 18991 } 18992 18993 final Bundle extras = new Bundle(); 18994 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18995 extras.putString(Intent.EXTRA_TITLE, label); 18996 mMoveCallbacks.notifyCreated(moveId, extras); 18997 18998 int installFlags; 18999 final boolean moveCompleteApp; 19000 final File measurePath; 19001 19002 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19003 installFlags = INSTALL_INTERNAL; 19004 moveCompleteApp = !currentAsec; 19005 measurePath = Environment.getDataAppDirectory(volumeUuid); 19006 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19007 installFlags = INSTALL_EXTERNAL; 19008 moveCompleteApp = false; 19009 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19010 } else { 19011 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19012 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19013 || !volume.isMountedWritable()) { 19014 unfreezePackage(packageName); 19015 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19016 "Move location not mounted private volume"); 19017 } 19018 19019 Preconditions.checkState(!currentAsec); 19020 19021 installFlags = INSTALL_INTERNAL; 19022 moveCompleteApp = true; 19023 measurePath = Environment.getDataAppDirectory(volumeUuid); 19024 } 19025 19026 final PackageStats stats = new PackageStats(null, -1); 19027 synchronized (mInstaller) { 19028 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19029 unfreezePackage(packageName); 19030 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19031 "Failed to measure package size"); 19032 } 19033 } 19034 19035 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19036 + stats.dataSize); 19037 19038 final long startFreeBytes = measurePath.getFreeSpace(); 19039 final long sizeBytes; 19040 if (moveCompleteApp) { 19041 sizeBytes = stats.codeSize + stats.dataSize; 19042 } else { 19043 sizeBytes = stats.codeSize; 19044 } 19045 19046 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19047 unfreezePackage(packageName); 19048 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19049 "Not enough free space to move"); 19050 } 19051 19052 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19053 19054 final CountDownLatch installedLatch = new CountDownLatch(1); 19055 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19056 @Override 19057 public void onUserActionRequired(Intent intent) throws RemoteException { 19058 throw new IllegalStateException(); 19059 } 19060 19061 @Override 19062 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19063 Bundle extras) throws RemoteException { 19064 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19065 + PackageManager.installStatusToString(returnCode, msg)); 19066 19067 installedLatch.countDown(); 19068 19069 // Regardless of success or failure of the move operation, 19070 // always unfreeze the package 19071 unfreezePackage(packageName); 19072 19073 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19074 switch (status) { 19075 case PackageInstaller.STATUS_SUCCESS: 19076 mMoveCallbacks.notifyStatusChanged(moveId, 19077 PackageManager.MOVE_SUCCEEDED); 19078 break; 19079 case PackageInstaller.STATUS_FAILURE_STORAGE: 19080 mMoveCallbacks.notifyStatusChanged(moveId, 19081 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19082 break; 19083 default: 19084 mMoveCallbacks.notifyStatusChanged(moveId, 19085 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19086 break; 19087 } 19088 } 19089 }; 19090 19091 final MoveInfo move; 19092 if (moveCompleteApp) { 19093 // Kick off a thread to report progress estimates 19094 new Thread() { 19095 @Override 19096 public void run() { 19097 while (true) { 19098 try { 19099 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19100 break; 19101 } 19102 } catch (InterruptedException ignored) { 19103 } 19104 19105 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19106 final int progress = 10 + (int) MathUtils.constrain( 19107 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19108 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19109 } 19110 } 19111 }.start(); 19112 19113 final String dataAppName = codeFile.getName(); 19114 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19115 dataAppName, appId, seinfo, targetSdkVersion); 19116 } else { 19117 move = null; 19118 } 19119 19120 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19121 19122 final Message msg = mHandler.obtainMessage(INIT_COPY); 19123 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19124 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19125 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19126 packageAbiOverride, null); 19127 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19128 msg.obj = params; 19129 19130 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19131 System.identityHashCode(msg.obj)); 19132 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19133 System.identityHashCode(msg.obj)); 19134 19135 mHandler.sendMessage(msg); 19136 } 19137 19138 @Override 19139 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19141 19142 final int realMoveId = mNextMoveId.getAndIncrement(); 19143 final Bundle extras = new Bundle(); 19144 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19145 mMoveCallbacks.notifyCreated(realMoveId, extras); 19146 19147 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19148 @Override 19149 public void onCreated(int moveId, Bundle extras) { 19150 // Ignored 19151 } 19152 19153 @Override 19154 public void onStatusChanged(int moveId, int status, long estMillis) { 19155 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19156 } 19157 }; 19158 19159 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19160 storage.setPrimaryStorageUuid(volumeUuid, callback); 19161 return realMoveId; 19162 } 19163 19164 @Override 19165 public int getMoveStatus(int moveId) { 19166 mContext.enforceCallingOrSelfPermission( 19167 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19168 return mMoveCallbacks.mLastStatus.get(moveId); 19169 } 19170 19171 @Override 19172 public void registerMoveCallback(IPackageMoveObserver callback) { 19173 mContext.enforceCallingOrSelfPermission( 19174 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19175 mMoveCallbacks.register(callback); 19176 } 19177 19178 @Override 19179 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19180 mContext.enforceCallingOrSelfPermission( 19181 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19182 mMoveCallbacks.unregister(callback); 19183 } 19184 19185 @Override 19186 public boolean setInstallLocation(int loc) { 19187 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19188 null); 19189 if (getInstallLocation() == loc) { 19190 return true; 19191 } 19192 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19193 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19194 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19195 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19196 return true; 19197 } 19198 return false; 19199 } 19200 19201 @Override 19202 public int getInstallLocation() { 19203 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19204 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19205 PackageHelper.APP_INSTALL_AUTO); 19206 } 19207 19208 /** Called by UserManagerService */ 19209 void cleanUpUser(UserManagerService userManager, int userHandle) { 19210 synchronized (mPackages) { 19211 mDirtyUsers.remove(userHandle); 19212 mUserNeedsBadging.delete(userHandle); 19213 mSettings.removeUserLPw(userHandle); 19214 mPendingBroadcasts.remove(userHandle); 19215 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19216 } 19217 synchronized (mInstallLock) { 19218 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19219 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19220 final String volumeUuid = vol.getFsUuid(); 19221 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19222 try { 19223 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19224 } catch (InstallerException e) { 19225 Slog.w(TAG, "Failed to remove user data", e); 19226 } 19227 } 19228 synchronized (mPackages) { 19229 removeUnusedPackagesLILPw(userManager, userHandle); 19230 } 19231 } 19232 } 19233 19234 /** 19235 * We're removing userHandle and would like to remove any downloaded packages 19236 * that are no longer in use by any other user. 19237 * @param userHandle the user being removed 19238 */ 19239 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19240 final boolean DEBUG_CLEAN_APKS = false; 19241 int [] users = userManager.getUserIds(); 19242 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19243 while (psit.hasNext()) { 19244 PackageSetting ps = psit.next(); 19245 if (ps.pkg == null) { 19246 continue; 19247 } 19248 final String packageName = ps.pkg.packageName; 19249 // Skip over if system app 19250 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19251 continue; 19252 } 19253 if (DEBUG_CLEAN_APKS) { 19254 Slog.i(TAG, "Checking package " + packageName); 19255 } 19256 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19257 if (keep) { 19258 if (DEBUG_CLEAN_APKS) { 19259 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19260 } 19261 } else { 19262 for (int i = 0; i < users.length; i++) { 19263 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19264 keep = true; 19265 if (DEBUG_CLEAN_APKS) { 19266 Slog.i(TAG, " Keeping package " + packageName + " for user " 19267 + users[i]); 19268 } 19269 break; 19270 } 19271 } 19272 } 19273 if (!keep) { 19274 if (DEBUG_CLEAN_APKS) { 19275 Slog.i(TAG, " Removing package " + packageName); 19276 } 19277 mHandler.post(new Runnable() { 19278 public void run() { 19279 deletePackageX(packageName, userHandle, 0); 19280 } //end run 19281 }); 19282 } 19283 } 19284 } 19285 19286 /** Called by UserManagerService */ 19287 void createNewUser(int userHandle) { 19288 synchronized (mInstallLock) { 19289 try { 19290 mInstaller.createUserConfig(userHandle); 19291 } catch (InstallerException e) { 19292 Slog.w(TAG, "Failed to create user config", e); 19293 } 19294 mSettings.createNewUserLI(this, mInstaller, userHandle); 19295 } 19296 synchronized (mPackages) { 19297 applyFactoryDefaultBrowserLPw(userHandle); 19298 primeDomainVerificationsLPw(userHandle); 19299 } 19300 } 19301 19302 void newUserCreated(final int userHandle) { 19303 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19304 // If permission review for legacy apps is required, we represent 19305 // dagerous permissions for such apps as always granted runtime 19306 // permissions to keep per user flag state whether review is needed. 19307 // Hence, if a new user is added we have to propagate dangerous 19308 // permission grants for these legacy apps. 19309 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19310 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19311 | UPDATE_PERMISSIONS_REPLACE_ALL); 19312 } 19313 } 19314 19315 @Override 19316 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19317 mContext.enforceCallingOrSelfPermission( 19318 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19319 "Only package verification agents can read the verifier device identity"); 19320 19321 synchronized (mPackages) { 19322 return mSettings.getVerifierDeviceIdentityLPw(); 19323 } 19324 } 19325 19326 @Override 19327 public void setPermissionEnforced(String permission, boolean enforced) { 19328 // TODO: Now that we no longer change GID for storage, this should to away. 19329 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19330 "setPermissionEnforced"); 19331 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19332 synchronized (mPackages) { 19333 if (mSettings.mReadExternalStorageEnforced == null 19334 || mSettings.mReadExternalStorageEnforced != enforced) { 19335 mSettings.mReadExternalStorageEnforced = enforced; 19336 mSettings.writeLPr(); 19337 } 19338 } 19339 // kill any non-foreground processes so we restart them and 19340 // grant/revoke the GID. 19341 final IActivityManager am = ActivityManagerNative.getDefault(); 19342 if (am != null) { 19343 final long token = Binder.clearCallingIdentity(); 19344 try { 19345 am.killProcessesBelowForeground("setPermissionEnforcement"); 19346 } catch (RemoteException e) { 19347 } finally { 19348 Binder.restoreCallingIdentity(token); 19349 } 19350 } 19351 } else { 19352 throw new IllegalArgumentException("No selective enforcement for " + permission); 19353 } 19354 } 19355 19356 @Override 19357 @Deprecated 19358 public boolean isPermissionEnforced(String permission) { 19359 return true; 19360 } 19361 19362 @Override 19363 public boolean isStorageLow() { 19364 final long token = Binder.clearCallingIdentity(); 19365 try { 19366 final DeviceStorageMonitorInternal 19367 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19368 if (dsm != null) { 19369 return dsm.isMemoryLow(); 19370 } else { 19371 return false; 19372 } 19373 } finally { 19374 Binder.restoreCallingIdentity(token); 19375 } 19376 } 19377 19378 @Override 19379 public IPackageInstaller getPackageInstaller() { 19380 return mInstallerService; 19381 } 19382 19383 private boolean userNeedsBadging(int userId) { 19384 int index = mUserNeedsBadging.indexOfKey(userId); 19385 if (index < 0) { 19386 final UserInfo userInfo; 19387 final long token = Binder.clearCallingIdentity(); 19388 try { 19389 userInfo = sUserManager.getUserInfo(userId); 19390 } finally { 19391 Binder.restoreCallingIdentity(token); 19392 } 19393 final boolean b; 19394 if (userInfo != null && userInfo.isManagedProfile()) { 19395 b = true; 19396 } else { 19397 b = false; 19398 } 19399 mUserNeedsBadging.put(userId, b); 19400 return b; 19401 } 19402 return mUserNeedsBadging.valueAt(index); 19403 } 19404 19405 @Override 19406 public KeySet getKeySetByAlias(String packageName, String alias) { 19407 if (packageName == null || alias == null) { 19408 return null; 19409 } 19410 synchronized(mPackages) { 19411 final PackageParser.Package pkg = mPackages.get(packageName); 19412 if (pkg == null) { 19413 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19414 throw new IllegalArgumentException("Unknown package: " + packageName); 19415 } 19416 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19417 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19418 } 19419 } 19420 19421 @Override 19422 public KeySet getSigningKeySet(String packageName) { 19423 if (packageName == null) { 19424 return null; 19425 } 19426 synchronized(mPackages) { 19427 final PackageParser.Package pkg = mPackages.get(packageName); 19428 if (pkg == null) { 19429 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19430 throw new IllegalArgumentException("Unknown package: " + packageName); 19431 } 19432 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19433 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19434 throw new SecurityException("May not access signing KeySet of other apps."); 19435 } 19436 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19437 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19438 } 19439 } 19440 19441 @Override 19442 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19443 if (packageName == null || ks == null) { 19444 return false; 19445 } 19446 synchronized(mPackages) { 19447 final PackageParser.Package pkg = mPackages.get(packageName); 19448 if (pkg == null) { 19449 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19450 throw new IllegalArgumentException("Unknown package: " + packageName); 19451 } 19452 IBinder ksh = ks.getToken(); 19453 if (ksh instanceof KeySetHandle) { 19454 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19455 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19456 } 19457 return false; 19458 } 19459 } 19460 19461 @Override 19462 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19463 if (packageName == null || ks == null) { 19464 return false; 19465 } 19466 synchronized(mPackages) { 19467 final PackageParser.Package pkg = mPackages.get(packageName); 19468 if (pkg == null) { 19469 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19470 throw new IllegalArgumentException("Unknown package: " + packageName); 19471 } 19472 IBinder ksh = ks.getToken(); 19473 if (ksh instanceof KeySetHandle) { 19474 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19475 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19476 } 19477 return false; 19478 } 19479 } 19480 19481 private void deletePackageIfUnusedLPr(final String packageName) { 19482 PackageSetting ps = mSettings.mPackages.get(packageName); 19483 if (ps == null) { 19484 return; 19485 } 19486 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19487 // TODO Implement atomic delete if package is unused 19488 // It is currently possible that the package will be deleted even if it is installed 19489 // after this method returns. 19490 mHandler.post(new Runnable() { 19491 public void run() { 19492 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19493 } 19494 }); 19495 } 19496 } 19497 19498 /** 19499 * Check and throw if the given before/after packages would be considered a 19500 * downgrade. 19501 */ 19502 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19503 throws PackageManagerException { 19504 if (after.versionCode < before.mVersionCode) { 19505 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19506 "Update version code " + after.versionCode + " is older than current " 19507 + before.mVersionCode); 19508 } else if (after.versionCode == before.mVersionCode) { 19509 if (after.baseRevisionCode < before.baseRevisionCode) { 19510 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19511 "Update base revision code " + after.baseRevisionCode 19512 + " is older than current " + before.baseRevisionCode); 19513 } 19514 19515 if (!ArrayUtils.isEmpty(after.splitNames)) { 19516 for (int i = 0; i < after.splitNames.length; i++) { 19517 final String splitName = after.splitNames[i]; 19518 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19519 if (j != -1) { 19520 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19521 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19522 "Update split " + splitName + " revision code " 19523 + after.splitRevisionCodes[i] + " is older than current " 19524 + before.splitRevisionCodes[j]); 19525 } 19526 } 19527 } 19528 } 19529 } 19530 } 19531 19532 private static class MoveCallbacks extends Handler { 19533 private static final int MSG_CREATED = 1; 19534 private static final int MSG_STATUS_CHANGED = 2; 19535 19536 private final RemoteCallbackList<IPackageMoveObserver> 19537 mCallbacks = new RemoteCallbackList<>(); 19538 19539 private final SparseIntArray mLastStatus = new SparseIntArray(); 19540 19541 public MoveCallbacks(Looper looper) { 19542 super(looper); 19543 } 19544 19545 public void register(IPackageMoveObserver callback) { 19546 mCallbacks.register(callback); 19547 } 19548 19549 public void unregister(IPackageMoveObserver callback) { 19550 mCallbacks.unregister(callback); 19551 } 19552 19553 @Override 19554 public void handleMessage(Message msg) { 19555 final SomeArgs args = (SomeArgs) msg.obj; 19556 final int n = mCallbacks.beginBroadcast(); 19557 for (int i = 0; i < n; i++) { 19558 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19559 try { 19560 invokeCallback(callback, msg.what, args); 19561 } catch (RemoteException ignored) { 19562 } 19563 } 19564 mCallbacks.finishBroadcast(); 19565 args.recycle(); 19566 } 19567 19568 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19569 throws RemoteException { 19570 switch (what) { 19571 case MSG_CREATED: { 19572 callback.onCreated(args.argi1, (Bundle) args.arg2); 19573 break; 19574 } 19575 case MSG_STATUS_CHANGED: { 19576 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19577 break; 19578 } 19579 } 19580 } 19581 19582 private void notifyCreated(int moveId, Bundle extras) { 19583 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19584 19585 final SomeArgs args = SomeArgs.obtain(); 19586 args.argi1 = moveId; 19587 args.arg2 = extras; 19588 obtainMessage(MSG_CREATED, args).sendToTarget(); 19589 } 19590 19591 private void notifyStatusChanged(int moveId, int status) { 19592 notifyStatusChanged(moveId, status, -1); 19593 } 19594 19595 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19596 Slog.v(TAG, "Move " + moveId + " status " + status); 19597 19598 final SomeArgs args = SomeArgs.obtain(); 19599 args.argi1 = moveId; 19600 args.argi2 = status; 19601 args.arg3 = estMillis; 19602 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19603 19604 synchronized (mLastStatus) { 19605 mLastStatus.put(moveId, status); 19606 } 19607 } 19608 } 19609 19610 private final static class OnPermissionChangeListeners extends Handler { 19611 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19612 19613 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19614 new RemoteCallbackList<>(); 19615 19616 public OnPermissionChangeListeners(Looper looper) { 19617 super(looper); 19618 } 19619 19620 @Override 19621 public void handleMessage(Message msg) { 19622 switch (msg.what) { 19623 case MSG_ON_PERMISSIONS_CHANGED: { 19624 final int uid = msg.arg1; 19625 handleOnPermissionsChanged(uid); 19626 } break; 19627 } 19628 } 19629 19630 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19631 mPermissionListeners.register(listener); 19632 19633 } 19634 19635 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19636 mPermissionListeners.unregister(listener); 19637 } 19638 19639 public void onPermissionsChanged(int uid) { 19640 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19641 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19642 } 19643 } 19644 19645 private void handleOnPermissionsChanged(int uid) { 19646 final int count = mPermissionListeners.beginBroadcast(); 19647 try { 19648 for (int i = 0; i < count; i++) { 19649 IOnPermissionsChangeListener callback = mPermissionListeners 19650 .getBroadcastItem(i); 19651 try { 19652 callback.onPermissionsChanged(uid); 19653 } catch (RemoteException e) { 19654 Log.e(TAG, "Permission listener is dead", e); 19655 } 19656 } 19657 } finally { 19658 mPermissionListeners.finishBroadcast(); 19659 } 19660 } 19661 } 19662 19663 private class PackageManagerInternalImpl extends PackageManagerInternal { 19664 @Override 19665 public void setLocationPackagesProvider(PackagesProvider provider) { 19666 synchronized (mPackages) { 19667 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19668 } 19669 } 19670 19671 @Override 19672 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19673 synchronized (mPackages) { 19674 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19675 } 19676 } 19677 19678 @Override 19679 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19680 synchronized (mPackages) { 19681 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19682 } 19683 } 19684 19685 @Override 19686 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19687 synchronized (mPackages) { 19688 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19689 } 19690 } 19691 19692 @Override 19693 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19694 synchronized (mPackages) { 19695 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19696 } 19697 } 19698 19699 @Override 19700 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19701 synchronized (mPackages) { 19702 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19703 } 19704 } 19705 19706 @Override 19707 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19708 synchronized (mPackages) { 19709 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19710 packageName, userId); 19711 } 19712 } 19713 19714 @Override 19715 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19716 synchronized (mPackages) { 19717 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19718 packageName, userId); 19719 } 19720 } 19721 19722 @Override 19723 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19724 synchronized (mPackages) { 19725 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19726 packageName, userId); 19727 } 19728 } 19729 19730 @Override 19731 public void setKeepUninstalledPackages(final List<String> packageList) { 19732 Preconditions.checkNotNull(packageList); 19733 List<String> removedFromList = null; 19734 synchronized (mPackages) { 19735 if (mKeepUninstalledPackages != null) { 19736 final int packagesCount = mKeepUninstalledPackages.size(); 19737 for (int i = 0; i < packagesCount; i++) { 19738 String oldPackage = mKeepUninstalledPackages.get(i); 19739 if (packageList != null && packageList.contains(oldPackage)) { 19740 continue; 19741 } 19742 if (removedFromList == null) { 19743 removedFromList = new ArrayList<>(); 19744 } 19745 removedFromList.add(oldPackage); 19746 } 19747 } 19748 mKeepUninstalledPackages = new ArrayList<>(packageList); 19749 if (removedFromList != null) { 19750 final int removedCount = removedFromList.size(); 19751 for (int i = 0; i < removedCount; i++) { 19752 deletePackageIfUnusedLPr(removedFromList.get(i)); 19753 } 19754 } 19755 } 19756 } 19757 19758 @Override 19759 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19760 synchronized (mPackages) { 19761 // If we do not support permission review, done. 19762 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19763 return false; 19764 } 19765 19766 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19767 if (packageSetting == null) { 19768 return false; 19769 } 19770 19771 // Permission review applies only to apps not supporting the new permission model. 19772 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19773 return false; 19774 } 19775 19776 // Legacy apps have the permission and get user consent on launch. 19777 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19778 return permissionsState.isPermissionReviewRequired(userId); 19779 } 19780 } 19781 19782 @Override 19783 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19784 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19785 } 19786 19787 @Override 19788 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19789 int userId) { 19790 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19791 } 19792 } 19793 19794 @Override 19795 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19796 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19797 synchronized (mPackages) { 19798 final long identity = Binder.clearCallingIdentity(); 19799 try { 19800 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19801 packageNames, userId); 19802 } finally { 19803 Binder.restoreCallingIdentity(identity); 19804 } 19805 } 19806 } 19807 19808 private static void enforceSystemOrPhoneCaller(String tag) { 19809 int callingUid = Binder.getCallingUid(); 19810 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19811 throw new SecurityException( 19812 "Cannot call " + tag + " from UID " + callingUid); 19813 } 19814 } 19815 19816 boolean isHistoricalPackageUsageAvailable() { 19817 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19818 } 19819 19820 /** 19821 * Return a <b>copy</b> of the collection of packages known to the package manager. 19822 * @return A copy of the values of mPackages. 19823 */ 19824 Collection<PackageParser.Package> getPackages() { 19825 synchronized (mPackages) { 19826 return new ArrayList<>(mPackages.values()); 19827 } 19828 } 19829 19830 /** 19831 * Logs process start information (including base APK hash) to the security log. 19832 * @hide 19833 */ 19834 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19835 String apkFile, int pid) { 19836 if (!SecurityLog.isLoggingEnabled()) { 19837 return; 19838 } 19839 Bundle data = new Bundle(); 19840 data.putLong("startTimestamp", System.currentTimeMillis()); 19841 data.putString("processName", processName); 19842 data.putInt("uid", uid); 19843 data.putString("seinfo", seinfo); 19844 data.putString("apkFile", apkFile); 19845 data.putInt("pid", pid); 19846 Message msg = mProcessLoggingHandler.obtainMessage( 19847 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19848 msg.setData(data); 19849 mProcessLoggingHandler.sendMessage(msg); 19850 } 19851} 19852