PackageManagerService.java revision 828166bca4b21c38e59c1d6d651555095dee33a3
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.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.view.Display; 220 221import com.android.internal.R; 222import com.android.internal.annotations.GuardedBy; 223import com.android.internal.app.IMediaContainerService; 224import com.android.internal.app.ResolverActivity; 225import com.android.internal.content.NativeLibraryHelper; 226import com.android.internal.content.PackageHelper; 227import com.android.internal.os.IParcelFileDescriptorFactory; 228import com.android.internal.os.InstallerConnection.InstallerException; 229import com.android.internal.os.SomeArgs; 230import com.android.internal.os.Zygote; 231import com.android.internal.util.ArrayUtils; 232import com.android.internal.util.FastPrintWriter; 233import com.android.internal.util.FastXmlSerializer; 234import com.android.internal.util.IndentingPrintWriter; 235import com.android.internal.util.Preconditions; 236import com.android.internal.util.XmlUtils; 237import com.android.server.EventLogTags; 238import com.android.server.FgThread; 239import com.android.server.IntentResolver; 240import com.android.server.LocalServices; 241import com.android.server.ServiceThread; 242import com.android.server.SystemConfig; 243import com.android.server.Watchdog; 244import com.android.server.pm.PermissionsState.PermissionState; 245import com.android.server.pm.Settings.DatabaseVersion; 246import com.android.server.pm.Settings.VersionInfo; 247import com.android.server.storage.DeviceStorageMonitorInternal; 248 249import dalvik.system.DexFile; 250import dalvik.system.VMRuntime; 251 252import libcore.io.IoUtils; 253import libcore.util.EmptyArray; 254 255import org.xmlpull.v1.XmlPullParser; 256import org.xmlpull.v1.XmlPullParserException; 257import org.xmlpull.v1.XmlSerializer; 258 259import java.io.BufferedInputStream; 260import java.io.BufferedOutputStream; 261import java.io.BufferedReader; 262import java.io.ByteArrayInputStream; 263import java.io.ByteArrayOutputStream; 264import java.io.File; 265import java.io.FileDescriptor; 266import java.io.FileNotFoundException; 267import java.io.FileOutputStream; 268import java.io.FileReader; 269import java.io.FilenameFilter; 270import java.io.IOException; 271import java.io.InputStream; 272import java.io.PrintWriter; 273import java.nio.charset.StandardCharsets; 274import java.security.MessageDigest; 275import java.security.NoSuchAlgorithmException; 276import java.security.PublicKey; 277import java.security.cert.CertificateEncodingException; 278import java.security.cert.CertificateException; 279import java.text.SimpleDateFormat; 280import java.util.ArrayList; 281import java.util.Arrays; 282import java.util.Collection; 283import java.util.Collections; 284import java.util.Comparator; 285import java.util.Date; 286import java.util.HashSet; 287import java.util.Iterator; 288import java.util.List; 289import java.util.Map; 290import java.util.Objects; 291import java.util.Set; 292import java.util.concurrent.CountDownLatch; 293import java.util.concurrent.TimeUnit; 294import java.util.concurrent.atomic.AtomicBoolean; 295import java.util.concurrent.atomic.AtomicInteger; 296import java.util.concurrent.atomic.AtomicLong; 297 298/** 299 * Keep track of all those .apks everywhere. 300 * 301 * This is very central to the platform's security; please run the unit 302 * tests whenever making modifications here: 303 * 304runtest -c android.content.pm.PackageManagerTests frameworks-core 305 * 306 * {@hide} 307 */ 308public class PackageManagerService extends IPackageManager.Stub { 309 static final String TAG = "PackageManager"; 310 static final boolean DEBUG_SETTINGS = false; 311 static final boolean DEBUG_PREFERRED = false; 312 static final boolean DEBUG_UPGRADE = false; 313 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 314 private static final boolean DEBUG_BACKUP = false; 315 private static final boolean DEBUG_INSTALL = false; 316 private static final boolean DEBUG_REMOVE = false; 317 private static final boolean DEBUG_BROADCASTS = false; 318 private static final boolean DEBUG_SHOW_INFO = false; 319 private static final boolean DEBUG_PACKAGE_INFO = false; 320 private static final boolean DEBUG_INTENT_MATCHING = false; 321 private static final boolean DEBUG_PACKAGE_SCANNING = false; 322 private static final boolean DEBUG_VERIFY = false; 323 private static final boolean DEBUG_FILTERS = false; 324 325 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 326 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 327 // user, but by default initialize to this. 328 static final boolean DEBUG_DEXOPT = false; 329 330 private static final boolean DEBUG_ABI_SELECTION = false; 331 private static final boolean DEBUG_EPHEMERAL = false; 332 private static final boolean DEBUG_TRIAGED_MISSING = false; 333 private static final boolean DEBUG_APP_DATA = false; 334 335 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 336 337 private static final boolean DISABLE_EPHEMERAL_APPS = true; 338 339 private static final int RADIO_UID = Process.PHONE_UID; 340 private static final int LOG_UID = Process.LOG_UID; 341 private static final int NFC_UID = Process.NFC_UID; 342 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 343 private static final int SHELL_UID = Process.SHELL_UID; 344 345 // Cap the size of permission trees that 3rd party apps can define 346 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 347 348 // Suffix used during package installation when copying/moving 349 // package apks to install directory. 350 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 351 352 static final int SCAN_NO_DEX = 1<<1; 353 static final int SCAN_FORCE_DEX = 1<<2; 354 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 355 static final int SCAN_NEW_INSTALL = 1<<4; 356 static final int SCAN_NO_PATHS = 1<<5; 357 static final int SCAN_UPDATE_TIME = 1<<6; 358 static final int SCAN_DEFER_DEX = 1<<7; 359 static final int SCAN_BOOTING = 1<<8; 360 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 361 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 362 static final int SCAN_REPLACING = 1<<11; 363 static final int SCAN_REQUIRE_KNOWN = 1<<12; 364 static final int SCAN_MOVE = 1<<13; 365 static final int SCAN_INITIAL = 1<<14; 366 static final int SCAN_CHECK_ONLY = 1<<15; 367 static final int SCAN_DONT_KILL_APP = 1<<17; 368 369 static final int REMOVE_CHATTY = 1<<16; 370 371 private static final int[] EMPTY_INT_ARRAY = new int[0]; 372 373 /** 374 * Timeout (in milliseconds) after which the watchdog should declare that 375 * our handler thread is wedged. The usual default for such things is one 376 * minute but we sometimes do very lengthy I/O operations on this thread, 377 * such as installing multi-gigabyte applications, so ours needs to be longer. 378 */ 379 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 380 381 /** 382 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 383 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 384 * settings entry if available, otherwise we use the hardcoded default. If it's been 385 * more than this long since the last fstrim, we force one during the boot sequence. 386 * 387 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 388 * one gets run at the next available charging+idle time. This final mandatory 389 * no-fstrim check kicks in only of the other scheduling criteria is never met. 390 */ 391 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 392 393 /** 394 * Whether verification is enabled by default. 395 */ 396 private static final boolean DEFAULT_VERIFY_ENABLE = true; 397 398 /** 399 * The default maximum time to wait for the verification agent to return in 400 * milliseconds. 401 */ 402 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 403 404 /** 405 * The default response for package verification timeout. 406 * 407 * This can be either PackageManager.VERIFICATION_ALLOW or 408 * PackageManager.VERIFICATION_REJECT. 409 */ 410 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 411 412 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 413 414 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 415 DEFAULT_CONTAINER_PACKAGE, 416 "com.android.defcontainer.DefaultContainerService"); 417 418 private static final String KILL_APP_REASON_GIDS_CHANGED = 419 "permission grant or revoke changed gids"; 420 421 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 422 "permissions revoked"; 423 424 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 425 426 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 427 428 /** Permission grant: not grant the permission. */ 429 private static final int GRANT_DENIED = 1; 430 431 /** Permission grant: grant the permission as an install permission. */ 432 private static final int GRANT_INSTALL = 2; 433 434 /** Permission grant: grant the permission as a runtime one. */ 435 private static final int GRANT_RUNTIME = 3; 436 437 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 438 private static final int GRANT_UPGRADE = 4; 439 440 /** Canonical intent used to identify what counts as a "web browser" app */ 441 private static final Intent sBrowserIntent; 442 static { 443 sBrowserIntent = new Intent(); 444 sBrowserIntent.setAction(Intent.ACTION_VIEW); 445 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 446 sBrowserIntent.setData(Uri.parse("http:")); 447 } 448 449 /** 450 * The set of all protected actions [i.e. those actions for which a high priority 451 * intent filter is disallowed]. 452 */ 453 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 454 static { 455 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 456 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 457 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 458 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 459 } 460 461 // Compilation reasons. 462 public static final int REASON_FIRST_BOOT = 0; 463 public static final int REASON_BOOT = 1; 464 public static final int REASON_INSTALL = 2; 465 public static final int REASON_BACKGROUND_DEXOPT = 3; 466 public static final int REASON_AB_OTA = 4; 467 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 468 public static final int REASON_SHARED_APK = 6; 469 public static final int REASON_FORCED_DEXOPT = 7; 470 471 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 472 473 final ServiceThread mHandlerThread; 474 475 final PackageHandler mHandler; 476 477 private final ProcessLoggingHandler mProcessLoggingHandler; 478 479 /** 480 * Messages for {@link #mHandler} that need to wait for system ready before 481 * being dispatched. 482 */ 483 private ArrayList<Message> mPostSystemReadyMessages; 484 485 final int mSdkVersion = Build.VERSION.SDK_INT; 486 487 final Context mContext; 488 final boolean mFactoryTest; 489 final boolean mOnlyCore; 490 final DisplayMetrics mMetrics; 491 final int mDefParseFlags; 492 final String[] mSeparateProcesses; 493 final boolean mIsUpgrade; 494 final boolean mIsPreNUpgrade; 495 496 /** The location for ASEC container files on internal storage. */ 497 final String mAsecInternalPath; 498 499 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 500 // LOCK HELD. Can be called with mInstallLock held. 501 @GuardedBy("mInstallLock") 502 final Installer mInstaller; 503 504 /** Directory where installed third-party apps stored */ 505 final File mAppInstallDir; 506 final File mEphemeralInstallDir; 507 508 /** 509 * Directory to which applications installed internally have their 510 * 32 bit native libraries copied. 511 */ 512 private File mAppLib32InstallDir; 513 514 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 515 // apps. 516 final File mDrmAppPrivateInstallDir; 517 518 // ---------------------------------------------------------------- 519 520 // Lock for state used when installing and doing other long running 521 // operations. Methods that must be called with this lock held have 522 // the suffix "LI". 523 final Object mInstallLock = new Object(); 524 525 // ---------------------------------------------------------------- 526 527 // Keys are String (package name), values are Package. This also serves 528 // as the lock for the global state. Methods that must be called with 529 // this lock held have the prefix "LP". 530 @GuardedBy("mPackages") 531 final ArrayMap<String, PackageParser.Package> mPackages = 532 new ArrayMap<String, PackageParser.Package>(); 533 534 final ArrayMap<String, Set<String>> mKnownCodebase = 535 new ArrayMap<String, Set<String>>(); 536 537 // Tracks available target package names -> overlay package paths. 538 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 539 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 540 541 /** 542 * Tracks new system packages [received in an OTA] that we expect to 543 * find updated user-installed versions. Keys are package name, values 544 * are package location. 545 */ 546 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 547 /** 548 * Tracks high priority intent filters for protected actions. During boot, certain 549 * filter actions are protected and should never be allowed to have a high priority 550 * intent filter for them. However, there is one, and only one exception -- the 551 * setup wizard. It must be able to define a high priority intent filter for these 552 * actions to ensure there are no escapes from the wizard. We need to delay processing 553 * of these during boot as we need to look at all of the system packages in order 554 * to know which component is the setup wizard. 555 */ 556 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 557 /** 558 * Whether or not processing protected filters should be deferred. 559 */ 560 private boolean mDeferProtectedFilters = true; 561 562 /** 563 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 564 */ 565 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 566 /** 567 * Whether or not system app permissions should be promoted from install to runtime. 568 */ 569 boolean mPromoteSystemApps; 570 571 final Settings mSettings; 572 boolean mRestoredSettings; 573 574 // System configuration read by SystemConfig. 575 final int[] mGlobalGids; 576 final SparseArray<ArraySet<String>> mSystemPermissions; 577 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 578 579 // If mac_permissions.xml was found for seinfo labeling. 580 boolean mFoundPolicyFile; 581 582 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 583 584 public static final class SharedLibraryEntry { 585 public final String path; 586 public final String apk; 587 588 SharedLibraryEntry(String _path, String _apk) { 589 path = _path; 590 apk = _apk; 591 } 592 } 593 594 // Currently known shared libraries. 595 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 596 new ArrayMap<String, SharedLibraryEntry>(); 597 598 // All available activities, for your resolving pleasure. 599 final ActivityIntentResolver mActivities = 600 new ActivityIntentResolver(); 601 602 // All available receivers, for your resolving pleasure. 603 final ActivityIntentResolver mReceivers = 604 new ActivityIntentResolver(); 605 606 // All available services, for your resolving pleasure. 607 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 608 609 // All available providers, for your resolving pleasure. 610 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 611 612 // Mapping from provider base names (first directory in content URI codePath) 613 // to the provider information. 614 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 615 new ArrayMap<String, PackageParser.Provider>(); 616 617 // Mapping from instrumentation class names to info about them. 618 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 619 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 620 621 // Mapping from permission names to info about them. 622 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 623 new ArrayMap<String, PackageParser.PermissionGroup>(); 624 625 // Packages whose data we have transfered into another package, thus 626 // should no longer exist. 627 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 628 629 // Broadcast actions that are only available to the system. 630 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 631 632 /** List of packages waiting for verification. */ 633 final SparseArray<PackageVerificationState> mPendingVerification 634 = new SparseArray<PackageVerificationState>(); 635 636 /** Set of packages associated with each app op permission. */ 637 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 638 639 final PackageInstallerService mInstallerService; 640 641 private final PackageDexOptimizer mPackageDexOptimizer; 642 643 private AtomicInteger mNextMoveId = new AtomicInteger(); 644 private final MoveCallbacks mMoveCallbacks; 645 646 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 647 648 // Cache of users who need badging. 649 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 650 651 /** Token for keys in mPendingVerification. */ 652 private int mPendingVerificationToken = 0; 653 654 volatile boolean mSystemReady; 655 volatile boolean mSafeMode; 656 volatile boolean mHasSystemUidErrors; 657 658 ApplicationInfo mAndroidApplication; 659 final ActivityInfo mResolveActivity = new ActivityInfo(); 660 final ResolveInfo mResolveInfo = new ResolveInfo(); 661 ComponentName mResolveComponentName; 662 PackageParser.Package mPlatformPackage; 663 ComponentName mCustomResolverComponentName; 664 665 boolean mResolverReplaced = false; 666 667 private final @Nullable ComponentName mIntentFilterVerifierComponent; 668 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 669 670 private int mIntentFilterVerificationToken = 0; 671 672 /** Component that knows whether or not an ephemeral application exists */ 673 final ComponentName mEphemeralResolverComponent; 674 /** The service connection to the ephemeral resolver */ 675 final EphemeralResolverConnection mEphemeralResolverConnection; 676 677 /** Component used to install ephemeral applications */ 678 final ComponentName mEphemeralInstallerComponent; 679 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 680 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 681 682 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 683 = new SparseArray<IntentFilterVerificationState>(); 684 685 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 686 new DefaultPermissionGrantPolicy(this); 687 688 // List of packages names to keep cached, even if they are uninstalled for all users 689 private List<String> mKeepUninstalledPackages; 690 691 private static class IFVerificationParams { 692 PackageParser.Package pkg; 693 boolean replacing; 694 int userId; 695 int verifierUid; 696 697 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 698 int _userId, int _verifierUid) { 699 pkg = _pkg; 700 replacing = _replacing; 701 userId = _userId; 702 replacing = _replacing; 703 verifierUid = _verifierUid; 704 } 705 } 706 707 private interface IntentFilterVerifier<T extends IntentFilter> { 708 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 709 T filter, String packageName); 710 void startVerifications(int userId); 711 void receiveVerificationResponse(int verificationId); 712 } 713 714 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 715 private Context mContext; 716 private ComponentName mIntentFilterVerifierComponent; 717 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 718 719 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 720 mContext = context; 721 mIntentFilterVerifierComponent = verifierComponent; 722 } 723 724 private String getDefaultScheme() { 725 return IntentFilter.SCHEME_HTTPS; 726 } 727 728 @Override 729 public void startVerifications(int userId) { 730 // Launch verifications requests 731 int count = mCurrentIntentFilterVerifications.size(); 732 for (int n=0; n<count; n++) { 733 int verificationId = mCurrentIntentFilterVerifications.get(n); 734 final IntentFilterVerificationState ivs = 735 mIntentFilterVerificationStates.get(verificationId); 736 737 String packageName = ivs.getPackageName(); 738 739 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 740 final int filterCount = filters.size(); 741 ArraySet<String> domainsSet = new ArraySet<>(); 742 for (int m=0; m<filterCount; m++) { 743 PackageParser.ActivityIntentInfo filter = filters.get(m); 744 domainsSet.addAll(filter.getHostsList()); 745 } 746 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 747 synchronized (mPackages) { 748 if (mSettings.createIntentFilterVerificationIfNeededLPw( 749 packageName, domainsList) != null) { 750 scheduleWriteSettingsLocked(); 751 } 752 } 753 sendVerificationRequest(userId, verificationId, ivs); 754 } 755 mCurrentIntentFilterVerifications.clear(); 756 } 757 758 private void sendVerificationRequest(int userId, int verificationId, 759 IntentFilterVerificationState ivs) { 760 761 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 762 verificationIntent.putExtra( 763 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 764 verificationId); 765 verificationIntent.putExtra( 766 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 767 getDefaultScheme()); 768 verificationIntent.putExtra( 769 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 770 ivs.getHostsString()); 771 verificationIntent.putExtra( 772 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 773 ivs.getPackageName()); 774 verificationIntent.setComponent(mIntentFilterVerifierComponent); 775 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 776 777 UserHandle user = new UserHandle(userId); 778 mContext.sendBroadcastAsUser(verificationIntent, user); 779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 780 "Sending IntentFilter verification broadcast"); 781 } 782 783 public void receiveVerificationResponse(int verificationId) { 784 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 785 786 final boolean verified = ivs.isVerified(); 787 788 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 789 final int count = filters.size(); 790 if (DEBUG_DOMAIN_VERIFICATION) { 791 Slog.i(TAG, "Received verification response " + verificationId 792 + " for " + count + " filters, verified=" + verified); 793 } 794 for (int n=0; n<count; n++) { 795 PackageParser.ActivityIntentInfo filter = filters.get(n); 796 filter.setVerified(verified); 797 798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 799 + " verified with result:" + verified + " and hosts:" 800 + ivs.getHostsString()); 801 } 802 803 mIntentFilterVerificationStates.remove(verificationId); 804 805 final String packageName = ivs.getPackageName(); 806 IntentFilterVerificationInfo ivi = null; 807 808 synchronized (mPackages) { 809 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 810 } 811 if (ivi == null) { 812 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 813 + verificationId + " packageName:" + packageName); 814 return; 815 } 816 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 817 "Updating IntentFilterVerificationInfo for package " + packageName 818 +" verificationId:" + verificationId); 819 820 synchronized (mPackages) { 821 if (verified) { 822 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 823 } else { 824 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 825 } 826 scheduleWriteSettingsLocked(); 827 828 final int userId = ivs.getUserId(); 829 if (userId != UserHandle.USER_ALL) { 830 final int userStatus = 831 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 832 833 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 834 boolean needUpdate = false; 835 836 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 837 // already been set by the User thru the Disambiguation dialog 838 switch (userStatus) { 839 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 840 if (verified) { 841 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 842 } else { 843 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 844 } 845 needUpdate = true; 846 break; 847 848 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 849 if (verified) { 850 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 851 needUpdate = true; 852 } 853 break; 854 855 default: 856 // Nothing to do 857 } 858 859 if (needUpdate) { 860 mSettings.updateIntentFilterVerificationStatusLPw( 861 packageName, updatedStatus, userId); 862 scheduleWritePackageRestrictionsLocked(userId); 863 } 864 } 865 } 866 } 867 868 @Override 869 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 870 ActivityIntentInfo filter, String packageName) { 871 if (!hasValidDomains(filter)) { 872 return false; 873 } 874 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 875 if (ivs == null) { 876 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 877 packageName); 878 } 879 if (DEBUG_DOMAIN_VERIFICATION) { 880 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 881 } 882 ivs.addFilter(filter); 883 return true; 884 } 885 886 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 887 int userId, int verificationId, String packageName) { 888 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 889 verifierUid, userId, packageName); 890 ivs.setPendingState(); 891 synchronized (mPackages) { 892 mIntentFilterVerificationStates.append(verificationId, ivs); 893 mCurrentIntentFilterVerifications.add(verificationId); 894 } 895 return ivs; 896 } 897 } 898 899 private static boolean hasValidDomains(ActivityIntentInfo filter) { 900 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 901 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 902 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 903 } 904 905 // Set of pending broadcasts for aggregating enable/disable of components. 906 static class PendingPackageBroadcasts { 907 // for each user id, a map of <package name -> components within that package> 908 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 909 910 public PendingPackageBroadcasts() { 911 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 912 } 913 914 public ArrayList<String> get(int userId, String packageName) { 915 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 916 return packages.get(packageName); 917 } 918 919 public void put(int userId, String packageName, ArrayList<String> components) { 920 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 921 packages.put(packageName, components); 922 } 923 924 public void remove(int userId, String packageName) { 925 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 926 if (packages != null) { 927 packages.remove(packageName); 928 } 929 } 930 931 public void remove(int userId) { 932 mUidMap.remove(userId); 933 } 934 935 public int userIdCount() { 936 return mUidMap.size(); 937 } 938 939 public int userIdAt(int n) { 940 return mUidMap.keyAt(n); 941 } 942 943 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 944 return mUidMap.get(userId); 945 } 946 947 public int size() { 948 // total number of pending broadcast entries across all userIds 949 int num = 0; 950 for (int i = 0; i< mUidMap.size(); i++) { 951 num += mUidMap.valueAt(i).size(); 952 } 953 return num; 954 } 955 956 public void clear() { 957 mUidMap.clear(); 958 } 959 960 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 961 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 962 if (map == null) { 963 map = new ArrayMap<String, ArrayList<String>>(); 964 mUidMap.put(userId, map); 965 } 966 return map; 967 } 968 } 969 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 970 971 // Service Connection to remote media container service to copy 972 // package uri's from external media onto secure containers 973 // or internal storage. 974 private IMediaContainerService mContainerService = null; 975 976 static final int SEND_PENDING_BROADCAST = 1; 977 static final int MCS_BOUND = 3; 978 static final int END_COPY = 4; 979 static final int INIT_COPY = 5; 980 static final int MCS_UNBIND = 6; 981 static final int START_CLEANING_PACKAGE = 7; 982 static final int FIND_INSTALL_LOC = 8; 983 static final int POST_INSTALL = 9; 984 static final int MCS_RECONNECT = 10; 985 static final int MCS_GIVE_UP = 11; 986 static final int UPDATED_MEDIA_STATUS = 12; 987 static final int WRITE_SETTINGS = 13; 988 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 989 static final int PACKAGE_VERIFIED = 15; 990 static final int CHECK_PENDING_VERIFICATION = 16; 991 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 992 static final int INTENT_FILTER_VERIFIED = 18; 993 994 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 995 996 // Delay time in millisecs 997 static final int BROADCAST_DELAY = 10 * 1000; 998 999 static UserManagerService sUserManager; 1000 1001 // Stores a list of users whose package restrictions file needs to be updated 1002 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1003 1004 final private DefaultContainerConnection mDefContainerConn = 1005 new DefaultContainerConnection(); 1006 class DefaultContainerConnection implements ServiceConnection { 1007 public void onServiceConnected(ComponentName name, IBinder service) { 1008 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1009 IMediaContainerService imcs = 1010 IMediaContainerService.Stub.asInterface(service); 1011 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1012 } 1013 1014 public void onServiceDisconnected(ComponentName name) { 1015 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1016 } 1017 } 1018 1019 // Recordkeeping of restore-after-install operations that are currently in flight 1020 // between the Package Manager and the Backup Manager 1021 static class PostInstallData { 1022 public InstallArgs args; 1023 public PackageInstalledInfo res; 1024 1025 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1026 args = _a; 1027 res = _r; 1028 } 1029 } 1030 1031 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1032 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1033 1034 // XML tags for backup/restore of various bits of state 1035 private static final String TAG_PREFERRED_BACKUP = "pa"; 1036 private static final String TAG_DEFAULT_APPS = "da"; 1037 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1038 1039 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1040 private static final String TAG_ALL_GRANTS = "rt-grants"; 1041 private static final String TAG_GRANT = "grant"; 1042 private static final String ATTR_PACKAGE_NAME = "pkg"; 1043 1044 private static final String TAG_PERMISSION = "perm"; 1045 private static final String ATTR_PERMISSION_NAME = "name"; 1046 private static final String ATTR_IS_GRANTED = "g"; 1047 private static final String ATTR_USER_SET = "set"; 1048 private static final String ATTR_USER_FIXED = "fixed"; 1049 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1050 1051 // System/policy permission grants are not backed up 1052 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1053 FLAG_PERMISSION_POLICY_FIXED 1054 | FLAG_PERMISSION_SYSTEM_FIXED 1055 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1056 1057 // And we back up these user-adjusted states 1058 private static final int USER_RUNTIME_GRANT_MASK = 1059 FLAG_PERMISSION_USER_SET 1060 | FLAG_PERMISSION_USER_FIXED 1061 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1062 1063 final @Nullable String mRequiredVerifierPackage; 1064 final @NonNull String mRequiredInstallerPackage; 1065 final @Nullable String mSetupWizardPackage; 1066 final @NonNull String mServicesSystemSharedLibraryPackageName; 1067 1068 private final PackageUsage mPackageUsage = new PackageUsage(); 1069 1070 private class PackageUsage { 1071 private static final int WRITE_INTERVAL 1072 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1073 1074 private final Object mFileLock = new Object(); 1075 private final AtomicLong mLastWritten = new AtomicLong(0); 1076 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1077 1078 private boolean mIsHistoricalPackageUsageAvailable = true; 1079 1080 boolean isHistoricalPackageUsageAvailable() { 1081 return mIsHistoricalPackageUsageAvailable; 1082 } 1083 1084 void write(boolean force) { 1085 if (force) { 1086 writeInternal(); 1087 return; 1088 } 1089 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1090 && !DEBUG_DEXOPT) { 1091 return; 1092 } 1093 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1094 new Thread("PackageUsage_DiskWriter") { 1095 @Override 1096 public void run() { 1097 try { 1098 writeInternal(); 1099 } finally { 1100 mBackgroundWriteRunning.set(false); 1101 } 1102 } 1103 }.start(); 1104 } 1105 } 1106 1107 private void writeInternal() { 1108 synchronized (mPackages) { 1109 synchronized (mFileLock) { 1110 AtomicFile file = getFile(); 1111 FileOutputStream f = null; 1112 try { 1113 f = file.startWrite(); 1114 BufferedOutputStream out = new BufferedOutputStream(f); 1115 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1116 StringBuilder sb = new StringBuilder(); 1117 for (PackageParser.Package pkg : mPackages.values()) { 1118 if (pkg.mLastPackageUsageTimeInMills == 0) { 1119 continue; 1120 } 1121 sb.setLength(0); 1122 sb.append(pkg.packageName); 1123 sb.append(' '); 1124 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1125 sb.append('\n'); 1126 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1127 } 1128 out.flush(); 1129 file.finishWrite(f); 1130 } catch (IOException e) { 1131 if (f != null) { 1132 file.failWrite(f); 1133 } 1134 Log.e(TAG, "Failed to write package usage times", e); 1135 } 1136 } 1137 } 1138 mLastWritten.set(SystemClock.elapsedRealtime()); 1139 } 1140 1141 void readLP() { 1142 synchronized (mFileLock) { 1143 AtomicFile file = getFile(); 1144 BufferedInputStream in = null; 1145 try { 1146 in = new BufferedInputStream(file.openRead()); 1147 StringBuffer sb = new StringBuffer(); 1148 while (true) { 1149 String packageName = readToken(in, sb, ' '); 1150 if (packageName == null) { 1151 break; 1152 } 1153 String timeInMillisString = readToken(in, sb, '\n'); 1154 if (timeInMillisString == null) { 1155 throw new IOException("Failed to find last usage time for package " 1156 + packageName); 1157 } 1158 PackageParser.Package pkg = mPackages.get(packageName); 1159 if (pkg == null) { 1160 continue; 1161 } 1162 long timeInMillis; 1163 try { 1164 timeInMillis = Long.parseLong(timeInMillisString); 1165 } catch (NumberFormatException e) { 1166 throw new IOException("Failed to parse " + timeInMillisString 1167 + " as a long.", e); 1168 } 1169 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1170 } 1171 } catch (FileNotFoundException expected) { 1172 mIsHistoricalPackageUsageAvailable = false; 1173 } catch (IOException e) { 1174 Log.w(TAG, "Failed to read package usage times", e); 1175 } finally { 1176 IoUtils.closeQuietly(in); 1177 } 1178 } 1179 mLastWritten.set(SystemClock.elapsedRealtime()); 1180 } 1181 1182 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1183 throws IOException { 1184 sb.setLength(0); 1185 while (true) { 1186 int ch = in.read(); 1187 if (ch == -1) { 1188 if (sb.length() == 0) { 1189 return null; 1190 } 1191 throw new IOException("Unexpected EOF"); 1192 } 1193 if (ch == endOfToken) { 1194 return sb.toString(); 1195 } 1196 sb.append((char)ch); 1197 } 1198 } 1199 1200 private AtomicFile getFile() { 1201 File dataDir = Environment.getDataDirectory(); 1202 File systemDir = new File(dataDir, "system"); 1203 File fname = new File(systemDir, "package-usage.list"); 1204 return new AtomicFile(fname); 1205 } 1206 } 1207 1208 class PackageHandler extends Handler { 1209 private boolean mBound = false; 1210 final ArrayList<HandlerParams> mPendingInstalls = 1211 new ArrayList<HandlerParams>(); 1212 1213 private boolean connectToService() { 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1215 " DefaultContainerService"); 1216 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1217 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1218 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1219 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1220 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1221 mBound = true; 1222 return true; 1223 } 1224 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1225 return false; 1226 } 1227 1228 private void disconnectService() { 1229 mContainerService = null; 1230 mBound = false; 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1232 mContext.unbindService(mDefContainerConn); 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1234 } 1235 1236 PackageHandler(Looper looper) { 1237 super(looper); 1238 } 1239 1240 public void handleMessage(Message msg) { 1241 try { 1242 doHandleMessage(msg); 1243 } finally { 1244 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1245 } 1246 } 1247 1248 void doHandleMessage(Message msg) { 1249 switch (msg.what) { 1250 case INIT_COPY: { 1251 HandlerParams params = (HandlerParams) msg.obj; 1252 int idx = mPendingInstalls.size(); 1253 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1254 // If a bind was already initiated we dont really 1255 // need to do anything. The pending install 1256 // will be processed later on. 1257 if (!mBound) { 1258 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1259 System.identityHashCode(mHandler)); 1260 // If this is the only one pending we might 1261 // have to bind to the service again. 1262 if (!connectToService()) { 1263 Slog.e(TAG, "Failed to bind to media container service"); 1264 params.serviceError(); 1265 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1266 System.identityHashCode(mHandler)); 1267 if (params.traceMethod != null) { 1268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1269 params.traceCookie); 1270 } 1271 return; 1272 } else { 1273 // Once we bind to the service, the first 1274 // pending request will be processed. 1275 mPendingInstalls.add(idx, params); 1276 } 1277 } else { 1278 mPendingInstalls.add(idx, params); 1279 // Already bound to the service. Just make 1280 // sure we trigger off processing the first request. 1281 if (idx == 0) { 1282 mHandler.sendEmptyMessage(MCS_BOUND); 1283 } 1284 } 1285 break; 1286 } 1287 case MCS_BOUND: { 1288 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1289 if (msg.obj != null) { 1290 mContainerService = (IMediaContainerService) msg.obj; 1291 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1292 System.identityHashCode(mHandler)); 1293 } 1294 if (mContainerService == null) { 1295 if (!mBound) { 1296 // Something seriously wrong since we are not bound and we are not 1297 // waiting for connection. Bail out. 1298 Slog.e(TAG, "Cannot bind to media container service"); 1299 for (HandlerParams params : mPendingInstalls) { 1300 // Indicate service bind error 1301 params.serviceError(); 1302 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1303 System.identityHashCode(params)); 1304 if (params.traceMethod != null) { 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1306 params.traceMethod, params.traceCookie); 1307 } 1308 return; 1309 } 1310 mPendingInstalls.clear(); 1311 } else { 1312 Slog.w(TAG, "Waiting to connect to media container service"); 1313 } 1314 } else if (mPendingInstalls.size() > 0) { 1315 HandlerParams params = mPendingInstalls.get(0); 1316 if (params != null) { 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1318 System.identityHashCode(params)); 1319 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1320 if (params.startCopy()) { 1321 // We are done... look for more work or to 1322 // go idle. 1323 if (DEBUG_SD_INSTALL) Log.i(TAG, 1324 "Checking for more work or unbind..."); 1325 // Delete pending install 1326 if (mPendingInstalls.size() > 0) { 1327 mPendingInstalls.remove(0); 1328 } 1329 if (mPendingInstalls.size() == 0) { 1330 if (mBound) { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, 1332 "Posting delayed MCS_UNBIND"); 1333 removeMessages(MCS_UNBIND); 1334 Message ubmsg = obtainMessage(MCS_UNBIND); 1335 // Unbind after a little delay, to avoid 1336 // continual thrashing. 1337 sendMessageDelayed(ubmsg, 10000); 1338 } 1339 } else { 1340 // There are more pending requests in queue. 1341 // Just post MCS_BOUND message to trigger processing 1342 // of next pending install. 1343 if (DEBUG_SD_INSTALL) Log.i(TAG, 1344 "Posting MCS_BOUND for next work"); 1345 mHandler.sendEmptyMessage(MCS_BOUND); 1346 } 1347 } 1348 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1349 } 1350 } else { 1351 // Should never happen ideally. 1352 Slog.w(TAG, "Empty queue"); 1353 } 1354 break; 1355 } 1356 case MCS_RECONNECT: { 1357 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1358 if (mPendingInstalls.size() > 0) { 1359 if (mBound) { 1360 disconnectService(); 1361 } 1362 if (!connectToService()) { 1363 Slog.e(TAG, "Failed to bind to media container service"); 1364 for (HandlerParams params : mPendingInstalls) { 1365 // Indicate service bind error 1366 params.serviceError(); 1367 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1368 System.identityHashCode(params)); 1369 } 1370 mPendingInstalls.clear(); 1371 } 1372 } 1373 break; 1374 } 1375 case MCS_UNBIND: { 1376 // If there is no actual work left, then time to unbind. 1377 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1378 1379 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1380 if (mBound) { 1381 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1382 1383 disconnectService(); 1384 } 1385 } else if (mPendingInstalls.size() > 0) { 1386 // There are more pending requests in queue. 1387 // Just post MCS_BOUND message to trigger processing 1388 // of next pending install. 1389 mHandler.sendEmptyMessage(MCS_BOUND); 1390 } 1391 1392 break; 1393 } 1394 case MCS_GIVE_UP: { 1395 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1396 HandlerParams params = mPendingInstalls.remove(0); 1397 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1398 System.identityHashCode(params)); 1399 break; 1400 } 1401 case SEND_PENDING_BROADCAST: { 1402 String packages[]; 1403 ArrayList<String> components[]; 1404 int size = 0; 1405 int uids[]; 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 synchronized (mPackages) { 1408 if (mPendingBroadcasts == null) { 1409 return; 1410 } 1411 size = mPendingBroadcasts.size(); 1412 if (size <= 0) { 1413 // Nothing to be done. Just return 1414 return; 1415 } 1416 packages = new String[size]; 1417 components = new ArrayList[size]; 1418 uids = new int[size]; 1419 int i = 0; // filling out the above arrays 1420 1421 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1422 int packageUserId = mPendingBroadcasts.userIdAt(n); 1423 Iterator<Map.Entry<String, ArrayList<String>>> it 1424 = mPendingBroadcasts.packagesForUserId(packageUserId) 1425 .entrySet().iterator(); 1426 while (it.hasNext() && i < size) { 1427 Map.Entry<String, ArrayList<String>> ent = it.next(); 1428 packages[i] = ent.getKey(); 1429 components[i] = ent.getValue(); 1430 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1431 uids[i] = (ps != null) 1432 ? UserHandle.getUid(packageUserId, ps.appId) 1433 : -1; 1434 i++; 1435 } 1436 } 1437 size = i; 1438 mPendingBroadcasts.clear(); 1439 } 1440 // Send broadcasts 1441 for (int i = 0; i < size; i++) { 1442 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1443 } 1444 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1445 break; 1446 } 1447 case START_CLEANING_PACKAGE: { 1448 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1449 final String packageName = (String)msg.obj; 1450 final int userId = msg.arg1; 1451 final boolean andCode = msg.arg2 != 0; 1452 synchronized (mPackages) { 1453 if (userId == UserHandle.USER_ALL) { 1454 int[] users = sUserManager.getUserIds(); 1455 for (int user : users) { 1456 mSettings.addPackageToCleanLPw( 1457 new PackageCleanItem(user, packageName, andCode)); 1458 } 1459 } else { 1460 mSettings.addPackageToCleanLPw( 1461 new PackageCleanItem(userId, packageName, andCode)); 1462 } 1463 } 1464 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1465 startCleaningPackages(); 1466 } break; 1467 case POST_INSTALL: { 1468 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1469 1470 PostInstallData data = mRunningInstalls.get(msg.arg1); 1471 mRunningInstalls.delete(msg.arg1); 1472 1473 if (data != null) { 1474 InstallArgs args = data.args; 1475 PackageInstalledInfo parentRes = data.res; 1476 1477 final boolean grantPermissions = (args.installFlags 1478 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1479 final boolean killApp = (args.installFlags 1480 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1481 final String[] grantedPermissions = args.installGrantPermissions; 1482 1483 // Handle the parent package 1484 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1485 grantedPermissions, args.observer); 1486 1487 // Handle the child packages 1488 final int childCount = (parentRes.addedChildPackages != null) 1489 ? parentRes.addedChildPackages.size() : 0; 1490 for (int i = 0; i < childCount; i++) { 1491 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1492 handlePackagePostInstall(childRes, grantPermissions, killApp, 1493 grantedPermissions, args.observer); 1494 } 1495 1496 // Log tracing if needed 1497 if (args.traceMethod != null) { 1498 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1499 args.traceCookie); 1500 } 1501 } else { 1502 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1503 } 1504 1505 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1506 } break; 1507 case UPDATED_MEDIA_STATUS: { 1508 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1509 boolean reportStatus = msg.arg1 == 1; 1510 boolean doGc = msg.arg2 == 1; 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1512 if (doGc) { 1513 // Force a gc to clear up stale containers. 1514 Runtime.getRuntime().gc(); 1515 } 1516 if (msg.obj != null) { 1517 @SuppressWarnings("unchecked") 1518 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1519 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1520 // Unload containers 1521 unloadAllContainers(args); 1522 } 1523 if (reportStatus) { 1524 try { 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1526 PackageHelper.getMountService().finishMediaUpdate(); 1527 } catch (RemoteException e) { 1528 Log.e(TAG, "MountService not running?"); 1529 } 1530 } 1531 } break; 1532 case WRITE_SETTINGS: { 1533 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1534 synchronized (mPackages) { 1535 removeMessages(WRITE_SETTINGS); 1536 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1537 mSettings.writeLPr(); 1538 mDirtyUsers.clear(); 1539 } 1540 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1541 } break; 1542 case WRITE_PACKAGE_RESTRICTIONS: { 1543 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1544 synchronized (mPackages) { 1545 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1546 for (int userId : mDirtyUsers) { 1547 mSettings.writePackageRestrictionsLPr(userId); 1548 } 1549 mDirtyUsers.clear(); 1550 } 1551 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1552 } break; 1553 case CHECK_PENDING_VERIFICATION: { 1554 final int verificationId = msg.arg1; 1555 final PackageVerificationState state = mPendingVerification.get(verificationId); 1556 1557 if ((state != null) && !state.timeoutExtended()) { 1558 final InstallArgs args = state.getInstallArgs(); 1559 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1560 1561 Slog.i(TAG, "Verification timed out for " + originUri); 1562 mPendingVerification.remove(verificationId); 1563 1564 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1565 1566 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1567 Slog.i(TAG, "Continuing with installation of " + originUri); 1568 state.setVerifierResponse(Binder.getCallingUid(), 1569 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1570 broadcastPackageVerified(verificationId, originUri, 1571 PackageManager.VERIFICATION_ALLOW, 1572 state.getInstallArgs().getUser()); 1573 try { 1574 ret = args.copyApk(mContainerService, true); 1575 } catch (RemoteException e) { 1576 Slog.e(TAG, "Could not contact the ContainerService"); 1577 } 1578 } else { 1579 broadcastPackageVerified(verificationId, originUri, 1580 PackageManager.VERIFICATION_REJECT, 1581 state.getInstallArgs().getUser()); 1582 } 1583 1584 Trace.asyncTraceEnd( 1585 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1586 1587 processPendingInstall(args, ret); 1588 mHandler.sendEmptyMessage(MCS_UNBIND); 1589 } 1590 break; 1591 } 1592 case PACKAGE_VERIFIED: { 1593 final int verificationId = msg.arg1; 1594 1595 final PackageVerificationState state = mPendingVerification.get(verificationId); 1596 if (state == null) { 1597 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1598 break; 1599 } 1600 1601 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1602 1603 state.setVerifierResponse(response.callerUid, response.code); 1604 1605 if (state.isVerificationComplete()) { 1606 mPendingVerification.remove(verificationId); 1607 1608 final InstallArgs args = state.getInstallArgs(); 1609 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1610 1611 int ret; 1612 if (state.isInstallAllowed()) { 1613 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1614 broadcastPackageVerified(verificationId, originUri, 1615 response.code, state.getInstallArgs().getUser()); 1616 try { 1617 ret = args.copyApk(mContainerService, true); 1618 } catch (RemoteException e) { 1619 Slog.e(TAG, "Could not contact the ContainerService"); 1620 } 1621 } else { 1622 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1623 } 1624 1625 Trace.asyncTraceEnd( 1626 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1627 1628 processPendingInstall(args, ret); 1629 mHandler.sendEmptyMessage(MCS_UNBIND); 1630 } 1631 1632 break; 1633 } 1634 case START_INTENT_FILTER_VERIFICATIONS: { 1635 IFVerificationParams params = (IFVerificationParams) msg.obj; 1636 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1637 params.replacing, params.pkg); 1638 break; 1639 } 1640 case INTENT_FILTER_VERIFIED: { 1641 final int verificationId = msg.arg1; 1642 1643 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1644 verificationId); 1645 if (state == null) { 1646 Slog.w(TAG, "Invalid IntentFilter verification token " 1647 + verificationId + " received"); 1648 break; 1649 } 1650 1651 final int userId = state.getUserId(); 1652 1653 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1654 "Processing IntentFilter verification with token:" 1655 + verificationId + " and userId:" + userId); 1656 1657 final IntentFilterVerificationResponse response = 1658 (IntentFilterVerificationResponse) msg.obj; 1659 1660 state.setVerifierResponse(response.callerUid, response.code); 1661 1662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1663 "IntentFilter verification with token:" + verificationId 1664 + " and userId:" + userId 1665 + " is settings verifier response with response code:" 1666 + response.code); 1667 1668 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1669 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1670 + response.getFailedDomainsString()); 1671 } 1672 1673 if (state.isVerificationComplete()) { 1674 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1675 } else { 1676 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1677 "IntentFilter verification with token:" + verificationId 1678 + " was not said to be complete"); 1679 } 1680 1681 break; 1682 } 1683 } 1684 } 1685 } 1686 1687 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1688 boolean killApp, String[] grantedPermissions, 1689 IPackageInstallObserver2 installObserver) { 1690 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1691 // Send the removed broadcasts 1692 if (res.removedInfo != null) { 1693 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1694 } 1695 1696 // Now that we successfully installed the package, grant runtime 1697 // permissions if requested before broadcasting the install. 1698 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1699 >= Build.VERSION_CODES.M) { 1700 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1701 } 1702 1703 final boolean update = res.removedInfo != null 1704 && res.removedInfo.removedPackage != null; 1705 1706 // If this is the first time we have child packages for a disabled privileged 1707 // app that had no children, we grant requested runtime permissions to the new 1708 // children if the parent on the system image had them already granted. 1709 if (res.pkg.parentPackage != null) { 1710 synchronized (mPackages) { 1711 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1712 } 1713 } 1714 1715 synchronized (mPackages) { 1716 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1717 } 1718 1719 final String packageName = res.pkg.applicationInfo.packageName; 1720 Bundle extras = new Bundle(1); 1721 extras.putInt(Intent.EXTRA_UID, res.uid); 1722 1723 // Determine the set of users who are adding this package for 1724 // the first time vs. those who are seeing an update. 1725 int[] firstUsers = EMPTY_INT_ARRAY; 1726 int[] updateUsers = EMPTY_INT_ARRAY; 1727 if (res.origUsers == null || res.origUsers.length == 0) { 1728 firstUsers = res.newUsers; 1729 } else { 1730 for (int newUser : res.newUsers) { 1731 boolean isNew = true; 1732 for (int origUser : res.origUsers) { 1733 if (origUser == newUser) { 1734 isNew = false; 1735 break; 1736 } 1737 } 1738 if (isNew) { 1739 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1740 } else { 1741 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1742 } 1743 } 1744 } 1745 1746 // Send installed broadcasts if the install/update is not ephemeral 1747 if (!isEphemeral(res.pkg)) { 1748 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1749 1750 // Send added for users that see the package for the first time 1751 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1752 extras, 0 /*flags*/, null /*targetPackage*/, 1753 null /*finishedReceiver*/, firstUsers); 1754 1755 // Send added for users that don't see the package for the first time 1756 if (update) { 1757 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1758 } 1759 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1760 extras, 0 /*flags*/, null /*targetPackage*/, 1761 null /*finishedReceiver*/, updateUsers); 1762 1763 // Send replaced for users that don't see the package for the first time 1764 if (update) { 1765 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1766 packageName, extras, 0 /*flags*/, 1767 null /*targetPackage*/, null /*finishedReceiver*/, 1768 updateUsers); 1769 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1770 null /*package*/, null /*extras*/, 0 /*flags*/, 1771 packageName /*targetPackage*/, 1772 null /*finishedReceiver*/, updateUsers); 1773 } 1774 1775 // Send broadcast package appeared if forward locked/external for all users 1776 // treat asec-hosted packages like removable media on upgrade 1777 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1778 if (DEBUG_INSTALL) { 1779 Slog.i(TAG, "upgrading pkg " + res.pkg 1780 + " is ASEC-hosted -> AVAILABLE"); 1781 } 1782 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1783 ArrayList<String> pkgList = new ArrayList<>(1); 1784 pkgList.add(packageName); 1785 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1786 } 1787 } 1788 1789 // Work that needs to happen on first install within each user 1790 if (firstUsers != null && firstUsers.length > 0) { 1791 synchronized (mPackages) { 1792 for (int userId : firstUsers) { 1793 // If this app is a browser and it's newly-installed for some 1794 // users, clear any default-browser state in those users. The 1795 // app's nature doesn't depend on the user, so we can just check 1796 // its browser nature in any user and generalize. 1797 if (packageIsBrowser(packageName, userId)) { 1798 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1799 } 1800 1801 // We may also need to apply pending (restored) runtime 1802 // permission grants within these users. 1803 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1804 } 1805 } 1806 } 1807 1808 // Log current value of "unknown sources" setting 1809 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1810 getUnknownSourcesSettings()); 1811 1812 // Force a gc to clear up things 1813 Runtime.getRuntime().gc(); 1814 1815 // Remove the replaced package's older resources safely now 1816 // We delete after a gc for applications on sdcard. 1817 if (res.removedInfo != null && res.removedInfo.args != null) { 1818 synchronized (mInstallLock) { 1819 res.removedInfo.args.doPostDeleteLI(true); 1820 } 1821 } 1822 } 1823 1824 // If someone is watching installs - notify them 1825 if (installObserver != null) { 1826 try { 1827 Bundle extras = extrasForInstallResult(res); 1828 installObserver.onPackageInstalled(res.name, res.returnCode, 1829 res.returnMsg, extras); 1830 } catch (RemoteException e) { 1831 Slog.i(TAG, "Observer no longer exists."); 1832 } 1833 } 1834 } 1835 1836 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1837 PackageParser.Package pkg) { 1838 if (pkg.parentPackage == null) { 1839 return; 1840 } 1841 if (pkg.requestedPermissions == null) { 1842 return; 1843 } 1844 final PackageSetting disabledSysParentPs = mSettings 1845 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1846 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1847 || !disabledSysParentPs.isPrivileged() 1848 || (disabledSysParentPs.childPackageNames != null 1849 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1850 return; 1851 } 1852 final int[] allUserIds = sUserManager.getUserIds(); 1853 final int permCount = pkg.requestedPermissions.size(); 1854 for (int i = 0; i < permCount; i++) { 1855 String permission = pkg.requestedPermissions.get(i); 1856 BasePermission bp = mSettings.mPermissions.get(permission); 1857 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1858 continue; 1859 } 1860 for (int userId : allUserIds) { 1861 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1862 permission, userId)) { 1863 grantRuntimePermission(pkg.packageName, permission, userId); 1864 } 1865 } 1866 } 1867 } 1868 1869 private StorageEventListener mStorageListener = new StorageEventListener() { 1870 @Override 1871 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1872 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1873 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1874 final String volumeUuid = vol.getFsUuid(); 1875 1876 // Clean up any users or apps that were removed or recreated 1877 // while this volume was missing 1878 reconcileUsers(volumeUuid); 1879 reconcileApps(volumeUuid); 1880 1881 // Clean up any install sessions that expired or were 1882 // cancelled while this volume was missing 1883 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1884 1885 loadPrivatePackages(vol); 1886 1887 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1888 unloadPrivatePackages(vol); 1889 } 1890 } 1891 1892 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1893 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1894 updateExternalMediaStatus(true, false); 1895 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1896 updateExternalMediaStatus(false, false); 1897 } 1898 } 1899 } 1900 1901 @Override 1902 public void onVolumeForgotten(String fsUuid) { 1903 if (TextUtils.isEmpty(fsUuid)) { 1904 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1905 return; 1906 } 1907 1908 // Remove any apps installed on the forgotten volume 1909 synchronized (mPackages) { 1910 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1911 for (PackageSetting ps : packages) { 1912 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1913 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1914 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1915 } 1916 1917 mSettings.onVolumeForgotten(fsUuid); 1918 mSettings.writeLPr(); 1919 } 1920 } 1921 }; 1922 1923 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1924 String[] grantedPermissions) { 1925 for (int userId : userIds) { 1926 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1927 } 1928 1929 // We could have touched GID membership, so flush out packages.list 1930 synchronized (mPackages) { 1931 mSettings.writePackageListLPr(); 1932 } 1933 } 1934 1935 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1936 String[] grantedPermissions) { 1937 SettingBase sb = (SettingBase) pkg.mExtras; 1938 if (sb == null) { 1939 return; 1940 } 1941 1942 PermissionsState permissionsState = sb.getPermissionsState(); 1943 1944 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1945 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1946 1947 synchronized (mPackages) { 1948 for (String permission : pkg.requestedPermissions) { 1949 BasePermission bp = mSettings.mPermissions.get(permission); 1950 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1951 && (grantedPermissions == null 1952 || ArrayUtils.contains(grantedPermissions, permission))) { 1953 final int flags = permissionsState.getPermissionFlags(permission, userId); 1954 // Installer cannot change immutable permissions. 1955 if ((flags & immutableFlags) == 0) { 1956 grantRuntimePermission(pkg.packageName, permission, userId); 1957 } 1958 } 1959 } 1960 } 1961 } 1962 1963 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1964 Bundle extras = null; 1965 switch (res.returnCode) { 1966 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1967 extras = new Bundle(); 1968 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1969 res.origPermission); 1970 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1971 res.origPackage); 1972 break; 1973 } 1974 case PackageManager.INSTALL_SUCCEEDED: { 1975 extras = new Bundle(); 1976 extras.putBoolean(Intent.EXTRA_REPLACING, 1977 res.removedInfo != null && res.removedInfo.removedPackage != null); 1978 break; 1979 } 1980 } 1981 return extras; 1982 } 1983 1984 void scheduleWriteSettingsLocked() { 1985 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1986 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1987 } 1988 } 1989 1990 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1991 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1992 scheduleWritePackageRestrictionsLocked(userId); 1993 } 1994 1995 void scheduleWritePackageRestrictionsLocked(int userId) { 1996 final int[] userIds = (userId == UserHandle.USER_ALL) 1997 ? sUserManager.getUserIds() : new int[]{userId}; 1998 for (int nextUserId : userIds) { 1999 if (!sUserManager.exists(nextUserId)) return; 2000 mDirtyUsers.add(nextUserId); 2001 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2002 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2003 } 2004 } 2005 } 2006 2007 public static PackageManagerService main(Context context, Installer installer, 2008 boolean factoryTest, boolean onlyCore) { 2009 // Self-check for initial settings. 2010 PackageManagerServiceCompilerMapping.checkProperties(); 2011 2012 PackageManagerService m = new PackageManagerService(context, installer, 2013 factoryTest, onlyCore); 2014 m.enableSystemUserPackages(); 2015 ServiceManager.addService("package", m); 2016 return m; 2017 } 2018 2019 private void enableSystemUserPackages() { 2020 if (!UserManager.isSplitSystemUser()) { 2021 return; 2022 } 2023 // For system user, enable apps based on the following conditions: 2024 // - app is whitelisted or belong to one of these groups: 2025 // -- system app which has no launcher icons 2026 // -- system app which has INTERACT_ACROSS_USERS permission 2027 // -- system IME app 2028 // - app is not in the blacklist 2029 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2030 Set<String> enableApps = new ArraySet<>(); 2031 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2032 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2033 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2034 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2035 enableApps.addAll(wlApps); 2036 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2037 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2038 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2039 enableApps.removeAll(blApps); 2040 Log.i(TAG, "Applications installed for system user: " + enableApps); 2041 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2042 UserHandle.SYSTEM); 2043 final int allAppsSize = allAps.size(); 2044 synchronized (mPackages) { 2045 for (int i = 0; i < allAppsSize; i++) { 2046 String pName = allAps.get(i); 2047 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2048 // Should not happen, but we shouldn't be failing if it does 2049 if (pkgSetting == null) { 2050 continue; 2051 } 2052 boolean install = enableApps.contains(pName); 2053 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2054 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2055 + " for system user"); 2056 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2057 } 2058 } 2059 } 2060 } 2061 2062 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2063 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2064 Context.DISPLAY_SERVICE); 2065 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2066 } 2067 2068 public PackageManagerService(Context context, Installer installer, 2069 boolean factoryTest, boolean onlyCore) { 2070 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2071 SystemClock.uptimeMillis()); 2072 2073 if (mSdkVersion <= 0) { 2074 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2075 } 2076 2077 mContext = context; 2078 mFactoryTest = factoryTest; 2079 mOnlyCore = onlyCore; 2080 mMetrics = new DisplayMetrics(); 2081 mSettings = new Settings(mPackages); 2082 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2083 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2084 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2085 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2086 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2087 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2088 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2089 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2090 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2091 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2092 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2094 2095 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2096 if (separateProcesses != null && separateProcesses.length() > 0) { 2097 if ("*".equals(separateProcesses)) { 2098 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2099 mSeparateProcesses = null; 2100 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2101 } else { 2102 mDefParseFlags = 0; 2103 mSeparateProcesses = separateProcesses.split(","); 2104 Slog.w(TAG, "Running with debug.separate_processes: " 2105 + separateProcesses); 2106 } 2107 } else { 2108 mDefParseFlags = 0; 2109 mSeparateProcesses = null; 2110 } 2111 2112 mInstaller = installer; 2113 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2114 "*dexopt*"); 2115 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2116 2117 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2118 FgThread.get().getLooper()); 2119 2120 getDefaultDisplayMetrics(context, mMetrics); 2121 2122 SystemConfig systemConfig = SystemConfig.getInstance(); 2123 mGlobalGids = systemConfig.getGlobalGids(); 2124 mSystemPermissions = systemConfig.getSystemPermissions(); 2125 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2126 2127 synchronized (mInstallLock) { 2128 // writer 2129 synchronized (mPackages) { 2130 mHandlerThread = new ServiceThread(TAG, 2131 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2132 mHandlerThread.start(); 2133 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2134 mProcessLoggingHandler = new ProcessLoggingHandler(); 2135 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2136 2137 File dataDir = Environment.getDataDirectory(); 2138 mAppInstallDir = new File(dataDir, "app"); 2139 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2140 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2141 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2142 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2143 2144 sUserManager = new UserManagerService(context, this, mPackages); 2145 2146 // Propagate permission configuration in to package manager. 2147 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2148 = systemConfig.getPermissions(); 2149 for (int i=0; i<permConfig.size(); i++) { 2150 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2151 BasePermission bp = mSettings.mPermissions.get(perm.name); 2152 if (bp == null) { 2153 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2154 mSettings.mPermissions.put(perm.name, bp); 2155 } 2156 if (perm.gids != null) { 2157 bp.setGids(perm.gids, perm.perUser); 2158 } 2159 } 2160 2161 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2162 for (int i=0; i<libConfig.size(); i++) { 2163 mSharedLibraries.put(libConfig.keyAt(i), 2164 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2165 } 2166 2167 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2168 2169 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2170 2171 String customResolverActivity = Resources.getSystem().getString( 2172 R.string.config_customResolverActivity); 2173 if (TextUtils.isEmpty(customResolverActivity)) { 2174 customResolverActivity = null; 2175 } else { 2176 mCustomResolverComponentName = ComponentName.unflattenFromString( 2177 customResolverActivity); 2178 } 2179 2180 long startTime = SystemClock.uptimeMillis(); 2181 2182 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2183 startTime); 2184 2185 // Set flag to monitor and not change apk file paths when 2186 // scanning install directories. 2187 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2188 2189 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2190 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2191 2192 if (bootClassPath == null) { 2193 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2194 } 2195 2196 if (systemServerClassPath == null) { 2197 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2198 } 2199 2200 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2201 final String[] dexCodeInstructionSets = 2202 getDexCodeInstructionSets( 2203 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2204 2205 /** 2206 * Ensure all external libraries have had dexopt run on them. 2207 */ 2208 if (mSharedLibraries.size() > 0) { 2209 // NOTE: For now, we're compiling these system "shared libraries" 2210 // (and framework jars) into all available architectures. It's possible 2211 // to compile them only when we come across an app that uses them (there's 2212 // already logic for that in scanPackageLI) but that adds some complexity. 2213 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2214 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2215 final String lib = libEntry.path; 2216 if (lib == null) { 2217 continue; 2218 } 2219 2220 try { 2221 // Shared libraries do not have profiles so we perform a full 2222 // AOT compilation (if needed). 2223 int dexoptNeeded = DexFile.getDexOptNeeded( 2224 lib, dexCodeInstructionSet, 2225 getCompilerFilterForReason(REASON_SHARED_APK), 2226 false /* newProfile */); 2227 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2228 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2229 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2230 getCompilerFilterForReason(REASON_SHARED_APK), 2231 StorageManager.UUID_PRIVATE_INTERNAL); 2232 } 2233 } catch (FileNotFoundException e) { 2234 Slog.w(TAG, "Library not found: " + lib); 2235 } catch (IOException | InstallerException e) { 2236 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2237 + e.getMessage()); 2238 } 2239 } 2240 } 2241 } 2242 2243 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2244 2245 final VersionInfo ver = mSettings.getInternalVersion(); 2246 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2247 2248 // when upgrading from pre-M, promote system app permissions from install to runtime 2249 mPromoteSystemApps = 2250 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2251 2252 // save off the names of pre-existing system packages prior to scanning; we don't 2253 // want to automatically grant runtime permissions for new system apps 2254 if (mPromoteSystemApps) { 2255 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2256 while (pkgSettingIter.hasNext()) { 2257 PackageSetting ps = pkgSettingIter.next(); 2258 if (isSystemApp(ps)) { 2259 mExistingSystemPackages.add(ps.name); 2260 } 2261 } 2262 } 2263 2264 // When upgrading from pre-N, we need to handle package extraction like first boot, 2265 // as there is no profiling data available. 2266 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2267 mSettings.setNWorkDone(); 2268 2269 // Collect vendor overlay packages. 2270 // (Do this before scanning any apps.) 2271 // For security and version matching reason, only consider 2272 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2273 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2274 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2276 2277 // Find base frameworks (resource packages without code). 2278 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2279 | PackageParser.PARSE_IS_SYSTEM_DIR 2280 | PackageParser.PARSE_IS_PRIVILEGED, 2281 scanFlags | SCAN_NO_DEX, 0); 2282 2283 // Collected privileged system packages. 2284 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2285 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2286 | PackageParser.PARSE_IS_SYSTEM_DIR 2287 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2288 2289 // Collect ordinary system packages. 2290 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2291 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2292 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2293 2294 // Collect all vendor packages. 2295 File vendorAppDir = new File("/vendor/app"); 2296 try { 2297 vendorAppDir = vendorAppDir.getCanonicalFile(); 2298 } catch (IOException e) { 2299 // failed to look up canonical path, continue with original one 2300 } 2301 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2302 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2303 2304 // Collect all OEM packages. 2305 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2306 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2308 2309 // Prune any system packages that no longer exist. 2310 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2311 if (!mOnlyCore) { 2312 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2313 while (psit.hasNext()) { 2314 PackageSetting ps = psit.next(); 2315 2316 /* 2317 * If this is not a system app, it can't be a 2318 * disable system app. 2319 */ 2320 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2321 continue; 2322 } 2323 2324 /* 2325 * If the package is scanned, it's not erased. 2326 */ 2327 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2328 if (scannedPkg != null) { 2329 /* 2330 * If the system app is both scanned and in the 2331 * disabled packages list, then it must have been 2332 * added via OTA. Remove it from the currently 2333 * scanned package so the previously user-installed 2334 * application can be scanned. 2335 */ 2336 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2337 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2338 + ps.name + "; removing system app. Last known codePath=" 2339 + ps.codePathString + ", installStatus=" + ps.installStatus 2340 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2341 + scannedPkg.mVersionCode); 2342 removePackageLI(scannedPkg, true); 2343 mExpectingBetter.put(ps.name, ps.codePath); 2344 } 2345 2346 continue; 2347 } 2348 2349 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2350 psit.remove(); 2351 logCriticalInfo(Log.WARN, "System package " + ps.name 2352 + " no longer exists; wiping its data"); 2353 removeDataDirsLI(null, ps.name); 2354 } else { 2355 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2356 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2357 possiblyDeletedUpdatedSystemApps.add(ps.name); 2358 } 2359 } 2360 } 2361 } 2362 2363 //look for any incomplete package installations 2364 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2365 //clean up list 2366 for(int i = 0; i < deletePkgsList.size(); i++) { 2367 //clean up here 2368 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2369 } 2370 //delete tmp files 2371 deleteTempPackageFiles(); 2372 2373 // Remove any shared userIDs that have no associated packages 2374 mSettings.pruneSharedUsersLPw(); 2375 2376 if (!mOnlyCore) { 2377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2378 SystemClock.uptimeMillis()); 2379 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2380 2381 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2382 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2383 2384 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2385 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2386 2387 /** 2388 * Remove disable package settings for any updated system 2389 * apps that were removed via an OTA. If they're not a 2390 * previously-updated app, remove them completely. 2391 * Otherwise, just revoke their system-level permissions. 2392 */ 2393 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2394 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2395 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2396 2397 String msg; 2398 if (deletedPkg == null) { 2399 msg = "Updated system package " + deletedAppName 2400 + " no longer exists; wiping its data"; 2401 removeDataDirsLI(null, deletedAppName); 2402 } else { 2403 msg = "Updated system app + " + deletedAppName 2404 + " no longer present; removing system privileges for " 2405 + deletedAppName; 2406 2407 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2408 2409 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2410 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2411 } 2412 logCriticalInfo(Log.WARN, msg); 2413 } 2414 2415 /** 2416 * Make sure all system apps that we expected to appear on 2417 * the userdata partition actually showed up. If they never 2418 * appeared, crawl back and revive the system version. 2419 */ 2420 for (int i = 0; i < mExpectingBetter.size(); i++) { 2421 final String packageName = mExpectingBetter.keyAt(i); 2422 if (!mPackages.containsKey(packageName)) { 2423 final File scanFile = mExpectingBetter.valueAt(i); 2424 2425 logCriticalInfo(Log.WARN, "Expected better " + packageName 2426 + " but never showed up; reverting to system"); 2427 2428 final int reparseFlags; 2429 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2430 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2431 | PackageParser.PARSE_IS_SYSTEM_DIR 2432 | PackageParser.PARSE_IS_PRIVILEGED; 2433 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2434 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2435 | PackageParser.PARSE_IS_SYSTEM_DIR; 2436 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2437 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR; 2439 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2440 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR; 2442 } else { 2443 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2444 continue; 2445 } 2446 2447 mSettings.enableSystemPackageLPw(packageName); 2448 2449 try { 2450 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2451 } catch (PackageManagerException e) { 2452 Slog.e(TAG, "Failed to parse original system package: " 2453 + e.getMessage()); 2454 } 2455 } 2456 } 2457 } 2458 mExpectingBetter.clear(); 2459 2460 // Resolve protected action filters. Only the setup wizard is allowed to 2461 // have a high priority filter for these actions. 2462 mSetupWizardPackage = getSetupWizardPackageName(); 2463 if (mProtectedFilters.size() > 0) { 2464 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2465 Slog.i(TAG, "No setup wizard;" 2466 + " All protected intents capped to priority 0"); 2467 } 2468 for (ActivityIntentInfo filter : mProtectedFilters) { 2469 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2470 if (DEBUG_FILTERS) { 2471 Slog.i(TAG, "Found setup wizard;" 2472 + " allow priority " + filter.getPriority() + ";" 2473 + " package: " + filter.activity.info.packageName 2474 + " activity: " + filter.activity.className 2475 + " priority: " + filter.getPriority()); 2476 } 2477 // skip setup wizard; allow it to keep the high priority filter 2478 continue; 2479 } 2480 Slog.w(TAG, "Protected action; cap priority to 0;" 2481 + " package: " + filter.activity.info.packageName 2482 + " activity: " + filter.activity.className 2483 + " origPrio: " + filter.getPriority()); 2484 filter.setPriority(0); 2485 } 2486 } 2487 mDeferProtectedFilters = false; 2488 mProtectedFilters.clear(); 2489 2490 // Now that we know all of the shared libraries, update all clients to have 2491 // the correct library paths. 2492 updateAllSharedLibrariesLPw(); 2493 2494 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2495 // NOTE: We ignore potential failures here during a system scan (like 2496 // the rest of the commands above) because there's precious little we 2497 // can do about it. A settings error is reported, though. 2498 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2499 false /* boot complete */); 2500 } 2501 2502 // Now that we know all the packages we are keeping, 2503 // read and update their last usage times. 2504 mPackageUsage.readLP(); 2505 2506 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2507 SystemClock.uptimeMillis()); 2508 Slog.i(TAG, "Time to scan packages: " 2509 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2510 + " seconds"); 2511 2512 // If the platform SDK has changed since the last time we booted, 2513 // we need to re-grant app permission to catch any new ones that 2514 // appear. This is really a hack, and means that apps can in some 2515 // cases get permissions that the user didn't initially explicitly 2516 // allow... it would be nice to have some better way to handle 2517 // this situation. 2518 int updateFlags = UPDATE_PERMISSIONS_ALL; 2519 if (ver.sdkVersion != mSdkVersion) { 2520 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2521 + mSdkVersion + "; regranting permissions for internal storage"); 2522 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2523 } 2524 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2525 ver.sdkVersion = mSdkVersion; 2526 2527 // If this is the first boot or an update from pre-M, and it is a normal 2528 // boot, then we need to initialize the default preferred apps across 2529 // all defined users. 2530 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2531 for (UserInfo user : sUserManager.getUsers(true)) { 2532 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2533 applyFactoryDefaultBrowserLPw(user.id); 2534 primeDomainVerificationsLPw(user.id); 2535 } 2536 } 2537 2538 // Prepare storage for system user really early during boot, 2539 // since core system apps like SettingsProvider and SystemUI 2540 // can't wait for user to start 2541 final int storageFlags; 2542 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2543 storageFlags = StorageManager.FLAG_STORAGE_DE; 2544 } else { 2545 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2546 } 2547 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2548 storageFlags); 2549 2550 // If this is first boot after an OTA, and a normal boot, then 2551 // we need to clear code cache directories. 2552 if (mIsUpgrade && !onlyCore) { 2553 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2554 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2555 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2556 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2557 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2558 } 2559 } 2560 ver.fingerprint = Build.FINGERPRINT; 2561 } 2562 2563 checkDefaultBrowser(); 2564 2565 // clear only after permissions and other defaults have been updated 2566 mExistingSystemPackages.clear(); 2567 mPromoteSystemApps = false; 2568 2569 // All the changes are done during package scanning. 2570 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2571 2572 // can downgrade to reader 2573 mSettings.writeLPr(); 2574 2575 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2576 SystemClock.uptimeMillis()); 2577 2578 if (!mOnlyCore) { 2579 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2580 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2581 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2582 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2583 mIntentFilterVerifierComponent); 2584 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2585 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2586 getRequiredSharedLibraryLPr( 2587 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2588 } else { 2589 mRequiredVerifierPackage = null; 2590 mRequiredInstallerPackage = null; 2591 mIntentFilterVerifierComponent = null; 2592 mIntentFilterVerifier = null; 2593 mServicesSystemSharedLibraryPackageName = null; 2594 } 2595 2596 mInstallerService = new PackageInstallerService(context, this); 2597 2598 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2599 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2600 // both the installer and resolver must be present to enable ephemeral 2601 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2602 if (DEBUG_EPHEMERAL) { 2603 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2604 + " installer:" + ephemeralInstallerComponent); 2605 } 2606 mEphemeralResolverComponent = ephemeralResolverComponent; 2607 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2608 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2609 mEphemeralResolverConnection = 2610 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2611 } else { 2612 if (DEBUG_EPHEMERAL) { 2613 final String missingComponent = 2614 (ephemeralResolverComponent == null) 2615 ? (ephemeralInstallerComponent == null) 2616 ? "resolver and installer" 2617 : "resolver" 2618 : "installer"; 2619 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2620 } 2621 mEphemeralResolverComponent = null; 2622 mEphemeralInstallerComponent = null; 2623 mEphemeralResolverConnection = null; 2624 } 2625 2626 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2627 } // synchronized (mPackages) 2628 } // synchronized (mInstallLock) 2629 2630 // Now after opening every single application zip, make sure they 2631 // are all flushed. Not really needed, but keeps things nice and 2632 // tidy. 2633 Runtime.getRuntime().gc(); 2634 2635 // The initial scanning above does many calls into installd while 2636 // holding the mPackages lock, but we're mostly interested in yelling 2637 // once we have a booted system. 2638 mInstaller.setWarnIfHeld(mPackages); 2639 2640 // Expose private service for system components to use. 2641 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2642 } 2643 2644 @Override 2645 public boolean isFirstBoot() { 2646 return !mRestoredSettings; 2647 } 2648 2649 @Override 2650 public boolean isOnlyCoreApps() { 2651 return mOnlyCore; 2652 } 2653 2654 @Override 2655 public boolean isUpgrade() { 2656 return mIsUpgrade; 2657 } 2658 2659 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2660 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2661 2662 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2663 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2664 UserHandle.USER_SYSTEM); 2665 if (matches.size() == 1) { 2666 return matches.get(0).getComponentInfo().packageName; 2667 } else { 2668 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2669 return null; 2670 } 2671 } 2672 2673 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2674 synchronized (mPackages) { 2675 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2676 if (libraryEntry == null) { 2677 throw new IllegalStateException("Missing required shared library:" + libraryName); 2678 } 2679 return libraryEntry.apk; 2680 } 2681 } 2682 2683 private @NonNull String getRequiredInstallerLPr() { 2684 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2685 intent.addCategory(Intent.CATEGORY_DEFAULT); 2686 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2687 2688 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2689 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2690 UserHandle.USER_SYSTEM); 2691 if (matches.size() == 1) { 2692 ResolveInfo resolveInfo = matches.get(0); 2693 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2694 throw new RuntimeException("The installer must be a privileged app"); 2695 } 2696 return matches.get(0).getComponentInfo().packageName; 2697 } else { 2698 throw new RuntimeException("There must be exactly one installer; found " + matches); 2699 } 2700 } 2701 2702 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2703 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2704 2705 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2706 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2707 UserHandle.USER_SYSTEM); 2708 ResolveInfo best = null; 2709 final int N = matches.size(); 2710 for (int i = 0; i < N; i++) { 2711 final ResolveInfo cur = matches.get(i); 2712 final String packageName = cur.getComponentInfo().packageName; 2713 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2714 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2715 continue; 2716 } 2717 2718 if (best == null || cur.priority > best.priority) { 2719 best = cur; 2720 } 2721 } 2722 2723 if (best != null) { 2724 return best.getComponentInfo().getComponentName(); 2725 } else { 2726 throw new RuntimeException("There must be at least one intent filter verifier"); 2727 } 2728 } 2729 2730 private @Nullable ComponentName getEphemeralResolverLPr() { 2731 final String[] packageArray = 2732 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2733 if (packageArray.length == 0) { 2734 if (DEBUG_EPHEMERAL) { 2735 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2736 } 2737 return null; 2738 } 2739 2740 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2741 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2742 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2743 UserHandle.USER_SYSTEM); 2744 2745 final int N = resolvers.size(); 2746 if (N == 0) { 2747 if (DEBUG_EPHEMERAL) { 2748 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2749 } 2750 return null; 2751 } 2752 2753 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2754 for (int i = 0; i < N; i++) { 2755 final ResolveInfo info = resolvers.get(i); 2756 2757 if (info.serviceInfo == null) { 2758 continue; 2759 } 2760 2761 final String packageName = info.serviceInfo.packageName; 2762 if (!possiblePackages.contains(packageName)) { 2763 if (DEBUG_EPHEMERAL) { 2764 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2765 + " pkg: " + packageName + ", info:" + info); 2766 } 2767 continue; 2768 } 2769 2770 if (DEBUG_EPHEMERAL) { 2771 Slog.v(TAG, "Ephemeral resolver found;" 2772 + " pkg: " + packageName + ", info:" + info); 2773 } 2774 return new ComponentName(packageName, info.serviceInfo.name); 2775 } 2776 if (DEBUG_EPHEMERAL) { 2777 Slog.v(TAG, "Ephemeral resolver NOT found"); 2778 } 2779 return null; 2780 } 2781 2782 private @Nullable ComponentName getEphemeralInstallerLPr() { 2783 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2784 intent.addCategory(Intent.CATEGORY_DEFAULT); 2785 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2786 2787 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2788 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2789 UserHandle.USER_SYSTEM); 2790 if (matches.size() == 0) { 2791 return null; 2792 } else if (matches.size() == 1) { 2793 return matches.get(0).getComponentInfo().getComponentName(); 2794 } else { 2795 throw new RuntimeException( 2796 "There must be at most one ephemeral installer; found " + matches); 2797 } 2798 } 2799 2800 private void primeDomainVerificationsLPw(int userId) { 2801 if (DEBUG_DOMAIN_VERIFICATION) { 2802 Slog.d(TAG, "Priming domain verifications in user " + userId); 2803 } 2804 2805 SystemConfig systemConfig = SystemConfig.getInstance(); 2806 ArraySet<String> packages = systemConfig.getLinkedApps(); 2807 ArraySet<String> domains = new ArraySet<String>(); 2808 2809 for (String packageName : packages) { 2810 PackageParser.Package pkg = mPackages.get(packageName); 2811 if (pkg != null) { 2812 if (!pkg.isSystemApp()) { 2813 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2814 continue; 2815 } 2816 2817 domains.clear(); 2818 for (PackageParser.Activity a : pkg.activities) { 2819 for (ActivityIntentInfo filter : a.intents) { 2820 if (hasValidDomains(filter)) { 2821 domains.addAll(filter.getHostsList()); 2822 } 2823 } 2824 } 2825 2826 if (domains.size() > 0) { 2827 if (DEBUG_DOMAIN_VERIFICATION) { 2828 Slog.v(TAG, " + " + packageName); 2829 } 2830 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2831 // state w.r.t. the formal app-linkage "no verification attempted" state; 2832 // and then 'always' in the per-user state actually used for intent resolution. 2833 final IntentFilterVerificationInfo ivi; 2834 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2835 new ArrayList<String>(domains)); 2836 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2837 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2838 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2839 } else { 2840 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2841 + "' does not handle web links"); 2842 } 2843 } else { 2844 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2845 } 2846 } 2847 2848 scheduleWritePackageRestrictionsLocked(userId); 2849 scheduleWriteSettingsLocked(); 2850 } 2851 2852 private void applyFactoryDefaultBrowserLPw(int userId) { 2853 // The default browser app's package name is stored in a string resource, 2854 // with a product-specific overlay used for vendor customization. 2855 String browserPkg = mContext.getResources().getString( 2856 com.android.internal.R.string.default_browser); 2857 if (!TextUtils.isEmpty(browserPkg)) { 2858 // non-empty string => required to be a known package 2859 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2860 if (ps == null) { 2861 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2862 browserPkg = null; 2863 } else { 2864 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2865 } 2866 } 2867 2868 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2869 // default. If there's more than one, just leave everything alone. 2870 if (browserPkg == null) { 2871 calculateDefaultBrowserLPw(userId); 2872 } 2873 } 2874 2875 private void calculateDefaultBrowserLPw(int userId) { 2876 List<String> allBrowsers = resolveAllBrowserApps(userId); 2877 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2878 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2879 } 2880 2881 private List<String> resolveAllBrowserApps(int userId) { 2882 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2883 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2884 PackageManager.MATCH_ALL, userId); 2885 2886 final int count = list.size(); 2887 List<String> result = new ArrayList<String>(count); 2888 for (int i=0; i<count; i++) { 2889 ResolveInfo info = list.get(i); 2890 if (info.activityInfo == null 2891 || !info.handleAllWebDataURI 2892 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2893 || result.contains(info.activityInfo.packageName)) { 2894 continue; 2895 } 2896 result.add(info.activityInfo.packageName); 2897 } 2898 2899 return result; 2900 } 2901 2902 private boolean packageIsBrowser(String packageName, int userId) { 2903 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2904 PackageManager.MATCH_ALL, userId); 2905 final int N = list.size(); 2906 for (int i = 0; i < N; i++) { 2907 ResolveInfo info = list.get(i); 2908 if (packageName.equals(info.activityInfo.packageName)) { 2909 return true; 2910 } 2911 } 2912 return false; 2913 } 2914 2915 private void checkDefaultBrowser() { 2916 final int myUserId = UserHandle.myUserId(); 2917 final String packageName = getDefaultBrowserPackageName(myUserId); 2918 if (packageName != null) { 2919 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2920 if (info == null) { 2921 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2922 synchronized (mPackages) { 2923 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2924 } 2925 } 2926 } 2927 } 2928 2929 @Override 2930 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2931 throws RemoteException { 2932 try { 2933 return super.onTransact(code, data, reply, flags); 2934 } catch (RuntimeException e) { 2935 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2936 Slog.wtf(TAG, "Package Manager Crash", e); 2937 } 2938 throw e; 2939 } 2940 } 2941 2942 void cleanupInstallFailedPackage(PackageSetting ps) { 2943 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2944 2945 removeDataDirsLI(ps.volumeUuid, ps.name); 2946 if (ps.codePath != null) { 2947 removeCodePathLI(ps.codePath); 2948 } 2949 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2950 if (ps.resourcePath.isDirectory()) { 2951 FileUtils.deleteContents(ps.resourcePath); 2952 } 2953 ps.resourcePath.delete(); 2954 } 2955 mSettings.removePackageLPw(ps.name); 2956 } 2957 2958 static int[] appendInts(int[] cur, int[] add) { 2959 if (add == null) return cur; 2960 if (cur == null) return add; 2961 final int N = add.length; 2962 for (int i=0; i<N; i++) { 2963 cur = appendInt(cur, add[i]); 2964 } 2965 return cur; 2966 } 2967 2968 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 2969 if (!sUserManager.exists(userId)) return null; 2970 if (ps == null) { 2971 return null; 2972 } 2973 final PackageParser.Package p = ps.pkg; 2974 if (p == null) { 2975 return null; 2976 } 2977 2978 final PermissionsState permissionsState = ps.getPermissionsState(); 2979 2980 final int[] gids = permissionsState.computeGids(userId); 2981 final Set<String> permissions = permissionsState.getPermissions(userId); 2982 final PackageUserState state = ps.readUserState(userId); 2983 2984 return PackageParser.generatePackageInfo(p, gids, flags, 2985 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2986 } 2987 2988 @Override 2989 public void checkPackageStartable(String packageName, int userId) { 2990 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2991 2992 synchronized (mPackages) { 2993 final PackageSetting ps = mSettings.mPackages.get(packageName); 2994 if (ps == null) { 2995 throw new SecurityException("Package " + packageName + " was not found!"); 2996 } 2997 2998 if (!ps.getInstalled(userId)) { 2999 throw new SecurityException( 3000 "Package " + packageName + " was not installed for user " + userId + "!"); 3001 } 3002 3003 if (mSafeMode && !ps.isSystem()) { 3004 throw new SecurityException("Package " + packageName + " not a system app!"); 3005 } 3006 3007 if (ps.frozen) { 3008 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3009 } 3010 3011 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3012 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3013 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3014 } 3015 } 3016 } 3017 3018 @Override 3019 public boolean isPackageAvailable(String packageName, int userId) { 3020 if (!sUserManager.exists(userId)) return false; 3021 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3022 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3023 synchronized (mPackages) { 3024 PackageParser.Package p = mPackages.get(packageName); 3025 if (p != null) { 3026 final PackageSetting ps = (PackageSetting) p.mExtras; 3027 if (ps != null) { 3028 final PackageUserState state = ps.readUserState(userId); 3029 if (state != null) { 3030 return PackageParser.isAvailable(state); 3031 } 3032 } 3033 } 3034 } 3035 return false; 3036 } 3037 3038 @Override 3039 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3040 if (!sUserManager.exists(userId)) return null; 3041 flags = updateFlagsForPackage(flags, userId, packageName); 3042 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3043 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3044 // reader 3045 synchronized (mPackages) { 3046 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3047 PackageParser.Package p = null; 3048 if (matchFactoryOnly) { 3049 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3050 if (ps != null) { 3051 return generatePackageInfo(ps, flags, userId); 3052 } 3053 } 3054 if (p == null) { 3055 p = mPackages.get(packageName); 3056 if (matchFactoryOnly && !isSystemApp(p)) { 3057 return null; 3058 } 3059 } 3060 if (DEBUG_PACKAGE_INFO) 3061 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3062 if (p != null) { 3063 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3064 } 3065 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3066 final PackageSetting ps = mSettings.mPackages.get(packageName); 3067 return generatePackageInfo(ps, flags, userId); 3068 } 3069 } 3070 return null; 3071 } 3072 3073 @Override 3074 public String[] currentToCanonicalPackageNames(String[] names) { 3075 String[] out = new String[names.length]; 3076 // reader 3077 synchronized (mPackages) { 3078 for (int i=names.length-1; i>=0; i--) { 3079 PackageSetting ps = mSettings.mPackages.get(names[i]); 3080 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3081 } 3082 } 3083 return out; 3084 } 3085 3086 @Override 3087 public String[] canonicalToCurrentPackageNames(String[] names) { 3088 String[] out = new String[names.length]; 3089 // reader 3090 synchronized (mPackages) { 3091 for (int i=names.length-1; i>=0; i--) { 3092 String cur = mSettings.mRenamedPackages.get(names[i]); 3093 out[i] = cur != null ? cur : names[i]; 3094 } 3095 } 3096 return out; 3097 } 3098 3099 @Override 3100 public int getPackageUid(String packageName, int flags, int userId) { 3101 if (!sUserManager.exists(userId)) return -1; 3102 flags = updateFlagsForPackage(flags, userId, packageName); 3103 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3104 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3105 3106 // reader 3107 synchronized (mPackages) { 3108 final PackageParser.Package p = mPackages.get(packageName); 3109 if (p != null && p.isMatch(flags)) { 3110 return UserHandle.getUid(userId, p.applicationInfo.uid); 3111 } 3112 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3113 final PackageSetting ps = mSettings.mPackages.get(packageName); 3114 if (ps != null && ps.isMatch(flags)) { 3115 return UserHandle.getUid(userId, ps.appId); 3116 } 3117 } 3118 } 3119 3120 return -1; 3121 } 3122 3123 @Override 3124 public int[] getPackageGids(String packageName, int flags, int userId) { 3125 if (!sUserManager.exists(userId)) return null; 3126 flags = updateFlagsForPackage(flags, userId, packageName); 3127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3128 false /* requireFullPermission */, false /* checkShell */, 3129 "getPackageGids"); 3130 3131 // reader 3132 synchronized (mPackages) { 3133 final PackageParser.Package p = mPackages.get(packageName); 3134 if (p != null && p.isMatch(flags)) { 3135 PackageSetting ps = (PackageSetting) p.mExtras; 3136 return ps.getPermissionsState().computeGids(userId); 3137 } 3138 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3139 final PackageSetting ps = mSettings.mPackages.get(packageName); 3140 if (ps != null && ps.isMatch(flags)) { 3141 return ps.getPermissionsState().computeGids(userId); 3142 } 3143 } 3144 } 3145 3146 return null; 3147 } 3148 3149 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3150 if (bp.perm != null) { 3151 return PackageParser.generatePermissionInfo(bp.perm, flags); 3152 } 3153 PermissionInfo pi = new PermissionInfo(); 3154 pi.name = bp.name; 3155 pi.packageName = bp.sourcePackage; 3156 pi.nonLocalizedLabel = bp.name; 3157 pi.protectionLevel = bp.protectionLevel; 3158 return pi; 3159 } 3160 3161 @Override 3162 public PermissionInfo getPermissionInfo(String name, int flags) { 3163 // reader 3164 synchronized (mPackages) { 3165 final BasePermission p = mSettings.mPermissions.get(name); 3166 if (p != null) { 3167 return generatePermissionInfo(p, flags); 3168 } 3169 return null; 3170 } 3171 } 3172 3173 @Override 3174 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3175 int flags) { 3176 // reader 3177 synchronized (mPackages) { 3178 if (group != null && !mPermissionGroups.containsKey(group)) { 3179 // This is thrown as NameNotFoundException 3180 return null; 3181 } 3182 3183 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3184 for (BasePermission p : mSettings.mPermissions.values()) { 3185 if (group == null) { 3186 if (p.perm == null || p.perm.info.group == null) { 3187 out.add(generatePermissionInfo(p, flags)); 3188 } 3189 } else { 3190 if (p.perm != null && group.equals(p.perm.info.group)) { 3191 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3192 } 3193 } 3194 } 3195 return new ParceledListSlice<>(out); 3196 } 3197 } 3198 3199 @Override 3200 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3201 // reader 3202 synchronized (mPackages) { 3203 return PackageParser.generatePermissionGroupInfo( 3204 mPermissionGroups.get(name), flags); 3205 } 3206 } 3207 3208 @Override 3209 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3210 // reader 3211 synchronized (mPackages) { 3212 final int N = mPermissionGroups.size(); 3213 ArrayList<PermissionGroupInfo> out 3214 = new ArrayList<PermissionGroupInfo>(N); 3215 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3216 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3217 } 3218 return new ParceledListSlice<>(out); 3219 } 3220 } 3221 3222 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3223 int userId) { 3224 if (!sUserManager.exists(userId)) return null; 3225 PackageSetting ps = mSettings.mPackages.get(packageName); 3226 if (ps != null) { 3227 if (ps.pkg == null) { 3228 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3229 if (pInfo != null) { 3230 return pInfo.applicationInfo; 3231 } 3232 return null; 3233 } 3234 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3235 ps.readUserState(userId), userId); 3236 } 3237 return null; 3238 } 3239 3240 @Override 3241 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3242 if (!sUserManager.exists(userId)) return null; 3243 flags = updateFlagsForApplication(flags, userId, packageName); 3244 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3245 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3246 // writer 3247 synchronized (mPackages) { 3248 PackageParser.Package p = mPackages.get(packageName); 3249 if (DEBUG_PACKAGE_INFO) Log.v( 3250 TAG, "getApplicationInfo " + packageName 3251 + ": " + p); 3252 if (p != null) { 3253 PackageSetting ps = mSettings.mPackages.get(packageName); 3254 if (ps == null) return null; 3255 // Note: isEnabledLP() does not apply here - always return info 3256 return PackageParser.generateApplicationInfo( 3257 p, flags, ps.readUserState(userId), userId); 3258 } 3259 if ("android".equals(packageName)||"system".equals(packageName)) { 3260 return mAndroidApplication; 3261 } 3262 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3263 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3264 } 3265 } 3266 return null; 3267 } 3268 3269 @Override 3270 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3271 final IPackageDataObserver observer) { 3272 mContext.enforceCallingOrSelfPermission( 3273 android.Manifest.permission.CLEAR_APP_CACHE, null); 3274 // Queue up an async operation since clearing cache may take a little while. 3275 mHandler.post(new Runnable() { 3276 public void run() { 3277 mHandler.removeCallbacks(this); 3278 boolean success = true; 3279 synchronized (mInstallLock) { 3280 try { 3281 mInstaller.freeCache(volumeUuid, freeStorageSize); 3282 } catch (InstallerException e) { 3283 Slog.w(TAG, "Couldn't clear application caches: " + e); 3284 success = false; 3285 } 3286 } 3287 if (observer != null) { 3288 try { 3289 observer.onRemoveCompleted(null, success); 3290 } catch (RemoteException e) { 3291 Slog.w(TAG, "RemoveException when invoking call back"); 3292 } 3293 } 3294 } 3295 }); 3296 } 3297 3298 @Override 3299 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3300 final IntentSender pi) { 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.CLEAR_APP_CACHE, null); 3303 // Queue up an async operation since clearing cache may take a little while. 3304 mHandler.post(new Runnable() { 3305 public void run() { 3306 mHandler.removeCallbacks(this); 3307 boolean success = true; 3308 synchronized (mInstallLock) { 3309 try { 3310 mInstaller.freeCache(volumeUuid, freeStorageSize); 3311 } catch (InstallerException e) { 3312 Slog.w(TAG, "Couldn't clear application caches: " + e); 3313 success = false; 3314 } 3315 } 3316 if(pi != null) { 3317 try { 3318 // Callback via pending intent 3319 int code = success ? 1 : 0; 3320 pi.sendIntent(null, code, null, 3321 null, null); 3322 } catch (SendIntentException e1) { 3323 Slog.i(TAG, "Failed to send pending intent"); 3324 } 3325 } 3326 } 3327 }); 3328 } 3329 3330 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3331 synchronized (mInstallLock) { 3332 try { 3333 mInstaller.freeCache(volumeUuid, freeStorageSize); 3334 } catch (InstallerException e) { 3335 throw new IOException("Failed to free enough space", e); 3336 } 3337 } 3338 } 3339 3340 /** 3341 * Return if the user key is currently unlocked. 3342 */ 3343 private boolean isUserKeyUnlocked(int userId) { 3344 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3345 final IMountService mount = IMountService.Stub 3346 .asInterface(ServiceManager.getService("mount")); 3347 if (mount == null) { 3348 Slog.w(TAG, "Early during boot, assuming locked"); 3349 return false; 3350 } 3351 final long token = Binder.clearCallingIdentity(); 3352 try { 3353 return mount.isUserKeyUnlocked(userId); 3354 } catch (RemoteException e) { 3355 throw e.rethrowAsRuntimeException(); 3356 } finally { 3357 Binder.restoreCallingIdentity(token); 3358 } 3359 } else { 3360 return true; 3361 } 3362 } 3363 3364 /** 3365 * Update given flags based on encryption status of current user. 3366 */ 3367 private int updateFlags(int flags, int userId) { 3368 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3369 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3370 // Caller expressed an explicit opinion about what encryption 3371 // aware/unaware components they want to see, so fall through and 3372 // give them what they want 3373 } else { 3374 // Caller expressed no opinion, so match based on user state 3375 if (isUserKeyUnlocked(userId)) { 3376 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3377 } else { 3378 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3379 } 3380 } 3381 return flags; 3382 } 3383 3384 /** 3385 * Update given flags when being used to request {@link PackageInfo}. 3386 */ 3387 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3388 boolean triaged = true; 3389 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3390 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3391 // Caller is asking for component details, so they'd better be 3392 // asking for specific encryption matching behavior, or be triaged 3393 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3394 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3395 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3396 triaged = false; 3397 } 3398 } 3399 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3400 | PackageManager.MATCH_SYSTEM_ONLY 3401 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3402 triaged = false; 3403 } 3404 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3405 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3406 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3407 } 3408 return updateFlags(flags, userId); 3409 } 3410 3411 /** 3412 * Update given flags when being used to request {@link ApplicationInfo}. 3413 */ 3414 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3415 return updateFlagsForPackage(flags, userId, cookie); 3416 } 3417 3418 /** 3419 * Update given flags when being used to request {@link ComponentInfo}. 3420 */ 3421 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3422 if (cookie instanceof Intent) { 3423 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3424 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3425 } 3426 } 3427 3428 boolean triaged = true; 3429 // Caller is asking for component details, so they'd better be 3430 // asking for specific encryption matching behavior, or be triaged 3431 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3432 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3433 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3434 triaged = false; 3435 } 3436 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3437 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3438 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3439 } 3440 3441 return updateFlags(flags, userId); 3442 } 3443 3444 /** 3445 * Update given flags when being used to request {@link ResolveInfo}. 3446 */ 3447 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3448 // Safe mode means we shouldn't match any third-party components 3449 if (mSafeMode) { 3450 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3451 } 3452 3453 return updateFlagsForComponent(flags, userId, cookie); 3454 } 3455 3456 @Override 3457 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3458 if (!sUserManager.exists(userId)) return null; 3459 flags = updateFlagsForComponent(flags, userId, component); 3460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3461 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3462 synchronized (mPackages) { 3463 PackageParser.Activity a = mActivities.mActivities.get(component); 3464 3465 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3466 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3467 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3468 if (ps == null) return null; 3469 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3470 userId); 3471 } 3472 if (mResolveComponentName.equals(component)) { 3473 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3474 new PackageUserState(), userId); 3475 } 3476 } 3477 return null; 3478 } 3479 3480 @Override 3481 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3482 String resolvedType) { 3483 synchronized (mPackages) { 3484 if (component.equals(mResolveComponentName)) { 3485 // The resolver supports EVERYTHING! 3486 return true; 3487 } 3488 PackageParser.Activity a = mActivities.mActivities.get(component); 3489 if (a == null) { 3490 return false; 3491 } 3492 for (int i=0; i<a.intents.size(); i++) { 3493 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3494 intent.getData(), intent.getCategories(), TAG) >= 0) { 3495 return true; 3496 } 3497 } 3498 return false; 3499 } 3500 } 3501 3502 @Override 3503 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3504 if (!sUserManager.exists(userId)) return null; 3505 flags = updateFlagsForComponent(flags, userId, component); 3506 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3507 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3508 synchronized (mPackages) { 3509 PackageParser.Activity a = mReceivers.mActivities.get(component); 3510 if (DEBUG_PACKAGE_INFO) Log.v( 3511 TAG, "getReceiverInfo " + component + ": " + a); 3512 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3513 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3514 if (ps == null) return null; 3515 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3516 userId); 3517 } 3518 } 3519 return null; 3520 } 3521 3522 @Override 3523 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3524 if (!sUserManager.exists(userId)) return null; 3525 flags = updateFlagsForComponent(flags, userId, component); 3526 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3527 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3528 synchronized (mPackages) { 3529 PackageParser.Service s = mServices.mServices.get(component); 3530 if (DEBUG_PACKAGE_INFO) Log.v( 3531 TAG, "getServiceInfo " + component + ": " + s); 3532 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3533 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3534 if (ps == null) return null; 3535 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3536 userId); 3537 } 3538 } 3539 return null; 3540 } 3541 3542 @Override 3543 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3544 if (!sUserManager.exists(userId)) return null; 3545 flags = updateFlagsForComponent(flags, userId, component); 3546 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3547 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3548 synchronized (mPackages) { 3549 PackageParser.Provider p = mProviders.mProviders.get(component); 3550 if (DEBUG_PACKAGE_INFO) Log.v( 3551 TAG, "getProviderInfo " + component + ": " + p); 3552 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3553 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3554 if (ps == null) return null; 3555 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3556 userId); 3557 } 3558 } 3559 return null; 3560 } 3561 3562 @Override 3563 public String[] getSystemSharedLibraryNames() { 3564 Set<String> libSet; 3565 synchronized (mPackages) { 3566 libSet = mSharedLibraries.keySet(); 3567 int size = libSet.size(); 3568 if (size > 0) { 3569 String[] libs = new String[size]; 3570 libSet.toArray(libs); 3571 return libs; 3572 } 3573 } 3574 return null; 3575 } 3576 3577 @Override 3578 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3579 synchronized (mPackages) { 3580 return mServicesSystemSharedLibraryPackageName; 3581 } 3582 } 3583 3584 @Override 3585 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3586 synchronized (mPackages) { 3587 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3588 3589 final FeatureInfo fi = new FeatureInfo(); 3590 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3591 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3592 res.add(fi); 3593 3594 return new ParceledListSlice<>(res); 3595 } 3596 } 3597 3598 @Override 3599 public boolean hasSystemFeature(String name, int version) { 3600 synchronized (mPackages) { 3601 final FeatureInfo feat = mAvailableFeatures.get(name); 3602 if (feat == null) { 3603 return false; 3604 } else { 3605 return feat.version >= version; 3606 } 3607 } 3608 } 3609 3610 @Override 3611 public int checkPermission(String permName, String pkgName, int userId) { 3612 if (!sUserManager.exists(userId)) { 3613 return PackageManager.PERMISSION_DENIED; 3614 } 3615 3616 synchronized (mPackages) { 3617 final PackageParser.Package p = mPackages.get(pkgName); 3618 if (p != null && p.mExtras != null) { 3619 final PackageSetting ps = (PackageSetting) p.mExtras; 3620 final PermissionsState permissionsState = ps.getPermissionsState(); 3621 if (permissionsState.hasPermission(permName, userId)) { 3622 return PackageManager.PERMISSION_GRANTED; 3623 } 3624 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3625 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3626 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3627 return PackageManager.PERMISSION_GRANTED; 3628 } 3629 } 3630 } 3631 3632 return PackageManager.PERMISSION_DENIED; 3633 } 3634 3635 @Override 3636 public int checkUidPermission(String permName, int uid) { 3637 final int userId = UserHandle.getUserId(uid); 3638 3639 if (!sUserManager.exists(userId)) { 3640 return PackageManager.PERMISSION_DENIED; 3641 } 3642 3643 synchronized (mPackages) { 3644 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3645 if (obj != null) { 3646 final SettingBase ps = (SettingBase) obj; 3647 final PermissionsState permissionsState = ps.getPermissionsState(); 3648 if (permissionsState.hasPermission(permName, userId)) { 3649 return PackageManager.PERMISSION_GRANTED; 3650 } 3651 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3652 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3653 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3654 return PackageManager.PERMISSION_GRANTED; 3655 } 3656 } else { 3657 ArraySet<String> perms = mSystemPermissions.get(uid); 3658 if (perms != null) { 3659 if (perms.contains(permName)) { 3660 return PackageManager.PERMISSION_GRANTED; 3661 } 3662 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3663 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3664 return PackageManager.PERMISSION_GRANTED; 3665 } 3666 } 3667 } 3668 } 3669 3670 return PackageManager.PERMISSION_DENIED; 3671 } 3672 3673 @Override 3674 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3675 if (UserHandle.getCallingUserId() != userId) { 3676 mContext.enforceCallingPermission( 3677 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3678 "isPermissionRevokedByPolicy for user " + userId); 3679 } 3680 3681 if (checkPermission(permission, packageName, userId) 3682 == PackageManager.PERMISSION_GRANTED) { 3683 return false; 3684 } 3685 3686 final long identity = Binder.clearCallingIdentity(); 3687 try { 3688 final int flags = getPermissionFlags(permission, packageName, userId); 3689 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3690 } finally { 3691 Binder.restoreCallingIdentity(identity); 3692 } 3693 } 3694 3695 @Override 3696 public String getPermissionControllerPackageName() { 3697 synchronized (mPackages) { 3698 return mRequiredInstallerPackage; 3699 } 3700 } 3701 3702 /** 3703 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3704 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3705 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3706 * @param message the message to log on security exception 3707 */ 3708 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3709 boolean checkShell, String message) { 3710 if (userId < 0) { 3711 throw new IllegalArgumentException("Invalid userId " + userId); 3712 } 3713 if (checkShell) { 3714 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3715 } 3716 if (userId == UserHandle.getUserId(callingUid)) return; 3717 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3718 if (requireFullPermission) { 3719 mContext.enforceCallingOrSelfPermission( 3720 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3721 } else { 3722 try { 3723 mContext.enforceCallingOrSelfPermission( 3724 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3725 } catch (SecurityException se) { 3726 mContext.enforceCallingOrSelfPermission( 3727 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3728 } 3729 } 3730 } 3731 } 3732 3733 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3734 if (callingUid == Process.SHELL_UID) { 3735 if (userHandle >= 0 3736 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3737 throw new SecurityException("Shell does not have permission to access user " 3738 + userHandle); 3739 } else if (userHandle < 0) { 3740 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3741 + Debug.getCallers(3)); 3742 } 3743 } 3744 } 3745 3746 private BasePermission findPermissionTreeLP(String permName) { 3747 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3748 if (permName.startsWith(bp.name) && 3749 permName.length() > bp.name.length() && 3750 permName.charAt(bp.name.length()) == '.') { 3751 return bp; 3752 } 3753 } 3754 return null; 3755 } 3756 3757 private BasePermission checkPermissionTreeLP(String permName) { 3758 if (permName != null) { 3759 BasePermission bp = findPermissionTreeLP(permName); 3760 if (bp != null) { 3761 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3762 return bp; 3763 } 3764 throw new SecurityException("Calling uid " 3765 + Binder.getCallingUid() 3766 + " is not allowed to add to permission tree " 3767 + bp.name + " owned by uid " + bp.uid); 3768 } 3769 } 3770 throw new SecurityException("No permission tree found for " + permName); 3771 } 3772 3773 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3774 if (s1 == null) { 3775 return s2 == null; 3776 } 3777 if (s2 == null) { 3778 return false; 3779 } 3780 if (s1.getClass() != s2.getClass()) { 3781 return false; 3782 } 3783 return s1.equals(s2); 3784 } 3785 3786 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3787 if (pi1.icon != pi2.icon) return false; 3788 if (pi1.logo != pi2.logo) return false; 3789 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3790 if (!compareStrings(pi1.name, pi2.name)) return false; 3791 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3792 // We'll take care of setting this one. 3793 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3794 // These are not currently stored in settings. 3795 //if (!compareStrings(pi1.group, pi2.group)) return false; 3796 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3797 //if (pi1.labelRes != pi2.labelRes) return false; 3798 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3799 return true; 3800 } 3801 3802 int permissionInfoFootprint(PermissionInfo info) { 3803 int size = info.name.length(); 3804 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3805 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3806 return size; 3807 } 3808 3809 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3810 int size = 0; 3811 for (BasePermission perm : mSettings.mPermissions.values()) { 3812 if (perm.uid == tree.uid) { 3813 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3814 } 3815 } 3816 return size; 3817 } 3818 3819 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3820 // We calculate the max size of permissions defined by this uid and throw 3821 // if that plus the size of 'info' would exceed our stated maximum. 3822 if (tree.uid != Process.SYSTEM_UID) { 3823 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3824 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3825 throw new SecurityException("Permission tree size cap exceeded"); 3826 } 3827 } 3828 } 3829 3830 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3831 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3832 throw new SecurityException("Label must be specified in permission"); 3833 } 3834 BasePermission tree = checkPermissionTreeLP(info.name); 3835 BasePermission bp = mSettings.mPermissions.get(info.name); 3836 boolean added = bp == null; 3837 boolean changed = true; 3838 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3839 if (added) { 3840 enforcePermissionCapLocked(info, tree); 3841 bp = new BasePermission(info.name, tree.sourcePackage, 3842 BasePermission.TYPE_DYNAMIC); 3843 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3844 throw new SecurityException( 3845 "Not allowed to modify non-dynamic permission " 3846 + info.name); 3847 } else { 3848 if (bp.protectionLevel == fixedLevel 3849 && bp.perm.owner.equals(tree.perm.owner) 3850 && bp.uid == tree.uid 3851 && comparePermissionInfos(bp.perm.info, info)) { 3852 changed = false; 3853 } 3854 } 3855 bp.protectionLevel = fixedLevel; 3856 info = new PermissionInfo(info); 3857 info.protectionLevel = fixedLevel; 3858 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3859 bp.perm.info.packageName = tree.perm.info.packageName; 3860 bp.uid = tree.uid; 3861 if (added) { 3862 mSettings.mPermissions.put(info.name, bp); 3863 } 3864 if (changed) { 3865 if (!async) { 3866 mSettings.writeLPr(); 3867 } else { 3868 scheduleWriteSettingsLocked(); 3869 } 3870 } 3871 return added; 3872 } 3873 3874 @Override 3875 public boolean addPermission(PermissionInfo info) { 3876 synchronized (mPackages) { 3877 return addPermissionLocked(info, false); 3878 } 3879 } 3880 3881 @Override 3882 public boolean addPermissionAsync(PermissionInfo info) { 3883 synchronized (mPackages) { 3884 return addPermissionLocked(info, true); 3885 } 3886 } 3887 3888 @Override 3889 public void removePermission(String name) { 3890 synchronized (mPackages) { 3891 checkPermissionTreeLP(name); 3892 BasePermission bp = mSettings.mPermissions.get(name); 3893 if (bp != null) { 3894 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3895 throw new SecurityException( 3896 "Not allowed to modify non-dynamic permission " 3897 + name); 3898 } 3899 mSettings.mPermissions.remove(name); 3900 mSettings.writeLPr(); 3901 } 3902 } 3903 } 3904 3905 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3906 BasePermission bp) { 3907 int index = pkg.requestedPermissions.indexOf(bp.name); 3908 if (index == -1) { 3909 throw new SecurityException("Package " + pkg.packageName 3910 + " has not requested permission " + bp.name); 3911 } 3912 if (!bp.isRuntime() && !bp.isDevelopment()) { 3913 throw new SecurityException("Permission " + bp.name 3914 + " is not a changeable permission type"); 3915 } 3916 } 3917 3918 @Override 3919 public void grantRuntimePermission(String packageName, String name, final int userId) { 3920 if (!sUserManager.exists(userId)) { 3921 Log.e(TAG, "No such user:" + userId); 3922 return; 3923 } 3924 3925 mContext.enforceCallingOrSelfPermission( 3926 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3927 "grantRuntimePermission"); 3928 3929 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3930 true /* requireFullPermission */, true /* checkShell */, 3931 "grantRuntimePermission"); 3932 3933 final int uid; 3934 final SettingBase sb; 3935 3936 synchronized (mPackages) { 3937 final PackageParser.Package pkg = mPackages.get(packageName); 3938 if (pkg == null) { 3939 throw new IllegalArgumentException("Unknown package: " + packageName); 3940 } 3941 3942 final BasePermission bp = mSettings.mPermissions.get(name); 3943 if (bp == null) { 3944 throw new IllegalArgumentException("Unknown permission: " + name); 3945 } 3946 3947 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3948 3949 // If a permission review is required for legacy apps we represent 3950 // their permissions as always granted runtime ones since we need 3951 // to keep the review required permission flag per user while an 3952 // install permission's state is shared across all users. 3953 if (Build.PERMISSIONS_REVIEW_REQUIRED 3954 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3955 && bp.isRuntime()) { 3956 return; 3957 } 3958 3959 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3960 sb = (SettingBase) pkg.mExtras; 3961 if (sb == null) { 3962 throw new IllegalArgumentException("Unknown package: " + packageName); 3963 } 3964 3965 final PermissionsState permissionsState = sb.getPermissionsState(); 3966 3967 final int flags = permissionsState.getPermissionFlags(name, userId); 3968 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3969 throw new SecurityException("Cannot grant system fixed permission " 3970 + name + " for package " + packageName); 3971 } 3972 3973 if (bp.isDevelopment()) { 3974 // Development permissions must be handled specially, since they are not 3975 // normal runtime permissions. For now they apply to all users. 3976 if (permissionsState.grantInstallPermission(bp) != 3977 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3978 scheduleWriteSettingsLocked(); 3979 } 3980 return; 3981 } 3982 3983 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3984 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3985 return; 3986 } 3987 3988 final int result = permissionsState.grantRuntimePermission(bp, userId); 3989 switch (result) { 3990 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3991 return; 3992 } 3993 3994 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3995 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3996 mHandler.post(new Runnable() { 3997 @Override 3998 public void run() { 3999 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4000 } 4001 }); 4002 } 4003 break; 4004 } 4005 4006 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4007 4008 // Not critical if that is lost - app has to request again. 4009 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4010 } 4011 4012 // Only need to do this if user is initialized. Otherwise it's a new user 4013 // and there are no processes running as the user yet and there's no need 4014 // to make an expensive call to remount processes for the changed permissions. 4015 if (READ_EXTERNAL_STORAGE.equals(name) 4016 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4017 final long token = Binder.clearCallingIdentity(); 4018 try { 4019 if (sUserManager.isInitialized(userId)) { 4020 MountServiceInternal mountServiceInternal = LocalServices.getService( 4021 MountServiceInternal.class); 4022 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4023 } 4024 } finally { 4025 Binder.restoreCallingIdentity(token); 4026 } 4027 } 4028 } 4029 4030 @Override 4031 public void revokeRuntimePermission(String packageName, String name, int userId) { 4032 if (!sUserManager.exists(userId)) { 4033 Log.e(TAG, "No such user:" + userId); 4034 return; 4035 } 4036 4037 mContext.enforceCallingOrSelfPermission( 4038 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4039 "revokeRuntimePermission"); 4040 4041 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4042 true /* requireFullPermission */, true /* checkShell */, 4043 "revokeRuntimePermission"); 4044 4045 final int appId; 4046 4047 synchronized (mPackages) { 4048 final PackageParser.Package pkg = mPackages.get(packageName); 4049 if (pkg == null) { 4050 throw new IllegalArgumentException("Unknown package: " + packageName); 4051 } 4052 4053 final BasePermission bp = mSettings.mPermissions.get(name); 4054 if (bp == null) { 4055 throw new IllegalArgumentException("Unknown permission: " + name); 4056 } 4057 4058 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4059 4060 // If a permission review is required for legacy apps we represent 4061 // their permissions as always granted runtime ones since we need 4062 // to keep the review required permission flag per user while an 4063 // install permission's state is shared across all users. 4064 if (Build.PERMISSIONS_REVIEW_REQUIRED 4065 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4066 && bp.isRuntime()) { 4067 return; 4068 } 4069 4070 SettingBase sb = (SettingBase) pkg.mExtras; 4071 if (sb == null) { 4072 throw new IllegalArgumentException("Unknown package: " + packageName); 4073 } 4074 4075 final PermissionsState permissionsState = sb.getPermissionsState(); 4076 4077 final int flags = permissionsState.getPermissionFlags(name, userId); 4078 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4079 throw new SecurityException("Cannot revoke system fixed permission " 4080 + name + " for package " + packageName); 4081 } 4082 4083 if (bp.isDevelopment()) { 4084 // Development permissions must be handled specially, since they are not 4085 // normal runtime permissions. For now they apply to all users. 4086 if (permissionsState.revokeInstallPermission(bp) != 4087 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4088 scheduleWriteSettingsLocked(); 4089 } 4090 return; 4091 } 4092 4093 if (permissionsState.revokeRuntimePermission(bp, userId) == 4094 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4095 return; 4096 } 4097 4098 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4099 4100 // Critical, after this call app should never have the permission. 4101 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4102 4103 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4104 } 4105 4106 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4107 } 4108 4109 @Override 4110 public void resetRuntimePermissions() { 4111 mContext.enforceCallingOrSelfPermission( 4112 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4113 "revokeRuntimePermission"); 4114 4115 int callingUid = Binder.getCallingUid(); 4116 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4117 mContext.enforceCallingOrSelfPermission( 4118 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4119 "resetRuntimePermissions"); 4120 } 4121 4122 synchronized (mPackages) { 4123 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4124 for (int userId : UserManagerService.getInstance().getUserIds()) { 4125 final int packageCount = mPackages.size(); 4126 for (int i = 0; i < packageCount; i++) { 4127 PackageParser.Package pkg = mPackages.valueAt(i); 4128 if (!(pkg.mExtras instanceof PackageSetting)) { 4129 continue; 4130 } 4131 PackageSetting ps = (PackageSetting) pkg.mExtras; 4132 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4133 } 4134 } 4135 } 4136 } 4137 4138 @Override 4139 public int getPermissionFlags(String name, String packageName, int userId) { 4140 if (!sUserManager.exists(userId)) { 4141 return 0; 4142 } 4143 4144 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4145 4146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4147 true /* requireFullPermission */, false /* checkShell */, 4148 "getPermissionFlags"); 4149 4150 synchronized (mPackages) { 4151 final PackageParser.Package pkg = mPackages.get(packageName); 4152 if (pkg == null) { 4153 throw new IllegalArgumentException("Unknown package: " + packageName); 4154 } 4155 4156 final BasePermission bp = mSettings.mPermissions.get(name); 4157 if (bp == null) { 4158 throw new IllegalArgumentException("Unknown permission: " + name); 4159 } 4160 4161 SettingBase sb = (SettingBase) pkg.mExtras; 4162 if (sb == null) { 4163 throw new IllegalArgumentException("Unknown package: " + packageName); 4164 } 4165 4166 PermissionsState permissionsState = sb.getPermissionsState(); 4167 return permissionsState.getPermissionFlags(name, userId); 4168 } 4169 } 4170 4171 @Override 4172 public void updatePermissionFlags(String name, String packageName, int flagMask, 4173 int flagValues, int userId) { 4174 if (!sUserManager.exists(userId)) { 4175 return; 4176 } 4177 4178 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4179 4180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4181 true /* requireFullPermission */, true /* checkShell */, 4182 "updatePermissionFlags"); 4183 4184 // Only the system can change these flags and nothing else. 4185 if (getCallingUid() != Process.SYSTEM_UID) { 4186 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4187 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4188 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4189 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4190 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4191 } 4192 4193 synchronized (mPackages) { 4194 final PackageParser.Package pkg = mPackages.get(packageName); 4195 if (pkg == null) { 4196 throw new IllegalArgumentException("Unknown package: " + packageName); 4197 } 4198 4199 final BasePermission bp = mSettings.mPermissions.get(name); 4200 if (bp == null) { 4201 throw new IllegalArgumentException("Unknown permission: " + name); 4202 } 4203 4204 SettingBase sb = (SettingBase) pkg.mExtras; 4205 if (sb == null) { 4206 throw new IllegalArgumentException("Unknown package: " + packageName); 4207 } 4208 4209 PermissionsState permissionsState = sb.getPermissionsState(); 4210 4211 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4212 4213 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4214 // Install and runtime permissions are stored in different places, 4215 // so figure out what permission changed and persist the change. 4216 if (permissionsState.getInstallPermissionState(name) != null) { 4217 scheduleWriteSettingsLocked(); 4218 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4219 || hadState) { 4220 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4221 } 4222 } 4223 } 4224 } 4225 4226 /** 4227 * Update the permission flags for all packages and runtime permissions of a user in order 4228 * to allow device or profile owner to remove POLICY_FIXED. 4229 */ 4230 @Override 4231 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4232 if (!sUserManager.exists(userId)) { 4233 return; 4234 } 4235 4236 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4237 4238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4239 true /* requireFullPermission */, true /* checkShell */, 4240 "updatePermissionFlagsForAllApps"); 4241 4242 // Only the system can change system fixed flags. 4243 if (getCallingUid() != Process.SYSTEM_UID) { 4244 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4245 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4246 } 4247 4248 synchronized (mPackages) { 4249 boolean changed = false; 4250 final int packageCount = mPackages.size(); 4251 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4252 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4253 SettingBase sb = (SettingBase) pkg.mExtras; 4254 if (sb == null) { 4255 continue; 4256 } 4257 PermissionsState permissionsState = sb.getPermissionsState(); 4258 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4259 userId, flagMask, flagValues); 4260 } 4261 if (changed) { 4262 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4263 } 4264 } 4265 } 4266 4267 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4268 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4269 != PackageManager.PERMISSION_GRANTED 4270 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4271 != PackageManager.PERMISSION_GRANTED) { 4272 throw new SecurityException(message + " requires " 4273 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4274 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4275 } 4276 } 4277 4278 @Override 4279 public boolean shouldShowRequestPermissionRationale(String permissionName, 4280 String packageName, int userId) { 4281 if (UserHandle.getCallingUserId() != userId) { 4282 mContext.enforceCallingPermission( 4283 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4284 "canShowRequestPermissionRationale for user " + userId); 4285 } 4286 4287 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4288 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4289 return false; 4290 } 4291 4292 if (checkPermission(permissionName, packageName, userId) 4293 == PackageManager.PERMISSION_GRANTED) { 4294 return false; 4295 } 4296 4297 final int flags; 4298 4299 final long identity = Binder.clearCallingIdentity(); 4300 try { 4301 flags = getPermissionFlags(permissionName, 4302 packageName, userId); 4303 } finally { 4304 Binder.restoreCallingIdentity(identity); 4305 } 4306 4307 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4308 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4309 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4310 4311 if ((flags & fixedFlags) != 0) { 4312 return false; 4313 } 4314 4315 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4316 } 4317 4318 @Override 4319 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4320 mContext.enforceCallingOrSelfPermission( 4321 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4322 "addOnPermissionsChangeListener"); 4323 4324 synchronized (mPackages) { 4325 mOnPermissionChangeListeners.addListenerLocked(listener); 4326 } 4327 } 4328 4329 @Override 4330 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4331 synchronized (mPackages) { 4332 mOnPermissionChangeListeners.removeListenerLocked(listener); 4333 } 4334 } 4335 4336 @Override 4337 public boolean isProtectedBroadcast(String actionName) { 4338 synchronized (mPackages) { 4339 if (mProtectedBroadcasts.contains(actionName)) { 4340 return true; 4341 } else if (actionName != null) { 4342 // TODO: remove these terrible hacks 4343 if (actionName.startsWith("android.net.netmon.lingerExpired") 4344 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4345 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4346 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4347 return true; 4348 } 4349 } 4350 } 4351 return false; 4352 } 4353 4354 @Override 4355 public int checkSignatures(String pkg1, String pkg2) { 4356 synchronized (mPackages) { 4357 final PackageParser.Package p1 = mPackages.get(pkg1); 4358 final PackageParser.Package p2 = mPackages.get(pkg2); 4359 if (p1 == null || p1.mExtras == null 4360 || p2 == null || p2.mExtras == null) { 4361 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4362 } 4363 return compareSignatures(p1.mSignatures, p2.mSignatures); 4364 } 4365 } 4366 4367 @Override 4368 public int checkUidSignatures(int uid1, int uid2) { 4369 // Map to base uids. 4370 uid1 = UserHandle.getAppId(uid1); 4371 uid2 = UserHandle.getAppId(uid2); 4372 // reader 4373 synchronized (mPackages) { 4374 Signature[] s1; 4375 Signature[] s2; 4376 Object obj = mSettings.getUserIdLPr(uid1); 4377 if (obj != null) { 4378 if (obj instanceof SharedUserSetting) { 4379 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4380 } else if (obj instanceof PackageSetting) { 4381 s1 = ((PackageSetting)obj).signatures.mSignatures; 4382 } else { 4383 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4384 } 4385 } else { 4386 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4387 } 4388 obj = mSettings.getUserIdLPr(uid2); 4389 if (obj != null) { 4390 if (obj instanceof SharedUserSetting) { 4391 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4392 } else if (obj instanceof PackageSetting) { 4393 s2 = ((PackageSetting)obj).signatures.mSignatures; 4394 } else { 4395 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4396 } 4397 } else { 4398 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4399 } 4400 return compareSignatures(s1, s2); 4401 } 4402 } 4403 4404 private void killUid(int appId, int userId, String reason) { 4405 final long identity = Binder.clearCallingIdentity(); 4406 try { 4407 IActivityManager am = ActivityManagerNative.getDefault(); 4408 if (am != null) { 4409 try { 4410 am.killUid(appId, userId, reason); 4411 } catch (RemoteException e) { 4412 /* ignore - same process */ 4413 } 4414 } 4415 } finally { 4416 Binder.restoreCallingIdentity(identity); 4417 } 4418 } 4419 4420 /** 4421 * Compares two sets of signatures. Returns: 4422 * <br /> 4423 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4424 * <br /> 4425 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4426 * <br /> 4427 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4428 * <br /> 4429 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4430 * <br /> 4431 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4432 */ 4433 static int compareSignatures(Signature[] s1, Signature[] s2) { 4434 if (s1 == null) { 4435 return s2 == null 4436 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4437 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4438 } 4439 4440 if (s2 == null) { 4441 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4442 } 4443 4444 if (s1.length != s2.length) { 4445 return PackageManager.SIGNATURE_NO_MATCH; 4446 } 4447 4448 // Since both signature sets are of size 1, we can compare without HashSets. 4449 if (s1.length == 1) { 4450 return s1[0].equals(s2[0]) ? 4451 PackageManager.SIGNATURE_MATCH : 4452 PackageManager.SIGNATURE_NO_MATCH; 4453 } 4454 4455 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4456 for (Signature sig : s1) { 4457 set1.add(sig); 4458 } 4459 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4460 for (Signature sig : s2) { 4461 set2.add(sig); 4462 } 4463 // Make sure s2 contains all signatures in s1. 4464 if (set1.equals(set2)) { 4465 return PackageManager.SIGNATURE_MATCH; 4466 } 4467 return PackageManager.SIGNATURE_NO_MATCH; 4468 } 4469 4470 /** 4471 * If the database version for this type of package (internal storage or 4472 * external storage) is less than the version where package signatures 4473 * were updated, return true. 4474 */ 4475 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4476 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4477 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4478 } 4479 4480 /** 4481 * Used for backward compatibility to make sure any packages with 4482 * certificate chains get upgraded to the new style. {@code existingSigs} 4483 * will be in the old format (since they were stored on disk from before the 4484 * system upgrade) and {@code scannedSigs} will be in the newer format. 4485 */ 4486 private int compareSignaturesCompat(PackageSignatures existingSigs, 4487 PackageParser.Package scannedPkg) { 4488 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4489 return PackageManager.SIGNATURE_NO_MATCH; 4490 } 4491 4492 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4493 for (Signature sig : existingSigs.mSignatures) { 4494 existingSet.add(sig); 4495 } 4496 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4497 for (Signature sig : scannedPkg.mSignatures) { 4498 try { 4499 Signature[] chainSignatures = sig.getChainSignatures(); 4500 for (Signature chainSig : chainSignatures) { 4501 scannedCompatSet.add(chainSig); 4502 } 4503 } catch (CertificateEncodingException e) { 4504 scannedCompatSet.add(sig); 4505 } 4506 } 4507 /* 4508 * Make sure the expanded scanned set contains all signatures in the 4509 * existing one. 4510 */ 4511 if (scannedCompatSet.equals(existingSet)) { 4512 // Migrate the old signatures to the new scheme. 4513 existingSigs.assignSignatures(scannedPkg.mSignatures); 4514 // The new KeySets will be re-added later in the scanning process. 4515 synchronized (mPackages) { 4516 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4517 } 4518 return PackageManager.SIGNATURE_MATCH; 4519 } 4520 return PackageManager.SIGNATURE_NO_MATCH; 4521 } 4522 4523 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4524 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4525 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4526 } 4527 4528 private int compareSignaturesRecover(PackageSignatures existingSigs, 4529 PackageParser.Package scannedPkg) { 4530 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4531 return PackageManager.SIGNATURE_NO_MATCH; 4532 } 4533 4534 String msg = null; 4535 try { 4536 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4537 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4538 + scannedPkg.packageName); 4539 return PackageManager.SIGNATURE_MATCH; 4540 } 4541 } catch (CertificateException e) { 4542 msg = e.getMessage(); 4543 } 4544 4545 logCriticalInfo(Log.INFO, 4546 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4547 return PackageManager.SIGNATURE_NO_MATCH; 4548 } 4549 4550 @Override 4551 public List<String> getAllPackages() { 4552 synchronized (mPackages) { 4553 return new ArrayList<String>(mPackages.keySet()); 4554 } 4555 } 4556 4557 @Override 4558 public String[] getPackagesForUid(int uid) { 4559 uid = UserHandle.getAppId(uid); 4560 // reader 4561 synchronized (mPackages) { 4562 Object obj = mSettings.getUserIdLPr(uid); 4563 if (obj instanceof SharedUserSetting) { 4564 final SharedUserSetting sus = (SharedUserSetting) obj; 4565 final int N = sus.packages.size(); 4566 final String[] res = new String[N]; 4567 final Iterator<PackageSetting> it = sus.packages.iterator(); 4568 int i = 0; 4569 while (it.hasNext()) { 4570 res[i++] = it.next().name; 4571 } 4572 return res; 4573 } else if (obj instanceof PackageSetting) { 4574 final PackageSetting ps = (PackageSetting) obj; 4575 return new String[] { ps.name }; 4576 } 4577 } 4578 return null; 4579 } 4580 4581 @Override 4582 public String getNameForUid(int uid) { 4583 // reader 4584 synchronized (mPackages) { 4585 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4586 if (obj instanceof SharedUserSetting) { 4587 final SharedUserSetting sus = (SharedUserSetting) obj; 4588 return sus.name + ":" + sus.userId; 4589 } else if (obj instanceof PackageSetting) { 4590 final PackageSetting ps = (PackageSetting) obj; 4591 return ps.name; 4592 } 4593 } 4594 return null; 4595 } 4596 4597 @Override 4598 public int getUidForSharedUser(String sharedUserName) { 4599 if(sharedUserName == null) { 4600 return -1; 4601 } 4602 // reader 4603 synchronized (mPackages) { 4604 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4605 if (suid == null) { 4606 return -1; 4607 } 4608 return suid.userId; 4609 } 4610 } 4611 4612 @Override 4613 public int getFlagsForUid(int uid) { 4614 synchronized (mPackages) { 4615 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4616 if (obj instanceof SharedUserSetting) { 4617 final SharedUserSetting sus = (SharedUserSetting) obj; 4618 return sus.pkgFlags; 4619 } else if (obj instanceof PackageSetting) { 4620 final PackageSetting ps = (PackageSetting) obj; 4621 return ps.pkgFlags; 4622 } 4623 } 4624 return 0; 4625 } 4626 4627 @Override 4628 public int getPrivateFlagsForUid(int uid) { 4629 synchronized (mPackages) { 4630 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4631 if (obj instanceof SharedUserSetting) { 4632 final SharedUserSetting sus = (SharedUserSetting) obj; 4633 return sus.pkgPrivateFlags; 4634 } else if (obj instanceof PackageSetting) { 4635 final PackageSetting ps = (PackageSetting) obj; 4636 return ps.pkgPrivateFlags; 4637 } 4638 } 4639 return 0; 4640 } 4641 4642 @Override 4643 public boolean isUidPrivileged(int uid) { 4644 uid = UserHandle.getAppId(uid); 4645 // reader 4646 synchronized (mPackages) { 4647 Object obj = mSettings.getUserIdLPr(uid); 4648 if (obj instanceof SharedUserSetting) { 4649 final SharedUserSetting sus = (SharedUserSetting) obj; 4650 final Iterator<PackageSetting> it = sus.packages.iterator(); 4651 while (it.hasNext()) { 4652 if (it.next().isPrivileged()) { 4653 return true; 4654 } 4655 } 4656 } else if (obj instanceof PackageSetting) { 4657 final PackageSetting ps = (PackageSetting) obj; 4658 return ps.isPrivileged(); 4659 } 4660 } 4661 return false; 4662 } 4663 4664 @Override 4665 public String[] getAppOpPermissionPackages(String permissionName) { 4666 synchronized (mPackages) { 4667 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4668 if (pkgs == null) { 4669 return null; 4670 } 4671 return pkgs.toArray(new String[pkgs.size()]); 4672 } 4673 } 4674 4675 @Override 4676 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4677 int flags, int userId) { 4678 if (!sUserManager.exists(userId)) return null; 4679 flags = updateFlagsForResolve(flags, userId, intent); 4680 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4681 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4682 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4683 userId); 4684 final ResolveInfo bestChoice = 4685 chooseBestActivity(intent, resolvedType, flags, query, userId); 4686 4687 if (isEphemeralAllowed(intent, query, userId)) { 4688 final EphemeralResolveInfo ai = 4689 getEphemeralResolveInfo(intent, resolvedType, userId); 4690 if (ai != null) { 4691 if (DEBUG_EPHEMERAL) { 4692 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4693 } 4694 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4695 bestChoice.ephemeralResolveInfo = ai; 4696 } 4697 } 4698 return bestChoice; 4699 } 4700 4701 @Override 4702 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4703 IntentFilter filter, int match, ComponentName activity) { 4704 final int userId = UserHandle.getCallingUserId(); 4705 if (DEBUG_PREFERRED) { 4706 Log.v(TAG, "setLastChosenActivity intent=" + intent 4707 + " resolvedType=" + resolvedType 4708 + " flags=" + flags 4709 + " filter=" + filter 4710 + " match=" + match 4711 + " activity=" + activity); 4712 filter.dump(new PrintStreamPrinter(System.out), " "); 4713 } 4714 intent.setComponent(null); 4715 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4716 userId); 4717 // Find any earlier preferred or last chosen entries and nuke them 4718 findPreferredActivity(intent, resolvedType, 4719 flags, query, 0, false, true, false, userId); 4720 // Add the new activity as the last chosen for this filter 4721 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4722 "Setting last chosen"); 4723 } 4724 4725 @Override 4726 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4727 final int userId = UserHandle.getCallingUserId(); 4728 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4729 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4730 userId); 4731 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4732 false, false, false, userId); 4733 } 4734 4735 4736 private boolean isEphemeralAllowed( 4737 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4738 // Short circuit and return early if possible. 4739 if (DISABLE_EPHEMERAL_APPS) { 4740 return false; 4741 } 4742 final int callingUser = UserHandle.getCallingUserId(); 4743 if (callingUser != UserHandle.USER_SYSTEM) { 4744 return false; 4745 } 4746 if (mEphemeralResolverConnection == null) { 4747 return false; 4748 } 4749 if (intent.getComponent() != null) { 4750 return false; 4751 } 4752 if (intent.getPackage() != null) { 4753 return false; 4754 } 4755 final boolean isWebUri = hasWebURI(intent); 4756 if (!isWebUri) { 4757 return false; 4758 } 4759 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4760 synchronized (mPackages) { 4761 final int count = resolvedActivites.size(); 4762 for (int n = 0; n < count; n++) { 4763 ResolveInfo info = resolvedActivites.get(n); 4764 String packageName = info.activityInfo.packageName; 4765 PackageSetting ps = mSettings.mPackages.get(packageName); 4766 if (ps != null) { 4767 // Try to get the status from User settings first 4768 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4769 int status = (int) (packedStatus >> 32); 4770 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4771 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4772 if (DEBUG_EPHEMERAL) { 4773 Slog.v(TAG, "DENY ephemeral apps;" 4774 + " pkg: " + packageName + ", status: " + status); 4775 } 4776 return false; 4777 } 4778 } 4779 } 4780 } 4781 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4782 return true; 4783 } 4784 4785 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4786 int userId) { 4787 MessageDigest digest = null; 4788 try { 4789 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4790 } catch (NoSuchAlgorithmException e) { 4791 // If we can't create a digest, ignore ephemeral apps. 4792 return null; 4793 } 4794 4795 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4796 final byte[] digestBytes = digest.digest(hostBytes); 4797 int shaPrefix = 4798 digestBytes[0] << 24 4799 | digestBytes[1] << 16 4800 | digestBytes[2] << 8 4801 | digestBytes[3] << 0; 4802 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4803 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4804 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4805 // No hash prefix match; there are no ephemeral apps for this domain. 4806 return null; 4807 } 4808 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4809 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4810 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4811 continue; 4812 } 4813 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4814 // No filters; this should never happen. 4815 if (filters.isEmpty()) { 4816 continue; 4817 } 4818 // We have a domain match; resolve the filters to see if anything matches. 4819 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4820 for (int j = filters.size() - 1; j >= 0; --j) { 4821 final EphemeralResolveIntentInfo intentInfo = 4822 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4823 ephemeralResolver.addFilter(intentInfo); 4824 } 4825 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4826 intent, resolvedType, false /*defaultOnly*/, userId); 4827 if (!matchedResolveInfoList.isEmpty()) { 4828 return matchedResolveInfoList.get(0); 4829 } 4830 } 4831 // Hash or filter mis-match; no ephemeral apps for this domain. 4832 return null; 4833 } 4834 4835 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4836 int flags, List<ResolveInfo> query, int userId) { 4837 if (query != null) { 4838 final int N = query.size(); 4839 if (N == 1) { 4840 return query.get(0); 4841 } else if (N > 1) { 4842 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4843 // If there is more than one activity with the same priority, 4844 // then let the user decide between them. 4845 ResolveInfo r0 = query.get(0); 4846 ResolveInfo r1 = query.get(1); 4847 if (DEBUG_INTENT_MATCHING || debug) { 4848 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4849 + r1.activityInfo.name + "=" + r1.priority); 4850 } 4851 // If the first activity has a higher priority, or a different 4852 // default, then it is always desirable to pick it. 4853 if (r0.priority != r1.priority 4854 || r0.preferredOrder != r1.preferredOrder 4855 || r0.isDefault != r1.isDefault) { 4856 return query.get(0); 4857 } 4858 // If we have saved a preference for a preferred activity for 4859 // this Intent, use that. 4860 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4861 flags, query, r0.priority, true, false, debug, userId); 4862 if (ri != null) { 4863 return ri; 4864 } 4865 ri = new ResolveInfo(mResolveInfo); 4866 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4867 ri.activityInfo.applicationInfo = new ApplicationInfo( 4868 ri.activityInfo.applicationInfo); 4869 if (userId != 0) { 4870 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4871 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4872 } 4873 // Make sure that the resolver is displayable in car mode 4874 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4875 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4876 return ri; 4877 } 4878 } 4879 return null; 4880 } 4881 4882 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4883 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4884 final int N = query.size(); 4885 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4886 .get(userId); 4887 // Get the list of persistent preferred activities that handle the intent 4888 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4889 List<PersistentPreferredActivity> pprefs = ppir != null 4890 ? ppir.queryIntent(intent, resolvedType, 4891 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4892 : null; 4893 if (pprefs != null && pprefs.size() > 0) { 4894 final int M = pprefs.size(); 4895 for (int i=0; i<M; i++) { 4896 final PersistentPreferredActivity ppa = pprefs.get(i); 4897 if (DEBUG_PREFERRED || debug) { 4898 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4899 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4900 + "\n component=" + ppa.mComponent); 4901 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4902 } 4903 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4904 flags | MATCH_DISABLED_COMPONENTS, userId); 4905 if (DEBUG_PREFERRED || debug) { 4906 Slog.v(TAG, "Found persistent preferred activity:"); 4907 if (ai != null) { 4908 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4909 } else { 4910 Slog.v(TAG, " null"); 4911 } 4912 } 4913 if (ai == null) { 4914 // This previously registered persistent preferred activity 4915 // component is no longer known. Ignore it and do NOT remove it. 4916 continue; 4917 } 4918 for (int j=0; j<N; j++) { 4919 final ResolveInfo ri = query.get(j); 4920 if (!ri.activityInfo.applicationInfo.packageName 4921 .equals(ai.applicationInfo.packageName)) { 4922 continue; 4923 } 4924 if (!ri.activityInfo.name.equals(ai.name)) { 4925 continue; 4926 } 4927 // Found a persistent preference that can handle the intent. 4928 if (DEBUG_PREFERRED || debug) { 4929 Slog.v(TAG, "Returning persistent preferred activity: " + 4930 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4931 } 4932 return ri; 4933 } 4934 } 4935 } 4936 return null; 4937 } 4938 4939 // TODO: handle preferred activities missing while user has amnesia 4940 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4941 List<ResolveInfo> query, int priority, boolean always, 4942 boolean removeMatches, boolean debug, int userId) { 4943 if (!sUserManager.exists(userId)) return null; 4944 flags = updateFlagsForResolve(flags, userId, intent); 4945 // writer 4946 synchronized (mPackages) { 4947 if (intent.getSelector() != null) { 4948 intent = intent.getSelector(); 4949 } 4950 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4951 4952 // Try to find a matching persistent preferred activity. 4953 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4954 debug, userId); 4955 4956 // If a persistent preferred activity matched, use it. 4957 if (pri != null) { 4958 return pri; 4959 } 4960 4961 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4962 // Get the list of preferred activities that handle the intent 4963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4964 List<PreferredActivity> prefs = pir != null 4965 ? pir.queryIntent(intent, resolvedType, 4966 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4967 : null; 4968 if (prefs != null && prefs.size() > 0) { 4969 boolean changed = false; 4970 try { 4971 // First figure out how good the original match set is. 4972 // We will only allow preferred activities that came 4973 // from the same match quality. 4974 int match = 0; 4975 4976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4977 4978 final int N = query.size(); 4979 for (int j=0; j<N; j++) { 4980 final ResolveInfo ri = query.get(j); 4981 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4982 + ": 0x" + Integer.toHexString(match)); 4983 if (ri.match > match) { 4984 match = ri.match; 4985 } 4986 } 4987 4988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4989 + Integer.toHexString(match)); 4990 4991 match &= IntentFilter.MATCH_CATEGORY_MASK; 4992 final int M = prefs.size(); 4993 for (int i=0; i<M; i++) { 4994 final PreferredActivity pa = prefs.get(i); 4995 if (DEBUG_PREFERRED || debug) { 4996 Slog.v(TAG, "Checking PreferredActivity ds=" 4997 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4998 + "\n component=" + pa.mPref.mComponent); 4999 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5000 } 5001 if (pa.mPref.mMatch != match) { 5002 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5003 + Integer.toHexString(pa.mPref.mMatch)); 5004 continue; 5005 } 5006 // If it's not an "always" type preferred activity and that's what we're 5007 // looking for, skip it. 5008 if (always && !pa.mPref.mAlways) { 5009 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5010 continue; 5011 } 5012 final ActivityInfo ai = getActivityInfo( 5013 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5014 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5015 userId); 5016 if (DEBUG_PREFERRED || debug) { 5017 Slog.v(TAG, "Found preferred activity:"); 5018 if (ai != null) { 5019 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5020 } else { 5021 Slog.v(TAG, " null"); 5022 } 5023 } 5024 if (ai == null) { 5025 // This previously registered preferred activity 5026 // component is no longer known. Most likely an update 5027 // to the app was installed and in the new version this 5028 // component no longer exists. Clean it up by removing 5029 // it from the preferred activities list, and skip it. 5030 Slog.w(TAG, "Removing dangling preferred activity: " 5031 + pa.mPref.mComponent); 5032 pir.removeFilter(pa); 5033 changed = true; 5034 continue; 5035 } 5036 for (int j=0; j<N; j++) { 5037 final ResolveInfo ri = query.get(j); 5038 if (!ri.activityInfo.applicationInfo.packageName 5039 .equals(ai.applicationInfo.packageName)) { 5040 continue; 5041 } 5042 if (!ri.activityInfo.name.equals(ai.name)) { 5043 continue; 5044 } 5045 5046 if (removeMatches) { 5047 pir.removeFilter(pa); 5048 changed = true; 5049 if (DEBUG_PREFERRED) { 5050 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5051 } 5052 break; 5053 } 5054 5055 // Okay we found a previously set preferred or last chosen app. 5056 // If the result set is different from when this 5057 // was created, we need to clear it and re-ask the 5058 // user their preference, if we're looking for an "always" type entry. 5059 if (always && !pa.mPref.sameSet(query)) { 5060 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5061 + intent + " type " + resolvedType); 5062 if (DEBUG_PREFERRED) { 5063 Slog.v(TAG, "Removing preferred activity since set changed " 5064 + pa.mPref.mComponent); 5065 } 5066 pir.removeFilter(pa); 5067 // Re-add the filter as a "last chosen" entry (!always) 5068 PreferredActivity lastChosen = new PreferredActivity( 5069 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5070 pir.addFilter(lastChosen); 5071 changed = true; 5072 return null; 5073 } 5074 5075 // Yay! Either the set matched or we're looking for the last chosen 5076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5077 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5078 return ri; 5079 } 5080 } 5081 } finally { 5082 if (changed) { 5083 if (DEBUG_PREFERRED) { 5084 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5085 } 5086 scheduleWritePackageRestrictionsLocked(userId); 5087 } 5088 } 5089 } 5090 } 5091 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5092 return null; 5093 } 5094 5095 /* 5096 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5097 */ 5098 @Override 5099 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5100 int targetUserId) { 5101 mContext.enforceCallingOrSelfPermission( 5102 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5103 List<CrossProfileIntentFilter> matches = 5104 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5105 if (matches != null) { 5106 int size = matches.size(); 5107 for (int i = 0; i < size; i++) { 5108 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5109 } 5110 } 5111 if (hasWebURI(intent)) { 5112 // cross-profile app linking works only towards the parent. 5113 final UserInfo parent = getProfileParent(sourceUserId); 5114 synchronized(mPackages) { 5115 int flags = updateFlagsForResolve(0, parent.id, intent); 5116 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5117 intent, resolvedType, flags, sourceUserId, parent.id); 5118 return xpDomainInfo != null; 5119 } 5120 } 5121 return false; 5122 } 5123 5124 private UserInfo getProfileParent(int userId) { 5125 final long identity = Binder.clearCallingIdentity(); 5126 try { 5127 return sUserManager.getProfileParent(userId); 5128 } finally { 5129 Binder.restoreCallingIdentity(identity); 5130 } 5131 } 5132 5133 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5134 String resolvedType, int userId) { 5135 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5136 if (resolver != null) { 5137 return resolver.queryIntent(intent, resolvedType, false, userId); 5138 } 5139 return null; 5140 } 5141 5142 @Override 5143 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5144 String resolvedType, int flags, int userId) { 5145 return new ParceledListSlice<>( 5146 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5147 } 5148 5149 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5150 String resolvedType, int flags, int userId) { 5151 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5152 flags = updateFlagsForResolve(flags, userId, intent); 5153 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5154 false /* requireFullPermission */, false /* checkShell */, 5155 "query intent activities"); 5156 ComponentName comp = intent.getComponent(); 5157 if (comp == null) { 5158 if (intent.getSelector() != null) { 5159 intent = intent.getSelector(); 5160 comp = intent.getComponent(); 5161 } 5162 } 5163 5164 if (comp != null) { 5165 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5166 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5167 if (ai != null) { 5168 final ResolveInfo ri = new ResolveInfo(); 5169 ri.activityInfo = ai; 5170 list.add(ri); 5171 } 5172 return list; 5173 } 5174 5175 // reader 5176 synchronized (mPackages) { 5177 final String pkgName = intent.getPackage(); 5178 if (pkgName == null) { 5179 List<CrossProfileIntentFilter> matchingFilters = 5180 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5181 // Check for results that need to skip the current profile. 5182 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5183 resolvedType, flags, userId); 5184 if (xpResolveInfo != null) { 5185 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5186 result.add(xpResolveInfo); 5187 return filterIfNotSystemUser(result, userId); 5188 } 5189 5190 // Check for results in the current profile. 5191 List<ResolveInfo> result = mActivities.queryIntent( 5192 intent, resolvedType, flags, userId); 5193 result = filterIfNotSystemUser(result, userId); 5194 5195 // Check for cross profile results. 5196 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5197 xpResolveInfo = queryCrossProfileIntents( 5198 matchingFilters, intent, resolvedType, flags, userId, 5199 hasNonNegativePriorityResult); 5200 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5201 boolean isVisibleToUser = filterIfNotSystemUser( 5202 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5203 if (isVisibleToUser) { 5204 result.add(xpResolveInfo); 5205 Collections.sort(result, mResolvePrioritySorter); 5206 } 5207 } 5208 if (hasWebURI(intent)) { 5209 CrossProfileDomainInfo xpDomainInfo = null; 5210 final UserInfo parent = getProfileParent(userId); 5211 if (parent != null) { 5212 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5213 flags, userId, parent.id); 5214 } 5215 if (xpDomainInfo != null) { 5216 if (xpResolveInfo != null) { 5217 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5218 // in the result. 5219 result.remove(xpResolveInfo); 5220 } 5221 if (result.size() == 0) { 5222 result.add(xpDomainInfo.resolveInfo); 5223 return result; 5224 } 5225 } else if (result.size() <= 1) { 5226 return result; 5227 } 5228 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5229 xpDomainInfo, userId); 5230 Collections.sort(result, mResolvePrioritySorter); 5231 } 5232 return result; 5233 } 5234 final PackageParser.Package pkg = mPackages.get(pkgName); 5235 if (pkg != null) { 5236 return filterIfNotSystemUser( 5237 mActivities.queryIntentForPackage( 5238 intent, resolvedType, flags, pkg.activities, userId), 5239 userId); 5240 } 5241 return new ArrayList<ResolveInfo>(); 5242 } 5243 } 5244 5245 private static class CrossProfileDomainInfo { 5246 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5247 ResolveInfo resolveInfo; 5248 /* Best domain verification status of the activities found in the other profile */ 5249 int bestDomainVerificationStatus; 5250 } 5251 5252 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5253 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5254 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5255 sourceUserId)) { 5256 return null; 5257 } 5258 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5259 resolvedType, flags, parentUserId); 5260 5261 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5262 return null; 5263 } 5264 CrossProfileDomainInfo result = null; 5265 int size = resultTargetUser.size(); 5266 for (int i = 0; i < size; i++) { 5267 ResolveInfo riTargetUser = resultTargetUser.get(i); 5268 // Intent filter verification is only for filters that specify a host. So don't return 5269 // those that handle all web uris. 5270 if (riTargetUser.handleAllWebDataURI) { 5271 continue; 5272 } 5273 String packageName = riTargetUser.activityInfo.packageName; 5274 PackageSetting ps = mSettings.mPackages.get(packageName); 5275 if (ps == null) { 5276 continue; 5277 } 5278 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5279 int status = (int)(verificationState >> 32); 5280 if (result == null) { 5281 result = new CrossProfileDomainInfo(); 5282 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5283 sourceUserId, parentUserId); 5284 result.bestDomainVerificationStatus = status; 5285 } else { 5286 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5287 result.bestDomainVerificationStatus); 5288 } 5289 } 5290 // Don't consider matches with status NEVER across profiles. 5291 if (result != null && result.bestDomainVerificationStatus 5292 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5293 return null; 5294 } 5295 return result; 5296 } 5297 5298 /** 5299 * Verification statuses are ordered from the worse to the best, except for 5300 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5301 */ 5302 private int bestDomainVerificationStatus(int status1, int status2) { 5303 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5304 return status2; 5305 } 5306 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5307 return status1; 5308 } 5309 return (int) MathUtils.max(status1, status2); 5310 } 5311 5312 private boolean isUserEnabled(int userId) { 5313 long callingId = Binder.clearCallingIdentity(); 5314 try { 5315 UserInfo userInfo = sUserManager.getUserInfo(userId); 5316 return userInfo != null && userInfo.isEnabled(); 5317 } finally { 5318 Binder.restoreCallingIdentity(callingId); 5319 } 5320 } 5321 5322 /** 5323 * Filter out activities with systemUserOnly flag set, when current user is not System. 5324 * 5325 * @return filtered list 5326 */ 5327 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5328 if (userId == UserHandle.USER_SYSTEM) { 5329 return resolveInfos; 5330 } 5331 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5332 ResolveInfo info = resolveInfos.get(i); 5333 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5334 resolveInfos.remove(i); 5335 } 5336 } 5337 return resolveInfos; 5338 } 5339 5340 /** 5341 * @param resolveInfos list of resolve infos in descending priority order 5342 * @return if the list contains a resolve info with non-negative priority 5343 */ 5344 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5345 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5346 } 5347 5348 private static boolean hasWebURI(Intent intent) { 5349 if (intent.getData() == null) { 5350 return false; 5351 } 5352 final String scheme = intent.getScheme(); 5353 if (TextUtils.isEmpty(scheme)) { 5354 return false; 5355 } 5356 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5357 } 5358 5359 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5360 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5361 int userId) { 5362 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5363 5364 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5365 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5366 candidates.size()); 5367 } 5368 5369 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5370 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5371 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5372 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5373 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5374 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5375 5376 synchronized (mPackages) { 5377 final int count = candidates.size(); 5378 // First, try to use linked apps. Partition the candidates into four lists: 5379 // one for the final results, one for the "do not use ever", one for "undefined status" 5380 // and finally one for "browser app type". 5381 for (int n=0; n<count; n++) { 5382 ResolveInfo info = candidates.get(n); 5383 String packageName = info.activityInfo.packageName; 5384 PackageSetting ps = mSettings.mPackages.get(packageName); 5385 if (ps != null) { 5386 // Add to the special match all list (Browser use case) 5387 if (info.handleAllWebDataURI) { 5388 matchAllList.add(info); 5389 continue; 5390 } 5391 // Try to get the status from User settings first 5392 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5393 int status = (int)(packedStatus >> 32); 5394 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5395 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5396 if (DEBUG_DOMAIN_VERIFICATION) { 5397 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5398 + " : linkgen=" + linkGeneration); 5399 } 5400 // Use link-enabled generation as preferredOrder, i.e. 5401 // prefer newly-enabled over earlier-enabled. 5402 info.preferredOrder = linkGeneration; 5403 alwaysList.add(info); 5404 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5405 if (DEBUG_DOMAIN_VERIFICATION) { 5406 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5407 } 5408 neverList.add(info); 5409 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5410 if (DEBUG_DOMAIN_VERIFICATION) { 5411 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5412 } 5413 alwaysAskList.add(info); 5414 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5415 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5416 if (DEBUG_DOMAIN_VERIFICATION) { 5417 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5418 } 5419 undefinedList.add(info); 5420 } 5421 } 5422 } 5423 5424 // We'll want to include browser possibilities in a few cases 5425 boolean includeBrowser = false; 5426 5427 // First try to add the "always" resolution(s) for the current user, if any 5428 if (alwaysList.size() > 0) { 5429 result.addAll(alwaysList); 5430 } else { 5431 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5432 result.addAll(undefinedList); 5433 // Maybe add one for the other profile. 5434 if (xpDomainInfo != null && ( 5435 xpDomainInfo.bestDomainVerificationStatus 5436 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5437 result.add(xpDomainInfo.resolveInfo); 5438 } 5439 includeBrowser = true; 5440 } 5441 5442 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5443 // If there were 'always' entries their preferred order has been set, so we also 5444 // back that off to make the alternatives equivalent 5445 if (alwaysAskList.size() > 0) { 5446 for (ResolveInfo i : result) { 5447 i.preferredOrder = 0; 5448 } 5449 result.addAll(alwaysAskList); 5450 includeBrowser = true; 5451 } 5452 5453 if (includeBrowser) { 5454 // Also add browsers (all of them or only the default one) 5455 if (DEBUG_DOMAIN_VERIFICATION) { 5456 Slog.v(TAG, " ...including browsers in candidate set"); 5457 } 5458 if ((matchFlags & MATCH_ALL) != 0) { 5459 result.addAll(matchAllList); 5460 } else { 5461 // Browser/generic handling case. If there's a default browser, go straight 5462 // to that (but only if there is no other higher-priority match). 5463 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5464 int maxMatchPrio = 0; 5465 ResolveInfo defaultBrowserMatch = null; 5466 final int numCandidates = matchAllList.size(); 5467 for (int n = 0; n < numCandidates; n++) { 5468 ResolveInfo info = matchAllList.get(n); 5469 // track the highest overall match priority... 5470 if (info.priority > maxMatchPrio) { 5471 maxMatchPrio = info.priority; 5472 } 5473 // ...and the highest-priority default browser match 5474 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5475 if (defaultBrowserMatch == null 5476 || (defaultBrowserMatch.priority < info.priority)) { 5477 if (debug) { 5478 Slog.v(TAG, "Considering default browser match " + info); 5479 } 5480 defaultBrowserMatch = info; 5481 } 5482 } 5483 } 5484 if (defaultBrowserMatch != null 5485 && defaultBrowserMatch.priority >= maxMatchPrio 5486 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5487 { 5488 if (debug) { 5489 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5490 } 5491 result.add(defaultBrowserMatch); 5492 } else { 5493 result.addAll(matchAllList); 5494 } 5495 } 5496 5497 // If there is nothing selected, add all candidates and remove the ones that the user 5498 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5499 if (result.size() == 0) { 5500 result.addAll(candidates); 5501 result.removeAll(neverList); 5502 } 5503 } 5504 } 5505 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5506 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5507 result.size()); 5508 for (ResolveInfo info : result) { 5509 Slog.v(TAG, " + " + info.activityInfo); 5510 } 5511 } 5512 return result; 5513 } 5514 5515 // Returns a packed value as a long: 5516 // 5517 // high 'int'-sized word: link status: undefined/ask/never/always. 5518 // low 'int'-sized word: relative priority among 'always' results. 5519 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5520 long result = ps.getDomainVerificationStatusForUser(userId); 5521 // if none available, get the master status 5522 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5523 if (ps.getIntentFilterVerificationInfo() != null) { 5524 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5525 } 5526 } 5527 return result; 5528 } 5529 5530 private ResolveInfo querySkipCurrentProfileIntents( 5531 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5532 int flags, int sourceUserId) { 5533 if (matchingFilters != null) { 5534 int size = matchingFilters.size(); 5535 for (int i = 0; i < size; i ++) { 5536 CrossProfileIntentFilter filter = matchingFilters.get(i); 5537 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5538 // Checking if there are activities in the target user that can handle the 5539 // intent. 5540 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5541 resolvedType, flags, sourceUserId); 5542 if (resolveInfo != null) { 5543 return resolveInfo; 5544 } 5545 } 5546 } 5547 } 5548 return null; 5549 } 5550 5551 // Return matching ResolveInfo in target user if any. 5552 private ResolveInfo queryCrossProfileIntents( 5553 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5554 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5555 if (matchingFilters != null) { 5556 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5557 // match the same intent. For performance reasons, it is better not to 5558 // run queryIntent twice for the same userId 5559 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5560 int size = matchingFilters.size(); 5561 for (int i = 0; i < size; i++) { 5562 CrossProfileIntentFilter filter = matchingFilters.get(i); 5563 int targetUserId = filter.getTargetUserId(); 5564 boolean skipCurrentProfile = 5565 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5566 boolean skipCurrentProfileIfNoMatchFound = 5567 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5568 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5569 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5570 // Checking if there are activities in the target user that can handle the 5571 // intent. 5572 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5573 resolvedType, flags, sourceUserId); 5574 if (resolveInfo != null) return resolveInfo; 5575 alreadyTriedUserIds.put(targetUserId, true); 5576 } 5577 } 5578 } 5579 return null; 5580 } 5581 5582 /** 5583 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5584 * will forward the intent to the filter's target user. 5585 * Otherwise, returns null. 5586 */ 5587 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5588 String resolvedType, int flags, int sourceUserId) { 5589 int targetUserId = filter.getTargetUserId(); 5590 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5591 resolvedType, flags, targetUserId); 5592 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5593 // If all the matches in the target profile are suspended, return null. 5594 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5595 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5596 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5597 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5598 targetUserId); 5599 } 5600 } 5601 } 5602 return null; 5603 } 5604 5605 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5606 int sourceUserId, int targetUserId) { 5607 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5608 long ident = Binder.clearCallingIdentity(); 5609 boolean targetIsProfile; 5610 try { 5611 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5612 } finally { 5613 Binder.restoreCallingIdentity(ident); 5614 } 5615 String className; 5616 if (targetIsProfile) { 5617 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5618 } else { 5619 className = FORWARD_INTENT_TO_PARENT; 5620 } 5621 ComponentName forwardingActivityComponentName = new ComponentName( 5622 mAndroidApplication.packageName, className); 5623 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5624 sourceUserId); 5625 if (!targetIsProfile) { 5626 forwardingActivityInfo.showUserIcon = targetUserId; 5627 forwardingResolveInfo.noResourceId = true; 5628 } 5629 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5630 forwardingResolveInfo.priority = 0; 5631 forwardingResolveInfo.preferredOrder = 0; 5632 forwardingResolveInfo.match = 0; 5633 forwardingResolveInfo.isDefault = true; 5634 forwardingResolveInfo.filter = filter; 5635 forwardingResolveInfo.targetUserId = targetUserId; 5636 return forwardingResolveInfo; 5637 } 5638 5639 @Override 5640 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5641 Intent[] specifics, String[] specificTypes, Intent intent, 5642 String resolvedType, int flags, int userId) { 5643 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5644 specificTypes, intent, resolvedType, flags, userId)); 5645 } 5646 5647 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5648 Intent[] specifics, String[] specificTypes, Intent intent, 5649 String resolvedType, int flags, int userId) { 5650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5651 flags = updateFlagsForResolve(flags, userId, intent); 5652 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5653 false /* requireFullPermission */, false /* checkShell */, 5654 "query intent activity options"); 5655 final String resultsAction = intent.getAction(); 5656 5657 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5658 | PackageManager.GET_RESOLVED_FILTER, userId); 5659 5660 if (DEBUG_INTENT_MATCHING) { 5661 Log.v(TAG, "Query " + intent + ": " + results); 5662 } 5663 5664 int specificsPos = 0; 5665 int N; 5666 5667 // todo: note that the algorithm used here is O(N^2). This 5668 // isn't a problem in our current environment, but if we start running 5669 // into situations where we have more than 5 or 10 matches then this 5670 // should probably be changed to something smarter... 5671 5672 // First we go through and resolve each of the specific items 5673 // that were supplied, taking care of removing any corresponding 5674 // duplicate items in the generic resolve list. 5675 if (specifics != null) { 5676 for (int i=0; i<specifics.length; i++) { 5677 final Intent sintent = specifics[i]; 5678 if (sintent == null) { 5679 continue; 5680 } 5681 5682 if (DEBUG_INTENT_MATCHING) { 5683 Log.v(TAG, "Specific #" + i + ": " + sintent); 5684 } 5685 5686 String action = sintent.getAction(); 5687 if (resultsAction != null && resultsAction.equals(action)) { 5688 // If this action was explicitly requested, then don't 5689 // remove things that have it. 5690 action = null; 5691 } 5692 5693 ResolveInfo ri = null; 5694 ActivityInfo ai = null; 5695 5696 ComponentName comp = sintent.getComponent(); 5697 if (comp == null) { 5698 ri = resolveIntent( 5699 sintent, 5700 specificTypes != null ? specificTypes[i] : null, 5701 flags, userId); 5702 if (ri == null) { 5703 continue; 5704 } 5705 if (ri == mResolveInfo) { 5706 // ACK! Must do something better with this. 5707 } 5708 ai = ri.activityInfo; 5709 comp = new ComponentName(ai.applicationInfo.packageName, 5710 ai.name); 5711 } else { 5712 ai = getActivityInfo(comp, flags, userId); 5713 if (ai == null) { 5714 continue; 5715 } 5716 } 5717 5718 // Look for any generic query activities that are duplicates 5719 // of this specific one, and remove them from the results. 5720 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5721 N = results.size(); 5722 int j; 5723 for (j=specificsPos; j<N; j++) { 5724 ResolveInfo sri = results.get(j); 5725 if ((sri.activityInfo.name.equals(comp.getClassName()) 5726 && sri.activityInfo.applicationInfo.packageName.equals( 5727 comp.getPackageName())) 5728 || (action != null && sri.filter.matchAction(action))) { 5729 results.remove(j); 5730 if (DEBUG_INTENT_MATCHING) Log.v( 5731 TAG, "Removing duplicate item from " + j 5732 + " due to specific " + specificsPos); 5733 if (ri == null) { 5734 ri = sri; 5735 } 5736 j--; 5737 N--; 5738 } 5739 } 5740 5741 // Add this specific item to its proper place. 5742 if (ri == null) { 5743 ri = new ResolveInfo(); 5744 ri.activityInfo = ai; 5745 } 5746 results.add(specificsPos, ri); 5747 ri.specificIndex = i; 5748 specificsPos++; 5749 } 5750 } 5751 5752 // Now we go through the remaining generic results and remove any 5753 // duplicate actions that are found here. 5754 N = results.size(); 5755 for (int i=specificsPos; i<N-1; i++) { 5756 final ResolveInfo rii = results.get(i); 5757 if (rii.filter == null) { 5758 continue; 5759 } 5760 5761 // Iterate over all of the actions of this result's intent 5762 // filter... typically this should be just one. 5763 final Iterator<String> it = rii.filter.actionsIterator(); 5764 if (it == null) { 5765 continue; 5766 } 5767 while (it.hasNext()) { 5768 final String action = it.next(); 5769 if (resultsAction != null && resultsAction.equals(action)) { 5770 // If this action was explicitly requested, then don't 5771 // remove things that have it. 5772 continue; 5773 } 5774 for (int j=i+1; j<N; j++) { 5775 final ResolveInfo rij = results.get(j); 5776 if (rij.filter != null && rij.filter.hasAction(action)) { 5777 results.remove(j); 5778 if (DEBUG_INTENT_MATCHING) Log.v( 5779 TAG, "Removing duplicate item from " + j 5780 + " due to action " + action + " at " + i); 5781 j--; 5782 N--; 5783 } 5784 } 5785 } 5786 5787 // If the caller didn't request filter information, drop it now 5788 // so we don't have to marshall/unmarshall it. 5789 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5790 rii.filter = null; 5791 } 5792 } 5793 5794 // Filter out the caller activity if so requested. 5795 if (caller != null) { 5796 N = results.size(); 5797 for (int i=0; i<N; i++) { 5798 ActivityInfo ainfo = results.get(i).activityInfo; 5799 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5800 && caller.getClassName().equals(ainfo.name)) { 5801 results.remove(i); 5802 break; 5803 } 5804 } 5805 } 5806 5807 // If the caller didn't request filter information, 5808 // drop them now so we don't have to 5809 // marshall/unmarshall it. 5810 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5811 N = results.size(); 5812 for (int i=0; i<N; i++) { 5813 results.get(i).filter = null; 5814 } 5815 } 5816 5817 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5818 return results; 5819 } 5820 5821 @Override 5822 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5823 String resolvedType, int flags, int userId) { 5824 return new ParceledListSlice<>( 5825 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5826 } 5827 5828 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5829 String resolvedType, int flags, int userId) { 5830 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5831 flags = updateFlagsForResolve(flags, userId, intent); 5832 ComponentName comp = intent.getComponent(); 5833 if (comp == null) { 5834 if (intent.getSelector() != null) { 5835 intent = intent.getSelector(); 5836 comp = intent.getComponent(); 5837 } 5838 } 5839 if (comp != null) { 5840 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5841 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5842 if (ai != null) { 5843 ResolveInfo ri = new ResolveInfo(); 5844 ri.activityInfo = ai; 5845 list.add(ri); 5846 } 5847 return list; 5848 } 5849 5850 // reader 5851 synchronized (mPackages) { 5852 String pkgName = intent.getPackage(); 5853 if (pkgName == null) { 5854 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5855 } 5856 final PackageParser.Package pkg = mPackages.get(pkgName); 5857 if (pkg != null) { 5858 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5859 userId); 5860 } 5861 return Collections.emptyList(); 5862 } 5863 } 5864 5865 @Override 5866 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5867 if (!sUserManager.exists(userId)) return null; 5868 flags = updateFlagsForResolve(flags, userId, intent); 5869 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5870 if (query != null) { 5871 if (query.size() >= 1) { 5872 // If there is more than one service with the same priority, 5873 // just arbitrarily pick the first one. 5874 return query.get(0); 5875 } 5876 } 5877 return null; 5878 } 5879 5880 @Override 5881 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5882 String resolvedType, int flags, int userId) { 5883 return new ParceledListSlice<>( 5884 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5885 } 5886 5887 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5888 String resolvedType, int flags, int userId) { 5889 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5890 flags = updateFlagsForResolve(flags, userId, intent); 5891 ComponentName comp = intent.getComponent(); 5892 if (comp == null) { 5893 if (intent.getSelector() != null) { 5894 intent = intent.getSelector(); 5895 comp = intent.getComponent(); 5896 } 5897 } 5898 if (comp != null) { 5899 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5900 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5901 if (si != null) { 5902 final ResolveInfo ri = new ResolveInfo(); 5903 ri.serviceInfo = si; 5904 list.add(ri); 5905 } 5906 return list; 5907 } 5908 5909 // reader 5910 synchronized (mPackages) { 5911 String pkgName = intent.getPackage(); 5912 if (pkgName == null) { 5913 return mServices.queryIntent(intent, resolvedType, flags, userId); 5914 } 5915 final PackageParser.Package pkg = mPackages.get(pkgName); 5916 if (pkg != null) { 5917 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5918 userId); 5919 } 5920 return Collections.emptyList(); 5921 } 5922 } 5923 5924 @Override 5925 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5926 String resolvedType, int flags, int userId) { 5927 return new ParceledListSlice<>( 5928 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5929 } 5930 5931 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5932 Intent intent, String resolvedType, int flags, int userId) { 5933 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5934 flags = updateFlagsForResolve(flags, userId, intent); 5935 ComponentName comp = intent.getComponent(); 5936 if (comp == null) { 5937 if (intent.getSelector() != null) { 5938 intent = intent.getSelector(); 5939 comp = intent.getComponent(); 5940 } 5941 } 5942 if (comp != null) { 5943 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5944 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5945 if (pi != null) { 5946 final ResolveInfo ri = new ResolveInfo(); 5947 ri.providerInfo = pi; 5948 list.add(ri); 5949 } 5950 return list; 5951 } 5952 5953 // reader 5954 synchronized (mPackages) { 5955 String pkgName = intent.getPackage(); 5956 if (pkgName == null) { 5957 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5958 } 5959 final PackageParser.Package pkg = mPackages.get(pkgName); 5960 if (pkg != null) { 5961 return mProviders.queryIntentForPackage( 5962 intent, resolvedType, flags, pkg.providers, userId); 5963 } 5964 return Collections.emptyList(); 5965 } 5966 } 5967 5968 @Override 5969 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5970 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5971 flags = updateFlagsForPackage(flags, userId, null); 5972 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5973 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5974 true /* requireFullPermission */, false /* checkShell */, 5975 "get installed packages"); 5976 5977 // writer 5978 synchronized (mPackages) { 5979 ArrayList<PackageInfo> list; 5980 if (listUninstalled) { 5981 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5982 for (PackageSetting ps : mSettings.mPackages.values()) { 5983 final PackageInfo pi; 5984 if (ps.pkg != null) { 5985 pi = generatePackageInfo(ps, flags, userId); 5986 } else { 5987 pi = generatePackageInfo(ps, flags, userId); 5988 } 5989 if (pi != null) { 5990 list.add(pi); 5991 } 5992 } 5993 } else { 5994 list = new ArrayList<PackageInfo>(mPackages.size()); 5995 for (PackageParser.Package p : mPackages.values()) { 5996 final PackageInfo pi = 5997 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 5998 if (pi != null) { 5999 list.add(pi); 6000 } 6001 } 6002 } 6003 6004 return new ParceledListSlice<PackageInfo>(list); 6005 } 6006 } 6007 6008 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6009 String[] permissions, boolean[] tmp, int flags, int userId) { 6010 int numMatch = 0; 6011 final PermissionsState permissionsState = ps.getPermissionsState(); 6012 for (int i=0; i<permissions.length; i++) { 6013 final String permission = permissions[i]; 6014 if (permissionsState.hasPermission(permission, userId)) { 6015 tmp[i] = true; 6016 numMatch++; 6017 } else { 6018 tmp[i] = false; 6019 } 6020 } 6021 if (numMatch == 0) { 6022 return; 6023 } 6024 final PackageInfo pi; 6025 if (ps.pkg != null) { 6026 pi = generatePackageInfo(ps, flags, userId); 6027 } else { 6028 pi = generatePackageInfo(ps, flags, userId); 6029 } 6030 // The above might return null in cases of uninstalled apps or install-state 6031 // skew across users/profiles. 6032 if (pi != null) { 6033 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6034 if (numMatch == permissions.length) { 6035 pi.requestedPermissions = permissions; 6036 } else { 6037 pi.requestedPermissions = new String[numMatch]; 6038 numMatch = 0; 6039 for (int i=0; i<permissions.length; i++) { 6040 if (tmp[i]) { 6041 pi.requestedPermissions[numMatch] = permissions[i]; 6042 numMatch++; 6043 } 6044 } 6045 } 6046 } 6047 list.add(pi); 6048 } 6049 } 6050 6051 @Override 6052 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6053 String[] permissions, int flags, int userId) { 6054 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6055 flags = updateFlagsForPackage(flags, userId, permissions); 6056 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6057 6058 // writer 6059 synchronized (mPackages) { 6060 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6061 boolean[] tmpBools = new boolean[permissions.length]; 6062 if (listUninstalled) { 6063 for (PackageSetting ps : mSettings.mPackages.values()) { 6064 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6065 } 6066 } else { 6067 for (PackageParser.Package pkg : mPackages.values()) { 6068 PackageSetting ps = (PackageSetting)pkg.mExtras; 6069 if (ps != null) { 6070 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6071 userId); 6072 } 6073 } 6074 } 6075 6076 return new ParceledListSlice<PackageInfo>(list); 6077 } 6078 } 6079 6080 @Override 6081 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6082 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6083 flags = updateFlagsForApplication(flags, userId, null); 6084 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6085 6086 // writer 6087 synchronized (mPackages) { 6088 ArrayList<ApplicationInfo> list; 6089 if (listUninstalled) { 6090 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6091 for (PackageSetting ps : mSettings.mPackages.values()) { 6092 ApplicationInfo ai; 6093 if (ps.pkg != null) { 6094 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6095 ps.readUserState(userId), userId); 6096 } else { 6097 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6098 } 6099 if (ai != null) { 6100 list.add(ai); 6101 } 6102 } 6103 } else { 6104 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6105 for (PackageParser.Package p : mPackages.values()) { 6106 if (p.mExtras != null) { 6107 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6108 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6109 if (ai != null) { 6110 list.add(ai); 6111 } 6112 } 6113 } 6114 } 6115 6116 return new ParceledListSlice<ApplicationInfo>(list); 6117 } 6118 } 6119 6120 @Override 6121 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6122 if (DISABLE_EPHEMERAL_APPS) { 6123 return null; 6124 } 6125 6126 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6127 "getEphemeralApplications"); 6128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6129 true /* requireFullPermission */, false /* checkShell */, 6130 "getEphemeralApplications"); 6131 synchronized (mPackages) { 6132 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6133 .getEphemeralApplicationsLPw(userId); 6134 if (ephemeralApps != null) { 6135 return new ParceledListSlice<>(ephemeralApps); 6136 } 6137 } 6138 return null; 6139 } 6140 6141 @Override 6142 public boolean isEphemeralApplication(String packageName, int userId) { 6143 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6144 true /* requireFullPermission */, false /* checkShell */, 6145 "isEphemeral"); 6146 if (DISABLE_EPHEMERAL_APPS) { 6147 return false; 6148 } 6149 6150 if (!isCallerSameApp(packageName)) { 6151 return false; 6152 } 6153 synchronized (mPackages) { 6154 PackageParser.Package pkg = mPackages.get(packageName); 6155 if (pkg != null) { 6156 return pkg.applicationInfo.isEphemeralApp(); 6157 } 6158 } 6159 return false; 6160 } 6161 6162 @Override 6163 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6164 if (DISABLE_EPHEMERAL_APPS) { 6165 return null; 6166 } 6167 6168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6169 true /* requireFullPermission */, false /* checkShell */, 6170 "getCookie"); 6171 if (!isCallerSameApp(packageName)) { 6172 return null; 6173 } 6174 synchronized (mPackages) { 6175 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6176 packageName, userId); 6177 } 6178 } 6179 6180 @Override 6181 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6182 if (DISABLE_EPHEMERAL_APPS) { 6183 return true; 6184 } 6185 6186 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6187 true /* requireFullPermission */, true /* checkShell */, 6188 "setCookie"); 6189 if (!isCallerSameApp(packageName)) { 6190 return false; 6191 } 6192 synchronized (mPackages) { 6193 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6194 packageName, cookie, userId); 6195 } 6196 } 6197 6198 @Override 6199 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6200 if (DISABLE_EPHEMERAL_APPS) { 6201 return null; 6202 } 6203 6204 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6205 "getEphemeralApplicationIcon"); 6206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6207 true /* requireFullPermission */, false /* checkShell */, 6208 "getEphemeralApplicationIcon"); 6209 synchronized (mPackages) { 6210 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6211 packageName, userId); 6212 } 6213 } 6214 6215 private boolean isCallerSameApp(String packageName) { 6216 PackageParser.Package pkg = mPackages.get(packageName); 6217 return pkg != null 6218 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6219 } 6220 6221 @Override 6222 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6223 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6224 } 6225 6226 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6227 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6228 6229 // reader 6230 synchronized (mPackages) { 6231 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6232 final int userId = UserHandle.getCallingUserId(); 6233 while (i.hasNext()) { 6234 final PackageParser.Package p = i.next(); 6235 if (p.applicationInfo == null) continue; 6236 6237 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6238 && !p.applicationInfo.isDirectBootAware(); 6239 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6240 && p.applicationInfo.isDirectBootAware(); 6241 6242 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6243 && (!mSafeMode || isSystemApp(p)) 6244 && (matchesUnaware || matchesAware)) { 6245 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6246 if (ps != null) { 6247 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6248 ps.readUserState(userId), userId); 6249 if (ai != null) { 6250 finalList.add(ai); 6251 } 6252 } 6253 } 6254 } 6255 } 6256 6257 return finalList; 6258 } 6259 6260 @Override 6261 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6262 if (!sUserManager.exists(userId)) return null; 6263 flags = updateFlagsForComponent(flags, userId, name); 6264 // reader 6265 synchronized (mPackages) { 6266 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6267 PackageSetting ps = provider != null 6268 ? mSettings.mPackages.get(provider.owner.packageName) 6269 : null; 6270 return ps != null 6271 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6272 ? PackageParser.generateProviderInfo(provider, flags, 6273 ps.readUserState(userId), userId) 6274 : null; 6275 } 6276 } 6277 6278 /** 6279 * @deprecated 6280 */ 6281 @Deprecated 6282 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6283 // reader 6284 synchronized (mPackages) { 6285 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6286 .entrySet().iterator(); 6287 final int userId = UserHandle.getCallingUserId(); 6288 while (i.hasNext()) { 6289 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6290 PackageParser.Provider p = entry.getValue(); 6291 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6292 6293 if (ps != null && p.syncable 6294 && (!mSafeMode || (p.info.applicationInfo.flags 6295 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6296 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6297 ps.readUserState(userId), userId); 6298 if (info != null) { 6299 outNames.add(entry.getKey()); 6300 outInfo.add(info); 6301 } 6302 } 6303 } 6304 } 6305 } 6306 6307 @Override 6308 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6309 int uid, int flags) { 6310 final int userId = processName != null ? UserHandle.getUserId(uid) 6311 : UserHandle.getCallingUserId(); 6312 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6313 flags = updateFlagsForComponent(flags, userId, processName); 6314 6315 ArrayList<ProviderInfo> finalList = null; 6316 // reader 6317 synchronized (mPackages) { 6318 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6319 while (i.hasNext()) { 6320 final PackageParser.Provider p = i.next(); 6321 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6322 if (ps != null && p.info.authority != null 6323 && (processName == null 6324 || (p.info.processName.equals(processName) 6325 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6326 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6327 if (finalList == null) { 6328 finalList = new ArrayList<ProviderInfo>(3); 6329 } 6330 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6331 ps.readUserState(userId), userId); 6332 if (info != null) { 6333 finalList.add(info); 6334 } 6335 } 6336 } 6337 } 6338 6339 if (finalList != null) { 6340 Collections.sort(finalList, mProviderInitOrderSorter); 6341 return new ParceledListSlice<ProviderInfo>(finalList); 6342 } 6343 6344 return ParceledListSlice.emptyList(); 6345 } 6346 6347 @Override 6348 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6349 // reader 6350 synchronized (mPackages) { 6351 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6352 return PackageParser.generateInstrumentationInfo(i, flags); 6353 } 6354 } 6355 6356 @Override 6357 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6358 String targetPackage, int flags) { 6359 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6360 } 6361 6362 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6363 int flags) { 6364 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6365 6366 // reader 6367 synchronized (mPackages) { 6368 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6369 while (i.hasNext()) { 6370 final PackageParser.Instrumentation p = i.next(); 6371 if (targetPackage == null 6372 || targetPackage.equals(p.info.targetPackage)) { 6373 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6374 flags); 6375 if (ii != null) { 6376 finalList.add(ii); 6377 } 6378 } 6379 } 6380 } 6381 6382 return finalList; 6383 } 6384 6385 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6386 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6387 if (overlays == null) { 6388 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6389 return; 6390 } 6391 for (PackageParser.Package opkg : overlays.values()) { 6392 // Not much to do if idmap fails: we already logged the error 6393 // and we certainly don't want to abort installation of pkg simply 6394 // because an overlay didn't fit properly. For these reasons, 6395 // ignore the return value of createIdmapForPackagePairLI. 6396 createIdmapForPackagePairLI(pkg, opkg); 6397 } 6398 } 6399 6400 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6401 PackageParser.Package opkg) { 6402 if (!opkg.mTrustedOverlay) { 6403 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6404 opkg.baseCodePath + ": overlay not trusted"); 6405 return false; 6406 } 6407 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6408 if (overlaySet == null) { 6409 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6410 opkg.baseCodePath + " but target package has no known overlays"); 6411 return false; 6412 } 6413 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6414 // TODO: generate idmap for split APKs 6415 try { 6416 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6417 } catch (InstallerException e) { 6418 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6419 + opkg.baseCodePath); 6420 return false; 6421 } 6422 PackageParser.Package[] overlayArray = 6423 overlaySet.values().toArray(new PackageParser.Package[0]); 6424 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6425 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6426 return p1.mOverlayPriority - p2.mOverlayPriority; 6427 } 6428 }; 6429 Arrays.sort(overlayArray, cmp); 6430 6431 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6432 int i = 0; 6433 for (PackageParser.Package p : overlayArray) { 6434 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6435 } 6436 return true; 6437 } 6438 6439 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6441 try { 6442 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6443 } finally { 6444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6445 } 6446 } 6447 6448 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6449 final File[] files = dir.listFiles(); 6450 if (ArrayUtils.isEmpty(files)) { 6451 Log.d(TAG, "No files in app dir " + dir); 6452 return; 6453 } 6454 6455 if (DEBUG_PACKAGE_SCANNING) { 6456 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6457 + " flags=0x" + Integer.toHexString(parseFlags)); 6458 } 6459 6460 for (File file : files) { 6461 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6462 && !PackageInstallerService.isStageName(file.getName()); 6463 if (!isPackage) { 6464 // Ignore entries which are not packages 6465 continue; 6466 } 6467 try { 6468 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6469 scanFlags, currentTime, null); 6470 } catch (PackageManagerException e) { 6471 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6472 6473 // Delete invalid userdata apps 6474 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6475 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6476 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6477 removeCodePathLI(file); 6478 } 6479 } 6480 } 6481 } 6482 6483 private static File getSettingsProblemFile() { 6484 File dataDir = Environment.getDataDirectory(); 6485 File systemDir = new File(dataDir, "system"); 6486 File fname = new File(systemDir, "uiderrors.txt"); 6487 return fname; 6488 } 6489 6490 static void reportSettingsProblem(int priority, String msg) { 6491 logCriticalInfo(priority, msg); 6492 } 6493 6494 static void logCriticalInfo(int priority, String msg) { 6495 Slog.println(priority, TAG, msg); 6496 EventLogTags.writePmCriticalInfo(msg); 6497 try { 6498 File fname = getSettingsProblemFile(); 6499 FileOutputStream out = new FileOutputStream(fname, true); 6500 PrintWriter pw = new FastPrintWriter(out); 6501 SimpleDateFormat formatter = new SimpleDateFormat(); 6502 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6503 pw.println(dateString + ": " + msg); 6504 pw.close(); 6505 FileUtils.setPermissions( 6506 fname.toString(), 6507 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6508 -1, -1); 6509 } catch (java.io.IOException e) { 6510 } 6511 } 6512 6513 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6514 int parseFlags) throws PackageManagerException { 6515 if (ps != null 6516 && ps.codePath.equals(srcFile) 6517 && ps.timeStamp == srcFile.lastModified() 6518 && !isCompatSignatureUpdateNeeded(pkg) 6519 && !isRecoverSignatureUpdateNeeded(pkg)) { 6520 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6521 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6522 ArraySet<PublicKey> signingKs; 6523 synchronized (mPackages) { 6524 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6525 } 6526 if (ps.signatures.mSignatures != null 6527 && ps.signatures.mSignatures.length != 0 6528 && signingKs != null) { 6529 // Optimization: reuse the existing cached certificates 6530 // if the package appears to be unchanged. 6531 pkg.mSignatures = ps.signatures.mSignatures; 6532 pkg.mSigningKeys = signingKs; 6533 return; 6534 } 6535 6536 Slog.w(TAG, "PackageSetting for " + ps.name 6537 + " is missing signatures. Collecting certs again to recover them."); 6538 } else { 6539 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6540 } 6541 6542 try { 6543 PackageParser.collectCertificates(pkg, parseFlags); 6544 } catch (PackageParserException e) { 6545 throw PackageManagerException.from(e); 6546 } 6547 } 6548 6549 /** 6550 * Traces a package scan. 6551 * @see #scanPackageLI(File, int, int, long, UserHandle) 6552 */ 6553 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6554 long currentTime, UserHandle user) throws PackageManagerException { 6555 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6556 try { 6557 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6558 } finally { 6559 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6560 } 6561 } 6562 6563 /** 6564 * Scans a package and returns the newly parsed package. 6565 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6566 */ 6567 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6568 long currentTime, UserHandle user) throws PackageManagerException { 6569 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6570 parseFlags |= mDefParseFlags; 6571 PackageParser pp = new PackageParser(); 6572 pp.setSeparateProcesses(mSeparateProcesses); 6573 pp.setOnlyCoreApps(mOnlyCore); 6574 pp.setDisplayMetrics(mMetrics); 6575 6576 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6577 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6578 } 6579 6580 final PackageParser.Package pkg; 6581 try { 6582 pkg = pp.parsePackage(scanFile, parseFlags); 6583 } catch (PackageParserException e) { 6584 throw PackageManagerException.from(e); 6585 } 6586 6587 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6588 } 6589 6590 /** 6591 * Scans a package and returns the newly parsed package. 6592 * @throws PackageManagerException on a parse error. 6593 */ 6594 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6595 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6596 throws PackageManagerException { 6597 // If the package has children and this is the first dive in the function 6598 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6599 // packages (parent and children) would be successfully scanned before the 6600 // actual scan since scanning mutates internal state and we want to atomically 6601 // install the package and its children. 6602 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6603 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6604 scanFlags |= SCAN_CHECK_ONLY; 6605 } 6606 } else { 6607 scanFlags &= ~SCAN_CHECK_ONLY; 6608 } 6609 6610 // Scan the parent 6611 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6612 scanFlags, currentTime, user); 6613 6614 // Scan the children 6615 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6616 for (int i = 0; i < childCount; i++) { 6617 PackageParser.Package childPackage = pkg.childPackages.get(i); 6618 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6619 currentTime, user); 6620 } 6621 6622 6623 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6624 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6625 } 6626 6627 return scannedPkg; 6628 } 6629 6630 /** 6631 * Scans a package and returns the newly parsed package. 6632 * @throws PackageManagerException on a parse error. 6633 */ 6634 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6635 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6636 throws PackageManagerException { 6637 PackageSetting ps = null; 6638 PackageSetting updatedPkg; 6639 // reader 6640 synchronized (mPackages) { 6641 // Look to see if we already know about this package. 6642 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6643 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6644 // This package has been renamed to its original name. Let's 6645 // use that. 6646 ps = mSettings.peekPackageLPr(oldName); 6647 } 6648 // If there was no original package, see one for the real package name. 6649 if (ps == null) { 6650 ps = mSettings.peekPackageLPr(pkg.packageName); 6651 } 6652 // Check to see if this package could be hiding/updating a system 6653 // package. Must look for it either under the original or real 6654 // package name depending on our state. 6655 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6656 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6657 6658 // If this is a package we don't know about on the system partition, we 6659 // may need to remove disabled child packages on the system partition 6660 // or may need to not add child packages if the parent apk is updated 6661 // on the data partition and no longer defines this child package. 6662 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6663 // If this is a parent package for an updated system app and this system 6664 // app got an OTA update which no longer defines some of the child packages 6665 // we have to prune them from the disabled system packages. 6666 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6667 if (disabledPs != null) { 6668 final int scannedChildCount = (pkg.childPackages != null) 6669 ? pkg.childPackages.size() : 0; 6670 final int disabledChildCount = disabledPs.childPackageNames != null 6671 ? disabledPs.childPackageNames.size() : 0; 6672 for (int i = 0; i < disabledChildCount; i++) { 6673 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6674 boolean disabledPackageAvailable = false; 6675 for (int j = 0; j < scannedChildCount; j++) { 6676 PackageParser.Package childPkg = pkg.childPackages.get(j); 6677 if (childPkg.packageName.equals(disabledChildPackageName)) { 6678 disabledPackageAvailable = true; 6679 break; 6680 } 6681 } 6682 if (!disabledPackageAvailable) { 6683 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6684 } 6685 } 6686 } 6687 } 6688 } 6689 6690 boolean updatedPkgBetter = false; 6691 // First check if this is a system package that may involve an update 6692 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6693 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6694 // it needs to drop FLAG_PRIVILEGED. 6695 if (locationIsPrivileged(scanFile)) { 6696 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6697 } else { 6698 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6699 } 6700 6701 if (ps != null && !ps.codePath.equals(scanFile)) { 6702 // The path has changed from what was last scanned... check the 6703 // version of the new path against what we have stored to determine 6704 // what to do. 6705 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6706 if (pkg.mVersionCode <= ps.versionCode) { 6707 // The system package has been updated and the code path does not match 6708 // Ignore entry. Skip it. 6709 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6710 + " ignored: updated version " + ps.versionCode 6711 + " better than this " + pkg.mVersionCode); 6712 if (!updatedPkg.codePath.equals(scanFile)) { 6713 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6714 + ps.name + " changing from " + updatedPkg.codePathString 6715 + " to " + scanFile); 6716 updatedPkg.codePath = scanFile; 6717 updatedPkg.codePathString = scanFile.toString(); 6718 updatedPkg.resourcePath = scanFile; 6719 updatedPkg.resourcePathString = scanFile.toString(); 6720 } 6721 updatedPkg.pkg = pkg; 6722 updatedPkg.versionCode = pkg.mVersionCode; 6723 6724 // Update the disabled system child packages to point to the package too. 6725 final int childCount = updatedPkg.childPackageNames != null 6726 ? updatedPkg.childPackageNames.size() : 0; 6727 for (int i = 0; i < childCount; i++) { 6728 String childPackageName = updatedPkg.childPackageNames.get(i); 6729 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6730 childPackageName); 6731 if (updatedChildPkg != null) { 6732 updatedChildPkg.pkg = pkg; 6733 updatedChildPkg.versionCode = pkg.mVersionCode; 6734 } 6735 } 6736 6737 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6738 + scanFile + " ignored: updated version " + ps.versionCode 6739 + " better than this " + pkg.mVersionCode); 6740 } else { 6741 // The current app on the system partition is better than 6742 // what we have updated to on the data partition; switch 6743 // back to the system partition version. 6744 // At this point, its safely assumed that package installation for 6745 // apps in system partition will go through. If not there won't be a working 6746 // version of the app 6747 // writer 6748 synchronized (mPackages) { 6749 // Just remove the loaded entries from package lists. 6750 mPackages.remove(ps.name); 6751 } 6752 6753 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6754 + " reverting from " + ps.codePathString 6755 + ": new version " + pkg.mVersionCode 6756 + " better than installed " + ps.versionCode); 6757 6758 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6759 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6760 synchronized (mInstallLock) { 6761 args.cleanUpResourcesLI(); 6762 } 6763 synchronized (mPackages) { 6764 mSettings.enableSystemPackageLPw(ps.name); 6765 } 6766 updatedPkgBetter = true; 6767 } 6768 } 6769 } 6770 6771 if (updatedPkg != null) { 6772 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6773 // initially 6774 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6775 6776 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6777 // flag set initially 6778 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6779 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6780 } 6781 } 6782 6783 // Verify certificates against what was last scanned 6784 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6785 6786 /* 6787 * A new system app appeared, but we already had a non-system one of the 6788 * same name installed earlier. 6789 */ 6790 boolean shouldHideSystemApp = false; 6791 if (updatedPkg == null && ps != null 6792 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6793 /* 6794 * Check to make sure the signatures match first. If they don't, 6795 * wipe the installed application and its data. 6796 */ 6797 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6798 != PackageManager.SIGNATURE_MATCH) { 6799 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6800 + " signatures don't match existing userdata copy; removing"); 6801 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6802 ps = null; 6803 } else { 6804 /* 6805 * If the newly-added system app is an older version than the 6806 * already installed version, hide it. It will be scanned later 6807 * and re-added like an update. 6808 */ 6809 if (pkg.mVersionCode <= ps.versionCode) { 6810 shouldHideSystemApp = true; 6811 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6812 + " but new version " + pkg.mVersionCode + " better than installed " 6813 + ps.versionCode + "; hiding system"); 6814 } else { 6815 /* 6816 * The newly found system app is a newer version that the 6817 * one previously installed. Simply remove the 6818 * already-installed application and replace it with our own 6819 * while keeping the application data. 6820 */ 6821 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6822 + " reverting from " + ps.codePathString + ": new version " 6823 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6824 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6825 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6826 synchronized (mInstallLock) { 6827 args.cleanUpResourcesLI(); 6828 } 6829 } 6830 } 6831 } 6832 6833 // The apk is forward locked (not public) if its code and resources 6834 // are kept in different files. (except for app in either system or 6835 // vendor path). 6836 // TODO grab this value from PackageSettings 6837 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6838 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6839 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6840 } 6841 } 6842 6843 // TODO: extend to support forward-locked splits 6844 String resourcePath = null; 6845 String baseResourcePath = null; 6846 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6847 if (ps != null && ps.resourcePathString != null) { 6848 resourcePath = ps.resourcePathString; 6849 baseResourcePath = ps.resourcePathString; 6850 } else { 6851 // Should not happen at all. Just log an error. 6852 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6853 } 6854 } else { 6855 resourcePath = pkg.codePath; 6856 baseResourcePath = pkg.baseCodePath; 6857 } 6858 6859 // Set application objects path explicitly. 6860 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6861 pkg.setApplicationInfoCodePath(pkg.codePath); 6862 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6863 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6864 pkg.setApplicationInfoResourcePath(resourcePath); 6865 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6866 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6867 6868 // Note that we invoke the following method only if we are about to unpack an application 6869 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6870 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6871 6872 /* 6873 * If the system app should be overridden by a previously installed 6874 * data, hide the system app now and let the /data/app scan pick it up 6875 * again. 6876 */ 6877 if (shouldHideSystemApp) { 6878 synchronized (mPackages) { 6879 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6880 } 6881 } 6882 6883 return scannedPkg; 6884 } 6885 6886 private static String fixProcessName(String defProcessName, 6887 String processName, int uid) { 6888 if (processName == null) { 6889 return defProcessName; 6890 } 6891 return processName; 6892 } 6893 6894 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6895 throws PackageManagerException { 6896 if (pkgSetting.signatures.mSignatures != null) { 6897 // Already existing package. Make sure signatures match 6898 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6899 == PackageManager.SIGNATURE_MATCH; 6900 if (!match) { 6901 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6902 == PackageManager.SIGNATURE_MATCH; 6903 } 6904 if (!match) { 6905 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6906 == PackageManager.SIGNATURE_MATCH; 6907 } 6908 if (!match) { 6909 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6910 + pkg.packageName + " signatures do not match the " 6911 + "previously installed version; ignoring!"); 6912 } 6913 } 6914 6915 // Check for shared user signatures 6916 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6917 // Already existing package. Make sure signatures match 6918 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6919 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6920 if (!match) { 6921 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6922 == PackageManager.SIGNATURE_MATCH; 6923 } 6924 if (!match) { 6925 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6926 == PackageManager.SIGNATURE_MATCH; 6927 } 6928 if (!match) { 6929 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6930 "Package " + pkg.packageName 6931 + " has no signatures that match those in shared user " 6932 + pkgSetting.sharedUser.name + "; ignoring!"); 6933 } 6934 } 6935 } 6936 6937 /** 6938 * Enforces that only the system UID or root's UID can call a method exposed 6939 * via Binder. 6940 * 6941 * @param message used as message if SecurityException is thrown 6942 * @throws SecurityException if the caller is not system or root 6943 */ 6944 private static final void enforceSystemOrRoot(String message) { 6945 final int uid = Binder.getCallingUid(); 6946 if (uid != Process.SYSTEM_UID && uid != 0) { 6947 throw new SecurityException(message); 6948 } 6949 } 6950 6951 @Override 6952 public void performFstrimIfNeeded() { 6953 enforceSystemOrRoot("Only the system can request fstrim"); 6954 6955 // Before everything else, see whether we need to fstrim. 6956 try { 6957 IMountService ms = PackageHelper.getMountService(); 6958 if (ms != null) { 6959 final boolean isUpgrade = isUpgrade(); 6960 boolean doTrim = isUpgrade; 6961 if (doTrim) { 6962 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6963 } else { 6964 final long interval = android.provider.Settings.Global.getLong( 6965 mContext.getContentResolver(), 6966 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6967 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6968 if (interval > 0) { 6969 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6970 if (timeSinceLast > interval) { 6971 doTrim = true; 6972 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6973 + "; running immediately"); 6974 } 6975 } 6976 } 6977 if (doTrim) { 6978 if (!isFirstBoot()) { 6979 try { 6980 ActivityManagerNative.getDefault().showBootMessage( 6981 mContext.getResources().getString( 6982 R.string.android_upgrading_fstrim), true); 6983 } catch (RemoteException e) { 6984 } 6985 } 6986 ms.runMaintenance(); 6987 } 6988 } else { 6989 Slog.e(TAG, "Mount service unavailable!"); 6990 } 6991 } catch (RemoteException e) { 6992 // Can't happen; MountService is local 6993 } 6994 } 6995 6996 @Override 6997 public void updatePackagesIfNeeded() { 6998 enforceSystemOrRoot("Only the system can request package update"); 6999 7000 // We need to re-extract after an OTA. 7001 boolean causeUpgrade = isUpgrade(); 7002 7003 // First boot or factory reset. 7004 // Note: we also handle devices that are upgrading to N right now as if it is their 7005 // first boot, as they do not have profile data. 7006 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7007 7008 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7009 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7010 7011 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7012 return; 7013 } 7014 7015 List<PackageParser.Package> pkgs; 7016 synchronized (mPackages) { 7017 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7018 } 7019 7020 int curr = 0; 7021 int total = pkgs.size(); 7022 for (PackageParser.Package pkg : pkgs) { 7023 curr++; 7024 7025 if (DEBUG_DEXOPT) { 7026 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7027 } 7028 7029 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 7030 // If the cache was pruned, any compiled odex files will likely be out of date 7031 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 7032 // Instead, force the extraction in this case. 7033 performDexOpt(pkg.packageName, 7034 null /* instructionSet */, 7035 false /* checkProfiles */, 7036 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7037 false /* force */); 7038 } 7039 } 7040 } 7041 7042 @Override 7043 public void notifyPackageUse(String packageName) { 7044 synchronized (mPackages) { 7045 PackageParser.Package p = mPackages.get(packageName); 7046 if (p == null) { 7047 return; 7048 } 7049 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7050 } 7051 } 7052 7053 // TODO: this is not used nor needed. Delete it. 7054 @Override 7055 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7056 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7057 getFullCompilerFilter(), false /* force */); 7058 } 7059 7060 @Override 7061 public boolean performDexOpt(String packageName, String instructionSet, 7062 boolean checkProfiles, int compileReason, boolean force) { 7063 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7064 getCompilerFilterForReason(compileReason), force); 7065 } 7066 7067 @Override 7068 public boolean performDexOptMode(String packageName, String instructionSet, 7069 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7070 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7071 targetCompilerFilter, force); 7072 } 7073 7074 private boolean performDexOptTraced(String packageName, String instructionSet, 7075 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7076 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7077 try { 7078 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7079 targetCompilerFilter, force); 7080 } finally { 7081 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7082 } 7083 } 7084 7085 private boolean performDexOptInternal(String packageName, String instructionSet, 7086 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7087 PackageParser.Package p; 7088 final String targetInstructionSet; 7089 synchronized (mPackages) { 7090 p = mPackages.get(packageName); 7091 if (p == null) { 7092 return false; 7093 } 7094 mPackageUsage.write(false); 7095 7096 targetInstructionSet = instructionSet != null ? instructionSet : 7097 getPrimaryInstructionSet(p.applicationInfo); 7098 } 7099 long callingId = Binder.clearCallingIdentity(); 7100 try { 7101 synchronized (mInstallLock) { 7102 final String[] instructionSets = new String[] { targetInstructionSet }; 7103 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7104 checkProfiles, targetCompilerFilter, force); 7105 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7106 } 7107 } finally { 7108 Binder.restoreCallingIdentity(callingId); 7109 } 7110 } 7111 7112 public ArraySet<String> getOptimizablePackages() { 7113 ArraySet<String> pkgs = new ArraySet<String>(); 7114 synchronized (mPackages) { 7115 for (PackageParser.Package p : mPackages.values()) { 7116 if (PackageDexOptimizer.canOptimizePackage(p)) { 7117 pkgs.add(p.packageName); 7118 } 7119 } 7120 } 7121 return pkgs; 7122 } 7123 7124 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7125 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7126 boolean force) { 7127 // Select the dex optimizer based on the force parameter. 7128 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7129 // allocate an object here. 7130 PackageDexOptimizer pdo = force 7131 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7132 : mPackageDexOptimizer; 7133 7134 // Optimize all dependencies first. Note: we ignore the return value and march on 7135 // on errors. 7136 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7137 if (!deps.isEmpty()) { 7138 for (PackageParser.Package depPackage : deps) { 7139 // TODO: Analyze and investigate if we (should) profile libraries. 7140 // Currently this will do a full compilation of the library by default. 7141 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7142 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7143 } 7144 } 7145 7146 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7147 } 7148 7149 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7150 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7151 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7152 Set<String> collectedNames = new HashSet<>(); 7153 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7154 7155 retValue.remove(p); 7156 7157 return retValue; 7158 } else { 7159 return Collections.emptyList(); 7160 } 7161 } 7162 7163 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7164 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7165 if (!collectedNames.contains(p.packageName)) { 7166 collectedNames.add(p.packageName); 7167 collected.add(p); 7168 7169 if (p.usesLibraries != null) { 7170 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7171 } 7172 if (p.usesOptionalLibraries != null) { 7173 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7174 collectedNames); 7175 } 7176 } 7177 } 7178 7179 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7180 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7181 for (String libName : libs) { 7182 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7183 if (libPkg != null) { 7184 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7185 } 7186 } 7187 } 7188 7189 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7190 synchronized (mPackages) { 7191 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7192 if (lib != null && lib.apk != null) { 7193 return mPackages.get(lib.apk); 7194 } 7195 } 7196 return null; 7197 } 7198 7199 public void shutdown() { 7200 mPackageUsage.write(true); 7201 } 7202 7203 @Override 7204 public void forceDexOpt(String packageName) { 7205 enforceSystemOrRoot("forceDexOpt"); 7206 7207 PackageParser.Package pkg; 7208 synchronized (mPackages) { 7209 pkg = mPackages.get(packageName); 7210 if (pkg == null) { 7211 throw new IllegalArgumentException("Unknown package: " + packageName); 7212 } 7213 } 7214 7215 synchronized (mInstallLock) { 7216 final String[] instructionSets = new String[] { 7217 getPrimaryInstructionSet(pkg.applicationInfo) }; 7218 7219 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7220 7221 // Whoever is calling forceDexOpt wants a fully compiled package. 7222 // Don't use profiles since that may cause compilation to be skipped. 7223 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7224 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7225 true /* force */); 7226 7227 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7228 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7229 throw new IllegalStateException("Failed to dexopt: " + res); 7230 } 7231 } 7232 } 7233 7234 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7235 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7236 Slog.w(TAG, "Unable to update from " + oldPkg.name 7237 + " to " + newPkg.packageName 7238 + ": old package not in system partition"); 7239 return false; 7240 } else if (mPackages.get(oldPkg.name) != null) { 7241 Slog.w(TAG, "Unable to update from " + oldPkg.name 7242 + " to " + newPkg.packageName 7243 + ": old package still exists"); 7244 return false; 7245 } 7246 return true; 7247 } 7248 7249 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7250 // TODO: triage flags as part of 26466827 7251 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7252 7253 boolean res = true; 7254 final int[] users = sUserManager.getUserIds(); 7255 for (int user : users) { 7256 try { 7257 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7258 } catch (InstallerException e) { 7259 Slog.w(TAG, "Failed to delete data directory", e); 7260 res = false; 7261 } 7262 } 7263 return res; 7264 } 7265 7266 void removeCodePathLI(File codePath) { 7267 if (codePath.isDirectory()) { 7268 try { 7269 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7270 } catch (InstallerException e) { 7271 Slog.w(TAG, "Failed to remove code path", e); 7272 } 7273 } else { 7274 codePath.delete(); 7275 } 7276 } 7277 7278 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7279 try { 7280 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7281 } catch (InstallerException e) { 7282 Slog.w(TAG, "Failed to destroy app data", e); 7283 } 7284 } 7285 7286 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7287 int appId, String seinfo) { 7288 try { 7289 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7290 } catch (InstallerException e) { 7291 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7292 } 7293 } 7294 7295 private void deleteProfilesLI(String packageName, boolean destroy) { 7296 final PackageParser.Package pkg; 7297 synchronized (mPackages) { 7298 pkg = mPackages.get(packageName); 7299 } 7300 if (pkg == null) { 7301 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7302 return; 7303 } 7304 deleteProfilesLI(pkg, destroy); 7305 } 7306 7307 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7308 try { 7309 if (destroy) { 7310 mInstaller.destroyAppProfiles(pkg.packageName); 7311 } else { 7312 mInstaller.clearAppProfiles(pkg.packageName); 7313 } 7314 } catch (InstallerException ex) { 7315 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7316 } 7317 } 7318 7319 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7320 final PackageParser.Package pkg; 7321 synchronized (mPackages) { 7322 pkg = mPackages.get(packageName); 7323 } 7324 if (pkg == null) { 7325 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7326 return; 7327 } 7328 deleteCodeCacheDirsLI(pkg); 7329 } 7330 7331 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7332 // TODO: triage flags as part of 26466827 7333 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7334 7335 int[] users = sUserManager.getUserIds(); 7336 int res = 0; 7337 for (int user : users) { 7338 // Remove the parent code cache 7339 try { 7340 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7341 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7342 } catch (InstallerException e) { 7343 Slog.w(TAG, "Failed to delete code cache directory", e); 7344 } 7345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7346 for (int i = 0; i < childCount; i++) { 7347 PackageParser.Package childPkg = pkg.childPackages.get(i); 7348 // Remove the child code cache 7349 try { 7350 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7351 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7352 } catch (InstallerException e) { 7353 Slog.w(TAG, "Failed to delete code cache directory", e); 7354 } 7355 } 7356 } 7357 } 7358 7359 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7360 long lastUpdateTime) { 7361 // Set parent install/update time 7362 PackageSetting ps = (PackageSetting) pkg.mExtras; 7363 if (ps != null) { 7364 ps.firstInstallTime = firstInstallTime; 7365 ps.lastUpdateTime = lastUpdateTime; 7366 } 7367 // Set children install/update time 7368 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7369 for (int i = 0; i < childCount; i++) { 7370 PackageParser.Package childPkg = pkg.childPackages.get(i); 7371 ps = (PackageSetting) childPkg.mExtras; 7372 if (ps != null) { 7373 ps.firstInstallTime = firstInstallTime; 7374 ps.lastUpdateTime = lastUpdateTime; 7375 } 7376 } 7377 } 7378 7379 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7380 PackageParser.Package changingLib) { 7381 if (file.path != null) { 7382 usesLibraryFiles.add(file.path); 7383 return; 7384 } 7385 PackageParser.Package p = mPackages.get(file.apk); 7386 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7387 // If we are doing this while in the middle of updating a library apk, 7388 // then we need to make sure to use that new apk for determining the 7389 // dependencies here. (We haven't yet finished committing the new apk 7390 // to the package manager state.) 7391 if (p == null || p.packageName.equals(changingLib.packageName)) { 7392 p = changingLib; 7393 } 7394 } 7395 if (p != null) { 7396 usesLibraryFiles.addAll(p.getAllCodePaths()); 7397 } 7398 } 7399 7400 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7401 PackageParser.Package changingLib) throws PackageManagerException { 7402 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7403 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7404 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7405 for (int i=0; i<N; i++) { 7406 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7407 if (file == null) { 7408 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7409 "Package " + pkg.packageName + " requires unavailable shared library " 7410 + pkg.usesLibraries.get(i) + "; failing!"); 7411 } 7412 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7413 } 7414 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7415 for (int i=0; i<N; i++) { 7416 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7417 if (file == null) { 7418 Slog.w(TAG, "Package " + pkg.packageName 7419 + " desires unavailable shared library " 7420 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7421 } else { 7422 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7423 } 7424 } 7425 N = usesLibraryFiles.size(); 7426 if (N > 0) { 7427 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7428 } else { 7429 pkg.usesLibraryFiles = null; 7430 } 7431 } 7432 } 7433 7434 private static boolean hasString(List<String> list, List<String> which) { 7435 if (list == null) { 7436 return false; 7437 } 7438 for (int i=list.size()-1; i>=0; i--) { 7439 for (int j=which.size()-1; j>=0; j--) { 7440 if (which.get(j).equals(list.get(i))) { 7441 return true; 7442 } 7443 } 7444 } 7445 return false; 7446 } 7447 7448 private void updateAllSharedLibrariesLPw() { 7449 for (PackageParser.Package pkg : mPackages.values()) { 7450 try { 7451 updateSharedLibrariesLPw(pkg, null); 7452 } catch (PackageManagerException e) { 7453 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7454 } 7455 } 7456 } 7457 7458 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7459 PackageParser.Package changingPkg) { 7460 ArrayList<PackageParser.Package> res = null; 7461 for (PackageParser.Package pkg : mPackages.values()) { 7462 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7463 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7464 if (res == null) { 7465 res = new ArrayList<PackageParser.Package>(); 7466 } 7467 res.add(pkg); 7468 try { 7469 updateSharedLibrariesLPw(pkg, changingPkg); 7470 } catch (PackageManagerException e) { 7471 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7472 } 7473 } 7474 } 7475 return res; 7476 } 7477 7478 /** 7479 * Derive the value of the {@code cpuAbiOverride} based on the provided 7480 * value and an optional stored value from the package settings. 7481 */ 7482 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7483 String cpuAbiOverride = null; 7484 7485 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7486 cpuAbiOverride = null; 7487 } else if (abiOverride != null) { 7488 cpuAbiOverride = abiOverride; 7489 } else if (settings != null) { 7490 cpuAbiOverride = settings.cpuAbiOverrideString; 7491 } 7492 7493 return cpuAbiOverride; 7494 } 7495 7496 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7497 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7499 // If the package has children and this is the first dive in the function 7500 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7501 // whether all packages (parent and children) would be successfully scanned 7502 // before the actual scan since scanning mutates internal state and we want 7503 // to atomically install the package and its children. 7504 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7505 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7506 scanFlags |= SCAN_CHECK_ONLY; 7507 } 7508 } else { 7509 scanFlags &= ~SCAN_CHECK_ONLY; 7510 } 7511 7512 final PackageParser.Package scannedPkg; 7513 try { 7514 // Scan the parent 7515 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7516 // Scan the children 7517 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7518 for (int i = 0; i < childCount; i++) { 7519 PackageParser.Package childPkg = pkg.childPackages.get(i); 7520 scanPackageLI(childPkg, parseFlags, 7521 scanFlags, currentTime, user); 7522 } 7523 } finally { 7524 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7525 } 7526 7527 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7528 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7529 } 7530 7531 return scannedPkg; 7532 } 7533 7534 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7535 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7536 boolean success = false; 7537 try { 7538 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7539 currentTime, user); 7540 success = true; 7541 return res; 7542 } finally { 7543 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7544 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7545 } 7546 } 7547 } 7548 7549 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7550 int scanFlags, long currentTime, UserHandle user) 7551 throws PackageManagerException { 7552 final File scanFile = new File(pkg.codePath); 7553 if (pkg.applicationInfo.getCodePath() == null || 7554 pkg.applicationInfo.getResourcePath() == null) { 7555 // Bail out. The resource and code paths haven't been set. 7556 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7557 "Code and resource paths haven't been set correctly"); 7558 } 7559 7560 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7561 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7562 } else { 7563 // Only allow system apps to be flagged as core apps. 7564 pkg.coreApp = false; 7565 } 7566 7567 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7568 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7569 } 7570 7571 if (mCustomResolverComponentName != null && 7572 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7573 setUpCustomResolverActivity(pkg); 7574 } 7575 7576 if (pkg.packageName.equals("android")) { 7577 synchronized (mPackages) { 7578 if (mAndroidApplication != null) { 7579 Slog.w(TAG, "*************************************************"); 7580 Slog.w(TAG, "Core android package being redefined. Skipping."); 7581 Slog.w(TAG, " file=" + scanFile); 7582 Slog.w(TAG, "*************************************************"); 7583 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7584 "Core android package being redefined. Skipping."); 7585 } 7586 7587 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7588 // Set up information for our fall-back user intent resolution activity. 7589 mPlatformPackage = pkg; 7590 pkg.mVersionCode = mSdkVersion; 7591 mAndroidApplication = pkg.applicationInfo; 7592 7593 if (!mResolverReplaced) { 7594 mResolveActivity.applicationInfo = mAndroidApplication; 7595 mResolveActivity.name = ResolverActivity.class.getName(); 7596 mResolveActivity.packageName = mAndroidApplication.packageName; 7597 mResolveActivity.processName = "system:ui"; 7598 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7599 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7600 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7601 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7602 mResolveActivity.exported = true; 7603 mResolveActivity.enabled = true; 7604 mResolveInfo.activityInfo = mResolveActivity; 7605 mResolveInfo.priority = 0; 7606 mResolveInfo.preferredOrder = 0; 7607 mResolveInfo.match = 0; 7608 mResolveComponentName = new ComponentName( 7609 mAndroidApplication.packageName, mResolveActivity.name); 7610 } 7611 } 7612 } 7613 } 7614 7615 if (DEBUG_PACKAGE_SCANNING) { 7616 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7617 Log.d(TAG, "Scanning package " + pkg.packageName); 7618 } 7619 7620 synchronized (mPackages) { 7621 if (mPackages.containsKey(pkg.packageName) 7622 || mSharedLibraries.containsKey(pkg.packageName)) { 7623 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7624 "Application package " + pkg.packageName 7625 + " already installed. Skipping duplicate."); 7626 } 7627 7628 // If we're only installing presumed-existing packages, require that the 7629 // scanned APK is both already known and at the path previously established 7630 // for it. Previously unknown packages we pick up normally, but if we have an 7631 // a priori expectation about this package's install presence, enforce it. 7632 // With a singular exception for new system packages. When an OTA contains 7633 // a new system package, we allow the codepath to change from a system location 7634 // to the user-installed location. If we don't allow this change, any newer, 7635 // user-installed version of the application will be ignored. 7636 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7637 if (mExpectingBetter.containsKey(pkg.packageName)) { 7638 logCriticalInfo(Log.WARN, 7639 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7640 } else { 7641 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7642 if (known != null) { 7643 if (DEBUG_PACKAGE_SCANNING) { 7644 Log.d(TAG, "Examining " + pkg.codePath 7645 + " and requiring known paths " + known.codePathString 7646 + " & " + known.resourcePathString); 7647 } 7648 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7649 || !pkg.applicationInfo.getResourcePath().equals( 7650 known.resourcePathString)) { 7651 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7652 "Application package " + pkg.packageName 7653 + " found at " + pkg.applicationInfo.getCodePath() 7654 + " but expected at " + known.codePathString 7655 + "; ignoring."); 7656 } 7657 } 7658 } 7659 } 7660 } 7661 7662 // Initialize package source and resource directories 7663 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7664 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7665 7666 SharedUserSetting suid = null; 7667 PackageSetting pkgSetting = null; 7668 7669 if (!isSystemApp(pkg)) { 7670 // Only system apps can use these features. 7671 pkg.mOriginalPackages = null; 7672 pkg.mRealPackage = null; 7673 pkg.mAdoptPermissions = null; 7674 } 7675 7676 // Getting the package setting may have a side-effect, so if we 7677 // are only checking if scan would succeed, stash a copy of the 7678 // old setting to restore at the end. 7679 PackageSetting nonMutatedPs = null; 7680 7681 // writer 7682 synchronized (mPackages) { 7683 if (pkg.mSharedUserId != null) { 7684 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7685 if (suid == null) { 7686 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7687 "Creating application package " + pkg.packageName 7688 + " for shared user failed"); 7689 } 7690 if (DEBUG_PACKAGE_SCANNING) { 7691 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7692 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7693 + "): packages=" + suid.packages); 7694 } 7695 } 7696 7697 // Check if we are renaming from an original package name. 7698 PackageSetting origPackage = null; 7699 String realName = null; 7700 if (pkg.mOriginalPackages != null) { 7701 // This package may need to be renamed to a previously 7702 // installed name. Let's check on that... 7703 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7704 if (pkg.mOriginalPackages.contains(renamed)) { 7705 // This package had originally been installed as the 7706 // original name, and we have already taken care of 7707 // transitioning to the new one. Just update the new 7708 // one to continue using the old name. 7709 realName = pkg.mRealPackage; 7710 if (!pkg.packageName.equals(renamed)) { 7711 // Callers into this function may have already taken 7712 // care of renaming the package; only do it here if 7713 // it is not already done. 7714 pkg.setPackageName(renamed); 7715 } 7716 7717 } else { 7718 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7719 if ((origPackage = mSettings.peekPackageLPr( 7720 pkg.mOriginalPackages.get(i))) != null) { 7721 // We do have the package already installed under its 7722 // original name... should we use it? 7723 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7724 // New package is not compatible with original. 7725 origPackage = null; 7726 continue; 7727 } else if (origPackage.sharedUser != null) { 7728 // Make sure uid is compatible between packages. 7729 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7730 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7731 + " to " + pkg.packageName + ": old uid " 7732 + origPackage.sharedUser.name 7733 + " differs from " + pkg.mSharedUserId); 7734 origPackage = null; 7735 continue; 7736 } 7737 } else { 7738 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7739 + pkg.packageName + " to old name " + origPackage.name); 7740 } 7741 break; 7742 } 7743 } 7744 } 7745 } 7746 7747 if (mTransferedPackages.contains(pkg.packageName)) { 7748 Slog.w(TAG, "Package " + pkg.packageName 7749 + " was transferred to another, but its .apk remains"); 7750 } 7751 7752 // See comments in nonMutatedPs declaration 7753 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7754 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7755 if (foundPs != null) { 7756 nonMutatedPs = new PackageSetting(foundPs); 7757 } 7758 } 7759 7760 // Just create the setting, don't add it yet. For already existing packages 7761 // the PkgSetting exists already and doesn't have to be created. 7762 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7763 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7764 pkg.applicationInfo.primaryCpuAbi, 7765 pkg.applicationInfo.secondaryCpuAbi, 7766 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7767 user, false); 7768 if (pkgSetting == null) { 7769 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7770 "Creating application package " + pkg.packageName + " failed"); 7771 } 7772 7773 if (pkgSetting.origPackage != null) { 7774 // If we are first transitioning from an original package, 7775 // fix up the new package's name now. We need to do this after 7776 // looking up the package under its new name, so getPackageLP 7777 // can take care of fiddling things correctly. 7778 pkg.setPackageName(origPackage.name); 7779 7780 // File a report about this. 7781 String msg = "New package " + pkgSetting.realName 7782 + " renamed to replace old package " + pkgSetting.name; 7783 reportSettingsProblem(Log.WARN, msg); 7784 7785 // Make a note of it. 7786 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7787 mTransferedPackages.add(origPackage.name); 7788 } 7789 7790 // No longer need to retain this. 7791 pkgSetting.origPackage = null; 7792 } 7793 7794 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7795 // Make a note of it. 7796 mTransferedPackages.add(pkg.packageName); 7797 } 7798 7799 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7800 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7801 } 7802 7803 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7804 // Check all shared libraries and map to their actual file path. 7805 // We only do this here for apps not on a system dir, because those 7806 // are the only ones that can fail an install due to this. We 7807 // will take care of the system apps by updating all of their 7808 // library paths after the scan is done. 7809 updateSharedLibrariesLPw(pkg, null); 7810 } 7811 7812 if (mFoundPolicyFile) { 7813 SELinuxMMAC.assignSeinfoValue(pkg); 7814 } 7815 7816 pkg.applicationInfo.uid = pkgSetting.appId; 7817 pkg.mExtras = pkgSetting; 7818 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7819 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7820 // We just determined the app is signed correctly, so bring 7821 // over the latest parsed certs. 7822 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7823 } else { 7824 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7825 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7826 "Package " + pkg.packageName + " upgrade keys do not match the " 7827 + "previously installed version"); 7828 } else { 7829 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7830 String msg = "System package " + pkg.packageName 7831 + " signature changed; retaining data."; 7832 reportSettingsProblem(Log.WARN, msg); 7833 } 7834 } 7835 } else { 7836 try { 7837 verifySignaturesLP(pkgSetting, pkg); 7838 // We just determined the app is signed correctly, so bring 7839 // over the latest parsed certs. 7840 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7841 } catch (PackageManagerException e) { 7842 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7843 throw e; 7844 } 7845 // The signature has changed, but this package is in the system 7846 // image... let's recover! 7847 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7848 // However... if this package is part of a shared user, but it 7849 // doesn't match the signature of the shared user, let's fail. 7850 // What this means is that you can't change the signatures 7851 // associated with an overall shared user, which doesn't seem all 7852 // that unreasonable. 7853 if (pkgSetting.sharedUser != null) { 7854 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7855 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7856 throw new PackageManagerException( 7857 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7858 "Signature mismatch for shared user: " 7859 + pkgSetting.sharedUser); 7860 } 7861 } 7862 // File a report about this. 7863 String msg = "System package " + pkg.packageName 7864 + " signature changed; retaining data."; 7865 reportSettingsProblem(Log.WARN, msg); 7866 } 7867 } 7868 // Verify that this new package doesn't have any content providers 7869 // that conflict with existing packages. Only do this if the 7870 // package isn't already installed, since we don't want to break 7871 // things that are installed. 7872 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7873 final int N = pkg.providers.size(); 7874 int i; 7875 for (i=0; i<N; i++) { 7876 PackageParser.Provider p = pkg.providers.get(i); 7877 if (p.info.authority != null) { 7878 String names[] = p.info.authority.split(";"); 7879 for (int j = 0; j < names.length; j++) { 7880 if (mProvidersByAuthority.containsKey(names[j])) { 7881 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7882 final String otherPackageName = 7883 ((other != null && other.getComponentName() != null) ? 7884 other.getComponentName().getPackageName() : "?"); 7885 throw new PackageManagerException( 7886 INSTALL_FAILED_CONFLICTING_PROVIDER, 7887 "Can't install because provider name " + names[j] 7888 + " (in package " + pkg.applicationInfo.packageName 7889 + ") is already used by " + otherPackageName); 7890 } 7891 } 7892 } 7893 } 7894 } 7895 7896 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7897 // This package wants to adopt ownership of permissions from 7898 // another package. 7899 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7900 final String origName = pkg.mAdoptPermissions.get(i); 7901 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7902 if (orig != null) { 7903 if (verifyPackageUpdateLPr(orig, pkg)) { 7904 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7905 + pkg.packageName); 7906 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7907 } 7908 } 7909 } 7910 } 7911 } 7912 7913 final String pkgName = pkg.packageName; 7914 7915 final long scanFileTime = scanFile.lastModified(); 7916 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7917 pkg.applicationInfo.processName = fixProcessName( 7918 pkg.applicationInfo.packageName, 7919 pkg.applicationInfo.processName, 7920 pkg.applicationInfo.uid); 7921 7922 if (pkg != mPlatformPackage) { 7923 // Get all of our default paths setup 7924 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7925 } 7926 7927 final String path = scanFile.getPath(); 7928 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7929 7930 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7931 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7932 7933 // Some system apps still use directory structure for native libraries 7934 // in which case we might end up not detecting abi solely based on apk 7935 // structure. Try to detect abi based on directory structure. 7936 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7937 pkg.applicationInfo.primaryCpuAbi == null) { 7938 setBundledAppAbisAndRoots(pkg, pkgSetting); 7939 setNativeLibraryPaths(pkg); 7940 } 7941 7942 } else { 7943 if ((scanFlags & SCAN_MOVE) != 0) { 7944 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7945 // but we already have this packages package info in the PackageSetting. We just 7946 // use that and derive the native library path based on the new codepath. 7947 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7948 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7949 } 7950 7951 // Set native library paths again. For moves, the path will be updated based on the 7952 // ABIs we've determined above. For non-moves, the path will be updated based on the 7953 // ABIs we determined during compilation, but the path will depend on the final 7954 // package path (after the rename away from the stage path). 7955 setNativeLibraryPaths(pkg); 7956 } 7957 7958 // This is a special case for the "system" package, where the ABI is 7959 // dictated by the zygote configuration (and init.rc). We should keep track 7960 // of this ABI so that we can deal with "normal" applications that run under 7961 // the same UID correctly. 7962 if (mPlatformPackage == pkg) { 7963 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7964 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7965 } 7966 7967 // If there's a mismatch between the abi-override in the package setting 7968 // and the abiOverride specified for the install. Warn about this because we 7969 // would've already compiled the app without taking the package setting into 7970 // account. 7971 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7972 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7973 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7974 " for package " + pkg.packageName); 7975 } 7976 } 7977 7978 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7979 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7980 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7981 7982 // Copy the derived override back to the parsed package, so that we can 7983 // update the package settings accordingly. 7984 pkg.cpuAbiOverride = cpuAbiOverride; 7985 7986 if (DEBUG_ABI_SELECTION) { 7987 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7988 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7989 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7990 } 7991 7992 // Push the derived path down into PackageSettings so we know what to 7993 // clean up at uninstall time. 7994 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7995 7996 if (DEBUG_ABI_SELECTION) { 7997 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7998 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7999 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8000 } 8001 8002 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8003 // We don't do this here during boot because we can do it all 8004 // at once after scanning all existing packages. 8005 // 8006 // We also do this *before* we perform dexopt on this package, so that 8007 // we can avoid redundant dexopts, and also to make sure we've got the 8008 // code and package path correct. 8009 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8010 pkg, true /* boot complete */); 8011 } 8012 8013 if (mFactoryTest && pkg.requestedPermissions.contains( 8014 android.Manifest.permission.FACTORY_TEST)) { 8015 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8016 } 8017 8018 ArrayList<PackageParser.Package> clientLibPkgs = null; 8019 8020 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8021 if (nonMutatedPs != null) { 8022 synchronized (mPackages) { 8023 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8024 } 8025 } 8026 return pkg; 8027 } 8028 8029 // Only privileged apps and updated privileged apps can add child packages. 8030 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8031 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8032 throw new PackageManagerException("Only privileged apps and updated " 8033 + "privileged apps can add child packages. Ignoring package " 8034 + pkg.packageName); 8035 } 8036 final int childCount = pkg.childPackages.size(); 8037 for (int i = 0; i < childCount; i++) { 8038 PackageParser.Package childPkg = pkg.childPackages.get(i); 8039 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8040 childPkg.packageName)) { 8041 throw new PackageManagerException("Cannot override a child package of " 8042 + "another disabled system app. Ignoring package " + pkg.packageName); 8043 } 8044 } 8045 } 8046 8047 // writer 8048 synchronized (mPackages) { 8049 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8050 // Only system apps can add new shared libraries. 8051 if (pkg.libraryNames != null) { 8052 for (int i=0; i<pkg.libraryNames.size(); i++) { 8053 String name = pkg.libraryNames.get(i); 8054 boolean allowed = false; 8055 if (pkg.isUpdatedSystemApp()) { 8056 // New library entries can only be added through the 8057 // system image. This is important to get rid of a lot 8058 // of nasty edge cases: for example if we allowed a non- 8059 // system update of the app to add a library, then uninstalling 8060 // the update would make the library go away, and assumptions 8061 // we made such as through app install filtering would now 8062 // have allowed apps on the device which aren't compatible 8063 // with it. Better to just have the restriction here, be 8064 // conservative, and create many fewer cases that can negatively 8065 // impact the user experience. 8066 final PackageSetting sysPs = mSettings 8067 .getDisabledSystemPkgLPr(pkg.packageName); 8068 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8069 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8070 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8071 allowed = true; 8072 break; 8073 } 8074 } 8075 } 8076 } else { 8077 allowed = true; 8078 } 8079 if (allowed) { 8080 if (!mSharedLibraries.containsKey(name)) { 8081 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8082 } else if (!name.equals(pkg.packageName)) { 8083 Slog.w(TAG, "Package " + pkg.packageName + " library " 8084 + name + " already exists; skipping"); 8085 } 8086 } else { 8087 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8088 + name + " that is not declared on system image; skipping"); 8089 } 8090 } 8091 if ((scanFlags & SCAN_BOOTING) == 0) { 8092 // If we are not booting, we need to update any applications 8093 // that are clients of our shared library. If we are booting, 8094 // this will all be done once the scan is complete. 8095 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8096 } 8097 } 8098 } 8099 } 8100 8101 // Request the ActivityManager to kill the process(only for existing packages) 8102 // so that we do not end up in a confused state while the user is still using the older 8103 // version of the application while the new one gets installed. 8104 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8105 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8106 if (killApp) { 8107 if (isReplacing) { 8108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8109 8110 killApplication(pkg.applicationInfo.packageName, 8111 pkg.applicationInfo.uid, "replace pkg"); 8112 8113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8114 } 8115 } 8116 8117 // Also need to kill any apps that are dependent on the library. 8118 if (clientLibPkgs != null) { 8119 for (int i=0; i<clientLibPkgs.size(); i++) { 8120 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8121 killApplication(clientPkg.applicationInfo.packageName, 8122 clientPkg.applicationInfo.uid, "update lib"); 8123 } 8124 } 8125 8126 // Make sure we're not adding any bogus keyset info 8127 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8128 ksms.assertScannedPackageValid(pkg); 8129 8130 // writer 8131 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8132 8133 boolean createIdmapFailed = false; 8134 synchronized (mPackages) { 8135 // We don't expect installation to fail beyond this point 8136 8137 // Add the new setting to mSettings 8138 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8139 // Add the new setting to mPackages 8140 mPackages.put(pkg.applicationInfo.packageName, pkg); 8141 // Make sure we don't accidentally delete its data. 8142 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8143 while (iter.hasNext()) { 8144 PackageCleanItem item = iter.next(); 8145 if (pkgName.equals(item.packageName)) { 8146 iter.remove(); 8147 } 8148 } 8149 8150 // Take care of first install / last update times. 8151 if (currentTime != 0) { 8152 if (pkgSetting.firstInstallTime == 0) { 8153 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8154 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8155 pkgSetting.lastUpdateTime = currentTime; 8156 } 8157 } else if (pkgSetting.firstInstallTime == 0) { 8158 // We need *something*. Take time time stamp of the file. 8159 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8160 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8161 if (scanFileTime != pkgSetting.timeStamp) { 8162 // A package on the system image has changed; consider this 8163 // to be an update. 8164 pkgSetting.lastUpdateTime = scanFileTime; 8165 } 8166 } 8167 8168 // Add the package's KeySets to the global KeySetManagerService 8169 ksms.addScannedPackageLPw(pkg); 8170 8171 int N = pkg.providers.size(); 8172 StringBuilder r = null; 8173 int i; 8174 for (i=0; i<N; i++) { 8175 PackageParser.Provider p = pkg.providers.get(i); 8176 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8177 p.info.processName, pkg.applicationInfo.uid); 8178 mProviders.addProvider(p); 8179 p.syncable = p.info.isSyncable; 8180 if (p.info.authority != null) { 8181 String names[] = p.info.authority.split(";"); 8182 p.info.authority = null; 8183 for (int j = 0; j < names.length; j++) { 8184 if (j == 1 && p.syncable) { 8185 // We only want the first authority for a provider to possibly be 8186 // syncable, so if we already added this provider using a different 8187 // authority clear the syncable flag. We copy the provider before 8188 // changing it because the mProviders object contains a reference 8189 // to a provider that we don't want to change. 8190 // Only do this for the second authority since the resulting provider 8191 // object can be the same for all future authorities for this provider. 8192 p = new PackageParser.Provider(p); 8193 p.syncable = false; 8194 } 8195 if (!mProvidersByAuthority.containsKey(names[j])) { 8196 mProvidersByAuthority.put(names[j], p); 8197 if (p.info.authority == null) { 8198 p.info.authority = names[j]; 8199 } else { 8200 p.info.authority = p.info.authority + ";" + names[j]; 8201 } 8202 if (DEBUG_PACKAGE_SCANNING) { 8203 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8204 Log.d(TAG, "Registered content provider: " + names[j] 8205 + ", className = " + p.info.name + ", isSyncable = " 8206 + p.info.isSyncable); 8207 } 8208 } else { 8209 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8210 Slog.w(TAG, "Skipping provider name " + names[j] + 8211 " (in package " + pkg.applicationInfo.packageName + 8212 "): name already used by " 8213 + ((other != null && other.getComponentName() != null) 8214 ? other.getComponentName().getPackageName() : "?")); 8215 } 8216 } 8217 } 8218 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8219 if (r == null) { 8220 r = new StringBuilder(256); 8221 } else { 8222 r.append(' '); 8223 } 8224 r.append(p.info.name); 8225 } 8226 } 8227 if (r != null) { 8228 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8229 } 8230 8231 N = pkg.services.size(); 8232 r = null; 8233 for (i=0; i<N; i++) { 8234 PackageParser.Service s = pkg.services.get(i); 8235 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8236 s.info.processName, pkg.applicationInfo.uid); 8237 mServices.addService(s); 8238 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8239 if (r == null) { 8240 r = new StringBuilder(256); 8241 } else { 8242 r.append(' '); 8243 } 8244 r.append(s.info.name); 8245 } 8246 } 8247 if (r != null) { 8248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8249 } 8250 8251 N = pkg.receivers.size(); 8252 r = null; 8253 for (i=0; i<N; i++) { 8254 PackageParser.Activity a = pkg.receivers.get(i); 8255 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8256 a.info.processName, pkg.applicationInfo.uid); 8257 mReceivers.addActivity(a, "receiver"); 8258 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8259 if (r == null) { 8260 r = new StringBuilder(256); 8261 } else { 8262 r.append(' '); 8263 } 8264 r.append(a.info.name); 8265 } 8266 } 8267 if (r != null) { 8268 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8269 } 8270 8271 N = pkg.activities.size(); 8272 r = null; 8273 for (i=0; i<N; i++) { 8274 PackageParser.Activity a = pkg.activities.get(i); 8275 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8276 a.info.processName, pkg.applicationInfo.uid); 8277 mActivities.addActivity(a, "activity"); 8278 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8279 if (r == null) { 8280 r = new StringBuilder(256); 8281 } else { 8282 r.append(' '); 8283 } 8284 r.append(a.info.name); 8285 } 8286 } 8287 if (r != null) { 8288 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8289 } 8290 8291 N = pkg.permissionGroups.size(); 8292 r = null; 8293 for (i=0; i<N; i++) { 8294 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8295 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8296 if (cur == null) { 8297 mPermissionGroups.put(pg.info.name, pg); 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(pg.info.name); 8305 } 8306 } else { 8307 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8308 + pg.info.packageName + " ignored: original from " 8309 + cur.info.packageName); 8310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8311 if (r == null) { 8312 r = new StringBuilder(256); 8313 } else { 8314 r.append(' '); 8315 } 8316 r.append("DUP:"); 8317 r.append(pg.info.name); 8318 } 8319 } 8320 } 8321 if (r != null) { 8322 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8323 } 8324 8325 N = pkg.permissions.size(); 8326 r = null; 8327 for (i=0; i<N; i++) { 8328 PackageParser.Permission p = pkg.permissions.get(i); 8329 8330 // Assume by default that we did not install this permission into the system. 8331 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8332 8333 // Now that permission groups have a special meaning, we ignore permission 8334 // groups for legacy apps to prevent unexpected behavior. In particular, 8335 // permissions for one app being granted to someone just becase they happen 8336 // to be in a group defined by another app (before this had no implications). 8337 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8338 p.group = mPermissionGroups.get(p.info.group); 8339 // Warn for a permission in an unknown group. 8340 if (p.info.group != null && p.group == null) { 8341 Slog.w(TAG, "Permission " + p.info.name + " from package " 8342 + p.info.packageName + " in an unknown group " + p.info.group); 8343 } 8344 } 8345 8346 ArrayMap<String, BasePermission> permissionMap = 8347 p.tree ? mSettings.mPermissionTrees 8348 : mSettings.mPermissions; 8349 BasePermission bp = permissionMap.get(p.info.name); 8350 8351 // Allow system apps to redefine non-system permissions 8352 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8353 final boolean currentOwnerIsSystem = (bp.perm != null 8354 && isSystemApp(bp.perm.owner)); 8355 if (isSystemApp(p.owner)) { 8356 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8357 // It's a built-in permission and no owner, take ownership now 8358 bp.packageSetting = pkgSetting; 8359 bp.perm = p; 8360 bp.uid = pkg.applicationInfo.uid; 8361 bp.sourcePackage = p.info.packageName; 8362 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8363 } else if (!currentOwnerIsSystem) { 8364 String msg = "New decl " + p.owner + " of permission " 8365 + p.info.name + " is system; overriding " + bp.sourcePackage; 8366 reportSettingsProblem(Log.WARN, msg); 8367 bp = null; 8368 } 8369 } 8370 } 8371 8372 if (bp == null) { 8373 bp = new BasePermission(p.info.name, p.info.packageName, 8374 BasePermission.TYPE_NORMAL); 8375 permissionMap.put(p.info.name, bp); 8376 } 8377 8378 if (bp.perm == null) { 8379 if (bp.sourcePackage == null 8380 || bp.sourcePackage.equals(p.info.packageName)) { 8381 BasePermission tree = findPermissionTreeLP(p.info.name); 8382 if (tree == null 8383 || tree.sourcePackage.equals(p.info.packageName)) { 8384 bp.packageSetting = pkgSetting; 8385 bp.perm = p; 8386 bp.uid = pkg.applicationInfo.uid; 8387 bp.sourcePackage = p.info.packageName; 8388 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8389 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8390 if (r == null) { 8391 r = new StringBuilder(256); 8392 } else { 8393 r.append(' '); 8394 } 8395 r.append(p.info.name); 8396 } 8397 } else { 8398 Slog.w(TAG, "Permission " + p.info.name + " from package " 8399 + p.info.packageName + " ignored: base tree " 8400 + tree.name + " is from package " 8401 + tree.sourcePackage); 8402 } 8403 } else { 8404 Slog.w(TAG, "Permission " + p.info.name + " from package " 8405 + p.info.packageName + " ignored: original from " 8406 + bp.sourcePackage); 8407 } 8408 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8409 if (r == null) { 8410 r = new StringBuilder(256); 8411 } else { 8412 r.append(' '); 8413 } 8414 r.append("DUP:"); 8415 r.append(p.info.name); 8416 } 8417 if (bp.perm == p) { 8418 bp.protectionLevel = p.info.protectionLevel; 8419 } 8420 } 8421 8422 if (r != null) { 8423 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8424 } 8425 8426 N = pkg.instrumentation.size(); 8427 r = null; 8428 for (i=0; i<N; i++) { 8429 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8430 a.info.packageName = pkg.applicationInfo.packageName; 8431 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8432 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8433 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8434 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8435 a.info.dataDir = pkg.applicationInfo.dataDir; 8436 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8437 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8438 8439 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8440 // need other information about the application, like the ABI and what not ? 8441 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8442 mInstrumentation.put(a.getComponentName(), a); 8443 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8444 if (r == null) { 8445 r = new StringBuilder(256); 8446 } else { 8447 r.append(' '); 8448 } 8449 r.append(a.info.name); 8450 } 8451 } 8452 if (r != null) { 8453 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8454 } 8455 8456 if (pkg.protectedBroadcasts != null) { 8457 N = pkg.protectedBroadcasts.size(); 8458 for (i=0; i<N; i++) { 8459 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8460 } 8461 } 8462 8463 pkgSetting.setTimeStamp(scanFileTime); 8464 8465 // Create idmap files for pairs of (packages, overlay packages). 8466 // Note: "android", ie framework-res.apk, is handled by native layers. 8467 if (pkg.mOverlayTarget != null) { 8468 // This is an overlay package. 8469 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8470 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8471 mOverlays.put(pkg.mOverlayTarget, 8472 new ArrayMap<String, PackageParser.Package>()); 8473 } 8474 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8475 map.put(pkg.packageName, pkg); 8476 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8477 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8478 createIdmapFailed = true; 8479 } 8480 } 8481 } else if (mOverlays.containsKey(pkg.packageName) && 8482 !pkg.packageName.equals("android")) { 8483 // This is a regular package, with one or more known overlay packages. 8484 createIdmapsForPackageLI(pkg); 8485 } 8486 } 8487 8488 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8489 8490 if (createIdmapFailed) { 8491 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8492 "scanPackageLI failed to createIdmap"); 8493 } 8494 return pkg; 8495 } 8496 8497 /** 8498 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8499 * is derived purely on the basis of the contents of {@code scanFile} and 8500 * {@code cpuAbiOverride}. 8501 * 8502 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8503 */ 8504 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8505 String cpuAbiOverride, boolean extractLibs) 8506 throws PackageManagerException { 8507 // TODO: We can probably be smarter about this stuff. For installed apps, 8508 // we can calculate this information at install time once and for all. For 8509 // system apps, we can probably assume that this information doesn't change 8510 // after the first boot scan. As things stand, we do lots of unnecessary work. 8511 8512 // Give ourselves some initial paths; we'll come back for another 8513 // pass once we've determined ABI below. 8514 setNativeLibraryPaths(pkg); 8515 8516 // We would never need to extract libs for forward-locked and external packages, 8517 // since the container service will do it for us. We shouldn't attempt to 8518 // extract libs from system app when it was not updated. 8519 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8520 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8521 extractLibs = false; 8522 } 8523 8524 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8525 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8526 8527 NativeLibraryHelper.Handle handle = null; 8528 try { 8529 handle = NativeLibraryHelper.Handle.create(pkg); 8530 // TODO(multiArch): This can be null for apps that didn't go through the 8531 // usual installation process. We can calculate it again, like we 8532 // do during install time. 8533 // 8534 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8535 // unnecessary. 8536 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8537 8538 // Null out the abis so that they can be recalculated. 8539 pkg.applicationInfo.primaryCpuAbi = null; 8540 pkg.applicationInfo.secondaryCpuAbi = null; 8541 if (isMultiArch(pkg.applicationInfo)) { 8542 // Warn if we've set an abiOverride for multi-lib packages.. 8543 // By definition, we need to copy both 32 and 64 bit libraries for 8544 // such packages. 8545 if (pkg.cpuAbiOverride != null 8546 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8547 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8548 } 8549 8550 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8551 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8552 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8553 if (extractLibs) { 8554 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8555 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8556 useIsaSpecificSubdirs); 8557 } else { 8558 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8559 } 8560 } 8561 8562 maybeThrowExceptionForMultiArchCopy( 8563 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8564 8565 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8566 if (extractLibs) { 8567 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8568 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8569 useIsaSpecificSubdirs); 8570 } else { 8571 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8572 } 8573 } 8574 8575 maybeThrowExceptionForMultiArchCopy( 8576 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8577 8578 if (abi64 >= 0) { 8579 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8580 } 8581 8582 if (abi32 >= 0) { 8583 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8584 if (abi64 >= 0) { 8585 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8586 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8587 pkg.applicationInfo.primaryCpuAbi = abi; 8588 } else { 8589 pkg.applicationInfo.secondaryCpuAbi = abi; 8590 } 8591 } else { 8592 pkg.applicationInfo.primaryCpuAbi = abi; 8593 } 8594 } 8595 8596 } else { 8597 String[] abiList = (cpuAbiOverride != null) ? 8598 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8599 8600 // Enable gross and lame hacks for apps that are built with old 8601 // SDK tools. We must scan their APKs for renderscript bitcode and 8602 // not launch them if it's present. Don't bother checking on devices 8603 // that don't have 64 bit support. 8604 boolean needsRenderScriptOverride = false; 8605 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8606 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8607 abiList = Build.SUPPORTED_32_BIT_ABIS; 8608 needsRenderScriptOverride = true; 8609 } 8610 8611 final int copyRet; 8612 if (extractLibs) { 8613 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8614 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8615 } else { 8616 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8617 } 8618 8619 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8620 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8621 "Error unpackaging native libs for app, errorCode=" + copyRet); 8622 } 8623 8624 if (copyRet >= 0) { 8625 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8626 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8627 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8628 } else if (needsRenderScriptOverride) { 8629 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8630 } 8631 } 8632 } catch (IOException ioe) { 8633 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8634 } finally { 8635 IoUtils.closeQuietly(handle); 8636 } 8637 8638 // Now that we've calculated the ABIs and determined if it's an internal app, 8639 // we will go ahead and populate the nativeLibraryPath. 8640 setNativeLibraryPaths(pkg); 8641 } 8642 8643 /** 8644 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8645 * i.e, so that all packages can be run inside a single process if required. 8646 * 8647 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8648 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8649 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8650 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8651 * updating a package that belongs to a shared user. 8652 * 8653 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8654 * adds unnecessary complexity. 8655 */ 8656 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8657 PackageParser.Package scannedPackage, boolean bootComplete) { 8658 String requiredInstructionSet = null; 8659 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8660 requiredInstructionSet = VMRuntime.getInstructionSet( 8661 scannedPackage.applicationInfo.primaryCpuAbi); 8662 } 8663 8664 PackageSetting requirer = null; 8665 for (PackageSetting ps : packagesForUser) { 8666 // If packagesForUser contains scannedPackage, we skip it. This will happen 8667 // when scannedPackage is an update of an existing package. Without this check, 8668 // we will never be able to change the ABI of any package belonging to a shared 8669 // user, even if it's compatible with other packages. 8670 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8671 if (ps.primaryCpuAbiString == null) { 8672 continue; 8673 } 8674 8675 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8676 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8677 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8678 // this but there's not much we can do. 8679 String errorMessage = "Instruction set mismatch, " 8680 + ((requirer == null) ? "[caller]" : requirer) 8681 + " requires " + requiredInstructionSet + " whereas " + ps 8682 + " requires " + instructionSet; 8683 Slog.w(TAG, errorMessage); 8684 } 8685 8686 if (requiredInstructionSet == null) { 8687 requiredInstructionSet = instructionSet; 8688 requirer = ps; 8689 } 8690 } 8691 } 8692 8693 if (requiredInstructionSet != null) { 8694 String adjustedAbi; 8695 if (requirer != null) { 8696 // requirer != null implies that either scannedPackage was null or that scannedPackage 8697 // did not require an ABI, in which case we have to adjust scannedPackage to match 8698 // the ABI of the set (which is the same as requirer's ABI) 8699 adjustedAbi = requirer.primaryCpuAbiString; 8700 if (scannedPackage != null) { 8701 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8702 } 8703 } else { 8704 // requirer == null implies that we're updating all ABIs in the set to 8705 // match scannedPackage. 8706 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8707 } 8708 8709 for (PackageSetting ps : packagesForUser) { 8710 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8711 if (ps.primaryCpuAbiString != null) { 8712 continue; 8713 } 8714 8715 ps.primaryCpuAbiString = adjustedAbi; 8716 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8717 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8718 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8719 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8720 + " (requirer=" 8721 + (requirer == null ? "null" : requirer.pkg.packageName) 8722 + ", scannedPackage=" 8723 + (scannedPackage != null ? scannedPackage.packageName : "null") 8724 + ")"); 8725 try { 8726 mInstaller.rmdex(ps.codePathString, 8727 getDexCodeInstructionSet(getPreferredInstructionSet())); 8728 } catch (InstallerException ignored) { 8729 } 8730 } 8731 } 8732 } 8733 } 8734 } 8735 8736 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8737 synchronized (mPackages) { 8738 mResolverReplaced = true; 8739 // Set up information for custom user intent resolution activity. 8740 mResolveActivity.applicationInfo = pkg.applicationInfo; 8741 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8742 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8743 mResolveActivity.processName = pkg.applicationInfo.packageName; 8744 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8745 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8746 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8747 mResolveActivity.theme = 0; 8748 mResolveActivity.exported = true; 8749 mResolveActivity.enabled = true; 8750 mResolveInfo.activityInfo = mResolveActivity; 8751 mResolveInfo.priority = 0; 8752 mResolveInfo.preferredOrder = 0; 8753 mResolveInfo.match = 0; 8754 mResolveComponentName = mCustomResolverComponentName; 8755 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8756 mResolveComponentName); 8757 } 8758 } 8759 8760 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8761 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8762 8763 // Set up information for ephemeral installer activity 8764 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8765 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8766 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8767 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8768 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8769 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8770 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8771 mEphemeralInstallerActivity.theme = 0; 8772 mEphemeralInstallerActivity.exported = true; 8773 mEphemeralInstallerActivity.enabled = true; 8774 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8775 mEphemeralInstallerInfo.priority = 0; 8776 mEphemeralInstallerInfo.preferredOrder = 0; 8777 mEphemeralInstallerInfo.match = 0; 8778 8779 if (DEBUG_EPHEMERAL) { 8780 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8781 } 8782 } 8783 8784 private static String calculateBundledApkRoot(final String codePathString) { 8785 final File codePath = new File(codePathString); 8786 final File codeRoot; 8787 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8788 codeRoot = Environment.getRootDirectory(); 8789 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8790 codeRoot = Environment.getOemDirectory(); 8791 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8792 codeRoot = Environment.getVendorDirectory(); 8793 } else { 8794 // Unrecognized code path; take its top real segment as the apk root: 8795 // e.g. /something/app/blah.apk => /something 8796 try { 8797 File f = codePath.getCanonicalFile(); 8798 File parent = f.getParentFile(); // non-null because codePath is a file 8799 File tmp; 8800 while ((tmp = parent.getParentFile()) != null) { 8801 f = parent; 8802 parent = tmp; 8803 } 8804 codeRoot = f; 8805 Slog.w(TAG, "Unrecognized code path " 8806 + codePath + " - using " + codeRoot); 8807 } catch (IOException e) { 8808 // Can't canonicalize the code path -- shenanigans? 8809 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8810 return Environment.getRootDirectory().getPath(); 8811 } 8812 } 8813 return codeRoot.getPath(); 8814 } 8815 8816 /** 8817 * Derive and set the location of native libraries for the given package, 8818 * which varies depending on where and how the package was installed. 8819 */ 8820 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8821 final ApplicationInfo info = pkg.applicationInfo; 8822 final String codePath = pkg.codePath; 8823 final File codeFile = new File(codePath); 8824 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8825 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8826 8827 info.nativeLibraryRootDir = null; 8828 info.nativeLibraryRootRequiresIsa = false; 8829 info.nativeLibraryDir = null; 8830 info.secondaryNativeLibraryDir = null; 8831 8832 if (isApkFile(codeFile)) { 8833 // Monolithic install 8834 if (bundledApp) { 8835 // If "/system/lib64/apkname" exists, assume that is the per-package 8836 // native library directory to use; otherwise use "/system/lib/apkname". 8837 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8838 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8839 getPrimaryInstructionSet(info)); 8840 8841 // This is a bundled system app so choose the path based on the ABI. 8842 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8843 // is just the default path. 8844 final String apkName = deriveCodePathName(codePath); 8845 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8846 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8847 apkName).getAbsolutePath(); 8848 8849 if (info.secondaryCpuAbi != null) { 8850 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8851 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8852 secondaryLibDir, apkName).getAbsolutePath(); 8853 } 8854 } else if (asecApp) { 8855 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8856 .getAbsolutePath(); 8857 } else { 8858 final String apkName = deriveCodePathName(codePath); 8859 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8860 .getAbsolutePath(); 8861 } 8862 8863 info.nativeLibraryRootRequiresIsa = false; 8864 info.nativeLibraryDir = info.nativeLibraryRootDir; 8865 } else { 8866 // Cluster install 8867 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8868 info.nativeLibraryRootRequiresIsa = true; 8869 8870 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8871 getPrimaryInstructionSet(info)).getAbsolutePath(); 8872 8873 if (info.secondaryCpuAbi != null) { 8874 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8875 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8876 } 8877 } 8878 } 8879 8880 /** 8881 * Calculate the abis and roots for a bundled app. These can uniquely 8882 * be determined from the contents of the system partition, i.e whether 8883 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8884 * of this information, and instead assume that the system was built 8885 * sensibly. 8886 */ 8887 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8888 PackageSetting pkgSetting) { 8889 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8890 8891 // If "/system/lib64/apkname" exists, assume that is the per-package 8892 // native library directory to use; otherwise use "/system/lib/apkname". 8893 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8894 setBundledAppAbi(pkg, apkRoot, apkName); 8895 // pkgSetting might be null during rescan following uninstall of updates 8896 // to a bundled app, so accommodate that possibility. The settings in 8897 // that case will be established later from the parsed package. 8898 // 8899 // If the settings aren't null, sync them up with what we've just derived. 8900 // note that apkRoot isn't stored in the package settings. 8901 if (pkgSetting != null) { 8902 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8903 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8904 } 8905 } 8906 8907 /** 8908 * Deduces the ABI of a bundled app and sets the relevant fields on the 8909 * parsed pkg object. 8910 * 8911 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8912 * under which system libraries are installed. 8913 * @param apkName the name of the installed package. 8914 */ 8915 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8916 final File codeFile = new File(pkg.codePath); 8917 8918 final boolean has64BitLibs; 8919 final boolean has32BitLibs; 8920 if (isApkFile(codeFile)) { 8921 // Monolithic install 8922 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8923 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8924 } else { 8925 // Cluster install 8926 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8927 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8928 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8929 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8930 has64BitLibs = (new File(rootDir, isa)).exists(); 8931 } else { 8932 has64BitLibs = false; 8933 } 8934 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8935 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8936 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8937 has32BitLibs = (new File(rootDir, isa)).exists(); 8938 } else { 8939 has32BitLibs = false; 8940 } 8941 } 8942 8943 if (has64BitLibs && !has32BitLibs) { 8944 // The package has 64 bit libs, but not 32 bit libs. Its primary 8945 // ABI should be 64 bit. We can safely assume here that the bundled 8946 // native libraries correspond to the most preferred ABI in the list. 8947 8948 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8949 pkg.applicationInfo.secondaryCpuAbi = null; 8950 } else if (has32BitLibs && !has64BitLibs) { 8951 // The package has 32 bit libs but not 64 bit libs. Its primary 8952 // ABI should be 32 bit. 8953 8954 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8955 pkg.applicationInfo.secondaryCpuAbi = null; 8956 } else if (has32BitLibs && has64BitLibs) { 8957 // The application has both 64 and 32 bit bundled libraries. We check 8958 // here that the app declares multiArch support, and warn if it doesn't. 8959 // 8960 // We will be lenient here and record both ABIs. The primary will be the 8961 // ABI that's higher on the list, i.e, a device that's configured to prefer 8962 // 64 bit apps will see a 64 bit primary ABI, 8963 8964 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8965 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8966 } 8967 8968 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8969 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8970 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8971 } else { 8972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8973 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8974 } 8975 } else { 8976 pkg.applicationInfo.primaryCpuAbi = null; 8977 pkg.applicationInfo.secondaryCpuAbi = null; 8978 } 8979 } 8980 8981 private void killPackage(PackageParser.Package pkg, String reason) { 8982 // Kill the parent package 8983 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8984 // Kill the child packages 8985 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8986 for (int i = 0; i < childCount; i++) { 8987 PackageParser.Package childPkg = pkg.childPackages.get(i); 8988 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8989 } 8990 } 8991 8992 private void killApplication(String pkgName, int appId, String reason) { 8993 // Request the ActivityManager to kill the process(only for existing packages) 8994 // so that we do not end up in a confused state while the user is still using the older 8995 // version of the application while the new one gets installed. 8996 IActivityManager am = ActivityManagerNative.getDefault(); 8997 if (am != null) { 8998 try { 8999 am.killApplicationWithAppId(pkgName, appId, reason); 9000 } catch (RemoteException e) { 9001 } 9002 } 9003 } 9004 9005 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9006 // Remove the parent package setting 9007 PackageSetting ps = (PackageSetting) pkg.mExtras; 9008 if (ps != null) { 9009 removePackageLI(ps, chatty); 9010 } 9011 // Remove the child package setting 9012 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9013 for (int i = 0; i < childCount; i++) { 9014 PackageParser.Package childPkg = pkg.childPackages.get(i); 9015 ps = (PackageSetting) childPkg.mExtras; 9016 if (ps != null) { 9017 removePackageLI(ps, chatty); 9018 } 9019 } 9020 } 9021 9022 void removePackageLI(PackageSetting ps, boolean chatty) { 9023 if (DEBUG_INSTALL) { 9024 if (chatty) 9025 Log.d(TAG, "Removing package " + ps.name); 9026 } 9027 9028 // writer 9029 synchronized (mPackages) { 9030 mPackages.remove(ps.name); 9031 final PackageParser.Package pkg = ps.pkg; 9032 if (pkg != null) { 9033 cleanPackageDataStructuresLILPw(pkg, chatty); 9034 } 9035 } 9036 } 9037 9038 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9039 if (DEBUG_INSTALL) { 9040 if (chatty) 9041 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9042 } 9043 9044 // writer 9045 synchronized (mPackages) { 9046 // Remove the parent package 9047 mPackages.remove(pkg.applicationInfo.packageName); 9048 cleanPackageDataStructuresLILPw(pkg, chatty); 9049 9050 // Remove the child packages 9051 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9052 for (int i = 0; i < childCount; i++) { 9053 PackageParser.Package childPkg = pkg.childPackages.get(i); 9054 mPackages.remove(childPkg.applicationInfo.packageName); 9055 cleanPackageDataStructuresLILPw(childPkg, chatty); 9056 } 9057 } 9058 } 9059 9060 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9061 int N = pkg.providers.size(); 9062 StringBuilder r = null; 9063 int i; 9064 for (i=0; i<N; i++) { 9065 PackageParser.Provider p = pkg.providers.get(i); 9066 mProviders.removeProvider(p); 9067 if (p.info.authority == null) { 9068 9069 /* There was another ContentProvider with this authority when 9070 * this app was installed so this authority is null, 9071 * Ignore it as we don't have to unregister the provider. 9072 */ 9073 continue; 9074 } 9075 String names[] = p.info.authority.split(";"); 9076 for (int j = 0; j < names.length; j++) { 9077 if (mProvidersByAuthority.get(names[j]) == p) { 9078 mProvidersByAuthority.remove(names[j]); 9079 if (DEBUG_REMOVE) { 9080 if (chatty) 9081 Log.d(TAG, "Unregistered content provider: " + names[j] 9082 + ", className = " + p.info.name + ", isSyncable = " 9083 + p.info.isSyncable); 9084 } 9085 } 9086 } 9087 if (DEBUG_REMOVE && chatty) { 9088 if (r == null) { 9089 r = new StringBuilder(256); 9090 } else { 9091 r.append(' '); 9092 } 9093 r.append(p.info.name); 9094 } 9095 } 9096 if (r != null) { 9097 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9098 } 9099 9100 N = pkg.services.size(); 9101 r = null; 9102 for (i=0; i<N; i++) { 9103 PackageParser.Service s = pkg.services.get(i); 9104 mServices.removeService(s); 9105 if (chatty) { 9106 if (r == null) { 9107 r = new StringBuilder(256); 9108 } else { 9109 r.append(' '); 9110 } 9111 r.append(s.info.name); 9112 } 9113 } 9114 if (r != null) { 9115 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9116 } 9117 9118 N = pkg.receivers.size(); 9119 r = null; 9120 for (i=0; i<N; i++) { 9121 PackageParser.Activity a = pkg.receivers.get(i); 9122 mReceivers.removeActivity(a, "receiver"); 9123 if (DEBUG_REMOVE && chatty) { 9124 if (r == null) { 9125 r = new StringBuilder(256); 9126 } else { 9127 r.append(' '); 9128 } 9129 r.append(a.info.name); 9130 } 9131 } 9132 if (r != null) { 9133 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9134 } 9135 9136 N = pkg.activities.size(); 9137 r = null; 9138 for (i=0; i<N; i++) { 9139 PackageParser.Activity a = pkg.activities.get(i); 9140 mActivities.removeActivity(a, "activity"); 9141 if (DEBUG_REMOVE && chatty) { 9142 if (r == null) { 9143 r = new StringBuilder(256); 9144 } else { 9145 r.append(' '); 9146 } 9147 r.append(a.info.name); 9148 } 9149 } 9150 if (r != null) { 9151 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9152 } 9153 9154 N = pkg.permissions.size(); 9155 r = null; 9156 for (i=0; i<N; i++) { 9157 PackageParser.Permission p = pkg.permissions.get(i); 9158 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9159 if (bp == null) { 9160 bp = mSettings.mPermissionTrees.get(p.info.name); 9161 } 9162 if (bp != null && bp.perm == p) { 9163 bp.perm = null; 9164 if (DEBUG_REMOVE && chatty) { 9165 if (r == null) { 9166 r = new StringBuilder(256); 9167 } else { 9168 r.append(' '); 9169 } 9170 r.append(p.info.name); 9171 } 9172 } 9173 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9174 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9175 if (appOpPkgs != null) { 9176 appOpPkgs.remove(pkg.packageName); 9177 } 9178 } 9179 } 9180 if (r != null) { 9181 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9182 } 9183 9184 N = pkg.requestedPermissions.size(); 9185 r = null; 9186 for (i=0; i<N; i++) { 9187 String perm = pkg.requestedPermissions.get(i); 9188 BasePermission bp = mSettings.mPermissions.get(perm); 9189 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9190 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9191 if (appOpPkgs != null) { 9192 appOpPkgs.remove(pkg.packageName); 9193 if (appOpPkgs.isEmpty()) { 9194 mAppOpPermissionPackages.remove(perm); 9195 } 9196 } 9197 } 9198 } 9199 if (r != null) { 9200 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9201 } 9202 9203 N = pkg.instrumentation.size(); 9204 r = null; 9205 for (i=0; i<N; i++) { 9206 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9207 mInstrumentation.remove(a.getComponentName()); 9208 if (DEBUG_REMOVE && chatty) { 9209 if (r == null) { 9210 r = new StringBuilder(256); 9211 } else { 9212 r.append(' '); 9213 } 9214 r.append(a.info.name); 9215 } 9216 } 9217 if (r != null) { 9218 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9219 } 9220 9221 r = null; 9222 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9223 // Only system apps can hold shared libraries. 9224 if (pkg.libraryNames != null) { 9225 for (i=0; i<pkg.libraryNames.size(); i++) { 9226 String name = pkg.libraryNames.get(i); 9227 SharedLibraryEntry cur = mSharedLibraries.get(name); 9228 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9229 mSharedLibraries.remove(name); 9230 if (DEBUG_REMOVE && chatty) { 9231 if (r == null) { 9232 r = new StringBuilder(256); 9233 } else { 9234 r.append(' '); 9235 } 9236 r.append(name); 9237 } 9238 } 9239 } 9240 } 9241 } 9242 if (r != null) { 9243 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9244 } 9245 } 9246 9247 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9248 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9249 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9250 return true; 9251 } 9252 } 9253 return false; 9254 } 9255 9256 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9257 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9258 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9259 9260 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9261 // Update the parent permissions 9262 updatePermissionsLPw(pkg.packageName, pkg, flags); 9263 // Update the child permissions 9264 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9265 for (int i = 0; i < childCount; i++) { 9266 PackageParser.Package childPkg = pkg.childPackages.get(i); 9267 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9268 } 9269 } 9270 9271 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9272 int flags) { 9273 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9274 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9275 } 9276 9277 private void updatePermissionsLPw(String changingPkg, 9278 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9279 // Make sure there are no dangling permission trees. 9280 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9281 while (it.hasNext()) { 9282 final BasePermission bp = it.next(); 9283 if (bp.packageSetting == null) { 9284 // We may not yet have parsed the package, so just see if 9285 // we still know about its settings. 9286 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9287 } 9288 if (bp.packageSetting == null) { 9289 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9290 + " from package " + bp.sourcePackage); 9291 it.remove(); 9292 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9293 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9294 Slog.i(TAG, "Removing old permission tree: " + bp.name 9295 + " from package " + bp.sourcePackage); 9296 flags |= UPDATE_PERMISSIONS_ALL; 9297 it.remove(); 9298 } 9299 } 9300 } 9301 9302 // Make sure all dynamic permissions have been assigned to a package, 9303 // and make sure there are no dangling permissions. 9304 it = mSettings.mPermissions.values().iterator(); 9305 while (it.hasNext()) { 9306 final BasePermission bp = it.next(); 9307 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9308 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9309 + bp.name + " pkg=" + bp.sourcePackage 9310 + " info=" + bp.pendingInfo); 9311 if (bp.packageSetting == null && bp.pendingInfo != null) { 9312 final BasePermission tree = findPermissionTreeLP(bp.name); 9313 if (tree != null && tree.perm != null) { 9314 bp.packageSetting = tree.packageSetting; 9315 bp.perm = new PackageParser.Permission(tree.perm.owner, 9316 new PermissionInfo(bp.pendingInfo)); 9317 bp.perm.info.packageName = tree.perm.info.packageName; 9318 bp.perm.info.name = bp.name; 9319 bp.uid = tree.uid; 9320 } 9321 } 9322 } 9323 if (bp.packageSetting == null) { 9324 // We may not yet have parsed the package, so just see if 9325 // we still know about its settings. 9326 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9327 } 9328 if (bp.packageSetting == null) { 9329 Slog.w(TAG, "Removing dangling permission: " + bp.name 9330 + " from package " + bp.sourcePackage); 9331 it.remove(); 9332 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9333 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9334 Slog.i(TAG, "Removing old permission: " + bp.name 9335 + " from package " + bp.sourcePackage); 9336 flags |= UPDATE_PERMISSIONS_ALL; 9337 it.remove(); 9338 } 9339 } 9340 } 9341 9342 // Now update the permissions for all packages, in particular 9343 // replace the granted permissions of the system packages. 9344 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9345 for (PackageParser.Package pkg : mPackages.values()) { 9346 if (pkg != pkgInfo) { 9347 // Only replace for packages on requested volume 9348 final String volumeUuid = getVolumeUuidForPackage(pkg); 9349 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9350 && Objects.equals(replaceVolumeUuid, volumeUuid); 9351 grantPermissionsLPw(pkg, replace, changingPkg); 9352 } 9353 } 9354 } 9355 9356 if (pkgInfo != null) { 9357 // Only replace for packages on requested volume 9358 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9359 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9360 && Objects.equals(replaceVolumeUuid, volumeUuid); 9361 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9362 } 9363 } 9364 9365 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9366 String packageOfInterest) { 9367 // IMPORTANT: There are two types of permissions: install and runtime. 9368 // Install time permissions are granted when the app is installed to 9369 // all device users and users added in the future. Runtime permissions 9370 // are granted at runtime explicitly to specific users. Normal and signature 9371 // protected permissions are install time permissions. Dangerous permissions 9372 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9373 // otherwise they are runtime permissions. This function does not manage 9374 // runtime permissions except for the case an app targeting Lollipop MR1 9375 // being upgraded to target a newer SDK, in which case dangerous permissions 9376 // are transformed from install time to runtime ones. 9377 9378 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9379 if (ps == null) { 9380 return; 9381 } 9382 9383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9384 9385 PermissionsState permissionsState = ps.getPermissionsState(); 9386 PermissionsState origPermissions = permissionsState; 9387 9388 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9389 9390 boolean runtimePermissionsRevoked = false; 9391 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9392 9393 boolean changedInstallPermission = false; 9394 9395 if (replace) { 9396 ps.installPermissionsFixed = false; 9397 if (!ps.isSharedUser()) { 9398 origPermissions = new PermissionsState(permissionsState); 9399 permissionsState.reset(); 9400 } else { 9401 // We need to know only about runtime permission changes since the 9402 // calling code always writes the install permissions state but 9403 // the runtime ones are written only if changed. The only cases of 9404 // changed runtime permissions here are promotion of an install to 9405 // runtime and revocation of a runtime from a shared user. 9406 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9407 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9408 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9409 runtimePermissionsRevoked = true; 9410 } 9411 } 9412 } 9413 9414 permissionsState.setGlobalGids(mGlobalGids); 9415 9416 final int N = pkg.requestedPermissions.size(); 9417 for (int i=0; i<N; i++) { 9418 final String name = pkg.requestedPermissions.get(i); 9419 final BasePermission bp = mSettings.mPermissions.get(name); 9420 9421 if (DEBUG_INSTALL) { 9422 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9423 } 9424 9425 if (bp == null || bp.packageSetting == null) { 9426 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9427 Slog.w(TAG, "Unknown permission " + name 9428 + " in package " + pkg.packageName); 9429 } 9430 continue; 9431 } 9432 9433 final String perm = bp.name; 9434 boolean allowedSig = false; 9435 int grant = GRANT_DENIED; 9436 9437 // Keep track of app op permissions. 9438 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9439 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9440 if (pkgs == null) { 9441 pkgs = new ArraySet<>(); 9442 mAppOpPermissionPackages.put(bp.name, pkgs); 9443 } 9444 pkgs.add(pkg.packageName); 9445 } 9446 9447 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9448 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9449 >= Build.VERSION_CODES.M; 9450 switch (level) { 9451 case PermissionInfo.PROTECTION_NORMAL: { 9452 // For all apps normal permissions are install time ones. 9453 grant = GRANT_INSTALL; 9454 } break; 9455 9456 case PermissionInfo.PROTECTION_DANGEROUS: { 9457 // If a permission review is required for legacy apps we represent 9458 // their permissions as always granted runtime ones since we need 9459 // to keep the review required permission flag per user while an 9460 // install permission's state is shared across all users. 9461 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9462 // For legacy apps dangerous permissions are install time ones. 9463 grant = GRANT_INSTALL; 9464 } else if (origPermissions.hasInstallPermission(bp.name)) { 9465 // For legacy apps that became modern, install becomes runtime. 9466 grant = GRANT_UPGRADE; 9467 } else if (mPromoteSystemApps 9468 && isSystemApp(ps) 9469 && mExistingSystemPackages.contains(ps.name)) { 9470 // For legacy system apps, install becomes runtime. 9471 // We cannot check hasInstallPermission() for system apps since those 9472 // permissions were granted implicitly and not persisted pre-M. 9473 grant = GRANT_UPGRADE; 9474 } else { 9475 // For modern apps keep runtime permissions unchanged. 9476 grant = GRANT_RUNTIME; 9477 } 9478 } break; 9479 9480 case PermissionInfo.PROTECTION_SIGNATURE: { 9481 // For all apps signature permissions are install time ones. 9482 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9483 if (allowedSig) { 9484 grant = GRANT_INSTALL; 9485 } 9486 } break; 9487 } 9488 9489 if (DEBUG_INSTALL) { 9490 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9491 } 9492 9493 if (grant != GRANT_DENIED) { 9494 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9495 // If this is an existing, non-system package, then 9496 // we can't add any new permissions to it. 9497 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9498 // Except... if this is a permission that was added 9499 // to the platform (note: need to only do this when 9500 // updating the platform). 9501 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9502 grant = GRANT_DENIED; 9503 } 9504 } 9505 } 9506 9507 switch (grant) { 9508 case GRANT_INSTALL: { 9509 // Revoke this as runtime permission to handle the case of 9510 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9511 for (int userId : UserManagerService.getInstance().getUserIds()) { 9512 if (origPermissions.getRuntimePermissionState( 9513 bp.name, userId) != null) { 9514 // Revoke the runtime permission and clear the flags. 9515 origPermissions.revokeRuntimePermission(bp, userId); 9516 origPermissions.updatePermissionFlags(bp, userId, 9517 PackageManager.MASK_PERMISSION_FLAGS, 0); 9518 // If we revoked a permission permission, we have to write. 9519 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9520 changedRuntimePermissionUserIds, userId); 9521 } 9522 } 9523 // Grant an install permission. 9524 if (permissionsState.grantInstallPermission(bp) != 9525 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9526 changedInstallPermission = true; 9527 } 9528 } break; 9529 9530 case GRANT_RUNTIME: { 9531 // Grant previously granted runtime permissions. 9532 for (int userId : UserManagerService.getInstance().getUserIds()) { 9533 PermissionState permissionState = origPermissions 9534 .getRuntimePermissionState(bp.name, userId); 9535 int flags = permissionState != null 9536 ? permissionState.getFlags() : 0; 9537 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9538 if (permissionsState.grantRuntimePermission(bp, userId) == 9539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9540 // If we cannot put the permission as it was, we have to write. 9541 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9542 changedRuntimePermissionUserIds, userId); 9543 } 9544 // If the app supports runtime permissions no need for a review. 9545 if (Build.PERMISSIONS_REVIEW_REQUIRED 9546 && appSupportsRuntimePermissions 9547 && (flags & PackageManager 9548 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9549 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9550 // Since we changed the flags, we have to write. 9551 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9552 changedRuntimePermissionUserIds, userId); 9553 } 9554 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9555 && !appSupportsRuntimePermissions) { 9556 // For legacy apps that need a permission review, every new 9557 // runtime permission is granted but it is pending a review. 9558 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9559 permissionsState.grantRuntimePermission(bp, userId); 9560 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9561 // We changed the permission and flags, hence have to write. 9562 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9563 changedRuntimePermissionUserIds, userId); 9564 } 9565 } 9566 // Propagate the permission flags. 9567 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9568 } 9569 } break; 9570 9571 case GRANT_UPGRADE: { 9572 // Grant runtime permissions for a previously held install permission. 9573 PermissionState permissionState = origPermissions 9574 .getInstallPermissionState(bp.name); 9575 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9576 9577 if (origPermissions.revokeInstallPermission(bp) 9578 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9579 // We will be transferring the permission flags, so clear them. 9580 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9581 PackageManager.MASK_PERMISSION_FLAGS, 0); 9582 changedInstallPermission = true; 9583 } 9584 9585 // If the permission is not to be promoted to runtime we ignore it and 9586 // also its other flags as they are not applicable to install permissions. 9587 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9588 for (int userId : currentUserIds) { 9589 if (permissionsState.grantRuntimePermission(bp, userId) != 9590 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9591 // Transfer the permission flags. 9592 permissionsState.updatePermissionFlags(bp, userId, 9593 flags, flags); 9594 // If we granted the permission, we have to write. 9595 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9596 changedRuntimePermissionUserIds, userId); 9597 } 9598 } 9599 } 9600 } break; 9601 9602 default: { 9603 if (packageOfInterest == null 9604 || packageOfInterest.equals(pkg.packageName)) { 9605 Slog.w(TAG, "Not granting permission " + perm 9606 + " to package " + pkg.packageName 9607 + " because it was previously installed without"); 9608 } 9609 } break; 9610 } 9611 } else { 9612 if (permissionsState.revokeInstallPermission(bp) != 9613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9614 // Also drop the permission flags. 9615 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9616 PackageManager.MASK_PERMISSION_FLAGS, 0); 9617 changedInstallPermission = true; 9618 Slog.i(TAG, "Un-granting permission " + perm 9619 + " from package " + pkg.packageName 9620 + " (protectionLevel=" + bp.protectionLevel 9621 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9622 + ")"); 9623 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9624 // Don't print warning for app op permissions, since it is fine for them 9625 // not to be granted, there is a UI for the user to decide. 9626 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9627 Slog.w(TAG, "Not granting permission " + perm 9628 + " to package " + pkg.packageName 9629 + " (protectionLevel=" + bp.protectionLevel 9630 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9631 + ")"); 9632 } 9633 } 9634 } 9635 } 9636 9637 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9638 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9639 // This is the first that we have heard about this package, so the 9640 // permissions we have now selected are fixed until explicitly 9641 // changed. 9642 ps.installPermissionsFixed = true; 9643 } 9644 9645 // Persist the runtime permissions state for users with changes. If permissions 9646 // were revoked because no app in the shared user declares them we have to 9647 // write synchronously to avoid losing runtime permissions state. 9648 for (int userId : changedRuntimePermissionUserIds) { 9649 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9650 } 9651 9652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9653 } 9654 9655 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9656 boolean allowed = false; 9657 final int NP = PackageParser.NEW_PERMISSIONS.length; 9658 for (int ip=0; ip<NP; ip++) { 9659 final PackageParser.NewPermissionInfo npi 9660 = PackageParser.NEW_PERMISSIONS[ip]; 9661 if (npi.name.equals(perm) 9662 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9663 allowed = true; 9664 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9665 + pkg.packageName); 9666 break; 9667 } 9668 } 9669 return allowed; 9670 } 9671 9672 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9673 BasePermission bp, PermissionsState origPermissions) { 9674 boolean allowed; 9675 allowed = (compareSignatures( 9676 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9677 == PackageManager.SIGNATURE_MATCH) 9678 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9679 == PackageManager.SIGNATURE_MATCH); 9680 if (!allowed && (bp.protectionLevel 9681 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9682 if (isSystemApp(pkg)) { 9683 // For updated system applications, a system permission 9684 // is granted only if it had been defined by the original application. 9685 if (pkg.isUpdatedSystemApp()) { 9686 final PackageSetting sysPs = mSettings 9687 .getDisabledSystemPkgLPr(pkg.packageName); 9688 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9689 // If the original was granted this permission, we take 9690 // that grant decision as read and propagate it to the 9691 // update. 9692 if (sysPs.isPrivileged()) { 9693 allowed = true; 9694 } 9695 } else { 9696 // The system apk may have been updated with an older 9697 // version of the one on the data partition, but which 9698 // granted a new system permission that it didn't have 9699 // before. In this case we do want to allow the app to 9700 // now get the new permission if the ancestral apk is 9701 // privileged to get it. 9702 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9703 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9704 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9705 allowed = true; 9706 break; 9707 } 9708 } 9709 } 9710 // Also if a privileged parent package on the system image or any of 9711 // its children requested a privileged permission, the updated child 9712 // packages can also get the permission. 9713 if (pkg.parentPackage != null) { 9714 final PackageSetting disabledSysParentPs = mSettings 9715 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9716 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9717 && disabledSysParentPs.isPrivileged()) { 9718 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9719 allowed = true; 9720 } else if (disabledSysParentPs.pkg.childPackages != null) { 9721 final int count = disabledSysParentPs.pkg.childPackages.size(); 9722 for (int i = 0; i < count; i++) { 9723 PackageParser.Package disabledSysChildPkg = 9724 disabledSysParentPs.pkg.childPackages.get(i); 9725 if (isPackageRequestingPermission(disabledSysChildPkg, 9726 perm)) { 9727 allowed = true; 9728 break; 9729 } 9730 } 9731 } 9732 } 9733 } 9734 } 9735 } else { 9736 allowed = isPrivilegedApp(pkg); 9737 } 9738 } 9739 } 9740 if (!allowed) { 9741 if (!allowed && (bp.protectionLevel 9742 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9743 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9744 // If this was a previously normal/dangerous permission that got moved 9745 // to a system permission as part of the runtime permission redesign, then 9746 // we still want to blindly grant it to old apps. 9747 allowed = true; 9748 } 9749 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9750 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9751 // If this permission is to be granted to the system installer and 9752 // this app is an installer, then it gets the permission. 9753 allowed = true; 9754 } 9755 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9756 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9757 // If this permission is to be granted to the system verifier and 9758 // this app is a verifier, then it gets the permission. 9759 allowed = true; 9760 } 9761 if (!allowed && (bp.protectionLevel 9762 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9763 && isSystemApp(pkg)) { 9764 // Any pre-installed system app is allowed to get this permission. 9765 allowed = true; 9766 } 9767 if (!allowed && (bp.protectionLevel 9768 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9769 // For development permissions, a development permission 9770 // is granted only if it was already granted. 9771 allowed = origPermissions.hasInstallPermission(perm); 9772 } 9773 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9774 && pkg.packageName.equals(mSetupWizardPackage)) { 9775 // If this permission is to be granted to the system setup wizard and 9776 // this app is a setup wizard, then it gets the permission. 9777 allowed = true; 9778 } 9779 } 9780 return allowed; 9781 } 9782 9783 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9784 final int permCount = pkg.requestedPermissions.size(); 9785 for (int j = 0; j < permCount; j++) { 9786 String requestedPermission = pkg.requestedPermissions.get(j); 9787 if (permission.equals(requestedPermission)) { 9788 return true; 9789 } 9790 } 9791 return false; 9792 } 9793 9794 final class ActivityIntentResolver 9795 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9796 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9797 boolean defaultOnly, int userId) { 9798 if (!sUserManager.exists(userId)) return null; 9799 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9800 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9801 } 9802 9803 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9804 int userId) { 9805 if (!sUserManager.exists(userId)) return null; 9806 mFlags = flags; 9807 return super.queryIntent(intent, resolvedType, 9808 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9809 } 9810 9811 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9812 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9813 if (!sUserManager.exists(userId)) return null; 9814 if (packageActivities == null) { 9815 return null; 9816 } 9817 mFlags = flags; 9818 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9819 final int N = packageActivities.size(); 9820 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9821 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9822 9823 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9824 for (int i = 0; i < N; ++i) { 9825 intentFilters = packageActivities.get(i).intents; 9826 if (intentFilters != null && intentFilters.size() > 0) { 9827 PackageParser.ActivityIntentInfo[] array = 9828 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9829 intentFilters.toArray(array); 9830 listCut.add(array); 9831 } 9832 } 9833 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9834 } 9835 9836 /** 9837 * Finds a privileged activity that matches the specified activity names. 9838 */ 9839 private PackageParser.Activity findMatchingActivity( 9840 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9841 for (PackageParser.Activity sysActivity : activityList) { 9842 if (sysActivity.info.name.equals(activityInfo.name)) { 9843 return sysActivity; 9844 } 9845 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9846 return sysActivity; 9847 } 9848 if (sysActivity.info.targetActivity != null) { 9849 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9850 return sysActivity; 9851 } 9852 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9853 return sysActivity; 9854 } 9855 } 9856 } 9857 return null; 9858 } 9859 9860 public class IterGenerator<E> { 9861 public Iterator<E> generate(ActivityIntentInfo info) { 9862 return null; 9863 } 9864 } 9865 9866 public class ActionIterGenerator extends IterGenerator<String> { 9867 @Override 9868 public Iterator<String> generate(ActivityIntentInfo info) { 9869 return info.actionsIterator(); 9870 } 9871 } 9872 9873 public class CategoriesIterGenerator extends IterGenerator<String> { 9874 @Override 9875 public Iterator<String> generate(ActivityIntentInfo info) { 9876 return info.categoriesIterator(); 9877 } 9878 } 9879 9880 public class SchemesIterGenerator extends IterGenerator<String> { 9881 @Override 9882 public Iterator<String> generate(ActivityIntentInfo info) { 9883 return info.schemesIterator(); 9884 } 9885 } 9886 9887 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9888 @Override 9889 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9890 return info.authoritiesIterator(); 9891 } 9892 } 9893 9894 /** 9895 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9896 * MODIFIED. Do not pass in a list that should not be changed. 9897 */ 9898 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9899 IterGenerator<T> generator, Iterator<T> searchIterator) { 9900 // loop through the set of actions; every one must be found in the intent filter 9901 while (searchIterator.hasNext()) { 9902 // we must have at least one filter in the list to consider a match 9903 if (intentList.size() == 0) { 9904 break; 9905 } 9906 9907 final T searchAction = searchIterator.next(); 9908 9909 // loop through the set of intent filters 9910 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9911 while (intentIter.hasNext()) { 9912 final ActivityIntentInfo intentInfo = intentIter.next(); 9913 boolean selectionFound = false; 9914 9915 // loop through the intent filter's selection criteria; at least one 9916 // of them must match the searched criteria 9917 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9918 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9919 final T intentSelection = intentSelectionIter.next(); 9920 if (intentSelection != null && intentSelection.equals(searchAction)) { 9921 selectionFound = true; 9922 break; 9923 } 9924 } 9925 9926 // the selection criteria wasn't found in this filter's set; this filter 9927 // is not a potential match 9928 if (!selectionFound) { 9929 intentIter.remove(); 9930 } 9931 } 9932 } 9933 } 9934 9935 private boolean isProtectedAction(ActivityIntentInfo filter) { 9936 final Iterator<String> actionsIter = filter.actionsIterator(); 9937 while (actionsIter != null && actionsIter.hasNext()) { 9938 final String filterAction = actionsIter.next(); 9939 if (PROTECTED_ACTIONS.contains(filterAction)) { 9940 return true; 9941 } 9942 } 9943 return false; 9944 } 9945 9946 /** 9947 * Adjusts the priority of the given intent filter according to policy. 9948 * <p> 9949 * <ul> 9950 * <li>The priority for non privileged applications is capped to '0'</li> 9951 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9952 * <li>The priority for unbundled updates to privileged applications is capped to the 9953 * priority defined on the system partition</li> 9954 * </ul> 9955 * <p> 9956 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9957 * allowed to obtain any priority on any action. 9958 */ 9959 private void adjustPriority( 9960 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9961 // nothing to do; priority is fine as-is 9962 if (intent.getPriority() <= 0) { 9963 return; 9964 } 9965 9966 final ActivityInfo activityInfo = intent.activity.info; 9967 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9968 9969 final boolean privilegedApp = 9970 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9971 if (!privilegedApp) { 9972 // non-privileged applications can never define a priority >0 9973 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9974 + " package: " + applicationInfo.packageName 9975 + " activity: " + intent.activity.className 9976 + " origPrio: " + intent.getPriority()); 9977 intent.setPriority(0); 9978 return; 9979 } 9980 9981 if (systemActivities == null) { 9982 // the system package is not disabled; we're parsing the system partition 9983 if (isProtectedAction(intent)) { 9984 if (mDeferProtectedFilters) { 9985 // We can't deal with these just yet. No component should ever obtain a 9986 // >0 priority for a protected actions, with ONE exception -- the setup 9987 // wizard. The setup wizard, however, cannot be known until we're able to 9988 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 9989 // until all intent filters have been processed. Chicken, meet egg. 9990 // Let the filter temporarily have a high priority and rectify the 9991 // priorities after all system packages have been scanned. 9992 mProtectedFilters.add(intent); 9993 if (DEBUG_FILTERS) { 9994 Slog.i(TAG, "Protected action; save for later;" 9995 + " package: " + applicationInfo.packageName 9996 + " activity: " + intent.activity.className 9997 + " origPrio: " + intent.getPriority()); 9998 } 9999 return; 10000 } else { 10001 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10002 Slog.i(TAG, "No setup wizard;" 10003 + " All protected intents capped to priority 0"); 10004 } 10005 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10006 if (DEBUG_FILTERS) { 10007 Slog.i(TAG, "Found setup wizard;" 10008 + " allow priority " + intent.getPriority() + ";" 10009 + " package: " + intent.activity.info.packageName 10010 + " activity: " + intent.activity.className 10011 + " priority: " + intent.getPriority()); 10012 } 10013 // setup wizard gets whatever it wants 10014 return; 10015 } 10016 Slog.w(TAG, "Protected action; cap priority to 0;" 10017 + " package: " + intent.activity.info.packageName 10018 + " activity: " + intent.activity.className 10019 + " origPrio: " + intent.getPriority()); 10020 intent.setPriority(0); 10021 return; 10022 } 10023 } 10024 // privileged apps on the system image get whatever priority they request 10025 return; 10026 } 10027 10028 // privileged app unbundled update ... try to find the same activity 10029 final PackageParser.Activity foundActivity = 10030 findMatchingActivity(systemActivities, activityInfo); 10031 if (foundActivity == null) { 10032 // this is a new activity; it cannot obtain >0 priority 10033 if (DEBUG_FILTERS) { 10034 Slog.i(TAG, "New activity; cap priority to 0;" 10035 + " package: " + applicationInfo.packageName 10036 + " activity: " + intent.activity.className 10037 + " origPrio: " + intent.getPriority()); 10038 } 10039 intent.setPriority(0); 10040 return; 10041 } 10042 10043 // found activity, now check for filter equivalence 10044 10045 // a shallow copy is enough; we modify the list, not its contents 10046 final List<ActivityIntentInfo> intentListCopy = 10047 new ArrayList<>(foundActivity.intents); 10048 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10049 10050 // find matching action subsets 10051 final Iterator<String> actionsIterator = intent.actionsIterator(); 10052 if (actionsIterator != null) { 10053 getIntentListSubset( 10054 intentListCopy, new ActionIterGenerator(), actionsIterator); 10055 if (intentListCopy.size() == 0) { 10056 // no more intents to match; we're not equivalent 10057 if (DEBUG_FILTERS) { 10058 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10059 + " package: " + applicationInfo.packageName 10060 + " activity: " + intent.activity.className 10061 + " origPrio: " + intent.getPriority()); 10062 } 10063 intent.setPriority(0); 10064 return; 10065 } 10066 } 10067 10068 // find matching category subsets 10069 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10070 if (categoriesIterator != null) { 10071 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10072 categoriesIterator); 10073 if (intentListCopy.size() == 0) { 10074 // no more intents to match; we're not equivalent 10075 if (DEBUG_FILTERS) { 10076 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10077 + " package: " + applicationInfo.packageName 10078 + " activity: " + intent.activity.className 10079 + " origPrio: " + intent.getPriority()); 10080 } 10081 intent.setPriority(0); 10082 return; 10083 } 10084 } 10085 10086 // find matching schemes subsets 10087 final Iterator<String> schemesIterator = intent.schemesIterator(); 10088 if (schemesIterator != null) { 10089 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10090 schemesIterator); 10091 if (intentListCopy.size() == 0) { 10092 // no more intents to match; we're not equivalent 10093 if (DEBUG_FILTERS) { 10094 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10095 + " package: " + applicationInfo.packageName 10096 + " activity: " + intent.activity.className 10097 + " origPrio: " + intent.getPriority()); 10098 } 10099 intent.setPriority(0); 10100 return; 10101 } 10102 } 10103 10104 // find matching authorities subsets 10105 final Iterator<IntentFilter.AuthorityEntry> 10106 authoritiesIterator = intent.authoritiesIterator(); 10107 if (authoritiesIterator != null) { 10108 getIntentListSubset(intentListCopy, 10109 new AuthoritiesIterGenerator(), 10110 authoritiesIterator); 10111 if (intentListCopy.size() == 0) { 10112 // no more intents to match; we're not equivalent 10113 if (DEBUG_FILTERS) { 10114 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10115 + " package: " + applicationInfo.packageName 10116 + " activity: " + intent.activity.className 10117 + " origPrio: " + intent.getPriority()); 10118 } 10119 intent.setPriority(0); 10120 return; 10121 } 10122 } 10123 10124 // we found matching filter(s); app gets the max priority of all intents 10125 int cappedPriority = 0; 10126 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10127 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10128 } 10129 if (intent.getPriority() > cappedPriority) { 10130 if (DEBUG_FILTERS) { 10131 Slog.i(TAG, "Found matching filter(s);" 10132 + " cap priority to " + cappedPriority + ";" 10133 + " package: " + applicationInfo.packageName 10134 + " activity: " + intent.activity.className 10135 + " origPrio: " + intent.getPriority()); 10136 } 10137 intent.setPriority(cappedPriority); 10138 return; 10139 } 10140 // all this for nothing; the requested priority was <= what was on the system 10141 } 10142 10143 public final void addActivity(PackageParser.Activity a, String type) { 10144 mActivities.put(a.getComponentName(), a); 10145 if (DEBUG_SHOW_INFO) 10146 Log.v( 10147 TAG, " " + type + " " + 10148 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10149 if (DEBUG_SHOW_INFO) 10150 Log.v(TAG, " Class=" + a.info.name); 10151 final int NI = a.intents.size(); 10152 for (int j=0; j<NI; j++) { 10153 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10154 if ("activity".equals(type)) { 10155 final PackageSetting ps = 10156 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10157 final List<PackageParser.Activity> systemActivities = 10158 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10159 adjustPriority(systemActivities, intent); 10160 } 10161 if (DEBUG_SHOW_INFO) { 10162 Log.v(TAG, " IntentFilter:"); 10163 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10164 } 10165 if (!intent.debugCheck()) { 10166 Log.w(TAG, "==> For Activity " + a.info.name); 10167 } 10168 addFilter(intent); 10169 } 10170 } 10171 10172 public final void removeActivity(PackageParser.Activity a, String type) { 10173 mActivities.remove(a.getComponentName()); 10174 if (DEBUG_SHOW_INFO) { 10175 Log.v(TAG, " " + type + " " 10176 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10177 : a.info.name) + ":"); 10178 Log.v(TAG, " Class=" + a.info.name); 10179 } 10180 final int NI = a.intents.size(); 10181 for (int j=0; j<NI; j++) { 10182 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10183 if (DEBUG_SHOW_INFO) { 10184 Log.v(TAG, " IntentFilter:"); 10185 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10186 } 10187 removeFilter(intent); 10188 } 10189 } 10190 10191 @Override 10192 protected boolean allowFilterResult( 10193 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10194 ActivityInfo filterAi = filter.activity.info; 10195 for (int i=dest.size()-1; i>=0; i--) { 10196 ActivityInfo destAi = dest.get(i).activityInfo; 10197 if (destAi.name == filterAi.name 10198 && destAi.packageName == filterAi.packageName) { 10199 return false; 10200 } 10201 } 10202 return true; 10203 } 10204 10205 @Override 10206 protected ActivityIntentInfo[] newArray(int size) { 10207 return new ActivityIntentInfo[size]; 10208 } 10209 10210 @Override 10211 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10212 if (!sUserManager.exists(userId)) return true; 10213 PackageParser.Package p = filter.activity.owner; 10214 if (p != null) { 10215 PackageSetting ps = (PackageSetting)p.mExtras; 10216 if (ps != null) { 10217 // System apps are never considered stopped for purposes of 10218 // filtering, because there may be no way for the user to 10219 // actually re-launch them. 10220 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10221 && ps.getStopped(userId); 10222 } 10223 } 10224 return false; 10225 } 10226 10227 @Override 10228 protected boolean isPackageForFilter(String packageName, 10229 PackageParser.ActivityIntentInfo info) { 10230 return packageName.equals(info.activity.owner.packageName); 10231 } 10232 10233 @Override 10234 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10235 int match, int userId) { 10236 if (!sUserManager.exists(userId)) return null; 10237 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10238 return null; 10239 } 10240 final PackageParser.Activity activity = info.activity; 10241 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10242 if (ps == null) { 10243 return null; 10244 } 10245 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10246 ps.readUserState(userId), userId); 10247 if (ai == null) { 10248 return null; 10249 } 10250 final ResolveInfo res = new ResolveInfo(); 10251 res.activityInfo = ai; 10252 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10253 res.filter = info; 10254 } 10255 if (info != null) { 10256 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10257 } 10258 res.priority = info.getPriority(); 10259 res.preferredOrder = activity.owner.mPreferredOrder; 10260 //System.out.println("Result: " + res.activityInfo.className + 10261 // " = " + res.priority); 10262 res.match = match; 10263 res.isDefault = info.hasDefault; 10264 res.labelRes = info.labelRes; 10265 res.nonLocalizedLabel = info.nonLocalizedLabel; 10266 if (userNeedsBadging(userId)) { 10267 res.noResourceId = true; 10268 } else { 10269 res.icon = info.icon; 10270 } 10271 res.iconResourceId = info.icon; 10272 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10273 return res; 10274 } 10275 10276 @Override 10277 protected void sortResults(List<ResolveInfo> results) { 10278 Collections.sort(results, mResolvePrioritySorter); 10279 } 10280 10281 @Override 10282 protected void dumpFilter(PrintWriter out, String prefix, 10283 PackageParser.ActivityIntentInfo filter) { 10284 out.print(prefix); out.print( 10285 Integer.toHexString(System.identityHashCode(filter.activity))); 10286 out.print(' '); 10287 filter.activity.printComponentShortName(out); 10288 out.print(" filter "); 10289 out.println(Integer.toHexString(System.identityHashCode(filter))); 10290 } 10291 10292 @Override 10293 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10294 return filter.activity; 10295 } 10296 10297 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10298 PackageParser.Activity activity = (PackageParser.Activity)label; 10299 out.print(prefix); out.print( 10300 Integer.toHexString(System.identityHashCode(activity))); 10301 out.print(' '); 10302 activity.printComponentShortName(out); 10303 if (count > 1) { 10304 out.print(" ("); out.print(count); out.print(" filters)"); 10305 } 10306 out.println(); 10307 } 10308 10309 // Keys are String (activity class name), values are Activity. 10310 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10311 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10312 private int mFlags; 10313 } 10314 10315 private final class ServiceIntentResolver 10316 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10317 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10318 boolean defaultOnly, int userId) { 10319 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10320 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10321 } 10322 10323 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10324 int userId) { 10325 if (!sUserManager.exists(userId)) return null; 10326 mFlags = flags; 10327 return super.queryIntent(intent, resolvedType, 10328 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10329 } 10330 10331 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10332 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10333 if (!sUserManager.exists(userId)) return null; 10334 if (packageServices == null) { 10335 return null; 10336 } 10337 mFlags = flags; 10338 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10339 final int N = packageServices.size(); 10340 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10341 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10342 10343 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10344 for (int i = 0; i < N; ++i) { 10345 intentFilters = packageServices.get(i).intents; 10346 if (intentFilters != null && intentFilters.size() > 0) { 10347 PackageParser.ServiceIntentInfo[] array = 10348 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10349 intentFilters.toArray(array); 10350 listCut.add(array); 10351 } 10352 } 10353 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10354 } 10355 10356 public final void addService(PackageParser.Service s) { 10357 mServices.put(s.getComponentName(), s); 10358 if (DEBUG_SHOW_INFO) { 10359 Log.v(TAG, " " 10360 + (s.info.nonLocalizedLabel != null 10361 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10362 Log.v(TAG, " Class=" + s.info.name); 10363 } 10364 final int NI = s.intents.size(); 10365 int j; 10366 for (j=0; j<NI; j++) { 10367 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10368 if (DEBUG_SHOW_INFO) { 10369 Log.v(TAG, " IntentFilter:"); 10370 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10371 } 10372 if (!intent.debugCheck()) { 10373 Log.w(TAG, "==> For Service " + s.info.name); 10374 } 10375 addFilter(intent); 10376 } 10377 } 10378 10379 public final void removeService(PackageParser.Service s) { 10380 mServices.remove(s.getComponentName()); 10381 if (DEBUG_SHOW_INFO) { 10382 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10383 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10384 Log.v(TAG, " Class=" + s.info.name); 10385 } 10386 final int NI = s.intents.size(); 10387 int j; 10388 for (j=0; j<NI; j++) { 10389 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10390 if (DEBUG_SHOW_INFO) { 10391 Log.v(TAG, " IntentFilter:"); 10392 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10393 } 10394 removeFilter(intent); 10395 } 10396 } 10397 10398 @Override 10399 protected boolean allowFilterResult( 10400 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10401 ServiceInfo filterSi = filter.service.info; 10402 for (int i=dest.size()-1; i>=0; i--) { 10403 ServiceInfo destAi = dest.get(i).serviceInfo; 10404 if (destAi.name == filterSi.name 10405 && destAi.packageName == filterSi.packageName) { 10406 return false; 10407 } 10408 } 10409 return true; 10410 } 10411 10412 @Override 10413 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10414 return new PackageParser.ServiceIntentInfo[size]; 10415 } 10416 10417 @Override 10418 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10419 if (!sUserManager.exists(userId)) return true; 10420 PackageParser.Package p = filter.service.owner; 10421 if (p != null) { 10422 PackageSetting ps = (PackageSetting)p.mExtras; 10423 if (ps != null) { 10424 // System apps are never considered stopped for purposes of 10425 // filtering, because there may be no way for the user to 10426 // actually re-launch them. 10427 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10428 && ps.getStopped(userId); 10429 } 10430 } 10431 return false; 10432 } 10433 10434 @Override 10435 protected boolean isPackageForFilter(String packageName, 10436 PackageParser.ServiceIntentInfo info) { 10437 return packageName.equals(info.service.owner.packageName); 10438 } 10439 10440 @Override 10441 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10442 int match, int userId) { 10443 if (!sUserManager.exists(userId)) return null; 10444 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10445 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10446 return null; 10447 } 10448 final PackageParser.Service service = info.service; 10449 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10450 if (ps == null) { 10451 return null; 10452 } 10453 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10454 ps.readUserState(userId), userId); 10455 if (si == null) { 10456 return null; 10457 } 10458 final ResolveInfo res = new ResolveInfo(); 10459 res.serviceInfo = si; 10460 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10461 res.filter = filter; 10462 } 10463 res.priority = info.getPriority(); 10464 res.preferredOrder = service.owner.mPreferredOrder; 10465 res.match = match; 10466 res.isDefault = info.hasDefault; 10467 res.labelRes = info.labelRes; 10468 res.nonLocalizedLabel = info.nonLocalizedLabel; 10469 res.icon = info.icon; 10470 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10471 return res; 10472 } 10473 10474 @Override 10475 protected void sortResults(List<ResolveInfo> results) { 10476 Collections.sort(results, mResolvePrioritySorter); 10477 } 10478 10479 @Override 10480 protected void dumpFilter(PrintWriter out, String prefix, 10481 PackageParser.ServiceIntentInfo filter) { 10482 out.print(prefix); out.print( 10483 Integer.toHexString(System.identityHashCode(filter.service))); 10484 out.print(' '); 10485 filter.service.printComponentShortName(out); 10486 out.print(" filter "); 10487 out.println(Integer.toHexString(System.identityHashCode(filter))); 10488 } 10489 10490 @Override 10491 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10492 return filter.service; 10493 } 10494 10495 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10496 PackageParser.Service service = (PackageParser.Service)label; 10497 out.print(prefix); out.print( 10498 Integer.toHexString(System.identityHashCode(service))); 10499 out.print(' '); 10500 service.printComponentShortName(out); 10501 if (count > 1) { 10502 out.print(" ("); out.print(count); out.print(" filters)"); 10503 } 10504 out.println(); 10505 } 10506 10507// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10508// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10509// final List<ResolveInfo> retList = Lists.newArrayList(); 10510// while (i.hasNext()) { 10511// final ResolveInfo resolveInfo = (ResolveInfo) i; 10512// if (isEnabledLP(resolveInfo.serviceInfo)) { 10513// retList.add(resolveInfo); 10514// } 10515// } 10516// return retList; 10517// } 10518 10519 // Keys are String (activity class name), values are Activity. 10520 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10521 = new ArrayMap<ComponentName, PackageParser.Service>(); 10522 private int mFlags; 10523 }; 10524 10525 private final class ProviderIntentResolver 10526 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10527 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10528 boolean defaultOnly, int userId) { 10529 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10530 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10531 } 10532 10533 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10534 int userId) { 10535 if (!sUserManager.exists(userId)) 10536 return null; 10537 mFlags = flags; 10538 return super.queryIntent(intent, resolvedType, 10539 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10540 } 10541 10542 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10543 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10544 if (!sUserManager.exists(userId)) 10545 return null; 10546 if (packageProviders == null) { 10547 return null; 10548 } 10549 mFlags = flags; 10550 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10551 final int N = packageProviders.size(); 10552 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10553 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10554 10555 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10556 for (int i = 0; i < N; ++i) { 10557 intentFilters = packageProviders.get(i).intents; 10558 if (intentFilters != null && intentFilters.size() > 0) { 10559 PackageParser.ProviderIntentInfo[] array = 10560 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10561 intentFilters.toArray(array); 10562 listCut.add(array); 10563 } 10564 } 10565 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10566 } 10567 10568 public final void addProvider(PackageParser.Provider p) { 10569 if (mProviders.containsKey(p.getComponentName())) { 10570 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10571 return; 10572 } 10573 10574 mProviders.put(p.getComponentName(), p); 10575 if (DEBUG_SHOW_INFO) { 10576 Log.v(TAG, " " 10577 + (p.info.nonLocalizedLabel != null 10578 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10579 Log.v(TAG, " Class=" + p.info.name); 10580 } 10581 final int NI = p.intents.size(); 10582 int j; 10583 for (j = 0; j < NI; j++) { 10584 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10585 if (DEBUG_SHOW_INFO) { 10586 Log.v(TAG, " IntentFilter:"); 10587 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10588 } 10589 if (!intent.debugCheck()) { 10590 Log.w(TAG, "==> For Provider " + p.info.name); 10591 } 10592 addFilter(intent); 10593 } 10594 } 10595 10596 public final void removeProvider(PackageParser.Provider p) { 10597 mProviders.remove(p.getComponentName()); 10598 if (DEBUG_SHOW_INFO) { 10599 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10600 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10601 Log.v(TAG, " Class=" + p.info.name); 10602 } 10603 final int NI = p.intents.size(); 10604 int j; 10605 for (j = 0; j < NI; j++) { 10606 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10607 if (DEBUG_SHOW_INFO) { 10608 Log.v(TAG, " IntentFilter:"); 10609 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10610 } 10611 removeFilter(intent); 10612 } 10613 } 10614 10615 @Override 10616 protected boolean allowFilterResult( 10617 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10618 ProviderInfo filterPi = filter.provider.info; 10619 for (int i = dest.size() - 1; i >= 0; i--) { 10620 ProviderInfo destPi = dest.get(i).providerInfo; 10621 if (destPi.name == filterPi.name 10622 && destPi.packageName == filterPi.packageName) { 10623 return false; 10624 } 10625 } 10626 return true; 10627 } 10628 10629 @Override 10630 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10631 return new PackageParser.ProviderIntentInfo[size]; 10632 } 10633 10634 @Override 10635 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10636 if (!sUserManager.exists(userId)) 10637 return true; 10638 PackageParser.Package p = filter.provider.owner; 10639 if (p != null) { 10640 PackageSetting ps = (PackageSetting) p.mExtras; 10641 if (ps != null) { 10642 // System apps are never considered stopped for purposes of 10643 // filtering, because there may be no way for the user to 10644 // actually re-launch them. 10645 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10646 && ps.getStopped(userId); 10647 } 10648 } 10649 return false; 10650 } 10651 10652 @Override 10653 protected boolean isPackageForFilter(String packageName, 10654 PackageParser.ProviderIntentInfo info) { 10655 return packageName.equals(info.provider.owner.packageName); 10656 } 10657 10658 @Override 10659 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10660 int match, int userId) { 10661 if (!sUserManager.exists(userId)) 10662 return null; 10663 final PackageParser.ProviderIntentInfo info = filter; 10664 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10665 return null; 10666 } 10667 final PackageParser.Provider provider = info.provider; 10668 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10669 if (ps == null) { 10670 return null; 10671 } 10672 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10673 ps.readUserState(userId), userId); 10674 if (pi == null) { 10675 return null; 10676 } 10677 final ResolveInfo res = new ResolveInfo(); 10678 res.providerInfo = pi; 10679 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10680 res.filter = filter; 10681 } 10682 res.priority = info.getPriority(); 10683 res.preferredOrder = provider.owner.mPreferredOrder; 10684 res.match = match; 10685 res.isDefault = info.hasDefault; 10686 res.labelRes = info.labelRes; 10687 res.nonLocalizedLabel = info.nonLocalizedLabel; 10688 res.icon = info.icon; 10689 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10690 return res; 10691 } 10692 10693 @Override 10694 protected void sortResults(List<ResolveInfo> results) { 10695 Collections.sort(results, mResolvePrioritySorter); 10696 } 10697 10698 @Override 10699 protected void dumpFilter(PrintWriter out, String prefix, 10700 PackageParser.ProviderIntentInfo filter) { 10701 out.print(prefix); 10702 out.print( 10703 Integer.toHexString(System.identityHashCode(filter.provider))); 10704 out.print(' '); 10705 filter.provider.printComponentShortName(out); 10706 out.print(" filter "); 10707 out.println(Integer.toHexString(System.identityHashCode(filter))); 10708 } 10709 10710 @Override 10711 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10712 return filter.provider; 10713 } 10714 10715 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10716 PackageParser.Provider provider = (PackageParser.Provider)label; 10717 out.print(prefix); out.print( 10718 Integer.toHexString(System.identityHashCode(provider))); 10719 out.print(' '); 10720 provider.printComponentShortName(out); 10721 if (count > 1) { 10722 out.print(" ("); out.print(count); out.print(" filters)"); 10723 } 10724 out.println(); 10725 } 10726 10727 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10728 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10729 private int mFlags; 10730 } 10731 10732 private static final class EphemeralIntentResolver 10733 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10734 @Override 10735 protected EphemeralResolveIntentInfo[] newArray(int size) { 10736 return new EphemeralResolveIntentInfo[size]; 10737 } 10738 10739 @Override 10740 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10741 return true; 10742 } 10743 10744 @Override 10745 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10746 int userId) { 10747 if (!sUserManager.exists(userId)) { 10748 return null; 10749 } 10750 return info.getEphemeralResolveInfo(); 10751 } 10752 } 10753 10754 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10755 new Comparator<ResolveInfo>() { 10756 public int compare(ResolveInfo r1, ResolveInfo r2) { 10757 int v1 = r1.priority; 10758 int v2 = r2.priority; 10759 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10760 if (v1 != v2) { 10761 return (v1 > v2) ? -1 : 1; 10762 } 10763 v1 = r1.preferredOrder; 10764 v2 = r2.preferredOrder; 10765 if (v1 != v2) { 10766 return (v1 > v2) ? -1 : 1; 10767 } 10768 if (r1.isDefault != r2.isDefault) { 10769 return r1.isDefault ? -1 : 1; 10770 } 10771 v1 = r1.match; 10772 v2 = r2.match; 10773 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10774 if (v1 != v2) { 10775 return (v1 > v2) ? -1 : 1; 10776 } 10777 if (r1.system != r2.system) { 10778 return r1.system ? -1 : 1; 10779 } 10780 if (r1.activityInfo != null) { 10781 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10782 } 10783 if (r1.serviceInfo != null) { 10784 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10785 } 10786 if (r1.providerInfo != null) { 10787 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10788 } 10789 return 0; 10790 } 10791 }; 10792 10793 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10794 new Comparator<ProviderInfo>() { 10795 public int compare(ProviderInfo p1, ProviderInfo p2) { 10796 final int v1 = p1.initOrder; 10797 final int v2 = p2.initOrder; 10798 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10799 } 10800 }; 10801 10802 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10803 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10804 final int[] userIds) { 10805 mHandler.post(new Runnable() { 10806 @Override 10807 public void run() { 10808 try { 10809 final IActivityManager am = ActivityManagerNative.getDefault(); 10810 if (am == null) return; 10811 final int[] resolvedUserIds; 10812 if (userIds == null) { 10813 resolvedUserIds = am.getRunningUserIds(); 10814 } else { 10815 resolvedUserIds = userIds; 10816 } 10817 for (int id : resolvedUserIds) { 10818 final Intent intent = new Intent(action, 10819 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10820 if (extras != null) { 10821 intent.putExtras(extras); 10822 } 10823 if (targetPkg != null) { 10824 intent.setPackage(targetPkg); 10825 } 10826 // Modify the UID when posting to other users 10827 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10828 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10829 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10830 intent.putExtra(Intent.EXTRA_UID, uid); 10831 } 10832 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10833 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10834 if (DEBUG_BROADCASTS) { 10835 RuntimeException here = new RuntimeException("here"); 10836 here.fillInStackTrace(); 10837 Slog.d(TAG, "Sending to user " + id + ": " 10838 + intent.toShortString(false, true, false, false) 10839 + " " + intent.getExtras(), here); 10840 } 10841 am.broadcastIntent(null, intent, null, finishedReceiver, 10842 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10843 null, finishedReceiver != null, false, id); 10844 } 10845 } catch (RemoteException ex) { 10846 } 10847 } 10848 }); 10849 } 10850 10851 /** 10852 * Check if the external storage media is available. This is true if there 10853 * is a mounted external storage medium or if the external storage is 10854 * emulated. 10855 */ 10856 private boolean isExternalMediaAvailable() { 10857 return mMediaMounted || Environment.isExternalStorageEmulated(); 10858 } 10859 10860 @Override 10861 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10862 // writer 10863 synchronized (mPackages) { 10864 if (!isExternalMediaAvailable()) { 10865 // If the external storage is no longer mounted at this point, 10866 // the caller may not have been able to delete all of this 10867 // packages files and can not delete any more. Bail. 10868 return null; 10869 } 10870 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10871 if (lastPackage != null) { 10872 pkgs.remove(lastPackage); 10873 } 10874 if (pkgs.size() > 0) { 10875 return pkgs.get(0); 10876 } 10877 } 10878 return null; 10879 } 10880 10881 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10882 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10883 userId, andCode ? 1 : 0, packageName); 10884 if (mSystemReady) { 10885 msg.sendToTarget(); 10886 } else { 10887 if (mPostSystemReadyMessages == null) { 10888 mPostSystemReadyMessages = new ArrayList<>(); 10889 } 10890 mPostSystemReadyMessages.add(msg); 10891 } 10892 } 10893 10894 void startCleaningPackages() { 10895 // reader 10896 if (!isExternalMediaAvailable()) { 10897 return; 10898 } 10899 synchronized (mPackages) { 10900 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10901 return; 10902 } 10903 } 10904 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10905 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10906 IActivityManager am = ActivityManagerNative.getDefault(); 10907 if (am != null) { 10908 try { 10909 am.startService(null, intent, null, mContext.getOpPackageName(), 10910 UserHandle.USER_SYSTEM); 10911 } catch (RemoteException e) { 10912 } 10913 } 10914 } 10915 10916 @Override 10917 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10918 int installFlags, String installerPackageName, int userId) { 10919 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10920 10921 final int callingUid = Binder.getCallingUid(); 10922 enforceCrossUserPermission(callingUid, userId, 10923 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10924 10925 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10926 try { 10927 if (observer != null) { 10928 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10929 } 10930 } catch (RemoteException re) { 10931 } 10932 return; 10933 } 10934 10935 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10936 installFlags |= PackageManager.INSTALL_FROM_ADB; 10937 10938 } else { 10939 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10940 // about installerPackageName. 10941 10942 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10943 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10944 } 10945 10946 UserHandle user; 10947 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10948 user = UserHandle.ALL; 10949 } else { 10950 user = new UserHandle(userId); 10951 } 10952 10953 // Only system components can circumvent runtime permissions when installing. 10954 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10955 && mContext.checkCallingOrSelfPermission(Manifest.permission 10956 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10957 throw new SecurityException("You need the " 10958 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10959 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10960 } 10961 10962 final File originFile = new File(originPath); 10963 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10964 10965 final Message msg = mHandler.obtainMessage(INIT_COPY); 10966 final VerificationInfo verificationInfo = new VerificationInfo( 10967 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10968 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10969 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10970 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10971 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10972 msg.obj = params; 10973 10974 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10975 System.identityHashCode(msg.obj)); 10976 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10977 System.identityHashCode(msg.obj)); 10978 10979 mHandler.sendMessage(msg); 10980 } 10981 10982 void installStage(String packageName, File stagedDir, String stagedCid, 10983 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10984 String installerPackageName, int installerUid, UserHandle user) { 10985 if (DEBUG_EPHEMERAL) { 10986 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10987 Slog.d(TAG, "Ephemeral install of " + packageName); 10988 } 10989 } 10990 final VerificationInfo verificationInfo = new VerificationInfo( 10991 sessionParams.originatingUri, sessionParams.referrerUri, 10992 sessionParams.originatingUid, installerUid); 10993 10994 final OriginInfo origin; 10995 if (stagedDir != null) { 10996 origin = OriginInfo.fromStagedFile(stagedDir); 10997 } else { 10998 origin = OriginInfo.fromStagedContainer(stagedCid); 10999 } 11000 11001 final Message msg = mHandler.obtainMessage(INIT_COPY); 11002 final InstallParams params = new InstallParams(origin, null, observer, 11003 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11004 verificationInfo, user, sessionParams.abiOverride, 11005 sessionParams.grantedRuntimePermissions); 11006 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11007 msg.obj = params; 11008 11009 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11010 System.identityHashCode(msg.obj)); 11011 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11012 System.identityHashCode(msg.obj)); 11013 11014 mHandler.sendMessage(msg); 11015 } 11016 11017 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11018 int userId) { 11019 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11020 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11021 } 11022 11023 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11024 int appId, int userId) { 11025 Bundle extras = new Bundle(1); 11026 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11027 11028 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11029 packageName, extras, 0, null, null, new int[] {userId}); 11030 try { 11031 IActivityManager am = ActivityManagerNative.getDefault(); 11032 if (isSystem && am.isUserRunning(userId, 0)) { 11033 // The just-installed/enabled app is bundled on the system, so presumed 11034 // to be able to run automatically without needing an explicit launch. 11035 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11036 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11037 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11038 .setPackage(packageName); 11039 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11040 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11041 } 11042 } catch (RemoteException e) { 11043 // shouldn't happen 11044 Slog.w(TAG, "Unable to bootstrap installed package", e); 11045 } 11046 } 11047 11048 @Override 11049 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11050 int userId) { 11051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11052 PackageSetting pkgSetting; 11053 final int uid = Binder.getCallingUid(); 11054 enforceCrossUserPermission(uid, userId, 11055 true /* requireFullPermission */, true /* checkShell */, 11056 "setApplicationHiddenSetting for user " + userId); 11057 11058 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11059 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11060 return false; 11061 } 11062 11063 long callingId = Binder.clearCallingIdentity(); 11064 try { 11065 boolean sendAdded = false; 11066 boolean sendRemoved = false; 11067 // writer 11068 synchronized (mPackages) { 11069 pkgSetting = mSettings.mPackages.get(packageName); 11070 if (pkgSetting == null) { 11071 return false; 11072 } 11073 if (pkgSetting.getHidden(userId) != hidden) { 11074 pkgSetting.setHidden(hidden, userId); 11075 mSettings.writePackageRestrictionsLPr(userId); 11076 if (hidden) { 11077 sendRemoved = true; 11078 } else { 11079 sendAdded = true; 11080 } 11081 } 11082 } 11083 if (sendAdded) { 11084 sendPackageAddedForUser(packageName, pkgSetting, userId); 11085 return true; 11086 } 11087 if (sendRemoved) { 11088 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11089 "hiding pkg"); 11090 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11091 return true; 11092 } 11093 } finally { 11094 Binder.restoreCallingIdentity(callingId); 11095 } 11096 return false; 11097 } 11098 11099 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11100 int userId) { 11101 final PackageRemovedInfo info = new PackageRemovedInfo(); 11102 info.removedPackage = packageName; 11103 info.removedUsers = new int[] {userId}; 11104 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11105 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11106 } 11107 11108 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11109 if (pkgList.length > 0) { 11110 Bundle extras = new Bundle(1); 11111 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11112 11113 sendPackageBroadcast( 11114 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11115 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11116 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11117 new int[] {userId}); 11118 } 11119 } 11120 11121 /** 11122 * Returns true if application is not found or there was an error. Otherwise it returns 11123 * the hidden state of the package for the given user. 11124 */ 11125 @Override 11126 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11129 true /* requireFullPermission */, false /* checkShell */, 11130 "getApplicationHidden for user " + userId); 11131 PackageSetting pkgSetting; 11132 long callingId = Binder.clearCallingIdentity(); 11133 try { 11134 // writer 11135 synchronized (mPackages) { 11136 pkgSetting = mSettings.mPackages.get(packageName); 11137 if (pkgSetting == null) { 11138 return true; 11139 } 11140 return pkgSetting.getHidden(userId); 11141 } 11142 } finally { 11143 Binder.restoreCallingIdentity(callingId); 11144 } 11145 } 11146 11147 /** 11148 * @hide 11149 */ 11150 @Override 11151 public int installExistingPackageAsUser(String packageName, int userId) { 11152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11153 null); 11154 PackageSetting pkgSetting; 11155 final int uid = Binder.getCallingUid(); 11156 enforceCrossUserPermission(uid, userId, 11157 true /* requireFullPermission */, true /* checkShell */, 11158 "installExistingPackage for user " + userId); 11159 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11160 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11161 } 11162 11163 long callingId = Binder.clearCallingIdentity(); 11164 try { 11165 boolean installed = false; 11166 11167 // writer 11168 synchronized (mPackages) { 11169 pkgSetting = mSettings.mPackages.get(packageName); 11170 if (pkgSetting == null) { 11171 return PackageManager.INSTALL_FAILED_INVALID_URI; 11172 } 11173 if (!pkgSetting.getInstalled(userId)) { 11174 pkgSetting.setInstalled(true, userId); 11175 pkgSetting.setHidden(false, userId); 11176 mSettings.writePackageRestrictionsLPr(userId); 11177 installed = true; 11178 } 11179 } 11180 11181 if (installed) { 11182 if (pkgSetting.pkg != null) { 11183 prepareAppDataAfterInstall(pkgSetting.pkg); 11184 } 11185 sendPackageAddedForUser(packageName, pkgSetting, userId); 11186 } 11187 } finally { 11188 Binder.restoreCallingIdentity(callingId); 11189 } 11190 11191 return PackageManager.INSTALL_SUCCEEDED; 11192 } 11193 11194 boolean isUserRestricted(int userId, String restrictionKey) { 11195 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11196 if (restrictions.getBoolean(restrictionKey, false)) { 11197 Log.w(TAG, "User is restricted: " + restrictionKey); 11198 return true; 11199 } 11200 return false; 11201 } 11202 11203 @Override 11204 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11205 int userId) { 11206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11207 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11208 true /* requireFullPermission */, true /* checkShell */, 11209 "setPackagesSuspended for user " + userId); 11210 11211 if (ArrayUtils.isEmpty(packageNames)) { 11212 return packageNames; 11213 } 11214 11215 // List of package names for whom the suspended state has changed. 11216 List<String> changedPackages = new ArrayList<>(packageNames.length); 11217 // List of package names for whom the suspended state is not set as requested in this 11218 // method. 11219 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11220 for (int i = 0; i < packageNames.length; i++) { 11221 String packageName = packageNames[i]; 11222 long callingId = Binder.clearCallingIdentity(); 11223 try { 11224 boolean changed = false; 11225 final int appId; 11226 synchronized (mPackages) { 11227 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11228 if (pkgSetting == null) { 11229 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11230 + "\". Skipping suspending/un-suspending."); 11231 unactionedPackages.add(packageName); 11232 continue; 11233 } 11234 appId = pkgSetting.appId; 11235 if (pkgSetting.getSuspended(userId) != suspended) { 11236 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11237 unactionedPackages.add(packageName); 11238 continue; 11239 } 11240 pkgSetting.setSuspended(suspended, userId); 11241 mSettings.writePackageRestrictionsLPr(userId); 11242 changed = true; 11243 changedPackages.add(packageName); 11244 } 11245 } 11246 11247 if (changed && suspended) { 11248 killApplication(packageName, UserHandle.getUid(userId, appId), 11249 "suspending package"); 11250 } 11251 } finally { 11252 Binder.restoreCallingIdentity(callingId); 11253 } 11254 } 11255 11256 if (!changedPackages.isEmpty()) { 11257 sendPackagesSuspendedForUser(changedPackages.toArray( 11258 new String[changedPackages.size()]), userId, suspended); 11259 } 11260 11261 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11262 } 11263 11264 @Override 11265 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11267 true /* requireFullPermission */, false /* checkShell */, 11268 "isPackageSuspendedForUser for user " + userId); 11269 synchronized (mPackages) { 11270 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11271 if (pkgSetting == null) { 11272 throw new IllegalArgumentException("Unknown target package: " + packageName); 11273 } 11274 return pkgSetting.getSuspended(userId); 11275 } 11276 } 11277 11278 /** 11279 * TODO: cache and disallow blocking the active dialer. 11280 * 11281 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11282 */ 11283 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11284 if (isPackageDeviceAdmin(packageName, userId)) { 11285 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11286 + "\": has an active device admin"); 11287 return false; 11288 } 11289 11290 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11291 if (packageName.equals(activeLauncherPackageName)) { 11292 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11293 + "\": contains the active launcher"); 11294 return false; 11295 } 11296 11297 if (packageName.equals(mRequiredInstallerPackage)) { 11298 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11299 + "\": required for package installation"); 11300 return false; 11301 } 11302 11303 if (packageName.equals(mRequiredVerifierPackage)) { 11304 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11305 + "\": required for package verification"); 11306 return false; 11307 } 11308 11309 final PackageParser.Package pkg = mPackages.get(packageName); 11310 if (pkg != null && isPrivilegedApp(pkg)) { 11311 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11312 + "\": is a privileged app"); 11313 return false; 11314 } 11315 11316 return true; 11317 } 11318 11319 private String getActiveLauncherPackageName(int userId) { 11320 Intent intent = new Intent(Intent.ACTION_MAIN); 11321 intent.addCategory(Intent.CATEGORY_HOME); 11322 ResolveInfo resolveInfo = resolveIntent( 11323 intent, 11324 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11325 PackageManager.MATCH_DEFAULT_ONLY, 11326 userId); 11327 11328 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11329 } 11330 11331 @Override 11332 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11333 mContext.enforceCallingOrSelfPermission( 11334 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11335 "Only package verification agents can verify applications"); 11336 11337 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11338 final PackageVerificationResponse response = new PackageVerificationResponse( 11339 verificationCode, Binder.getCallingUid()); 11340 msg.arg1 = id; 11341 msg.obj = response; 11342 mHandler.sendMessage(msg); 11343 } 11344 11345 @Override 11346 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11347 long millisecondsToDelay) { 11348 mContext.enforceCallingOrSelfPermission( 11349 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11350 "Only package verification agents can extend verification timeouts"); 11351 11352 final PackageVerificationState state = mPendingVerification.get(id); 11353 final PackageVerificationResponse response = new PackageVerificationResponse( 11354 verificationCodeAtTimeout, Binder.getCallingUid()); 11355 11356 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11357 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11358 } 11359 if (millisecondsToDelay < 0) { 11360 millisecondsToDelay = 0; 11361 } 11362 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11363 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11364 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11365 } 11366 11367 if ((state != null) && !state.timeoutExtended()) { 11368 state.extendTimeout(); 11369 11370 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11371 msg.arg1 = id; 11372 msg.obj = response; 11373 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11374 } 11375 } 11376 11377 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11378 int verificationCode, UserHandle user) { 11379 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11380 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11381 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11382 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11383 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11384 11385 mContext.sendBroadcastAsUser(intent, user, 11386 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11387 } 11388 11389 private ComponentName matchComponentForVerifier(String packageName, 11390 List<ResolveInfo> receivers) { 11391 ActivityInfo targetReceiver = null; 11392 11393 final int NR = receivers.size(); 11394 for (int i = 0; i < NR; i++) { 11395 final ResolveInfo info = receivers.get(i); 11396 if (info.activityInfo == null) { 11397 continue; 11398 } 11399 11400 if (packageName.equals(info.activityInfo.packageName)) { 11401 targetReceiver = info.activityInfo; 11402 break; 11403 } 11404 } 11405 11406 if (targetReceiver == null) { 11407 return null; 11408 } 11409 11410 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11411 } 11412 11413 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11414 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11415 if (pkgInfo.verifiers.length == 0) { 11416 return null; 11417 } 11418 11419 final int N = pkgInfo.verifiers.length; 11420 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11421 for (int i = 0; i < N; i++) { 11422 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11423 11424 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11425 receivers); 11426 if (comp == null) { 11427 continue; 11428 } 11429 11430 final int verifierUid = getUidForVerifier(verifierInfo); 11431 if (verifierUid == -1) { 11432 continue; 11433 } 11434 11435 if (DEBUG_VERIFY) { 11436 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11437 + " with the correct signature"); 11438 } 11439 sufficientVerifiers.add(comp); 11440 verificationState.addSufficientVerifier(verifierUid); 11441 } 11442 11443 return sufficientVerifiers; 11444 } 11445 11446 private int getUidForVerifier(VerifierInfo verifierInfo) { 11447 synchronized (mPackages) { 11448 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11449 if (pkg == null) { 11450 return -1; 11451 } else if (pkg.mSignatures.length != 1) { 11452 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11453 + " has more than one signature; ignoring"); 11454 return -1; 11455 } 11456 11457 /* 11458 * If the public key of the package's signature does not match 11459 * our expected public key, then this is a different package and 11460 * we should skip. 11461 */ 11462 11463 final byte[] expectedPublicKey; 11464 try { 11465 final Signature verifierSig = pkg.mSignatures[0]; 11466 final PublicKey publicKey = verifierSig.getPublicKey(); 11467 expectedPublicKey = publicKey.getEncoded(); 11468 } catch (CertificateException e) { 11469 return -1; 11470 } 11471 11472 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11473 11474 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11475 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11476 + " does not have the expected public key; ignoring"); 11477 return -1; 11478 } 11479 11480 return pkg.applicationInfo.uid; 11481 } 11482 } 11483 11484 @Override 11485 public void finishPackageInstall(int token) { 11486 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11487 11488 if (DEBUG_INSTALL) { 11489 Slog.v(TAG, "BM finishing package install for " + token); 11490 } 11491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11492 11493 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11494 mHandler.sendMessage(msg); 11495 } 11496 11497 /** 11498 * Get the verification agent timeout. 11499 * 11500 * @return verification timeout in milliseconds 11501 */ 11502 private long getVerificationTimeout() { 11503 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11504 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11505 DEFAULT_VERIFICATION_TIMEOUT); 11506 } 11507 11508 /** 11509 * Get the default verification agent response code. 11510 * 11511 * @return default verification response code 11512 */ 11513 private int getDefaultVerificationResponse() { 11514 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11515 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11516 DEFAULT_VERIFICATION_RESPONSE); 11517 } 11518 11519 /** 11520 * Check whether or not package verification has been enabled. 11521 * 11522 * @return true if verification should be performed 11523 */ 11524 private boolean isVerificationEnabled(int userId, int installFlags) { 11525 if (!DEFAULT_VERIFY_ENABLE) { 11526 return false; 11527 } 11528 // Ephemeral apps don't get the full verification treatment 11529 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11530 if (DEBUG_EPHEMERAL) { 11531 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11532 } 11533 return false; 11534 } 11535 11536 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11537 11538 // Check if installing from ADB 11539 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11540 // Do not run verification in a test harness environment 11541 if (ActivityManager.isRunningInTestHarness()) { 11542 return false; 11543 } 11544 if (ensureVerifyAppsEnabled) { 11545 return true; 11546 } 11547 // Check if the developer does not want package verification for ADB installs 11548 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11549 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11550 return false; 11551 } 11552 } 11553 11554 if (ensureVerifyAppsEnabled) { 11555 return true; 11556 } 11557 11558 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11559 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11560 } 11561 11562 @Override 11563 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11564 throws RemoteException { 11565 mContext.enforceCallingOrSelfPermission( 11566 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11567 "Only intentfilter verification agents can verify applications"); 11568 11569 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11570 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11571 Binder.getCallingUid(), verificationCode, failedDomains); 11572 msg.arg1 = id; 11573 msg.obj = response; 11574 mHandler.sendMessage(msg); 11575 } 11576 11577 @Override 11578 public int getIntentVerificationStatus(String packageName, int userId) { 11579 synchronized (mPackages) { 11580 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11581 } 11582 } 11583 11584 @Override 11585 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11586 mContext.enforceCallingOrSelfPermission( 11587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11588 11589 boolean result = false; 11590 synchronized (mPackages) { 11591 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11592 } 11593 if (result) { 11594 scheduleWritePackageRestrictionsLocked(userId); 11595 } 11596 return result; 11597 } 11598 11599 @Override 11600 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11601 String packageName) { 11602 synchronized (mPackages) { 11603 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11604 } 11605 } 11606 11607 @Override 11608 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11609 if (TextUtils.isEmpty(packageName)) { 11610 return ParceledListSlice.emptyList(); 11611 } 11612 synchronized (mPackages) { 11613 PackageParser.Package pkg = mPackages.get(packageName); 11614 if (pkg == null || pkg.activities == null) { 11615 return ParceledListSlice.emptyList(); 11616 } 11617 final int count = pkg.activities.size(); 11618 ArrayList<IntentFilter> result = new ArrayList<>(); 11619 for (int n=0; n<count; n++) { 11620 PackageParser.Activity activity = pkg.activities.get(n); 11621 if (activity.intents != null && activity.intents.size() > 0) { 11622 result.addAll(activity.intents); 11623 } 11624 } 11625 return new ParceledListSlice<>(result); 11626 } 11627 } 11628 11629 @Override 11630 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11631 mContext.enforceCallingOrSelfPermission( 11632 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11633 11634 synchronized (mPackages) { 11635 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11636 if (packageName != null) { 11637 result |= updateIntentVerificationStatus(packageName, 11638 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11639 userId); 11640 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11641 packageName, userId); 11642 } 11643 return result; 11644 } 11645 } 11646 11647 @Override 11648 public String getDefaultBrowserPackageName(int userId) { 11649 synchronized (mPackages) { 11650 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11651 } 11652 } 11653 11654 /** 11655 * Get the "allow unknown sources" setting. 11656 * 11657 * @return the current "allow unknown sources" setting 11658 */ 11659 private int getUnknownSourcesSettings() { 11660 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11661 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11662 -1); 11663 } 11664 11665 @Override 11666 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11667 final int uid = Binder.getCallingUid(); 11668 // writer 11669 synchronized (mPackages) { 11670 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11671 if (targetPackageSetting == null) { 11672 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11673 } 11674 11675 PackageSetting installerPackageSetting; 11676 if (installerPackageName != null) { 11677 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11678 if (installerPackageSetting == null) { 11679 throw new IllegalArgumentException("Unknown installer package: " 11680 + installerPackageName); 11681 } 11682 } else { 11683 installerPackageSetting = null; 11684 } 11685 11686 Signature[] callerSignature; 11687 Object obj = mSettings.getUserIdLPr(uid); 11688 if (obj != null) { 11689 if (obj instanceof SharedUserSetting) { 11690 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11691 } else if (obj instanceof PackageSetting) { 11692 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11693 } else { 11694 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11695 } 11696 } else { 11697 throw new SecurityException("Unknown calling UID: " + uid); 11698 } 11699 11700 // Verify: can't set installerPackageName to a package that is 11701 // not signed with the same cert as the caller. 11702 if (installerPackageSetting != null) { 11703 if (compareSignatures(callerSignature, 11704 installerPackageSetting.signatures.mSignatures) 11705 != PackageManager.SIGNATURE_MATCH) { 11706 throw new SecurityException( 11707 "Caller does not have same cert as new installer package " 11708 + installerPackageName); 11709 } 11710 } 11711 11712 // Verify: if target already has an installer package, it must 11713 // be signed with the same cert as the caller. 11714 if (targetPackageSetting.installerPackageName != null) { 11715 PackageSetting setting = mSettings.mPackages.get( 11716 targetPackageSetting.installerPackageName); 11717 // If the currently set package isn't valid, then it's always 11718 // okay to change it. 11719 if (setting != null) { 11720 if (compareSignatures(callerSignature, 11721 setting.signatures.mSignatures) 11722 != PackageManager.SIGNATURE_MATCH) { 11723 throw new SecurityException( 11724 "Caller does not have same cert as old installer package " 11725 + targetPackageSetting.installerPackageName); 11726 } 11727 } 11728 } 11729 11730 // Okay! 11731 targetPackageSetting.installerPackageName = installerPackageName; 11732 scheduleWriteSettingsLocked(); 11733 } 11734 } 11735 11736 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11737 // Queue up an async operation since the package installation may take a little while. 11738 mHandler.post(new Runnable() { 11739 public void run() { 11740 mHandler.removeCallbacks(this); 11741 // Result object to be returned 11742 PackageInstalledInfo res = new PackageInstalledInfo(); 11743 res.setReturnCode(currentStatus); 11744 res.uid = -1; 11745 res.pkg = null; 11746 res.removedInfo = null; 11747 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11748 args.doPreInstall(res.returnCode); 11749 synchronized (mInstallLock) { 11750 installPackageTracedLI(args, res); 11751 } 11752 args.doPostInstall(res.returnCode, res.uid); 11753 } 11754 11755 // A restore should be performed at this point if (a) the install 11756 // succeeded, (b) the operation is not an update, and (c) the new 11757 // package has not opted out of backup participation. 11758 final boolean update = res.removedInfo != null 11759 && res.removedInfo.removedPackage != null; 11760 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11761 boolean doRestore = !update 11762 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11763 11764 // Set up the post-install work request bookkeeping. This will be used 11765 // and cleaned up by the post-install event handling regardless of whether 11766 // there's a restore pass performed. Token values are >= 1. 11767 int token; 11768 if (mNextInstallToken < 0) mNextInstallToken = 1; 11769 token = mNextInstallToken++; 11770 11771 PostInstallData data = new PostInstallData(args, res); 11772 mRunningInstalls.put(token, data); 11773 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11774 11775 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11776 // Pass responsibility to the Backup Manager. It will perform a 11777 // restore if appropriate, then pass responsibility back to the 11778 // Package Manager to run the post-install observer callbacks 11779 // and broadcasts. 11780 IBackupManager bm = IBackupManager.Stub.asInterface( 11781 ServiceManager.getService(Context.BACKUP_SERVICE)); 11782 if (bm != null) { 11783 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11784 + " to BM for possible restore"); 11785 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11786 try { 11787 // TODO: http://b/22388012 11788 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11789 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11790 } else { 11791 doRestore = false; 11792 } 11793 } catch (RemoteException e) { 11794 // can't happen; the backup manager is local 11795 } catch (Exception e) { 11796 Slog.e(TAG, "Exception trying to enqueue restore", e); 11797 doRestore = false; 11798 } 11799 } else { 11800 Slog.e(TAG, "Backup Manager not found!"); 11801 doRestore = false; 11802 } 11803 } 11804 11805 if (!doRestore) { 11806 // No restore possible, or the Backup Manager was mysteriously not 11807 // available -- just fire the post-install work request directly. 11808 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11809 11810 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11811 11812 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11813 mHandler.sendMessage(msg); 11814 } 11815 } 11816 }); 11817 } 11818 11819 private abstract class HandlerParams { 11820 private static final int MAX_RETRIES = 4; 11821 11822 /** 11823 * Number of times startCopy() has been attempted and had a non-fatal 11824 * error. 11825 */ 11826 private int mRetries = 0; 11827 11828 /** User handle for the user requesting the information or installation. */ 11829 private final UserHandle mUser; 11830 String traceMethod; 11831 int traceCookie; 11832 11833 HandlerParams(UserHandle user) { 11834 mUser = user; 11835 } 11836 11837 UserHandle getUser() { 11838 return mUser; 11839 } 11840 11841 HandlerParams setTraceMethod(String traceMethod) { 11842 this.traceMethod = traceMethod; 11843 return this; 11844 } 11845 11846 HandlerParams setTraceCookie(int traceCookie) { 11847 this.traceCookie = traceCookie; 11848 return this; 11849 } 11850 11851 final boolean startCopy() { 11852 boolean res; 11853 try { 11854 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11855 11856 if (++mRetries > MAX_RETRIES) { 11857 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11858 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11859 handleServiceError(); 11860 return false; 11861 } else { 11862 handleStartCopy(); 11863 res = true; 11864 } 11865 } catch (RemoteException e) { 11866 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11867 mHandler.sendEmptyMessage(MCS_RECONNECT); 11868 res = false; 11869 } 11870 handleReturnCode(); 11871 return res; 11872 } 11873 11874 final void serviceError() { 11875 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11876 handleServiceError(); 11877 handleReturnCode(); 11878 } 11879 11880 abstract void handleStartCopy() throws RemoteException; 11881 abstract void handleServiceError(); 11882 abstract void handleReturnCode(); 11883 } 11884 11885 class MeasureParams extends HandlerParams { 11886 private final PackageStats mStats; 11887 private boolean mSuccess; 11888 11889 private final IPackageStatsObserver mObserver; 11890 11891 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11892 super(new UserHandle(stats.userHandle)); 11893 mObserver = observer; 11894 mStats = stats; 11895 } 11896 11897 @Override 11898 public String toString() { 11899 return "MeasureParams{" 11900 + Integer.toHexString(System.identityHashCode(this)) 11901 + " " + mStats.packageName + "}"; 11902 } 11903 11904 @Override 11905 void handleStartCopy() throws RemoteException { 11906 synchronized (mInstallLock) { 11907 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11908 } 11909 11910 if (mSuccess) { 11911 final boolean mounted; 11912 if (Environment.isExternalStorageEmulated()) { 11913 mounted = true; 11914 } else { 11915 final String status = Environment.getExternalStorageState(); 11916 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11917 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11918 } 11919 11920 if (mounted) { 11921 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11922 11923 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11924 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11925 11926 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11927 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11928 11929 // Always subtract cache size, since it's a subdirectory 11930 mStats.externalDataSize -= mStats.externalCacheSize; 11931 11932 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11933 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11934 11935 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11936 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11937 } 11938 } 11939 } 11940 11941 @Override 11942 void handleReturnCode() { 11943 if (mObserver != null) { 11944 try { 11945 mObserver.onGetStatsCompleted(mStats, mSuccess); 11946 } catch (RemoteException e) { 11947 Slog.i(TAG, "Observer no longer exists."); 11948 } 11949 } 11950 } 11951 11952 @Override 11953 void handleServiceError() { 11954 Slog.e(TAG, "Could not measure application " + mStats.packageName 11955 + " external storage"); 11956 } 11957 } 11958 11959 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11960 throws RemoteException { 11961 long result = 0; 11962 for (File path : paths) { 11963 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11964 } 11965 return result; 11966 } 11967 11968 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11969 for (File path : paths) { 11970 try { 11971 mcs.clearDirectory(path.getAbsolutePath()); 11972 } catch (RemoteException e) { 11973 } 11974 } 11975 } 11976 11977 static class OriginInfo { 11978 /** 11979 * Location where install is coming from, before it has been 11980 * copied/renamed into place. This could be a single monolithic APK 11981 * file, or a cluster directory. This location may be untrusted. 11982 */ 11983 final File file; 11984 final String cid; 11985 11986 /** 11987 * Flag indicating that {@link #file} or {@link #cid} has already been 11988 * staged, meaning downstream users don't need to defensively copy the 11989 * contents. 11990 */ 11991 final boolean staged; 11992 11993 /** 11994 * Flag indicating that {@link #file} or {@link #cid} is an already 11995 * installed app that is being moved. 11996 */ 11997 final boolean existing; 11998 11999 final String resolvedPath; 12000 final File resolvedFile; 12001 12002 static OriginInfo fromNothing() { 12003 return new OriginInfo(null, null, false, false); 12004 } 12005 12006 static OriginInfo fromUntrustedFile(File file) { 12007 return new OriginInfo(file, null, false, false); 12008 } 12009 12010 static OriginInfo fromExistingFile(File file) { 12011 return new OriginInfo(file, null, false, true); 12012 } 12013 12014 static OriginInfo fromStagedFile(File file) { 12015 return new OriginInfo(file, null, true, false); 12016 } 12017 12018 static OriginInfo fromStagedContainer(String cid) { 12019 return new OriginInfo(null, cid, true, false); 12020 } 12021 12022 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12023 this.file = file; 12024 this.cid = cid; 12025 this.staged = staged; 12026 this.existing = existing; 12027 12028 if (cid != null) { 12029 resolvedPath = PackageHelper.getSdDir(cid); 12030 resolvedFile = new File(resolvedPath); 12031 } else if (file != null) { 12032 resolvedPath = file.getAbsolutePath(); 12033 resolvedFile = file; 12034 } else { 12035 resolvedPath = null; 12036 resolvedFile = null; 12037 } 12038 } 12039 } 12040 12041 static class MoveInfo { 12042 final int moveId; 12043 final String fromUuid; 12044 final String toUuid; 12045 final String packageName; 12046 final String dataAppName; 12047 final int appId; 12048 final String seinfo; 12049 final int targetSdkVersion; 12050 12051 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12052 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12053 this.moveId = moveId; 12054 this.fromUuid = fromUuid; 12055 this.toUuid = toUuid; 12056 this.packageName = packageName; 12057 this.dataAppName = dataAppName; 12058 this.appId = appId; 12059 this.seinfo = seinfo; 12060 this.targetSdkVersion = targetSdkVersion; 12061 } 12062 } 12063 12064 static class VerificationInfo { 12065 /** A constant used to indicate that a uid value is not present. */ 12066 public static final int NO_UID = -1; 12067 12068 /** URI referencing where the package was downloaded from. */ 12069 final Uri originatingUri; 12070 12071 /** HTTP referrer URI associated with the originatingURI. */ 12072 final Uri referrer; 12073 12074 /** UID of the application that the install request originated from. */ 12075 final int originatingUid; 12076 12077 /** UID of application requesting the install */ 12078 final int installerUid; 12079 12080 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12081 this.originatingUri = originatingUri; 12082 this.referrer = referrer; 12083 this.originatingUid = originatingUid; 12084 this.installerUid = installerUid; 12085 } 12086 } 12087 12088 class InstallParams extends HandlerParams { 12089 final OriginInfo origin; 12090 final MoveInfo move; 12091 final IPackageInstallObserver2 observer; 12092 int installFlags; 12093 final String installerPackageName; 12094 final String volumeUuid; 12095 private InstallArgs mArgs; 12096 private int mRet; 12097 final String packageAbiOverride; 12098 final String[] grantedRuntimePermissions; 12099 final VerificationInfo verificationInfo; 12100 12101 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12102 int installFlags, String installerPackageName, String volumeUuid, 12103 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12104 String[] grantedPermissions) { 12105 super(user); 12106 this.origin = origin; 12107 this.move = move; 12108 this.observer = observer; 12109 this.installFlags = installFlags; 12110 this.installerPackageName = installerPackageName; 12111 this.volumeUuid = volumeUuid; 12112 this.verificationInfo = verificationInfo; 12113 this.packageAbiOverride = packageAbiOverride; 12114 this.grantedRuntimePermissions = grantedPermissions; 12115 } 12116 12117 @Override 12118 public String toString() { 12119 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12120 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12121 } 12122 12123 private int installLocationPolicy(PackageInfoLite pkgLite) { 12124 String packageName = pkgLite.packageName; 12125 int installLocation = pkgLite.installLocation; 12126 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12127 // reader 12128 synchronized (mPackages) { 12129 // Currently installed package which the new package is attempting to replace or 12130 // null if no such package is installed. 12131 PackageParser.Package installedPkg = mPackages.get(packageName); 12132 // Package which currently owns the data which the new package will own if installed. 12133 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12134 // will be null whereas dataOwnerPkg will contain information about the package 12135 // which was uninstalled while keeping its data. 12136 PackageParser.Package dataOwnerPkg = installedPkg; 12137 if (dataOwnerPkg == null) { 12138 PackageSetting ps = mSettings.mPackages.get(packageName); 12139 if (ps != null) { 12140 dataOwnerPkg = ps.pkg; 12141 } 12142 } 12143 12144 if (dataOwnerPkg != null) { 12145 // If installed, the package will get access to data left on the device by its 12146 // predecessor. As a security measure, this is permited only if this is not a 12147 // version downgrade or if the predecessor package is marked as debuggable and 12148 // a downgrade is explicitly requested. 12149 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 12150 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 12151 try { 12152 checkDowngrade(dataOwnerPkg, pkgLite); 12153 } catch (PackageManagerException e) { 12154 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12155 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12156 } 12157 } 12158 } 12159 12160 if (installedPkg != null) { 12161 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12162 // Check for updated system application. 12163 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12164 if (onSd) { 12165 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12166 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12167 } 12168 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12169 } else { 12170 if (onSd) { 12171 // Install flag overrides everything. 12172 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12173 } 12174 // If current upgrade specifies particular preference 12175 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12176 // Application explicitly specified internal. 12177 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12178 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12179 // App explictly prefers external. Let policy decide 12180 } else { 12181 // Prefer previous location 12182 if (isExternal(installedPkg)) { 12183 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12184 } 12185 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12186 } 12187 } 12188 } else { 12189 // Invalid install. Return error code 12190 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12191 } 12192 } 12193 } 12194 // All the special cases have been taken care of. 12195 // Return result based on recommended install location. 12196 if (onSd) { 12197 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12198 } 12199 return pkgLite.recommendedInstallLocation; 12200 } 12201 12202 /* 12203 * Invoke remote method to get package information and install 12204 * location values. Override install location based on default 12205 * policy if needed and then create install arguments based 12206 * on the install location. 12207 */ 12208 public void handleStartCopy() throws RemoteException { 12209 int ret = PackageManager.INSTALL_SUCCEEDED; 12210 12211 // If we're already staged, we've firmly committed to an install location 12212 if (origin.staged) { 12213 if (origin.file != null) { 12214 installFlags |= PackageManager.INSTALL_INTERNAL; 12215 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12216 } else if (origin.cid != null) { 12217 installFlags |= PackageManager.INSTALL_EXTERNAL; 12218 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12219 } else { 12220 throw new IllegalStateException("Invalid stage location"); 12221 } 12222 } 12223 12224 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12225 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12226 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12227 PackageInfoLite pkgLite = null; 12228 12229 if (onInt && onSd) { 12230 // Check if both bits are set. 12231 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12232 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12233 } else if (onSd && ephemeral) { 12234 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12235 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12236 } else { 12237 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12238 packageAbiOverride); 12239 12240 if (DEBUG_EPHEMERAL && ephemeral) { 12241 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12242 } 12243 12244 /* 12245 * If we have too little free space, try to free cache 12246 * before giving up. 12247 */ 12248 if (!origin.staged && pkgLite.recommendedInstallLocation 12249 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12250 // TODO: focus freeing disk space on the target device 12251 final StorageManager storage = StorageManager.from(mContext); 12252 final long lowThreshold = storage.getStorageLowBytes( 12253 Environment.getDataDirectory()); 12254 12255 final long sizeBytes = mContainerService.calculateInstalledSize( 12256 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12257 12258 try { 12259 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12260 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12261 installFlags, packageAbiOverride); 12262 } catch (InstallerException e) { 12263 Slog.w(TAG, "Failed to free cache", e); 12264 } 12265 12266 /* 12267 * The cache free must have deleted the file we 12268 * downloaded to install. 12269 * 12270 * TODO: fix the "freeCache" call to not delete 12271 * the file we care about. 12272 */ 12273 if (pkgLite.recommendedInstallLocation 12274 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12275 pkgLite.recommendedInstallLocation 12276 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12277 } 12278 } 12279 } 12280 12281 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12282 int loc = pkgLite.recommendedInstallLocation; 12283 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12284 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12285 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12286 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12287 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12288 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12289 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12290 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12291 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12292 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12293 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12294 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12295 } else { 12296 // Override with defaults if needed. 12297 loc = installLocationPolicy(pkgLite); 12298 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12299 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12300 } else if (!onSd && !onInt) { 12301 // Override install location with flags 12302 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12303 // Set the flag to install on external media. 12304 installFlags |= PackageManager.INSTALL_EXTERNAL; 12305 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12306 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12307 if (DEBUG_EPHEMERAL) { 12308 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12309 } 12310 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12311 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12312 |PackageManager.INSTALL_INTERNAL); 12313 } else { 12314 // Make sure the flag for installing on external 12315 // media is unset 12316 installFlags |= PackageManager.INSTALL_INTERNAL; 12317 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12318 } 12319 } 12320 } 12321 } 12322 12323 final InstallArgs args = createInstallArgs(this); 12324 mArgs = args; 12325 12326 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12327 // TODO: http://b/22976637 12328 // Apps installed for "all" users use the device owner to verify the app 12329 UserHandle verifierUser = getUser(); 12330 if (verifierUser == UserHandle.ALL) { 12331 verifierUser = UserHandle.SYSTEM; 12332 } 12333 12334 /* 12335 * Determine if we have any installed package verifiers. If we 12336 * do, then we'll defer to them to verify the packages. 12337 */ 12338 final int requiredUid = mRequiredVerifierPackage == null ? -1 12339 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12340 verifierUser.getIdentifier()); 12341 if (!origin.existing && requiredUid != -1 12342 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12343 final Intent verification = new Intent( 12344 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12345 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12346 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12347 PACKAGE_MIME_TYPE); 12348 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12349 12350 // Query all live verifiers based on current user state 12351 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12352 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12353 12354 if (DEBUG_VERIFY) { 12355 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12356 + verification.toString() + " with " + pkgLite.verifiers.length 12357 + " optional verifiers"); 12358 } 12359 12360 final int verificationId = mPendingVerificationToken++; 12361 12362 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12363 12364 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12365 installerPackageName); 12366 12367 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12368 installFlags); 12369 12370 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12371 pkgLite.packageName); 12372 12373 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12374 pkgLite.versionCode); 12375 12376 if (verificationInfo != null) { 12377 if (verificationInfo.originatingUri != null) { 12378 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12379 verificationInfo.originatingUri); 12380 } 12381 if (verificationInfo.referrer != null) { 12382 verification.putExtra(Intent.EXTRA_REFERRER, 12383 verificationInfo.referrer); 12384 } 12385 if (verificationInfo.originatingUid >= 0) { 12386 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12387 verificationInfo.originatingUid); 12388 } 12389 if (verificationInfo.installerUid >= 0) { 12390 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12391 verificationInfo.installerUid); 12392 } 12393 } 12394 12395 final PackageVerificationState verificationState = new PackageVerificationState( 12396 requiredUid, args); 12397 12398 mPendingVerification.append(verificationId, verificationState); 12399 12400 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12401 receivers, verificationState); 12402 12403 /* 12404 * If any sufficient verifiers were listed in the package 12405 * manifest, attempt to ask them. 12406 */ 12407 if (sufficientVerifiers != null) { 12408 final int N = sufficientVerifiers.size(); 12409 if (N == 0) { 12410 Slog.i(TAG, "Additional verifiers required, but none installed."); 12411 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12412 } else { 12413 for (int i = 0; i < N; i++) { 12414 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12415 12416 final Intent sufficientIntent = new Intent(verification); 12417 sufficientIntent.setComponent(verifierComponent); 12418 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12419 } 12420 } 12421 } 12422 12423 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12424 mRequiredVerifierPackage, receivers); 12425 if (ret == PackageManager.INSTALL_SUCCEEDED 12426 && mRequiredVerifierPackage != null) { 12427 Trace.asyncTraceBegin( 12428 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12429 /* 12430 * Send the intent to the required verification agent, 12431 * but only start the verification timeout after the 12432 * target BroadcastReceivers have run. 12433 */ 12434 verification.setComponent(requiredVerifierComponent); 12435 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12436 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12437 new BroadcastReceiver() { 12438 @Override 12439 public void onReceive(Context context, Intent intent) { 12440 final Message msg = mHandler 12441 .obtainMessage(CHECK_PENDING_VERIFICATION); 12442 msg.arg1 = verificationId; 12443 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12444 } 12445 }, null, 0, null, null); 12446 12447 /* 12448 * We don't want the copy to proceed until verification 12449 * succeeds, so null out this field. 12450 */ 12451 mArgs = null; 12452 } 12453 } else { 12454 /* 12455 * No package verification is enabled, so immediately start 12456 * the remote call to initiate copy using temporary file. 12457 */ 12458 ret = args.copyApk(mContainerService, true); 12459 } 12460 } 12461 12462 mRet = ret; 12463 } 12464 12465 @Override 12466 void handleReturnCode() { 12467 // If mArgs is null, then MCS couldn't be reached. When it 12468 // reconnects, it will try again to install. At that point, this 12469 // will succeed. 12470 if (mArgs != null) { 12471 processPendingInstall(mArgs, mRet); 12472 } 12473 } 12474 12475 @Override 12476 void handleServiceError() { 12477 mArgs = createInstallArgs(this); 12478 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12479 } 12480 12481 public boolean isForwardLocked() { 12482 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12483 } 12484 } 12485 12486 /** 12487 * Used during creation of InstallArgs 12488 * 12489 * @param installFlags package installation flags 12490 * @return true if should be installed on external storage 12491 */ 12492 private static boolean installOnExternalAsec(int installFlags) { 12493 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12494 return false; 12495 } 12496 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12497 return true; 12498 } 12499 return false; 12500 } 12501 12502 /** 12503 * Used during creation of InstallArgs 12504 * 12505 * @param installFlags package installation flags 12506 * @return true if should be installed as forward locked 12507 */ 12508 private static boolean installForwardLocked(int installFlags) { 12509 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12510 } 12511 12512 private InstallArgs createInstallArgs(InstallParams params) { 12513 if (params.move != null) { 12514 return new MoveInstallArgs(params); 12515 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12516 return new AsecInstallArgs(params); 12517 } else { 12518 return new FileInstallArgs(params); 12519 } 12520 } 12521 12522 /** 12523 * Create args that describe an existing installed package. Typically used 12524 * when cleaning up old installs, or used as a move source. 12525 */ 12526 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12527 String resourcePath, String[] instructionSets) { 12528 final boolean isInAsec; 12529 if (installOnExternalAsec(installFlags)) { 12530 /* Apps on SD card are always in ASEC containers. */ 12531 isInAsec = true; 12532 } else if (installForwardLocked(installFlags) 12533 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12534 /* 12535 * Forward-locked apps are only in ASEC containers if they're the 12536 * new style 12537 */ 12538 isInAsec = true; 12539 } else { 12540 isInAsec = false; 12541 } 12542 12543 if (isInAsec) { 12544 return new AsecInstallArgs(codePath, instructionSets, 12545 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12546 } else { 12547 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12548 } 12549 } 12550 12551 static abstract class InstallArgs { 12552 /** @see InstallParams#origin */ 12553 final OriginInfo origin; 12554 /** @see InstallParams#move */ 12555 final MoveInfo move; 12556 12557 final IPackageInstallObserver2 observer; 12558 // Always refers to PackageManager flags only 12559 final int installFlags; 12560 final String installerPackageName; 12561 final String volumeUuid; 12562 final UserHandle user; 12563 final String abiOverride; 12564 final String[] installGrantPermissions; 12565 /** If non-null, drop an async trace when the install completes */ 12566 final String traceMethod; 12567 final int traceCookie; 12568 12569 // The list of instruction sets supported by this app. This is currently 12570 // only used during the rmdex() phase to clean up resources. We can get rid of this 12571 // if we move dex files under the common app path. 12572 /* nullable */ String[] instructionSets; 12573 12574 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12575 int installFlags, String installerPackageName, String volumeUuid, 12576 UserHandle user, String[] instructionSets, 12577 String abiOverride, String[] installGrantPermissions, 12578 String traceMethod, int traceCookie) { 12579 this.origin = origin; 12580 this.move = move; 12581 this.installFlags = installFlags; 12582 this.observer = observer; 12583 this.installerPackageName = installerPackageName; 12584 this.volumeUuid = volumeUuid; 12585 this.user = user; 12586 this.instructionSets = instructionSets; 12587 this.abiOverride = abiOverride; 12588 this.installGrantPermissions = installGrantPermissions; 12589 this.traceMethod = traceMethod; 12590 this.traceCookie = traceCookie; 12591 } 12592 12593 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12594 abstract int doPreInstall(int status); 12595 12596 /** 12597 * Rename package into final resting place. All paths on the given 12598 * scanned package should be updated to reflect the rename. 12599 */ 12600 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12601 abstract int doPostInstall(int status, int uid); 12602 12603 /** @see PackageSettingBase#codePathString */ 12604 abstract String getCodePath(); 12605 /** @see PackageSettingBase#resourcePathString */ 12606 abstract String getResourcePath(); 12607 12608 // Need installer lock especially for dex file removal. 12609 abstract void cleanUpResourcesLI(); 12610 abstract boolean doPostDeleteLI(boolean delete); 12611 12612 /** 12613 * Called before the source arguments are copied. This is used mostly 12614 * for MoveParams when it needs to read the source file to put it in the 12615 * destination. 12616 */ 12617 int doPreCopy() { 12618 return PackageManager.INSTALL_SUCCEEDED; 12619 } 12620 12621 /** 12622 * Called after the source arguments are copied. This is used mostly for 12623 * MoveParams when it needs to read the source file to put it in the 12624 * destination. 12625 */ 12626 int doPostCopy(int uid) { 12627 return PackageManager.INSTALL_SUCCEEDED; 12628 } 12629 12630 protected boolean isFwdLocked() { 12631 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12632 } 12633 12634 protected boolean isExternalAsec() { 12635 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12636 } 12637 12638 protected boolean isEphemeral() { 12639 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12640 } 12641 12642 UserHandle getUser() { 12643 return user; 12644 } 12645 } 12646 12647 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12648 if (!allCodePaths.isEmpty()) { 12649 if (instructionSets == null) { 12650 throw new IllegalStateException("instructionSet == null"); 12651 } 12652 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12653 for (String codePath : allCodePaths) { 12654 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12655 try { 12656 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12657 } catch (InstallerException ignored) { 12658 } 12659 } 12660 } 12661 } 12662 } 12663 12664 /** 12665 * Logic to handle installation of non-ASEC applications, including copying 12666 * and renaming logic. 12667 */ 12668 class FileInstallArgs extends InstallArgs { 12669 private File codeFile; 12670 private File resourceFile; 12671 12672 // Example topology: 12673 // /data/app/com.example/base.apk 12674 // /data/app/com.example/split_foo.apk 12675 // /data/app/com.example/lib/arm/libfoo.so 12676 // /data/app/com.example/lib/arm64/libfoo.so 12677 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12678 12679 /** New install */ 12680 FileInstallArgs(InstallParams params) { 12681 super(params.origin, params.move, params.observer, params.installFlags, 12682 params.installerPackageName, params.volumeUuid, 12683 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12684 params.grantedRuntimePermissions, 12685 params.traceMethod, params.traceCookie); 12686 if (isFwdLocked()) { 12687 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12688 } 12689 } 12690 12691 /** Existing install */ 12692 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12693 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12694 null, null, null, 0); 12695 this.codeFile = (codePath != null) ? new File(codePath) : null; 12696 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12697 } 12698 12699 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12700 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12701 try { 12702 return doCopyApk(imcs, temp); 12703 } finally { 12704 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12705 } 12706 } 12707 12708 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12709 if (origin.staged) { 12710 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12711 codeFile = origin.file; 12712 resourceFile = origin.file; 12713 return PackageManager.INSTALL_SUCCEEDED; 12714 } 12715 12716 try { 12717 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12718 final File tempDir = 12719 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12720 codeFile = tempDir; 12721 resourceFile = tempDir; 12722 } catch (IOException e) { 12723 Slog.w(TAG, "Failed to create copy file: " + e); 12724 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12725 } 12726 12727 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12728 @Override 12729 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12730 if (!FileUtils.isValidExtFilename(name)) { 12731 throw new IllegalArgumentException("Invalid filename: " + name); 12732 } 12733 try { 12734 final File file = new File(codeFile, name); 12735 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12736 O_RDWR | O_CREAT, 0644); 12737 Os.chmod(file.getAbsolutePath(), 0644); 12738 return new ParcelFileDescriptor(fd); 12739 } catch (ErrnoException e) { 12740 throw new RemoteException("Failed to open: " + e.getMessage()); 12741 } 12742 } 12743 }; 12744 12745 int ret = PackageManager.INSTALL_SUCCEEDED; 12746 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12747 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12748 Slog.e(TAG, "Failed to copy package"); 12749 return ret; 12750 } 12751 12752 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12753 NativeLibraryHelper.Handle handle = null; 12754 try { 12755 handle = NativeLibraryHelper.Handle.create(codeFile); 12756 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12757 abiOverride); 12758 } catch (IOException e) { 12759 Slog.e(TAG, "Copying native libraries failed", e); 12760 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12761 } finally { 12762 IoUtils.closeQuietly(handle); 12763 } 12764 12765 return ret; 12766 } 12767 12768 int doPreInstall(int status) { 12769 if (status != PackageManager.INSTALL_SUCCEEDED) { 12770 cleanUp(); 12771 } 12772 return status; 12773 } 12774 12775 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12776 if (status != PackageManager.INSTALL_SUCCEEDED) { 12777 cleanUp(); 12778 return false; 12779 } 12780 12781 final File targetDir = codeFile.getParentFile(); 12782 final File beforeCodeFile = codeFile; 12783 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12784 12785 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12786 try { 12787 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12788 } catch (ErrnoException e) { 12789 Slog.w(TAG, "Failed to rename", e); 12790 return false; 12791 } 12792 12793 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12794 Slog.w(TAG, "Failed to restorecon"); 12795 return false; 12796 } 12797 12798 // Reflect the rename internally 12799 codeFile = afterCodeFile; 12800 resourceFile = afterCodeFile; 12801 12802 // Reflect the rename in scanned details 12803 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12804 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12805 afterCodeFile, pkg.baseCodePath)); 12806 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12807 afterCodeFile, pkg.splitCodePaths)); 12808 12809 // Reflect the rename in app info 12810 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12811 pkg.setApplicationInfoCodePath(pkg.codePath); 12812 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12813 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12814 pkg.setApplicationInfoResourcePath(pkg.codePath); 12815 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12816 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12817 12818 return true; 12819 } 12820 12821 int doPostInstall(int status, int uid) { 12822 if (status != PackageManager.INSTALL_SUCCEEDED) { 12823 cleanUp(); 12824 } 12825 return status; 12826 } 12827 12828 @Override 12829 String getCodePath() { 12830 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12831 } 12832 12833 @Override 12834 String getResourcePath() { 12835 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12836 } 12837 12838 private boolean cleanUp() { 12839 if (codeFile == null || !codeFile.exists()) { 12840 return false; 12841 } 12842 12843 removeCodePathLI(codeFile); 12844 12845 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12846 resourceFile.delete(); 12847 } 12848 12849 return true; 12850 } 12851 12852 void cleanUpResourcesLI() { 12853 // Try enumerating all code paths before deleting 12854 List<String> allCodePaths = Collections.EMPTY_LIST; 12855 if (codeFile != null && codeFile.exists()) { 12856 try { 12857 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12858 allCodePaths = pkg.getAllCodePaths(); 12859 } catch (PackageParserException e) { 12860 // Ignored; we tried our best 12861 } 12862 } 12863 12864 cleanUp(); 12865 removeDexFiles(allCodePaths, instructionSets); 12866 } 12867 12868 boolean doPostDeleteLI(boolean delete) { 12869 // XXX err, shouldn't we respect the delete flag? 12870 cleanUpResourcesLI(); 12871 return true; 12872 } 12873 } 12874 12875 private boolean isAsecExternal(String cid) { 12876 final String asecPath = PackageHelper.getSdFilesystem(cid); 12877 return !asecPath.startsWith(mAsecInternalPath); 12878 } 12879 12880 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12881 PackageManagerException { 12882 if (copyRet < 0) { 12883 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12884 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12885 throw new PackageManagerException(copyRet, message); 12886 } 12887 } 12888 } 12889 12890 /** 12891 * Extract the MountService "container ID" from the full code path of an 12892 * .apk. 12893 */ 12894 static String cidFromCodePath(String fullCodePath) { 12895 int eidx = fullCodePath.lastIndexOf("/"); 12896 String subStr1 = fullCodePath.substring(0, eidx); 12897 int sidx = subStr1.lastIndexOf("/"); 12898 return subStr1.substring(sidx+1, eidx); 12899 } 12900 12901 /** 12902 * Logic to handle installation of ASEC applications, including copying and 12903 * renaming logic. 12904 */ 12905 class AsecInstallArgs extends InstallArgs { 12906 static final String RES_FILE_NAME = "pkg.apk"; 12907 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12908 12909 String cid; 12910 String packagePath; 12911 String resourcePath; 12912 12913 /** New install */ 12914 AsecInstallArgs(InstallParams params) { 12915 super(params.origin, params.move, params.observer, params.installFlags, 12916 params.installerPackageName, params.volumeUuid, 12917 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12918 params.grantedRuntimePermissions, 12919 params.traceMethod, params.traceCookie); 12920 } 12921 12922 /** Existing install */ 12923 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12924 boolean isExternal, boolean isForwardLocked) { 12925 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12926 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12927 instructionSets, null, null, null, 0); 12928 // Hackily pretend we're still looking at a full code path 12929 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12930 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12931 } 12932 12933 // Extract cid from fullCodePath 12934 int eidx = fullCodePath.lastIndexOf("/"); 12935 String subStr1 = fullCodePath.substring(0, eidx); 12936 int sidx = subStr1.lastIndexOf("/"); 12937 cid = subStr1.substring(sidx+1, eidx); 12938 setMountPath(subStr1); 12939 } 12940 12941 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12942 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12943 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12944 instructionSets, null, null, null, 0); 12945 this.cid = cid; 12946 setMountPath(PackageHelper.getSdDir(cid)); 12947 } 12948 12949 void createCopyFile() { 12950 cid = mInstallerService.allocateExternalStageCidLegacy(); 12951 } 12952 12953 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12954 if (origin.staged && origin.cid != null) { 12955 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12956 cid = origin.cid; 12957 setMountPath(PackageHelper.getSdDir(cid)); 12958 return PackageManager.INSTALL_SUCCEEDED; 12959 } 12960 12961 if (temp) { 12962 createCopyFile(); 12963 } else { 12964 /* 12965 * Pre-emptively destroy the container since it's destroyed if 12966 * copying fails due to it existing anyway. 12967 */ 12968 PackageHelper.destroySdDir(cid); 12969 } 12970 12971 final String newMountPath = imcs.copyPackageToContainer( 12972 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12973 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12974 12975 if (newMountPath != null) { 12976 setMountPath(newMountPath); 12977 return PackageManager.INSTALL_SUCCEEDED; 12978 } else { 12979 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12980 } 12981 } 12982 12983 @Override 12984 String getCodePath() { 12985 return packagePath; 12986 } 12987 12988 @Override 12989 String getResourcePath() { 12990 return resourcePath; 12991 } 12992 12993 int doPreInstall(int status) { 12994 if (status != PackageManager.INSTALL_SUCCEEDED) { 12995 // Destroy container 12996 PackageHelper.destroySdDir(cid); 12997 } else { 12998 boolean mounted = PackageHelper.isContainerMounted(cid); 12999 if (!mounted) { 13000 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13001 Process.SYSTEM_UID); 13002 if (newMountPath != null) { 13003 setMountPath(newMountPath); 13004 } else { 13005 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13006 } 13007 } 13008 } 13009 return status; 13010 } 13011 13012 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13013 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13014 String newMountPath = null; 13015 if (PackageHelper.isContainerMounted(cid)) { 13016 // Unmount the container 13017 if (!PackageHelper.unMountSdDir(cid)) { 13018 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13019 return false; 13020 } 13021 } 13022 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13023 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13024 " which might be stale. Will try to clean up."); 13025 // Clean up the stale container and proceed to recreate. 13026 if (!PackageHelper.destroySdDir(newCacheId)) { 13027 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13028 return false; 13029 } 13030 // Successfully cleaned up stale container. Try to rename again. 13031 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13032 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13033 + " inspite of cleaning it up."); 13034 return false; 13035 } 13036 } 13037 if (!PackageHelper.isContainerMounted(newCacheId)) { 13038 Slog.w(TAG, "Mounting container " + newCacheId); 13039 newMountPath = PackageHelper.mountSdDir(newCacheId, 13040 getEncryptKey(), Process.SYSTEM_UID); 13041 } else { 13042 newMountPath = PackageHelper.getSdDir(newCacheId); 13043 } 13044 if (newMountPath == null) { 13045 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13046 return false; 13047 } 13048 Log.i(TAG, "Succesfully renamed " + cid + 13049 " to " + newCacheId + 13050 " at new path: " + newMountPath); 13051 cid = newCacheId; 13052 13053 final File beforeCodeFile = new File(packagePath); 13054 setMountPath(newMountPath); 13055 final File afterCodeFile = new File(packagePath); 13056 13057 // Reflect the rename in scanned details 13058 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13059 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13060 afterCodeFile, pkg.baseCodePath)); 13061 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13062 afterCodeFile, pkg.splitCodePaths)); 13063 13064 // Reflect the rename in app info 13065 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13066 pkg.setApplicationInfoCodePath(pkg.codePath); 13067 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13068 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13069 pkg.setApplicationInfoResourcePath(pkg.codePath); 13070 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13071 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13072 13073 return true; 13074 } 13075 13076 private void setMountPath(String mountPath) { 13077 final File mountFile = new File(mountPath); 13078 13079 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13080 if (monolithicFile.exists()) { 13081 packagePath = monolithicFile.getAbsolutePath(); 13082 if (isFwdLocked()) { 13083 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13084 } else { 13085 resourcePath = packagePath; 13086 } 13087 } else { 13088 packagePath = mountFile.getAbsolutePath(); 13089 resourcePath = packagePath; 13090 } 13091 } 13092 13093 int doPostInstall(int status, int uid) { 13094 if (status != PackageManager.INSTALL_SUCCEEDED) { 13095 cleanUp(); 13096 } else { 13097 final int groupOwner; 13098 final String protectedFile; 13099 if (isFwdLocked()) { 13100 groupOwner = UserHandle.getSharedAppGid(uid); 13101 protectedFile = RES_FILE_NAME; 13102 } else { 13103 groupOwner = -1; 13104 protectedFile = null; 13105 } 13106 13107 if (uid < Process.FIRST_APPLICATION_UID 13108 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13109 Slog.e(TAG, "Failed to finalize " + cid); 13110 PackageHelper.destroySdDir(cid); 13111 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13112 } 13113 13114 boolean mounted = PackageHelper.isContainerMounted(cid); 13115 if (!mounted) { 13116 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13117 } 13118 } 13119 return status; 13120 } 13121 13122 private void cleanUp() { 13123 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13124 13125 // Destroy secure container 13126 PackageHelper.destroySdDir(cid); 13127 } 13128 13129 private List<String> getAllCodePaths() { 13130 final File codeFile = new File(getCodePath()); 13131 if (codeFile != null && codeFile.exists()) { 13132 try { 13133 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13134 return pkg.getAllCodePaths(); 13135 } catch (PackageParserException e) { 13136 // Ignored; we tried our best 13137 } 13138 } 13139 return Collections.EMPTY_LIST; 13140 } 13141 13142 void cleanUpResourcesLI() { 13143 // Enumerate all code paths before deleting 13144 cleanUpResourcesLI(getAllCodePaths()); 13145 } 13146 13147 private void cleanUpResourcesLI(List<String> allCodePaths) { 13148 cleanUp(); 13149 removeDexFiles(allCodePaths, instructionSets); 13150 } 13151 13152 String getPackageName() { 13153 return getAsecPackageName(cid); 13154 } 13155 13156 boolean doPostDeleteLI(boolean delete) { 13157 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13158 final List<String> allCodePaths = getAllCodePaths(); 13159 boolean mounted = PackageHelper.isContainerMounted(cid); 13160 if (mounted) { 13161 // Unmount first 13162 if (PackageHelper.unMountSdDir(cid)) { 13163 mounted = false; 13164 } 13165 } 13166 if (!mounted && delete) { 13167 cleanUpResourcesLI(allCodePaths); 13168 } 13169 return !mounted; 13170 } 13171 13172 @Override 13173 int doPreCopy() { 13174 if (isFwdLocked()) { 13175 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13176 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13177 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13178 } 13179 } 13180 13181 return PackageManager.INSTALL_SUCCEEDED; 13182 } 13183 13184 @Override 13185 int doPostCopy(int uid) { 13186 if (isFwdLocked()) { 13187 if (uid < Process.FIRST_APPLICATION_UID 13188 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13189 RES_FILE_NAME)) { 13190 Slog.e(TAG, "Failed to finalize " + cid); 13191 PackageHelper.destroySdDir(cid); 13192 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13193 } 13194 } 13195 13196 return PackageManager.INSTALL_SUCCEEDED; 13197 } 13198 } 13199 13200 /** 13201 * Logic to handle movement of existing installed applications. 13202 */ 13203 class MoveInstallArgs extends InstallArgs { 13204 private File codeFile; 13205 private File resourceFile; 13206 13207 /** New install */ 13208 MoveInstallArgs(InstallParams params) { 13209 super(params.origin, params.move, params.observer, params.installFlags, 13210 params.installerPackageName, params.volumeUuid, 13211 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13212 params.grantedRuntimePermissions, 13213 params.traceMethod, params.traceCookie); 13214 } 13215 13216 int copyApk(IMediaContainerService imcs, boolean temp) { 13217 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13218 + move.fromUuid + " to " + move.toUuid); 13219 synchronized (mInstaller) { 13220 try { 13221 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13222 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13223 } catch (InstallerException e) { 13224 Slog.w(TAG, "Failed to move app", e); 13225 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13226 } 13227 } 13228 13229 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13230 resourceFile = codeFile; 13231 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13232 13233 return PackageManager.INSTALL_SUCCEEDED; 13234 } 13235 13236 int doPreInstall(int status) { 13237 if (status != PackageManager.INSTALL_SUCCEEDED) { 13238 cleanUp(move.toUuid); 13239 } 13240 return status; 13241 } 13242 13243 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13244 if (status != PackageManager.INSTALL_SUCCEEDED) { 13245 cleanUp(move.toUuid); 13246 return false; 13247 } 13248 13249 // Reflect the move in app info 13250 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13251 pkg.setApplicationInfoCodePath(pkg.codePath); 13252 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13253 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13254 pkg.setApplicationInfoResourcePath(pkg.codePath); 13255 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13256 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13257 13258 return true; 13259 } 13260 13261 int doPostInstall(int status, int uid) { 13262 if (status == PackageManager.INSTALL_SUCCEEDED) { 13263 cleanUp(move.fromUuid); 13264 } else { 13265 cleanUp(move.toUuid); 13266 } 13267 return status; 13268 } 13269 13270 @Override 13271 String getCodePath() { 13272 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13273 } 13274 13275 @Override 13276 String getResourcePath() { 13277 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13278 } 13279 13280 private boolean cleanUp(String volumeUuid) { 13281 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13282 move.dataAppName); 13283 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13284 synchronized (mInstallLock) { 13285 // Clean up both app data and code 13286 removeDataDirsLI(volumeUuid, move.packageName); 13287 removeCodePathLI(codeFile); 13288 } 13289 return true; 13290 } 13291 13292 void cleanUpResourcesLI() { 13293 throw new UnsupportedOperationException(); 13294 } 13295 13296 boolean doPostDeleteLI(boolean delete) { 13297 throw new UnsupportedOperationException(); 13298 } 13299 } 13300 13301 static String getAsecPackageName(String packageCid) { 13302 int idx = packageCid.lastIndexOf("-"); 13303 if (idx == -1) { 13304 return packageCid; 13305 } 13306 return packageCid.substring(0, idx); 13307 } 13308 13309 // Utility method used to create code paths based on package name and available index. 13310 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13311 String idxStr = ""; 13312 int idx = 1; 13313 // Fall back to default value of idx=1 if prefix is not 13314 // part of oldCodePath 13315 if (oldCodePath != null) { 13316 String subStr = oldCodePath; 13317 // Drop the suffix right away 13318 if (suffix != null && subStr.endsWith(suffix)) { 13319 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13320 } 13321 // If oldCodePath already contains prefix find out the 13322 // ending index to either increment or decrement. 13323 int sidx = subStr.lastIndexOf(prefix); 13324 if (sidx != -1) { 13325 subStr = subStr.substring(sidx + prefix.length()); 13326 if (subStr != null) { 13327 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13328 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13329 } 13330 try { 13331 idx = Integer.parseInt(subStr); 13332 if (idx <= 1) { 13333 idx++; 13334 } else { 13335 idx--; 13336 } 13337 } catch(NumberFormatException e) { 13338 } 13339 } 13340 } 13341 } 13342 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13343 return prefix + idxStr; 13344 } 13345 13346 private File getNextCodePath(File targetDir, String packageName) { 13347 int suffix = 1; 13348 File result; 13349 do { 13350 result = new File(targetDir, packageName + "-" + suffix); 13351 suffix++; 13352 } while (result.exists()); 13353 return result; 13354 } 13355 13356 // Utility method that returns the relative package path with respect 13357 // to the installation directory. Like say for /data/data/com.test-1.apk 13358 // string com.test-1 is returned. 13359 static String deriveCodePathName(String codePath) { 13360 if (codePath == null) { 13361 return null; 13362 } 13363 final File codeFile = new File(codePath); 13364 final String name = codeFile.getName(); 13365 if (codeFile.isDirectory()) { 13366 return name; 13367 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13368 final int lastDot = name.lastIndexOf('.'); 13369 return name.substring(0, lastDot); 13370 } else { 13371 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13372 return null; 13373 } 13374 } 13375 13376 static class PackageInstalledInfo { 13377 String name; 13378 int uid; 13379 // The set of users that originally had this package installed. 13380 int[] origUsers; 13381 // The set of users that now have this package installed. 13382 int[] newUsers; 13383 PackageParser.Package pkg; 13384 int returnCode; 13385 String returnMsg; 13386 PackageRemovedInfo removedInfo; 13387 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13388 13389 public void setError(int code, String msg) { 13390 setReturnCode(code); 13391 setReturnMessage(msg); 13392 Slog.w(TAG, msg); 13393 } 13394 13395 public void setError(String msg, PackageParserException e) { 13396 setReturnCode(e.error); 13397 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13398 Slog.w(TAG, msg, e); 13399 } 13400 13401 public void setError(String msg, PackageManagerException e) { 13402 returnCode = e.error; 13403 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13404 Slog.w(TAG, msg, e); 13405 } 13406 13407 public void setReturnCode(int returnCode) { 13408 this.returnCode = returnCode; 13409 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13410 for (int i = 0; i < childCount; i++) { 13411 addedChildPackages.valueAt(i).returnCode = returnCode; 13412 } 13413 } 13414 13415 private void setReturnMessage(String returnMsg) { 13416 this.returnMsg = returnMsg; 13417 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13418 for (int i = 0; i < childCount; i++) { 13419 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13420 } 13421 } 13422 13423 // In some error cases we want to convey more info back to the observer 13424 String origPackage; 13425 String origPermission; 13426 } 13427 13428 /* 13429 * Install a non-existing package. 13430 */ 13431 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13432 UserHandle user, String installerPackageName, String volumeUuid, 13433 PackageInstalledInfo res) { 13434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13435 13436 // Remember this for later, in case we need to rollback this install 13437 String pkgName = pkg.packageName; 13438 13439 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13440 13441 synchronized(mPackages) { 13442 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13443 // A package with the same name is already installed, though 13444 // it has been renamed to an older name. The package we 13445 // are trying to install should be installed as an update to 13446 // the existing one, but that has not been requested, so bail. 13447 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13448 + " without first uninstalling package running as " 13449 + mSettings.mRenamedPackages.get(pkgName)); 13450 return; 13451 } 13452 if (mPackages.containsKey(pkgName)) { 13453 // Don't allow installation over an existing package with the same name. 13454 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13455 + " without first uninstalling."); 13456 return; 13457 } 13458 } 13459 13460 try { 13461 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13462 System.currentTimeMillis(), user); 13463 13464 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13465 13466 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13467 prepareAppDataAfterInstall(newPackage); 13468 13469 } else { 13470 // Remove package from internal structures, but keep around any 13471 // data that might have already existed 13472 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13473 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13474 } 13475 } catch (PackageManagerException e) { 13476 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13477 } 13478 13479 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13480 } 13481 13482 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13483 // Can't rotate keys during boot or if sharedUser. 13484 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13485 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13486 return false; 13487 } 13488 // app is using upgradeKeySets; make sure all are valid 13489 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13490 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13491 for (int i = 0; i < upgradeKeySets.length; i++) { 13492 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13493 Slog.wtf(TAG, "Package " 13494 + (oldPs.name != null ? oldPs.name : "<null>") 13495 + " contains upgrade-key-set reference to unknown key-set: " 13496 + upgradeKeySets[i] 13497 + " reverting to signatures check."); 13498 return false; 13499 } 13500 } 13501 return true; 13502 } 13503 13504 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13505 // Upgrade keysets are being used. Determine if new package has a superset of the 13506 // required keys. 13507 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13508 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13509 for (int i = 0; i < upgradeKeySets.length; i++) { 13510 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13511 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13512 return true; 13513 } 13514 } 13515 return false; 13516 } 13517 13518 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13519 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13520 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13521 13522 final PackageParser.Package oldPackage; 13523 final String pkgName = pkg.packageName; 13524 final int[] allUsers; 13525 final boolean weFroze; 13526 13527 // First find the old package info and check signatures 13528 synchronized(mPackages) { 13529 oldPackage = mPackages.get(pkgName); 13530 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13531 if (isEphemeral && !oldIsEphemeral) { 13532 // can't downgrade from full to ephemeral 13533 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13534 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13535 return; 13536 } 13537 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13538 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13539 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13540 if (!checkUpgradeKeySetLP(ps, pkg)) { 13541 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13542 "New package not signed by keys specified by upgrade-keysets: " 13543 + pkgName); 13544 return; 13545 } 13546 } else { 13547 // default to original signature matching 13548 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13549 != PackageManager.SIGNATURE_MATCH) { 13550 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13551 "New package has a different signature: " + pkgName); 13552 return; 13553 } 13554 } 13555 13556 // In case of rollback, remember per-user/profile install state 13557 allUsers = sUserManager.getUserIds(); 13558 13559 // Mark the app as frozen to prevent launching during the upgrade 13560 // process, and then kill all running instances 13561 if (!ps.frozen) { 13562 ps.frozen = true; 13563 weFroze = true; 13564 } else { 13565 weFroze = false; 13566 } 13567 } 13568 13569 try { 13570 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13571 installerPackageName, res); 13572 } finally { 13573 // Regardless of success or failure of upgrade steps above, always 13574 // unfreeze the package if we froze it 13575 if (weFroze) { 13576 unfreezePackage(pkgName); 13577 } 13578 } 13579 } 13580 13581 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13582 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13583 String installerPackageName, PackageInstalledInfo res) { 13584 // Update what is removed 13585 res.removedInfo = new PackageRemovedInfo(); 13586 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13587 res.removedInfo.removedPackage = oldPackage.packageName; 13588 res.removedInfo.isUpdate = true; 13589 final int childCount = (oldPackage.childPackages != null) 13590 ? oldPackage.childPackages.size() : 0; 13591 for (int i = 0; i < childCount; i++) { 13592 boolean childPackageUpdated = false; 13593 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13594 if (res.addedChildPackages != null) { 13595 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13596 if (childRes != null) { 13597 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13598 childRes.removedInfo.removedPackage = childPkg.packageName; 13599 childRes.removedInfo.isUpdate = true; 13600 childPackageUpdated = true; 13601 } 13602 } 13603 if (!childPackageUpdated) { 13604 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13605 childRemovedRes.removedPackage = childPkg.packageName; 13606 childRemovedRes.isUpdate = false; 13607 childRemovedRes.dataRemoved = true; 13608 synchronized (mPackages) { 13609 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13610 if (childPs != null) { 13611 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13612 } 13613 } 13614 if (res.removedInfo.removedChildPackages == null) { 13615 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13616 } 13617 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13618 } 13619 } 13620 13621 boolean sysPkg = (isSystemApp(oldPackage)); 13622 if (sysPkg) { 13623 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13624 user, allUsers, installerPackageName, res); 13625 } else { 13626 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13627 user, allUsers, installerPackageName, res); 13628 } 13629 } 13630 13631 public List<String> getPreviousCodePaths(String packageName) { 13632 final PackageSetting ps = mSettings.mPackages.get(packageName); 13633 final List<String> result = new ArrayList<String>(); 13634 if (ps != null && ps.oldCodePaths != null) { 13635 result.addAll(ps.oldCodePaths); 13636 } 13637 return result; 13638 } 13639 13640 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13641 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13642 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13643 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13644 + deletedPackage); 13645 13646 String pkgName = deletedPackage.packageName; 13647 boolean deletedPkg = true; 13648 boolean addedPkg = false; 13649 boolean updatedSettings = false; 13650 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13651 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13652 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13653 13654 final long origUpdateTime = (pkg.mExtras != null) 13655 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13656 13657 // First delete the existing package while retaining the data directory 13658 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13659 res.removedInfo, true, pkg)) { 13660 // If the existing package wasn't successfully deleted 13661 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13662 deletedPkg = false; 13663 } else { 13664 // Successfully deleted the old package; proceed with replace. 13665 13666 // If deleted package lived in a container, give users a chance to 13667 // relinquish resources before killing. 13668 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13669 if (DEBUG_INSTALL) { 13670 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13671 } 13672 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13673 final ArrayList<String> pkgList = new ArrayList<String>(1); 13674 pkgList.add(deletedPackage.applicationInfo.packageName); 13675 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13676 } 13677 13678 deleteCodeCacheDirsLI(pkg); 13679 deleteProfilesLI(pkg, /*destroy*/ false); 13680 13681 try { 13682 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13683 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13684 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13685 13686 // Update the in-memory copy of the previous code paths. 13687 PackageSetting ps = mSettings.mPackages.get(pkgName); 13688 if (!killApp) { 13689 if (ps.oldCodePaths == null) { 13690 ps.oldCodePaths = new ArraySet<>(); 13691 } 13692 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13693 if (deletedPackage.splitCodePaths != null) { 13694 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13695 } 13696 } else { 13697 ps.oldCodePaths = null; 13698 } 13699 if (ps.childPackageNames != null) { 13700 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13701 final String childPkgName = ps.childPackageNames.get(i); 13702 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13703 childPs.oldCodePaths = ps.oldCodePaths; 13704 } 13705 } 13706 prepareAppDataAfterInstall(newPackage); 13707 addedPkg = true; 13708 } catch (PackageManagerException e) { 13709 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13710 } 13711 } 13712 13713 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13714 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13715 13716 // Revert all internal state mutations and added folders for the failed install 13717 if (addedPkg) { 13718 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13719 res.removedInfo, true, null); 13720 } 13721 13722 // Restore the old package 13723 if (deletedPkg) { 13724 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13725 File restoreFile = new File(deletedPackage.codePath); 13726 // Parse old package 13727 boolean oldExternal = isExternal(deletedPackage); 13728 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13729 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13730 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13731 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13732 try { 13733 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13734 null); 13735 } catch (PackageManagerException e) { 13736 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13737 + e.getMessage()); 13738 return; 13739 } 13740 13741 synchronized (mPackages) { 13742 // Ensure the installer package name up to date 13743 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13744 13745 // Update permissions for restored package 13746 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13747 13748 mSettings.writeLPr(); 13749 } 13750 13751 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13752 } 13753 } else { 13754 synchronized (mPackages) { 13755 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13756 if (ps != null) { 13757 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13758 if (res.removedInfo.removedChildPackages != null) { 13759 final int childCount = res.removedInfo.removedChildPackages.size(); 13760 // Iterate in reverse as we may modify the collection 13761 for (int i = childCount - 1; i >= 0; i--) { 13762 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13763 if (res.addedChildPackages.containsKey(childPackageName)) { 13764 res.removedInfo.removedChildPackages.removeAt(i); 13765 } else { 13766 PackageRemovedInfo childInfo = res.removedInfo 13767 .removedChildPackages.valueAt(i); 13768 childInfo.removedForAllUsers = mPackages.get( 13769 childInfo.removedPackage) == null; 13770 } 13771 } 13772 } 13773 } 13774 } 13775 } 13776 } 13777 13778 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13779 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13780 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13781 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13782 + ", old=" + deletedPackage); 13783 13784 final boolean disabledSystem; 13785 13786 // Set the system/privileged flags as needed 13787 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13788 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13789 != 0) { 13790 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13791 } 13792 13793 // Kill package processes including services, providers, etc. 13794 killPackage(deletedPackage, "replace sys pkg"); 13795 13796 // Remove existing system package 13797 removePackageLI(deletedPackage, true); 13798 13799 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13800 if (!disabledSystem) { 13801 // We didn't need to disable the .apk as a current system package, 13802 // which means we are replacing another update that is already 13803 // installed. We need to make sure to delete the older one's .apk. 13804 res.removedInfo.args = createInstallArgsForExisting(0, 13805 deletedPackage.applicationInfo.getCodePath(), 13806 deletedPackage.applicationInfo.getResourcePath(), 13807 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13808 } else { 13809 res.removedInfo.args = null; 13810 } 13811 13812 // Successfully disabled the old package. Now proceed with re-installation 13813 deleteCodeCacheDirsLI(pkg); 13814 deleteProfilesLI(pkg, /*destroy*/ false); 13815 13816 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13817 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13818 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13819 13820 PackageParser.Package newPackage = null; 13821 try { 13822 // Add the package to the internal data structures 13823 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13824 13825 // Set the update and install times 13826 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13827 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13828 System.currentTimeMillis()); 13829 13830 // Check for shared user id changes 13831 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13832 deletedPackage, newPackage); 13833 if (invalidPackageName != null) { 13834 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13835 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13836 + " to " + invalidPackageName); 13837 } 13838 13839 // Update the package dynamic state if succeeded 13840 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13841 // Now that the install succeeded make sure we remove data 13842 // directories for any child package the update removed. 13843 final int deletedChildCount = (deletedPackage.childPackages != null) 13844 ? deletedPackage.childPackages.size() : 0; 13845 final int newChildCount = (newPackage.childPackages != null) 13846 ? newPackage.childPackages.size() : 0; 13847 for (int i = 0; i < deletedChildCount; i++) { 13848 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13849 boolean childPackageDeleted = true; 13850 for (int j = 0; j < newChildCount; j++) { 13851 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13852 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13853 childPackageDeleted = false; 13854 break; 13855 } 13856 } 13857 if (childPackageDeleted) { 13858 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13859 deletedChildPkg.packageName); 13860 if (ps != null && res.removedInfo.removedChildPackages != null) { 13861 PackageRemovedInfo removedChildRes = res.removedInfo 13862 .removedChildPackages.get(deletedChildPkg.packageName); 13863 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13864 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13865 } 13866 } 13867 } 13868 13869 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13870 prepareAppDataAfterInstall(newPackage); 13871 } 13872 } catch (PackageManagerException e) { 13873 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13874 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13875 } 13876 13877 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13878 // Re installation failed. Restore old information 13879 // Remove new pkg information 13880 if (newPackage != null) { 13881 removeInstalledPackageLI(newPackage, true); 13882 } 13883 // Add back the old system package 13884 try { 13885 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13886 } catch (PackageManagerException e) { 13887 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13888 } 13889 13890 synchronized (mPackages) { 13891 if (disabledSystem) { 13892 enableSystemPackageLPw(deletedPackage); 13893 } 13894 13895 // Ensure the installer package name up to date 13896 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13897 13898 // Update permissions for restored package 13899 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13900 13901 mSettings.writeLPr(); 13902 } 13903 13904 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13905 + " after failed upgrade"); 13906 } 13907 } 13908 13909 /** 13910 * Checks whether the parent or any of the child packages have a change shared 13911 * user. For a package to be a valid update the shred users of the parent and 13912 * the children should match. We may later support changing child shared users. 13913 * @param oldPkg The updated package. 13914 * @param newPkg The update package. 13915 * @return The shared user that change between the versions. 13916 */ 13917 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13918 PackageParser.Package newPkg) { 13919 // Check parent shared user 13920 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13921 return newPkg.packageName; 13922 } 13923 // Check child shared users 13924 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13925 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13926 for (int i = 0; i < newChildCount; i++) { 13927 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13928 // If this child was present, did it have the same shared user? 13929 for (int j = 0; j < oldChildCount; j++) { 13930 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13931 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13932 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13933 return newChildPkg.packageName; 13934 } 13935 } 13936 } 13937 return null; 13938 } 13939 13940 private void removeNativeBinariesLI(PackageSetting ps) { 13941 // Remove the lib path for the parent package 13942 if (ps != null) { 13943 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13944 // Remove the lib path for the child packages 13945 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13946 for (int i = 0; i < childCount; i++) { 13947 PackageSetting childPs = null; 13948 synchronized (mPackages) { 13949 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13950 } 13951 if (childPs != null) { 13952 NativeLibraryHelper.removeNativeBinariesLI(childPs 13953 .legacyNativeLibraryPathString); 13954 } 13955 } 13956 } 13957 } 13958 13959 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13960 // Enable the parent package 13961 mSettings.enableSystemPackageLPw(pkg.packageName); 13962 // Enable the child packages 13963 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13964 for (int i = 0; i < childCount; i++) { 13965 PackageParser.Package childPkg = pkg.childPackages.get(i); 13966 mSettings.enableSystemPackageLPw(childPkg.packageName); 13967 } 13968 } 13969 13970 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13971 PackageParser.Package newPkg) { 13972 // Disable the parent package (parent always replaced) 13973 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13974 // Disable the child packages 13975 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13976 for (int i = 0; i < childCount; i++) { 13977 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13978 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13979 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13980 } 13981 return disabled; 13982 } 13983 13984 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13985 String installerPackageName) { 13986 // Enable the parent package 13987 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13988 // Enable the child packages 13989 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13990 for (int i = 0; i < childCount; i++) { 13991 PackageParser.Package childPkg = pkg.childPackages.get(i); 13992 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13993 } 13994 } 13995 13996 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13997 // Collect all used permissions in the UID 13998 ArraySet<String> usedPermissions = new ArraySet<>(); 13999 final int packageCount = su.packages.size(); 14000 for (int i = 0; i < packageCount; i++) { 14001 PackageSetting ps = su.packages.valueAt(i); 14002 if (ps.pkg == null) { 14003 continue; 14004 } 14005 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14006 for (int j = 0; j < requestedPermCount; j++) { 14007 String permission = ps.pkg.requestedPermissions.get(j); 14008 BasePermission bp = mSettings.mPermissions.get(permission); 14009 if (bp != null) { 14010 usedPermissions.add(permission); 14011 } 14012 } 14013 } 14014 14015 PermissionsState permissionsState = su.getPermissionsState(); 14016 // Prune install permissions 14017 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14018 final int installPermCount = installPermStates.size(); 14019 for (int i = installPermCount - 1; i >= 0; i--) { 14020 PermissionState permissionState = installPermStates.get(i); 14021 if (!usedPermissions.contains(permissionState.getName())) { 14022 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14023 if (bp != null) { 14024 permissionsState.revokeInstallPermission(bp); 14025 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14026 PackageManager.MASK_PERMISSION_FLAGS, 0); 14027 } 14028 } 14029 } 14030 14031 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14032 14033 // Prune runtime permissions 14034 for (int userId : allUserIds) { 14035 List<PermissionState> runtimePermStates = permissionsState 14036 .getRuntimePermissionStates(userId); 14037 final int runtimePermCount = runtimePermStates.size(); 14038 for (int i = runtimePermCount - 1; i >= 0; i--) { 14039 PermissionState permissionState = runtimePermStates.get(i); 14040 if (!usedPermissions.contains(permissionState.getName())) { 14041 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14042 if (bp != null) { 14043 permissionsState.revokeRuntimePermission(bp, userId); 14044 permissionsState.updatePermissionFlags(bp, userId, 14045 PackageManager.MASK_PERMISSION_FLAGS, 0); 14046 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14047 runtimePermissionChangedUserIds, userId); 14048 } 14049 } 14050 } 14051 } 14052 14053 return runtimePermissionChangedUserIds; 14054 } 14055 14056 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14057 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14058 // Update the parent package setting 14059 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14060 res, user); 14061 // Update the child packages setting 14062 final int childCount = (newPackage.childPackages != null) 14063 ? newPackage.childPackages.size() : 0; 14064 for (int i = 0; i < childCount; i++) { 14065 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14066 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14067 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14068 childRes.origUsers, childRes, user); 14069 } 14070 } 14071 14072 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14073 String installerPackageName, int[] allUsers, int[] installedForUsers, 14074 PackageInstalledInfo res, UserHandle user) { 14075 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14076 14077 String pkgName = newPackage.packageName; 14078 synchronized (mPackages) { 14079 //write settings. the installStatus will be incomplete at this stage. 14080 //note that the new package setting would have already been 14081 //added to mPackages. It hasn't been persisted yet. 14082 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14083 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14084 mSettings.writeLPr(); 14085 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14086 } 14087 14088 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14089 synchronized (mPackages) { 14090 updatePermissionsLPw(newPackage.packageName, newPackage, 14091 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14092 ? UPDATE_PERMISSIONS_ALL : 0)); 14093 // For system-bundled packages, we assume that installing an upgraded version 14094 // of the package implies that the user actually wants to run that new code, 14095 // so we enable the package. 14096 PackageSetting ps = mSettings.mPackages.get(pkgName); 14097 final int userId = user.getIdentifier(); 14098 if (ps != null) { 14099 if (isSystemApp(newPackage)) { 14100 if (DEBUG_INSTALL) { 14101 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14102 } 14103 // Enable system package for requested users 14104 if (res.origUsers != null) { 14105 for (int origUserId : res.origUsers) { 14106 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14107 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14108 origUserId, installerPackageName); 14109 } 14110 } 14111 } 14112 // Also convey the prior install/uninstall state 14113 if (allUsers != null && installedForUsers != null) { 14114 for (int currentUserId : allUsers) { 14115 final boolean installed = ArrayUtils.contains( 14116 installedForUsers, currentUserId); 14117 if (DEBUG_INSTALL) { 14118 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14119 } 14120 ps.setInstalled(installed, currentUserId); 14121 } 14122 // these install state changes will be persisted in the 14123 // upcoming call to mSettings.writeLPr(). 14124 } 14125 } 14126 // It's implied that when a user requests installation, they want the app to be 14127 // installed and enabled. 14128 if (userId != UserHandle.USER_ALL) { 14129 ps.setInstalled(true, userId); 14130 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14131 } 14132 } 14133 res.name = pkgName; 14134 res.uid = newPackage.applicationInfo.uid; 14135 res.pkg = newPackage; 14136 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14137 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14138 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14139 //to update install status 14140 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14141 mSettings.writeLPr(); 14142 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14143 } 14144 14145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14146 } 14147 14148 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14149 try { 14150 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14151 installPackageLI(args, res); 14152 } finally { 14153 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14154 } 14155 } 14156 14157 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14158 final int installFlags = args.installFlags; 14159 final String installerPackageName = args.installerPackageName; 14160 final String volumeUuid = args.volumeUuid; 14161 final File tmpPackageFile = new File(args.getCodePath()); 14162 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14163 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14164 || (args.volumeUuid != null)); 14165 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14166 boolean replace = false; 14167 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14168 if (args.move != null) { 14169 // moving a complete application; perform an initial scan on the new install location 14170 scanFlags |= SCAN_INITIAL; 14171 } 14172 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14173 scanFlags |= SCAN_DONT_KILL_APP; 14174 } 14175 14176 // Result object to be returned 14177 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14178 14179 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14180 14181 // Sanity check 14182 if (ephemeral && (forwardLocked || onExternal)) { 14183 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14184 + " external=" + onExternal); 14185 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14186 return; 14187 } 14188 14189 // Retrieve PackageSettings and parse package 14190 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14191 | PackageParser.PARSE_ENFORCE_CODE 14192 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14193 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14194 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14195 PackageParser pp = new PackageParser(); 14196 pp.setSeparateProcesses(mSeparateProcesses); 14197 pp.setDisplayMetrics(mMetrics); 14198 14199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14200 final PackageParser.Package pkg; 14201 try { 14202 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14203 } catch (PackageParserException e) { 14204 res.setError("Failed parse during installPackageLI", e); 14205 return; 14206 } finally { 14207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14208 } 14209 14210 // If we are installing a clustered package add results for the children 14211 if (pkg.childPackages != null) { 14212 synchronized (mPackages) { 14213 final int childCount = pkg.childPackages.size(); 14214 for (int i = 0; i < childCount; i++) { 14215 PackageParser.Package childPkg = pkg.childPackages.get(i); 14216 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14217 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14218 childRes.pkg = childPkg; 14219 childRes.name = childPkg.packageName; 14220 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14221 if (childPs != null) { 14222 childRes.origUsers = childPs.queryInstalledUsers( 14223 sUserManager.getUserIds(), true); 14224 } 14225 if ((mPackages.containsKey(childPkg.packageName))) { 14226 childRes.removedInfo = new PackageRemovedInfo(); 14227 childRes.removedInfo.removedPackage = childPkg.packageName; 14228 } 14229 if (res.addedChildPackages == null) { 14230 res.addedChildPackages = new ArrayMap<>(); 14231 } 14232 res.addedChildPackages.put(childPkg.packageName, childRes); 14233 } 14234 } 14235 } 14236 14237 // If package doesn't declare API override, mark that we have an install 14238 // time CPU ABI override. 14239 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14240 pkg.cpuAbiOverride = args.abiOverride; 14241 } 14242 14243 String pkgName = res.name = pkg.packageName; 14244 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14245 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14246 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14247 return; 14248 } 14249 } 14250 14251 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 14252 try { 14253 PackageParser.collectCertificates(pkg, parseFlags); 14254 } catch (PackageParserException e) { 14255 res.setError("Failed collect during installPackageLI", e); 14256 return; 14257 } finally { 14258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14259 } 14260 14261 // Get rid of all references to package scan path via parser. 14262 pp = null; 14263 String oldCodePath = null; 14264 boolean systemApp = false; 14265 synchronized (mPackages) { 14266 // Check if installing already existing package 14267 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14268 String oldName = mSettings.mRenamedPackages.get(pkgName); 14269 if (pkg.mOriginalPackages != null 14270 && pkg.mOriginalPackages.contains(oldName) 14271 && mPackages.containsKey(oldName)) { 14272 // This package is derived from an original package, 14273 // and this device has been updating from that original 14274 // name. We must continue using the original name, so 14275 // rename the new package here. 14276 pkg.setPackageName(oldName); 14277 pkgName = pkg.packageName; 14278 replace = true; 14279 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14280 + oldName + " pkgName=" + pkgName); 14281 } else if (mPackages.containsKey(pkgName)) { 14282 // This package, under its official name, already exists 14283 // on the device; we should replace it. 14284 replace = true; 14285 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14286 } 14287 14288 // Child packages are installed through the parent package 14289 if (pkg.parentPackage != null) { 14290 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14291 "Package " + pkg.packageName + " is child of package " 14292 + pkg.parentPackage.parentPackage + ". Child packages " 14293 + "can be updated only through the parent package."); 14294 return; 14295 } 14296 14297 if (replace) { 14298 // Prevent apps opting out from runtime permissions 14299 PackageParser.Package oldPackage = mPackages.get(pkgName); 14300 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14301 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14302 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14303 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14304 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14305 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14306 + " doesn't support runtime permissions but the old" 14307 + " target SDK " + oldTargetSdk + " does."); 14308 return; 14309 } 14310 14311 // Prevent installing of child packages 14312 if (oldPackage.parentPackage != null) { 14313 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14314 "Package " + pkg.packageName + " is child of package " 14315 + oldPackage.parentPackage + ". Child packages " 14316 + "can be updated only through the parent package."); 14317 return; 14318 } 14319 } 14320 } 14321 14322 PackageSetting ps = mSettings.mPackages.get(pkgName); 14323 if (ps != null) { 14324 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14325 14326 // Quick sanity check that we're signed correctly if updating; 14327 // we'll check this again later when scanning, but we want to 14328 // bail early here before tripping over redefined permissions. 14329 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14330 if (!checkUpgradeKeySetLP(ps, pkg)) { 14331 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14332 + pkg.packageName + " upgrade keys do not match the " 14333 + "previously installed version"); 14334 return; 14335 } 14336 } else { 14337 try { 14338 verifySignaturesLP(ps, pkg); 14339 } catch (PackageManagerException e) { 14340 res.setError(e.error, e.getMessage()); 14341 return; 14342 } 14343 } 14344 14345 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14346 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14347 systemApp = (ps.pkg.applicationInfo.flags & 14348 ApplicationInfo.FLAG_SYSTEM) != 0; 14349 } 14350 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14351 } 14352 14353 // Check whether the newly-scanned package wants to define an already-defined perm 14354 int N = pkg.permissions.size(); 14355 for (int i = N-1; i >= 0; i--) { 14356 PackageParser.Permission perm = pkg.permissions.get(i); 14357 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14358 if (bp != null) { 14359 // If the defining package is signed with our cert, it's okay. This 14360 // also includes the "updating the same package" case, of course. 14361 // "updating same package" could also involve key-rotation. 14362 final boolean sigsOk; 14363 if (bp.sourcePackage.equals(pkg.packageName) 14364 && (bp.packageSetting instanceof PackageSetting) 14365 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14366 scanFlags))) { 14367 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14368 } else { 14369 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14370 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14371 } 14372 if (!sigsOk) { 14373 // If the owning package is the system itself, we log but allow 14374 // install to proceed; we fail the install on all other permission 14375 // redefinitions. 14376 if (!bp.sourcePackage.equals("android")) { 14377 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14378 + pkg.packageName + " attempting to redeclare permission " 14379 + perm.info.name + " already owned by " + bp.sourcePackage); 14380 res.origPermission = perm.info.name; 14381 res.origPackage = bp.sourcePackage; 14382 return; 14383 } else { 14384 Slog.w(TAG, "Package " + pkg.packageName 14385 + " attempting to redeclare system permission " 14386 + perm.info.name + "; ignoring new declaration"); 14387 pkg.permissions.remove(i); 14388 } 14389 } 14390 } 14391 } 14392 } 14393 14394 if (systemApp) { 14395 if (onExternal) { 14396 // Abort update; system app can't be replaced with app on sdcard 14397 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14398 "Cannot install updates to system apps on sdcard"); 14399 return; 14400 } else if (ephemeral) { 14401 // Abort update; system app can't be replaced with an ephemeral app 14402 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14403 "Cannot update a system app with an ephemeral app"); 14404 return; 14405 } 14406 } 14407 14408 if (args.move != null) { 14409 // We did an in-place move, so dex is ready to roll 14410 scanFlags |= SCAN_NO_DEX; 14411 scanFlags |= SCAN_MOVE; 14412 14413 synchronized (mPackages) { 14414 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14415 if (ps == null) { 14416 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14417 "Missing settings for moved package " + pkgName); 14418 } 14419 14420 // We moved the entire application as-is, so bring over the 14421 // previously derived ABI information. 14422 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14423 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14424 } 14425 14426 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14427 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14428 scanFlags |= SCAN_NO_DEX; 14429 14430 try { 14431 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14432 args.abiOverride : pkg.cpuAbiOverride); 14433 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14434 true /* extract libs */); 14435 } catch (PackageManagerException pme) { 14436 Slog.e(TAG, "Error deriving application ABI", pme); 14437 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14438 return; 14439 } 14440 14441 14442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14443 // Do not run PackageDexOptimizer through the local performDexOpt 14444 // method because `pkg` is not in `mPackages` yet. 14445 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14446 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14448 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14449 String msg = "Extracking package failed for " + pkgName; 14450 res.setError(INSTALL_FAILED_DEXOPT, msg); 14451 return; 14452 } 14453 } 14454 14455 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14456 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14457 return; 14458 } 14459 14460 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14461 14462 if (replace) { 14463 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14464 installerPackageName, res); 14465 } else { 14466 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14467 args.user, installerPackageName, volumeUuid, res); 14468 } 14469 synchronized (mPackages) { 14470 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14471 if (ps != null) { 14472 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14473 } 14474 14475 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14476 for (int i = 0; i < childCount; i++) { 14477 PackageParser.Package childPkg = pkg.childPackages.get(i); 14478 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14479 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14480 if (childPs != null) { 14481 childRes.newUsers = childPs.queryInstalledUsers( 14482 sUserManager.getUserIds(), true); 14483 } 14484 } 14485 } 14486 } 14487 14488 private void startIntentFilterVerifications(int userId, boolean replacing, 14489 PackageParser.Package pkg) { 14490 if (mIntentFilterVerifierComponent == null) { 14491 Slog.w(TAG, "No IntentFilter verification will not be done as " 14492 + "there is no IntentFilterVerifier available!"); 14493 return; 14494 } 14495 14496 final int verifierUid = getPackageUid( 14497 mIntentFilterVerifierComponent.getPackageName(), 14498 MATCH_DEBUG_TRIAGED_MISSING, 14499 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14500 14501 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14502 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14503 mHandler.sendMessage(msg); 14504 14505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14506 for (int i = 0; i < childCount; i++) { 14507 PackageParser.Package childPkg = pkg.childPackages.get(i); 14508 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14509 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14510 mHandler.sendMessage(msg); 14511 } 14512 } 14513 14514 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14515 PackageParser.Package pkg) { 14516 int size = pkg.activities.size(); 14517 if (size == 0) { 14518 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14519 "No activity, so no need to verify any IntentFilter!"); 14520 return; 14521 } 14522 14523 final boolean hasDomainURLs = hasDomainURLs(pkg); 14524 if (!hasDomainURLs) { 14525 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14526 "No domain URLs, so no need to verify any IntentFilter!"); 14527 return; 14528 } 14529 14530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14531 + " if any IntentFilter from the " + size 14532 + " Activities needs verification ..."); 14533 14534 int count = 0; 14535 final String packageName = pkg.packageName; 14536 14537 synchronized (mPackages) { 14538 // If this is a new install and we see that we've already run verification for this 14539 // package, we have nothing to do: it means the state was restored from backup. 14540 if (!replacing) { 14541 IntentFilterVerificationInfo ivi = 14542 mSettings.getIntentFilterVerificationLPr(packageName); 14543 if (ivi != null) { 14544 if (DEBUG_DOMAIN_VERIFICATION) { 14545 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14546 + ivi.getStatusString()); 14547 } 14548 return; 14549 } 14550 } 14551 14552 // If any filters need to be verified, then all need to be. 14553 boolean needToVerify = false; 14554 for (PackageParser.Activity a : pkg.activities) { 14555 for (ActivityIntentInfo filter : a.intents) { 14556 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14557 if (DEBUG_DOMAIN_VERIFICATION) { 14558 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14559 } 14560 needToVerify = true; 14561 break; 14562 } 14563 } 14564 } 14565 14566 if (needToVerify) { 14567 final int verificationId = mIntentFilterVerificationToken++; 14568 for (PackageParser.Activity a : pkg.activities) { 14569 for (ActivityIntentInfo filter : a.intents) { 14570 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14571 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14572 "Verification needed for IntentFilter:" + filter.toString()); 14573 mIntentFilterVerifier.addOneIntentFilterVerification( 14574 verifierUid, userId, verificationId, filter, packageName); 14575 count++; 14576 } 14577 } 14578 } 14579 } 14580 } 14581 14582 if (count > 0) { 14583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14584 + " IntentFilter verification" + (count > 1 ? "s" : "") 14585 + " for userId:" + userId); 14586 mIntentFilterVerifier.startVerifications(userId); 14587 } else { 14588 if (DEBUG_DOMAIN_VERIFICATION) { 14589 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14590 } 14591 } 14592 } 14593 14594 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14595 final ComponentName cn = filter.activity.getComponentName(); 14596 final String packageName = cn.getPackageName(); 14597 14598 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14599 packageName); 14600 if (ivi == null) { 14601 return true; 14602 } 14603 int status = ivi.getStatus(); 14604 switch (status) { 14605 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14606 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14607 return true; 14608 14609 default: 14610 // Nothing to do 14611 return false; 14612 } 14613 } 14614 14615 private static boolean isMultiArch(ApplicationInfo info) { 14616 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14617 } 14618 14619 private static boolean isExternal(PackageParser.Package pkg) { 14620 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14621 } 14622 14623 private static boolean isExternal(PackageSetting ps) { 14624 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14625 } 14626 14627 private static boolean isEphemeral(PackageParser.Package pkg) { 14628 return pkg.applicationInfo.isEphemeralApp(); 14629 } 14630 14631 private static boolean isEphemeral(PackageSetting ps) { 14632 return ps.pkg != null && isEphemeral(ps.pkg); 14633 } 14634 14635 private static boolean isSystemApp(PackageParser.Package pkg) { 14636 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14637 } 14638 14639 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14640 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14641 } 14642 14643 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14644 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14645 } 14646 14647 private static boolean isSystemApp(PackageSetting ps) { 14648 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14649 } 14650 14651 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14652 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14653 } 14654 14655 private int packageFlagsToInstallFlags(PackageSetting ps) { 14656 int installFlags = 0; 14657 if (isEphemeral(ps)) { 14658 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14659 } 14660 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14661 // This existing package was an external ASEC install when we have 14662 // the external flag without a UUID 14663 installFlags |= PackageManager.INSTALL_EXTERNAL; 14664 } 14665 if (ps.isForwardLocked()) { 14666 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14667 } 14668 return installFlags; 14669 } 14670 14671 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14672 if (isExternal(pkg)) { 14673 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14674 return StorageManager.UUID_PRIMARY_PHYSICAL; 14675 } else { 14676 return pkg.volumeUuid; 14677 } 14678 } else { 14679 return StorageManager.UUID_PRIVATE_INTERNAL; 14680 } 14681 } 14682 14683 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14684 if (isExternal(pkg)) { 14685 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14686 return mSettings.getExternalVersion(); 14687 } else { 14688 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14689 } 14690 } else { 14691 return mSettings.getInternalVersion(); 14692 } 14693 } 14694 14695 private void deleteTempPackageFiles() { 14696 final FilenameFilter filter = new FilenameFilter() { 14697 public boolean accept(File dir, String name) { 14698 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14699 } 14700 }; 14701 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14702 file.delete(); 14703 } 14704 } 14705 14706 @Override 14707 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14708 int flags) { 14709 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14710 flags); 14711 } 14712 14713 @Override 14714 public void deletePackage(final String packageName, 14715 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14716 mContext.enforceCallingOrSelfPermission( 14717 android.Manifest.permission.DELETE_PACKAGES, null); 14718 Preconditions.checkNotNull(packageName); 14719 Preconditions.checkNotNull(observer); 14720 final int uid = Binder.getCallingUid(); 14721 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14722 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14723 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14724 mContext.enforceCallingOrSelfPermission( 14725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14726 "deletePackage for user " + userId); 14727 } 14728 14729 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14730 try { 14731 observer.onPackageDeleted(packageName, 14732 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14733 } catch (RemoteException re) { 14734 } 14735 return; 14736 } 14737 14738 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14739 try { 14740 observer.onPackageDeleted(packageName, 14741 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14742 } catch (RemoteException re) { 14743 } 14744 return; 14745 } 14746 14747 if (DEBUG_REMOVE) { 14748 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14749 + " deleteAllUsers: " + deleteAllUsers ); 14750 } 14751 // Queue up an async operation since the package deletion may take a little while. 14752 mHandler.post(new Runnable() { 14753 public void run() { 14754 mHandler.removeCallbacks(this); 14755 int returnCode; 14756 if (!deleteAllUsers) { 14757 returnCode = deletePackageX(packageName, userId, flags); 14758 } else { 14759 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14760 // If nobody is blocking uninstall, proceed with delete for all users 14761 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14762 returnCode = deletePackageX(packageName, userId, flags); 14763 } else { 14764 // Otherwise uninstall individually for users with blockUninstalls=false 14765 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14766 for (int userId : users) { 14767 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14768 returnCode = deletePackageX(packageName, userId, userFlags); 14769 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14770 Slog.w(TAG, "Package delete failed for user " + userId 14771 + ", returnCode " + returnCode); 14772 } 14773 } 14774 } 14775 // The app has only been marked uninstalled for certain users. 14776 // We still need to report that delete was blocked 14777 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14778 } 14779 } 14780 try { 14781 observer.onPackageDeleted(packageName, returnCode, null); 14782 } catch (RemoteException e) { 14783 Log.i(TAG, "Observer no longer exists."); 14784 } //end catch 14785 } //end run 14786 }); 14787 } 14788 14789 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14790 int[] result = EMPTY_INT_ARRAY; 14791 for (int userId : userIds) { 14792 if (getBlockUninstallForUser(packageName, userId)) { 14793 result = ArrayUtils.appendInt(result, userId); 14794 } 14795 } 14796 return result; 14797 } 14798 14799 @Override 14800 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14801 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14802 } 14803 14804 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14805 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14806 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14807 try { 14808 if (dpm != null) { 14809 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14810 /* callingUserOnly =*/ false); 14811 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14812 : deviceOwnerComponentName.getPackageName(); 14813 // Does the package contains the device owner? 14814 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14815 // this check is probably not needed, since DO should be registered as a device 14816 // admin on some user too. (Original bug for this: b/17657954) 14817 if (packageName.equals(deviceOwnerPackageName)) { 14818 return true; 14819 } 14820 // Does it contain a device admin for any user? 14821 int[] users; 14822 if (userId == UserHandle.USER_ALL) { 14823 users = sUserManager.getUserIds(); 14824 } else { 14825 users = new int[]{userId}; 14826 } 14827 for (int i = 0; i < users.length; ++i) { 14828 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14829 return true; 14830 } 14831 } 14832 } 14833 } catch (RemoteException e) { 14834 } 14835 return false; 14836 } 14837 14838 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14839 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14840 } 14841 14842 /** 14843 * This method is an internal method that could be get invoked either 14844 * to delete an installed package or to clean up a failed installation. 14845 * After deleting an installed package, a broadcast is sent to notify any 14846 * listeners that the package has been installed. For cleaning up a failed 14847 * installation, the broadcast is not necessary since the package's 14848 * installation wouldn't have sent the initial broadcast either 14849 * The key steps in deleting a package are 14850 * deleting the package information in internal structures like mPackages, 14851 * deleting the packages base directories through installd 14852 * updating mSettings to reflect current status 14853 * persisting settings for later use 14854 * sending a broadcast if necessary 14855 */ 14856 private int deletePackageX(String packageName, int userId, int flags) { 14857 final PackageRemovedInfo info = new PackageRemovedInfo(); 14858 final boolean res; 14859 14860 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14861 ? UserHandle.ALL : new UserHandle(userId); 14862 14863 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14864 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14865 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14866 } 14867 14868 PackageSetting uninstalledPs = null; 14869 14870 // for the uninstall-updates case and restricted profiles, remember the per- 14871 // user handle installed state 14872 int[] allUsers; 14873 synchronized (mPackages) { 14874 uninstalledPs = mSettings.mPackages.get(packageName); 14875 if (uninstalledPs == null) { 14876 Slog.w(TAG, "Not removing non-existent package " + packageName); 14877 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14878 } 14879 allUsers = sUserManager.getUserIds(); 14880 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14881 } 14882 14883 synchronized (mInstallLock) { 14884 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14885 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14886 flags | REMOVE_CHATTY, info, true, null); 14887 synchronized (mPackages) { 14888 if (res) { 14889 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14890 } 14891 } 14892 } 14893 14894 if (res) { 14895 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14896 info.sendPackageRemovedBroadcasts(killApp); 14897 info.sendSystemPackageUpdatedBroadcasts(); 14898 info.sendSystemPackageAppearedBroadcasts(); 14899 } 14900 // Force a gc here. 14901 Runtime.getRuntime().gc(); 14902 // Delete the resources here after sending the broadcast to let 14903 // other processes clean up before deleting resources. 14904 if (info.args != null) { 14905 synchronized (mInstallLock) { 14906 info.args.doPostDeleteLI(true); 14907 } 14908 } 14909 14910 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14911 } 14912 14913 class PackageRemovedInfo { 14914 String removedPackage; 14915 int uid = -1; 14916 int removedAppId = -1; 14917 int[] origUsers; 14918 int[] removedUsers = null; 14919 boolean isRemovedPackageSystemUpdate = false; 14920 boolean isUpdate; 14921 boolean dataRemoved; 14922 boolean removedForAllUsers; 14923 // Clean up resources deleted packages. 14924 InstallArgs args = null; 14925 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14926 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14927 14928 void sendPackageRemovedBroadcasts(boolean killApp) { 14929 sendPackageRemovedBroadcastInternal(killApp); 14930 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14931 for (int i = 0; i < childCount; i++) { 14932 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14933 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14934 } 14935 } 14936 14937 void sendSystemPackageUpdatedBroadcasts() { 14938 if (isRemovedPackageSystemUpdate) { 14939 sendSystemPackageUpdatedBroadcastsInternal(); 14940 final int childCount = (removedChildPackages != null) 14941 ? removedChildPackages.size() : 0; 14942 for (int i = 0; i < childCount; i++) { 14943 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14944 if (childInfo.isRemovedPackageSystemUpdate) { 14945 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14946 } 14947 } 14948 } 14949 } 14950 14951 void sendSystemPackageAppearedBroadcasts() { 14952 final int packageCount = (appearedChildPackages != null) 14953 ? appearedChildPackages.size() : 0; 14954 for (int i = 0; i < packageCount; i++) { 14955 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14956 for (int userId : installedInfo.newUsers) { 14957 sendPackageAddedForUser(installedInfo.name, true, 14958 UserHandle.getAppId(installedInfo.uid), userId); 14959 } 14960 } 14961 } 14962 14963 private void sendSystemPackageUpdatedBroadcastsInternal() { 14964 Bundle extras = new Bundle(2); 14965 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14966 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14967 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14968 extras, 0, null, null, null); 14969 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14970 extras, 0, null, null, null); 14971 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14972 null, 0, removedPackage, null, null); 14973 } 14974 14975 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14976 Bundle extras = new Bundle(2); 14977 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14978 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14979 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14980 if (isUpdate || isRemovedPackageSystemUpdate) { 14981 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14982 } 14983 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14984 if (removedPackage != null) { 14985 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14986 extras, 0, null, null, removedUsers); 14987 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14988 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14989 removedPackage, extras, 0, null, null, removedUsers); 14990 } 14991 } 14992 if (removedAppId >= 0) { 14993 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14994 removedUsers); 14995 } 14996 } 14997 } 14998 14999 /* 15000 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15001 * flag is not set, the data directory is removed as well. 15002 * make sure this flag is set for partially installed apps. If not its meaningless to 15003 * delete a partially installed application. 15004 */ 15005 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 15006 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15007 String packageName = ps.name; 15008 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15009 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15010 // Retrieve object to delete permissions for shared user later on 15011 final PackageSetting deletedPs; 15012 // reader 15013 synchronized (mPackages) { 15014 deletedPs = mSettings.mPackages.get(packageName); 15015 if (outInfo != null) { 15016 outInfo.removedPackage = packageName; 15017 outInfo.removedUsers = deletedPs != null 15018 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15019 : null; 15020 } 15021 } 15022 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15023 removeDataDirsLI(ps.volumeUuid, packageName); 15024 if (outInfo != null) { 15025 outInfo.dataRemoved = true; 15026 } 15027 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15028 } 15029 // writer 15030 synchronized (mPackages) { 15031 if (deletedPs != null) { 15032 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15033 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15034 clearDefaultBrowserIfNeeded(packageName); 15035 if (outInfo != null) { 15036 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15037 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15038 } 15039 updatePermissionsLPw(deletedPs.name, null, 0); 15040 if (deletedPs.sharedUser != null) { 15041 // Remove permissions associated with package. Since runtime 15042 // permissions are per user we have to kill the removed package 15043 // or packages running under the shared user of the removed 15044 // package if revoking the permissions requested only by the removed 15045 // package is successful and this causes a change in gids. 15046 for (int userId : UserManagerService.getInstance().getUserIds()) { 15047 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15048 userId); 15049 if (userIdToKill == UserHandle.USER_ALL 15050 || userIdToKill >= UserHandle.USER_SYSTEM) { 15051 // If gids changed for this user, kill all affected packages. 15052 mHandler.post(new Runnable() { 15053 @Override 15054 public void run() { 15055 // This has to happen with no lock held. 15056 killApplication(deletedPs.name, deletedPs.appId, 15057 KILL_APP_REASON_GIDS_CHANGED); 15058 } 15059 }); 15060 break; 15061 } 15062 } 15063 } 15064 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15065 } 15066 // make sure to preserve per-user disabled state if this removal was just 15067 // a downgrade of a system app to the factory package 15068 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15069 if (DEBUG_REMOVE) { 15070 Slog.d(TAG, "Propagating install state across downgrade"); 15071 } 15072 for (int userId : allUserHandles) { 15073 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15074 if (DEBUG_REMOVE) { 15075 Slog.d(TAG, " user " + userId + " => " + installed); 15076 } 15077 ps.setInstalled(installed, userId); 15078 } 15079 } 15080 } 15081 // can downgrade to reader 15082 if (writeSettings) { 15083 // Save settings now 15084 mSettings.writeLPr(); 15085 } 15086 } 15087 if (outInfo != null) { 15088 // A user ID was deleted here. Go through all users and remove it 15089 // from KeyStore. 15090 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15091 } 15092 } 15093 15094 static boolean locationIsPrivileged(File path) { 15095 try { 15096 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15097 .getCanonicalPath(); 15098 return path.getCanonicalPath().startsWith(privilegedAppDir); 15099 } catch (IOException e) { 15100 Slog.e(TAG, "Unable to access code path " + path); 15101 } 15102 return false; 15103 } 15104 15105 /* 15106 * Tries to delete system package. 15107 */ 15108 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15109 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15110 boolean writeSettings) { 15111 if (deletedPs.parentPackageName != null) { 15112 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15113 return false; 15114 } 15115 15116 final boolean applyUserRestrictions 15117 = (allUserHandles != null) && (outInfo.origUsers != null); 15118 final PackageSetting disabledPs; 15119 // Confirm if the system package has been updated 15120 // An updated system app can be deleted. This will also have to restore 15121 // the system pkg from system partition 15122 // reader 15123 synchronized (mPackages) { 15124 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15125 } 15126 15127 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15128 + " disabledPs=" + disabledPs); 15129 15130 if (disabledPs == null) { 15131 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15132 return false; 15133 } else if (DEBUG_REMOVE) { 15134 Slog.d(TAG, "Deleting system pkg from data partition"); 15135 } 15136 15137 if (DEBUG_REMOVE) { 15138 if (applyUserRestrictions) { 15139 Slog.d(TAG, "Remembering install states:"); 15140 for (int userId : allUserHandles) { 15141 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15142 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15143 } 15144 } 15145 } 15146 15147 // Delete the updated package 15148 outInfo.isRemovedPackageSystemUpdate = true; 15149 if (outInfo.removedChildPackages != null) { 15150 final int childCount = (deletedPs.childPackageNames != null) 15151 ? deletedPs.childPackageNames.size() : 0; 15152 for (int i = 0; i < childCount; i++) { 15153 String childPackageName = deletedPs.childPackageNames.get(i); 15154 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15155 .contains(childPackageName)) { 15156 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15157 childPackageName); 15158 if (childInfo != null) { 15159 childInfo.isRemovedPackageSystemUpdate = true; 15160 } 15161 } 15162 } 15163 } 15164 15165 if (disabledPs.versionCode < deletedPs.versionCode) { 15166 // Delete data for downgrades 15167 flags &= ~PackageManager.DELETE_KEEP_DATA; 15168 } else { 15169 // Preserve data by setting flag 15170 flags |= PackageManager.DELETE_KEEP_DATA; 15171 } 15172 15173 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15174 outInfo, writeSettings, disabledPs.pkg); 15175 if (!ret) { 15176 return false; 15177 } 15178 15179 // writer 15180 synchronized (mPackages) { 15181 // Reinstate the old system package 15182 enableSystemPackageLPw(disabledPs.pkg); 15183 // Remove any native libraries from the upgraded package. 15184 removeNativeBinariesLI(deletedPs); 15185 } 15186 15187 // Install the system package 15188 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15189 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15190 if (locationIsPrivileged(disabledPs.codePath)) { 15191 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15192 } 15193 15194 final PackageParser.Package newPkg; 15195 try { 15196 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15197 } catch (PackageManagerException e) { 15198 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15199 + e.getMessage()); 15200 return false; 15201 } 15202 15203 prepareAppDataAfterInstall(newPkg); 15204 15205 // writer 15206 synchronized (mPackages) { 15207 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15208 15209 // Propagate the permissions state as we do not want to drop on the floor 15210 // runtime permissions. The update permissions method below will take 15211 // care of removing obsolete permissions and grant install permissions. 15212 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15213 updatePermissionsLPw(newPkg.packageName, newPkg, 15214 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15215 15216 if (applyUserRestrictions) { 15217 if (DEBUG_REMOVE) { 15218 Slog.d(TAG, "Propagating install state across reinstall"); 15219 } 15220 for (int userId : allUserHandles) { 15221 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15222 if (DEBUG_REMOVE) { 15223 Slog.d(TAG, " user " + userId + " => " + installed); 15224 } 15225 ps.setInstalled(installed, userId); 15226 15227 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15228 } 15229 // Regardless of writeSettings we need to ensure that this restriction 15230 // state propagation is persisted 15231 mSettings.writeAllUsersPackageRestrictionsLPr(); 15232 } 15233 // can downgrade to reader here 15234 if (writeSettings) { 15235 mSettings.writeLPr(); 15236 } 15237 } 15238 return true; 15239 } 15240 15241 private boolean deleteInstalledPackageLI(PackageSetting ps, 15242 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15243 PackageRemovedInfo outInfo, boolean writeSettings, 15244 PackageParser.Package replacingPackage) { 15245 synchronized (mPackages) { 15246 if (outInfo != null) { 15247 outInfo.uid = ps.appId; 15248 } 15249 15250 if (outInfo != null && outInfo.removedChildPackages != null) { 15251 final int childCount = (ps.childPackageNames != null) 15252 ? ps.childPackageNames.size() : 0; 15253 for (int i = 0; i < childCount; i++) { 15254 String childPackageName = ps.childPackageNames.get(i); 15255 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15256 if (childPs == null) { 15257 return false; 15258 } 15259 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15260 childPackageName); 15261 if (childInfo != null) { 15262 childInfo.uid = childPs.appId; 15263 } 15264 } 15265 } 15266 } 15267 15268 // Delete package data from internal structures and also remove data if flag is set 15269 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15270 15271 // Delete the child packages data 15272 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15273 for (int i = 0; i < childCount; i++) { 15274 PackageSetting childPs; 15275 synchronized (mPackages) { 15276 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15277 } 15278 if (childPs != null) { 15279 PackageRemovedInfo childOutInfo = (outInfo != null 15280 && outInfo.removedChildPackages != null) 15281 ? outInfo.removedChildPackages.get(childPs.name) : null; 15282 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15283 && (replacingPackage != null 15284 && !replacingPackage.hasChildPackage(childPs.name)) 15285 ? flags & ~DELETE_KEEP_DATA : flags; 15286 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15287 deleteFlags, writeSettings); 15288 } 15289 } 15290 15291 // Delete application code and resources only for parent packages 15292 if (ps.parentPackageName == null) { 15293 if (deleteCodeAndResources && (outInfo != null)) { 15294 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15295 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15296 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15297 } 15298 } 15299 15300 return true; 15301 } 15302 15303 @Override 15304 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15305 int userId) { 15306 mContext.enforceCallingOrSelfPermission( 15307 android.Manifest.permission.DELETE_PACKAGES, null); 15308 synchronized (mPackages) { 15309 PackageSetting ps = mSettings.mPackages.get(packageName); 15310 if (ps == null) { 15311 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15312 return false; 15313 } 15314 if (!ps.getInstalled(userId)) { 15315 // Can't block uninstall for an app that is not installed or enabled. 15316 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15317 return false; 15318 } 15319 ps.setBlockUninstall(blockUninstall, userId); 15320 mSettings.writePackageRestrictionsLPr(userId); 15321 } 15322 return true; 15323 } 15324 15325 @Override 15326 public boolean getBlockUninstallForUser(String packageName, int userId) { 15327 synchronized (mPackages) { 15328 PackageSetting ps = mSettings.mPackages.get(packageName); 15329 if (ps == null) { 15330 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15331 return false; 15332 } 15333 return ps.getBlockUninstall(userId); 15334 } 15335 } 15336 15337 @Override 15338 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15339 int callingUid = Binder.getCallingUid(); 15340 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15341 throw new SecurityException( 15342 "setRequiredForSystemUser can only be run by the system or root"); 15343 } 15344 synchronized (mPackages) { 15345 PackageSetting ps = mSettings.mPackages.get(packageName); 15346 if (ps == null) { 15347 Log.w(TAG, "Package doesn't exist: " + packageName); 15348 return false; 15349 } 15350 if (systemUserApp) { 15351 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15352 } else { 15353 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15354 } 15355 mSettings.writeLPr(); 15356 } 15357 return true; 15358 } 15359 15360 /* 15361 * This method handles package deletion in general 15362 */ 15363 private boolean deletePackageLI(String packageName, UserHandle user, 15364 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15365 PackageRemovedInfo outInfo, boolean writeSettings, 15366 PackageParser.Package replacingPackage) { 15367 if (packageName == null) { 15368 Slog.w(TAG, "Attempt to delete null packageName."); 15369 return false; 15370 } 15371 15372 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15373 15374 PackageSetting ps; 15375 15376 synchronized (mPackages) { 15377 ps = mSettings.mPackages.get(packageName); 15378 if (ps == null) { 15379 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15380 return false; 15381 } 15382 15383 if (ps.parentPackageName != null && (!isSystemApp(ps) 15384 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15385 if (DEBUG_REMOVE) { 15386 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15387 + ((user == null) ? UserHandle.USER_ALL : user)); 15388 } 15389 final int removedUserId = (user != null) ? user.getIdentifier() 15390 : UserHandle.USER_ALL; 15391 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15392 return false; 15393 } 15394 markPackageUninstalledForUserLPw(ps, user); 15395 scheduleWritePackageRestrictionsLocked(user); 15396 return true; 15397 } 15398 } 15399 15400 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15401 && user.getIdentifier() != UserHandle.USER_ALL)) { 15402 // The caller is asking that the package only be deleted for a single 15403 // user. To do this, we just mark its uninstalled state and delete 15404 // its data. If this is a system app, we only allow this to happen if 15405 // they have set the special DELETE_SYSTEM_APP which requests different 15406 // semantics than normal for uninstalling system apps. 15407 markPackageUninstalledForUserLPw(ps, user); 15408 15409 if (!isSystemApp(ps)) { 15410 // Do not uninstall the APK if an app should be cached 15411 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15412 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15413 // Other user still have this package installed, so all 15414 // we need to do is clear this user's data and save that 15415 // it is uninstalled. 15416 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15417 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15418 return false; 15419 } 15420 scheduleWritePackageRestrictionsLocked(user); 15421 return true; 15422 } else { 15423 // We need to set it back to 'installed' so the uninstall 15424 // broadcasts will be sent correctly. 15425 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15426 ps.setInstalled(true, user.getIdentifier()); 15427 } 15428 } else { 15429 // This is a system app, so we assume that the 15430 // other users still have this package installed, so all 15431 // we need to do is clear this user's data and save that 15432 // it is uninstalled. 15433 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15434 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15435 return false; 15436 } 15437 scheduleWritePackageRestrictionsLocked(user); 15438 return true; 15439 } 15440 } 15441 15442 // If we are deleting a composite package for all users, keep track 15443 // of result for each child. 15444 if (ps.childPackageNames != null && outInfo != null) { 15445 synchronized (mPackages) { 15446 final int childCount = ps.childPackageNames.size(); 15447 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15448 for (int i = 0; i < childCount; i++) { 15449 String childPackageName = ps.childPackageNames.get(i); 15450 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15451 childInfo.removedPackage = childPackageName; 15452 outInfo.removedChildPackages.put(childPackageName, childInfo); 15453 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15454 if (childPs != null) { 15455 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15456 } 15457 } 15458 } 15459 } 15460 15461 boolean ret = false; 15462 if (isSystemApp(ps)) { 15463 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15464 // When an updated system application is deleted we delete the existing resources 15465 // as well and fall back to existing code in system partition 15466 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15467 } else { 15468 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15469 // Kill application pre-emptively especially for apps on sd. 15470 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15471 if (killApp) { 15472 killApplication(packageName, ps.appId, "uninstall pkg"); 15473 } 15474 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15475 outInfo, writeSettings, replacingPackage); 15476 } 15477 15478 // Take a note whether we deleted the package for all users 15479 if (outInfo != null) { 15480 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15481 if (outInfo.removedChildPackages != null) { 15482 synchronized (mPackages) { 15483 final int childCount = outInfo.removedChildPackages.size(); 15484 for (int i = 0; i < childCount; i++) { 15485 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15486 if (childInfo != null) { 15487 childInfo.removedForAllUsers = mPackages.get( 15488 childInfo.removedPackage) == null; 15489 } 15490 } 15491 } 15492 } 15493 // If we uninstalled an update to a system app there may be some 15494 // child packages that appeared as they are declared in the system 15495 // app but were not declared in the update. 15496 if (isSystemApp(ps)) { 15497 synchronized (mPackages) { 15498 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15499 final int childCount = (updatedPs.childPackageNames != null) 15500 ? updatedPs.childPackageNames.size() : 0; 15501 for (int i = 0; i < childCount; i++) { 15502 String childPackageName = updatedPs.childPackageNames.get(i); 15503 if (outInfo.removedChildPackages == null 15504 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15505 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15506 if (childPs == null) { 15507 continue; 15508 } 15509 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15510 installRes.name = childPackageName; 15511 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15512 installRes.pkg = mPackages.get(childPackageName); 15513 installRes.uid = childPs.pkg.applicationInfo.uid; 15514 if (outInfo.appearedChildPackages == null) { 15515 outInfo.appearedChildPackages = new ArrayMap<>(); 15516 } 15517 outInfo.appearedChildPackages.put(childPackageName, installRes); 15518 } 15519 } 15520 } 15521 } 15522 } 15523 15524 return ret; 15525 } 15526 15527 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15528 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15529 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15530 for (int nextUserId : userIds) { 15531 if (DEBUG_REMOVE) { 15532 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15533 } 15534 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15535 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15536 false /*hidden*/, false /*suspended*/, null, null, null, 15537 false /*blockUninstall*/, 15538 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15539 } 15540 } 15541 15542 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15543 PackageRemovedInfo outInfo) { 15544 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15545 : new int[] {userId}; 15546 for (int nextUserId : userIds) { 15547 if (DEBUG_REMOVE) { 15548 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15549 + nextUserId); 15550 } 15551 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15552 try { 15553 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15554 } catch (InstallerException e) { 15555 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15556 return false; 15557 } 15558 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15559 schedulePackageCleaning(ps.name, nextUserId, false); 15560 synchronized (mPackages) { 15561 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15562 scheduleWritePackageRestrictionsLocked(nextUserId); 15563 } 15564 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15565 } 15566 } 15567 15568 if (outInfo != null) { 15569 outInfo.removedPackage = ps.name; 15570 outInfo.removedAppId = ps.appId; 15571 outInfo.removedUsers = userIds; 15572 } 15573 15574 return true; 15575 } 15576 15577 private final class ClearStorageConnection implements ServiceConnection { 15578 IMediaContainerService mContainerService; 15579 15580 @Override 15581 public void onServiceConnected(ComponentName name, IBinder service) { 15582 synchronized (this) { 15583 mContainerService = IMediaContainerService.Stub.asInterface(service); 15584 notifyAll(); 15585 } 15586 } 15587 15588 @Override 15589 public void onServiceDisconnected(ComponentName name) { 15590 } 15591 } 15592 15593 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15594 final boolean mounted; 15595 if (Environment.isExternalStorageEmulated()) { 15596 mounted = true; 15597 } else { 15598 final String status = Environment.getExternalStorageState(); 15599 15600 mounted = status.equals(Environment.MEDIA_MOUNTED) 15601 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15602 } 15603 15604 if (!mounted) { 15605 return; 15606 } 15607 15608 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15609 int[] users; 15610 if (userId == UserHandle.USER_ALL) { 15611 users = sUserManager.getUserIds(); 15612 } else { 15613 users = new int[] { userId }; 15614 } 15615 final ClearStorageConnection conn = new ClearStorageConnection(); 15616 if (mContext.bindServiceAsUser( 15617 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15618 try { 15619 for (int curUser : users) { 15620 long timeout = SystemClock.uptimeMillis() + 5000; 15621 synchronized (conn) { 15622 long now = SystemClock.uptimeMillis(); 15623 while (conn.mContainerService == null && now < timeout) { 15624 try { 15625 conn.wait(timeout - now); 15626 } catch (InterruptedException e) { 15627 } 15628 } 15629 } 15630 if (conn.mContainerService == null) { 15631 return; 15632 } 15633 15634 final UserEnvironment userEnv = new UserEnvironment(curUser); 15635 clearDirectory(conn.mContainerService, 15636 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15637 if (allData) { 15638 clearDirectory(conn.mContainerService, 15639 userEnv.buildExternalStorageAppDataDirs(packageName)); 15640 clearDirectory(conn.mContainerService, 15641 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15642 } 15643 } 15644 } finally { 15645 mContext.unbindService(conn); 15646 } 15647 } 15648 } 15649 15650 @Override 15651 public void clearApplicationProfileData(String packageName) { 15652 enforceSystemOrRoot("Only the system can clear all profile data"); 15653 try { 15654 mInstaller.clearAppProfiles(packageName); 15655 } catch (InstallerException ex) { 15656 Log.e(TAG, "Could not clear profile data of package " + packageName); 15657 } 15658 } 15659 15660 @Override 15661 public void clearApplicationUserData(final String packageName, 15662 final IPackageDataObserver observer, final int userId) { 15663 mContext.enforceCallingOrSelfPermission( 15664 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15665 15666 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15667 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15668 15669 final DevicePolicyManagerInternal dpmi = LocalServices 15670 .getService(DevicePolicyManagerInternal.class); 15671 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15672 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15673 } 15674 // Queue up an async operation since the package deletion may take a little while. 15675 mHandler.post(new Runnable() { 15676 public void run() { 15677 mHandler.removeCallbacks(this); 15678 final boolean succeeded; 15679 synchronized (mInstallLock) { 15680 succeeded = clearApplicationUserDataLI(packageName, userId); 15681 } 15682 clearExternalStorageDataSync(packageName, userId, true); 15683 if (succeeded) { 15684 // invoke DeviceStorageMonitor's update method to clear any notifications 15685 DeviceStorageMonitorInternal dsm = LocalServices 15686 .getService(DeviceStorageMonitorInternal.class); 15687 if (dsm != null) { 15688 dsm.checkMemory(); 15689 } 15690 } 15691 if(observer != null) { 15692 try { 15693 observer.onRemoveCompleted(packageName, succeeded); 15694 } catch (RemoteException e) { 15695 Log.i(TAG, "Observer no longer exists."); 15696 } 15697 } //end if observer 15698 } //end run 15699 }); 15700 } 15701 15702 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15703 if (packageName == null) { 15704 Slog.w(TAG, "Attempt to delete null packageName."); 15705 return false; 15706 } 15707 15708 // Try finding details about the requested package 15709 PackageParser.Package pkg; 15710 synchronized (mPackages) { 15711 pkg = mPackages.get(packageName); 15712 if (pkg == null) { 15713 final PackageSetting ps = mSettings.mPackages.get(packageName); 15714 if (ps != null) { 15715 pkg = ps.pkg; 15716 } 15717 } 15718 15719 if (pkg == null) { 15720 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15721 return false; 15722 } 15723 15724 PackageSetting ps = (PackageSetting) pkg.mExtras; 15725 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15726 } 15727 15728 // Always delete data directories for package, even if we found no other 15729 // record of app. This helps users recover from UID mismatches without 15730 // resorting to a full data wipe. 15731 // TODO: triage flags as part of 26466827 15732 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15733 try { 15734 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15735 } catch (InstallerException e) { 15736 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15737 return false; 15738 } 15739 15740 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15741 removeKeystoreDataIfNeeded(userId, appId); 15742 15743 // Create a native library symlink only if we have native libraries 15744 // and if the native libraries are 32 bit libraries. We do not provide 15745 // this symlink for 64 bit libraries. 15746 if (pkg.applicationInfo.primaryCpuAbi != null && 15747 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15748 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15749 try { 15750 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15751 nativeLibPath, userId); 15752 } catch (InstallerException e) { 15753 Slog.w(TAG, "Failed linking native library dir", e); 15754 return false; 15755 } 15756 } 15757 15758 return true; 15759 } 15760 15761 /** 15762 * Reverts user permission state changes (permissions and flags) in 15763 * all packages for a given user. 15764 * 15765 * @param userId The device user for which to do a reset. 15766 */ 15767 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15768 final int packageCount = mPackages.size(); 15769 for (int i = 0; i < packageCount; i++) { 15770 PackageParser.Package pkg = mPackages.valueAt(i); 15771 PackageSetting ps = (PackageSetting) pkg.mExtras; 15772 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15773 } 15774 } 15775 15776 /** 15777 * Reverts user permission state changes (permissions and flags). 15778 * 15779 * @param ps The package for which to reset. 15780 * @param userId The device user for which to do a reset. 15781 */ 15782 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15783 final PackageSetting ps, final int userId) { 15784 if (ps.pkg == null) { 15785 return; 15786 } 15787 15788 // These are flags that can change base on user actions. 15789 final int userSettableMask = FLAG_PERMISSION_USER_SET 15790 | FLAG_PERMISSION_USER_FIXED 15791 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15792 | FLAG_PERMISSION_REVIEW_REQUIRED; 15793 15794 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15795 | FLAG_PERMISSION_POLICY_FIXED; 15796 15797 boolean writeInstallPermissions = false; 15798 boolean writeRuntimePermissions = false; 15799 15800 final int permissionCount = ps.pkg.requestedPermissions.size(); 15801 for (int i = 0; i < permissionCount; i++) { 15802 String permission = ps.pkg.requestedPermissions.get(i); 15803 15804 BasePermission bp = mSettings.mPermissions.get(permission); 15805 if (bp == null) { 15806 continue; 15807 } 15808 15809 // If shared user we just reset the state to which only this app contributed. 15810 if (ps.sharedUser != null) { 15811 boolean used = false; 15812 final int packageCount = ps.sharedUser.packages.size(); 15813 for (int j = 0; j < packageCount; j++) { 15814 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15815 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15816 && pkg.pkg.requestedPermissions.contains(permission)) { 15817 used = true; 15818 break; 15819 } 15820 } 15821 if (used) { 15822 continue; 15823 } 15824 } 15825 15826 PermissionsState permissionsState = ps.getPermissionsState(); 15827 15828 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15829 15830 // Always clear the user settable flags. 15831 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15832 bp.name) != null; 15833 // If permission review is enabled and this is a legacy app, mark the 15834 // permission as requiring a review as this is the initial state. 15835 int flags = 0; 15836 if (Build.PERMISSIONS_REVIEW_REQUIRED 15837 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15838 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15839 } 15840 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15841 if (hasInstallState) { 15842 writeInstallPermissions = true; 15843 } else { 15844 writeRuntimePermissions = true; 15845 } 15846 } 15847 15848 // Below is only runtime permission handling. 15849 if (!bp.isRuntime()) { 15850 continue; 15851 } 15852 15853 // Never clobber system or policy. 15854 if ((oldFlags & policyOrSystemFlags) != 0) { 15855 continue; 15856 } 15857 15858 // If this permission was granted by default, make sure it is. 15859 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15860 if (permissionsState.grantRuntimePermission(bp, userId) 15861 != PERMISSION_OPERATION_FAILURE) { 15862 writeRuntimePermissions = true; 15863 } 15864 // If permission review is enabled the permissions for a legacy apps 15865 // are represented as constantly granted runtime ones, so don't revoke. 15866 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15867 // Otherwise, reset the permission. 15868 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15869 switch (revokeResult) { 15870 case PERMISSION_OPERATION_SUCCESS: 15871 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15872 writeRuntimePermissions = true; 15873 final int appId = ps.appId; 15874 mHandler.post(new Runnable() { 15875 @Override 15876 public void run() { 15877 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15878 } 15879 }); 15880 } break; 15881 } 15882 } 15883 } 15884 15885 // Synchronously write as we are taking permissions away. 15886 if (writeRuntimePermissions) { 15887 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15888 } 15889 15890 // Synchronously write as we are taking permissions away. 15891 if (writeInstallPermissions) { 15892 mSettings.writeLPr(); 15893 } 15894 } 15895 15896 /** 15897 * Remove entries from the keystore daemon. Will only remove it if the 15898 * {@code appId} is valid. 15899 */ 15900 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15901 if (appId < 0) { 15902 return; 15903 } 15904 15905 final KeyStore keyStore = KeyStore.getInstance(); 15906 if (keyStore != null) { 15907 if (userId == UserHandle.USER_ALL) { 15908 for (final int individual : sUserManager.getUserIds()) { 15909 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15910 } 15911 } else { 15912 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15913 } 15914 } else { 15915 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15916 } 15917 } 15918 15919 @Override 15920 public void deleteApplicationCacheFiles(final String packageName, 15921 final IPackageDataObserver observer) { 15922 mContext.enforceCallingOrSelfPermission( 15923 android.Manifest.permission.DELETE_CACHE_FILES, null); 15924 // Queue up an async operation since the package deletion may take a little while. 15925 final int userId = UserHandle.getCallingUserId(); 15926 mHandler.post(new Runnable() { 15927 public void run() { 15928 mHandler.removeCallbacks(this); 15929 final boolean succeded; 15930 synchronized (mInstallLock) { 15931 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15932 } 15933 clearExternalStorageDataSync(packageName, userId, false); 15934 if (observer != null) { 15935 try { 15936 observer.onRemoveCompleted(packageName, succeded); 15937 } catch (RemoteException e) { 15938 Log.i(TAG, "Observer no longer exists."); 15939 } 15940 } //end if observer 15941 } //end run 15942 }); 15943 } 15944 15945 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15946 if (packageName == null) { 15947 Slog.w(TAG, "Attempt to delete null packageName."); 15948 return false; 15949 } 15950 PackageParser.Package p; 15951 synchronized (mPackages) { 15952 p = mPackages.get(packageName); 15953 } 15954 if (p == null) { 15955 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15956 return false; 15957 } 15958 final ApplicationInfo applicationInfo = p.applicationInfo; 15959 if (applicationInfo == null) { 15960 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15961 return false; 15962 } 15963 // TODO: triage flags as part of 26466827 15964 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15965 try { 15966 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15967 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15968 } catch (InstallerException e) { 15969 Slog.w(TAG, "Couldn't remove cache files for package " 15970 + packageName + " u" + userId, e); 15971 return false; 15972 } 15973 return true; 15974 } 15975 15976 @Override 15977 public void getPackageSizeInfo(final String packageName, int userHandle, 15978 final IPackageStatsObserver observer) { 15979 mContext.enforceCallingOrSelfPermission( 15980 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15981 if (packageName == null) { 15982 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15983 } 15984 15985 PackageStats stats = new PackageStats(packageName, userHandle); 15986 15987 /* 15988 * Queue up an async operation since the package measurement may take a 15989 * little while. 15990 */ 15991 Message msg = mHandler.obtainMessage(INIT_COPY); 15992 msg.obj = new MeasureParams(stats, observer); 15993 mHandler.sendMessage(msg); 15994 } 15995 15996 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15997 PackageStats pStats) { 15998 if (packageName == null) { 15999 Slog.w(TAG, "Attempt to get size of null packageName."); 16000 return false; 16001 } 16002 PackageParser.Package p; 16003 boolean dataOnly = false; 16004 String libDirRoot = null; 16005 String asecPath = null; 16006 PackageSetting ps = null; 16007 synchronized (mPackages) { 16008 p = mPackages.get(packageName); 16009 ps = mSettings.mPackages.get(packageName); 16010 if(p == null) { 16011 dataOnly = true; 16012 if((ps == null) || (ps.pkg == null)) { 16013 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16014 return false; 16015 } 16016 p = ps.pkg; 16017 } 16018 if (ps != null) { 16019 libDirRoot = ps.legacyNativeLibraryPathString; 16020 } 16021 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16022 final long token = Binder.clearCallingIdentity(); 16023 try { 16024 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16025 if (secureContainerId != null) { 16026 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16027 } 16028 } finally { 16029 Binder.restoreCallingIdentity(token); 16030 } 16031 } 16032 } 16033 String publicSrcDir = null; 16034 if(!dataOnly) { 16035 final ApplicationInfo applicationInfo = p.applicationInfo; 16036 if (applicationInfo == null) { 16037 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16038 return false; 16039 } 16040 if (p.isForwardLocked()) { 16041 publicSrcDir = applicationInfo.getBaseResourcePath(); 16042 } 16043 } 16044 // TODO: extend to measure size of split APKs 16045 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16046 // not just the first level. 16047 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16048 // just the primary. 16049 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16050 16051 String apkPath; 16052 File packageDir = new File(p.codePath); 16053 16054 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16055 apkPath = packageDir.getAbsolutePath(); 16056 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16057 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16058 libDirRoot = null; 16059 } 16060 } else { 16061 apkPath = p.baseCodePath; 16062 } 16063 16064 // TODO: triage flags as part of 26466827 16065 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16066 try { 16067 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16068 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16069 } catch (InstallerException e) { 16070 return false; 16071 } 16072 16073 // Fix-up for forward-locked applications in ASEC containers. 16074 if (!isExternal(p)) { 16075 pStats.codeSize += pStats.externalCodeSize; 16076 pStats.externalCodeSize = 0L; 16077 } 16078 16079 return true; 16080 } 16081 16082 private int getUidTargetSdkVersionLockedLPr(int uid) { 16083 Object obj = mSettings.getUserIdLPr(uid); 16084 if (obj instanceof SharedUserSetting) { 16085 final SharedUserSetting sus = (SharedUserSetting) obj; 16086 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16087 final Iterator<PackageSetting> it = sus.packages.iterator(); 16088 while (it.hasNext()) { 16089 final PackageSetting ps = it.next(); 16090 if (ps.pkg != null) { 16091 int v = ps.pkg.applicationInfo.targetSdkVersion; 16092 if (v < vers) vers = v; 16093 } 16094 } 16095 return vers; 16096 } else if (obj instanceof PackageSetting) { 16097 final PackageSetting ps = (PackageSetting) obj; 16098 if (ps.pkg != null) { 16099 return ps.pkg.applicationInfo.targetSdkVersion; 16100 } 16101 } 16102 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16103 } 16104 16105 @Override 16106 public void addPreferredActivity(IntentFilter filter, int match, 16107 ComponentName[] set, ComponentName activity, int userId) { 16108 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16109 "Adding preferred"); 16110 } 16111 16112 private void addPreferredActivityInternal(IntentFilter filter, int match, 16113 ComponentName[] set, ComponentName activity, boolean always, int userId, 16114 String opname) { 16115 // writer 16116 int callingUid = Binder.getCallingUid(); 16117 enforceCrossUserPermission(callingUid, userId, 16118 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16119 if (filter.countActions() == 0) { 16120 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16121 return; 16122 } 16123 synchronized (mPackages) { 16124 if (mContext.checkCallingOrSelfPermission( 16125 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16126 != PackageManager.PERMISSION_GRANTED) { 16127 if (getUidTargetSdkVersionLockedLPr(callingUid) 16128 < Build.VERSION_CODES.FROYO) { 16129 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16130 + callingUid); 16131 return; 16132 } 16133 mContext.enforceCallingOrSelfPermission( 16134 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16135 } 16136 16137 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16138 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16139 + userId + ":"); 16140 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16141 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16142 scheduleWritePackageRestrictionsLocked(userId); 16143 } 16144 } 16145 16146 @Override 16147 public void replacePreferredActivity(IntentFilter filter, int match, 16148 ComponentName[] set, ComponentName activity, int userId) { 16149 if (filter.countActions() != 1) { 16150 throw new IllegalArgumentException( 16151 "replacePreferredActivity expects filter to have only 1 action."); 16152 } 16153 if (filter.countDataAuthorities() != 0 16154 || filter.countDataPaths() != 0 16155 || filter.countDataSchemes() > 1 16156 || filter.countDataTypes() != 0) { 16157 throw new IllegalArgumentException( 16158 "replacePreferredActivity expects filter to have no data authorities, " + 16159 "paths, or types; and at most one scheme."); 16160 } 16161 16162 final int callingUid = Binder.getCallingUid(); 16163 enforceCrossUserPermission(callingUid, userId, 16164 true /* requireFullPermission */, false /* checkShell */, 16165 "replace preferred activity"); 16166 synchronized (mPackages) { 16167 if (mContext.checkCallingOrSelfPermission( 16168 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16169 != PackageManager.PERMISSION_GRANTED) { 16170 if (getUidTargetSdkVersionLockedLPr(callingUid) 16171 < Build.VERSION_CODES.FROYO) { 16172 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16173 + Binder.getCallingUid()); 16174 return; 16175 } 16176 mContext.enforceCallingOrSelfPermission( 16177 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16178 } 16179 16180 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16181 if (pir != null) { 16182 // Get all of the existing entries that exactly match this filter. 16183 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16184 if (existing != null && existing.size() == 1) { 16185 PreferredActivity cur = existing.get(0); 16186 if (DEBUG_PREFERRED) { 16187 Slog.i(TAG, "Checking replace of preferred:"); 16188 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16189 if (!cur.mPref.mAlways) { 16190 Slog.i(TAG, " -- CUR; not mAlways!"); 16191 } else { 16192 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16193 Slog.i(TAG, " -- CUR: mSet=" 16194 + Arrays.toString(cur.mPref.mSetComponents)); 16195 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16196 Slog.i(TAG, " -- NEW: mMatch=" 16197 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16198 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16199 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16200 } 16201 } 16202 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16203 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16204 && cur.mPref.sameSet(set)) { 16205 // Setting the preferred activity to what it happens to be already 16206 if (DEBUG_PREFERRED) { 16207 Slog.i(TAG, "Replacing with same preferred activity " 16208 + cur.mPref.mShortComponent + " for user " 16209 + userId + ":"); 16210 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16211 } 16212 return; 16213 } 16214 } 16215 16216 if (existing != null) { 16217 if (DEBUG_PREFERRED) { 16218 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16220 } 16221 for (int i = 0; i < existing.size(); i++) { 16222 PreferredActivity pa = existing.get(i); 16223 if (DEBUG_PREFERRED) { 16224 Slog.i(TAG, "Removing existing preferred activity " 16225 + pa.mPref.mComponent + ":"); 16226 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16227 } 16228 pir.removeFilter(pa); 16229 } 16230 } 16231 } 16232 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16233 "Replacing preferred"); 16234 } 16235 } 16236 16237 @Override 16238 public void clearPackagePreferredActivities(String packageName) { 16239 final int uid = Binder.getCallingUid(); 16240 // writer 16241 synchronized (mPackages) { 16242 PackageParser.Package pkg = mPackages.get(packageName); 16243 if (pkg == null || pkg.applicationInfo.uid != uid) { 16244 if (mContext.checkCallingOrSelfPermission( 16245 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16246 != PackageManager.PERMISSION_GRANTED) { 16247 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16248 < Build.VERSION_CODES.FROYO) { 16249 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16250 + Binder.getCallingUid()); 16251 return; 16252 } 16253 mContext.enforceCallingOrSelfPermission( 16254 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16255 } 16256 } 16257 16258 int user = UserHandle.getCallingUserId(); 16259 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16260 scheduleWritePackageRestrictionsLocked(user); 16261 } 16262 } 16263 } 16264 16265 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16266 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16267 ArrayList<PreferredActivity> removed = null; 16268 boolean changed = false; 16269 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16270 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16271 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16272 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16273 continue; 16274 } 16275 Iterator<PreferredActivity> it = pir.filterIterator(); 16276 while (it.hasNext()) { 16277 PreferredActivity pa = it.next(); 16278 // Mark entry for removal only if it matches the package name 16279 // and the entry is of type "always". 16280 if (packageName == null || 16281 (pa.mPref.mComponent.getPackageName().equals(packageName) 16282 && pa.mPref.mAlways)) { 16283 if (removed == null) { 16284 removed = new ArrayList<PreferredActivity>(); 16285 } 16286 removed.add(pa); 16287 } 16288 } 16289 if (removed != null) { 16290 for (int j=0; j<removed.size(); j++) { 16291 PreferredActivity pa = removed.get(j); 16292 pir.removeFilter(pa); 16293 } 16294 changed = true; 16295 } 16296 } 16297 return changed; 16298 } 16299 16300 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16301 private void clearIntentFilterVerificationsLPw(int userId) { 16302 final int packageCount = mPackages.size(); 16303 for (int i = 0; i < packageCount; i++) { 16304 PackageParser.Package pkg = mPackages.valueAt(i); 16305 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16306 } 16307 } 16308 16309 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16310 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16311 if (userId == UserHandle.USER_ALL) { 16312 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16313 sUserManager.getUserIds())) { 16314 for (int oneUserId : sUserManager.getUserIds()) { 16315 scheduleWritePackageRestrictionsLocked(oneUserId); 16316 } 16317 } 16318 } else { 16319 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16320 scheduleWritePackageRestrictionsLocked(userId); 16321 } 16322 } 16323 } 16324 16325 void clearDefaultBrowserIfNeeded(String packageName) { 16326 for (int oneUserId : sUserManager.getUserIds()) { 16327 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16328 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16329 if (packageName.equals(defaultBrowserPackageName)) { 16330 setDefaultBrowserPackageName(null, oneUserId); 16331 } 16332 } 16333 } 16334 16335 @Override 16336 public void resetApplicationPreferences(int userId) { 16337 mContext.enforceCallingOrSelfPermission( 16338 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16339 // writer 16340 synchronized (mPackages) { 16341 final long identity = Binder.clearCallingIdentity(); 16342 try { 16343 clearPackagePreferredActivitiesLPw(null, userId); 16344 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16345 // TODO: We have to reset the default SMS and Phone. This requires 16346 // significant refactoring to keep all default apps in the package 16347 // manager (cleaner but more work) or have the services provide 16348 // callbacks to the package manager to request a default app reset. 16349 applyFactoryDefaultBrowserLPw(userId); 16350 clearIntentFilterVerificationsLPw(userId); 16351 primeDomainVerificationsLPw(userId); 16352 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16353 scheduleWritePackageRestrictionsLocked(userId); 16354 } finally { 16355 Binder.restoreCallingIdentity(identity); 16356 } 16357 } 16358 } 16359 16360 @Override 16361 public int getPreferredActivities(List<IntentFilter> outFilters, 16362 List<ComponentName> outActivities, String packageName) { 16363 16364 int num = 0; 16365 final int userId = UserHandle.getCallingUserId(); 16366 // reader 16367 synchronized (mPackages) { 16368 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16369 if (pir != null) { 16370 final Iterator<PreferredActivity> it = pir.filterIterator(); 16371 while (it.hasNext()) { 16372 final PreferredActivity pa = it.next(); 16373 if (packageName == null 16374 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16375 && pa.mPref.mAlways)) { 16376 if (outFilters != null) { 16377 outFilters.add(new IntentFilter(pa)); 16378 } 16379 if (outActivities != null) { 16380 outActivities.add(pa.mPref.mComponent); 16381 } 16382 } 16383 } 16384 } 16385 } 16386 16387 return num; 16388 } 16389 16390 @Override 16391 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16392 int userId) { 16393 int callingUid = Binder.getCallingUid(); 16394 if (callingUid != Process.SYSTEM_UID) { 16395 throw new SecurityException( 16396 "addPersistentPreferredActivity can only be run by the system"); 16397 } 16398 if (filter.countActions() == 0) { 16399 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16400 return; 16401 } 16402 synchronized (mPackages) { 16403 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16404 ":"); 16405 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16406 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16407 new PersistentPreferredActivity(filter, activity)); 16408 scheduleWritePackageRestrictionsLocked(userId); 16409 } 16410 } 16411 16412 @Override 16413 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16414 int callingUid = Binder.getCallingUid(); 16415 if (callingUid != Process.SYSTEM_UID) { 16416 throw new SecurityException( 16417 "clearPackagePersistentPreferredActivities can only be run by the system"); 16418 } 16419 ArrayList<PersistentPreferredActivity> removed = null; 16420 boolean changed = false; 16421 synchronized (mPackages) { 16422 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16423 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16424 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16425 .valueAt(i); 16426 if (userId != thisUserId) { 16427 continue; 16428 } 16429 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16430 while (it.hasNext()) { 16431 PersistentPreferredActivity ppa = it.next(); 16432 // Mark entry for removal only if it matches the package name. 16433 if (ppa.mComponent.getPackageName().equals(packageName)) { 16434 if (removed == null) { 16435 removed = new ArrayList<PersistentPreferredActivity>(); 16436 } 16437 removed.add(ppa); 16438 } 16439 } 16440 if (removed != null) { 16441 for (int j=0; j<removed.size(); j++) { 16442 PersistentPreferredActivity ppa = removed.get(j); 16443 ppir.removeFilter(ppa); 16444 } 16445 changed = true; 16446 } 16447 } 16448 16449 if (changed) { 16450 scheduleWritePackageRestrictionsLocked(userId); 16451 } 16452 } 16453 } 16454 16455 /** 16456 * Common machinery for picking apart a restored XML blob and passing 16457 * it to a caller-supplied functor to be applied to the running system. 16458 */ 16459 private void restoreFromXml(XmlPullParser parser, int userId, 16460 String expectedStartTag, BlobXmlRestorer functor) 16461 throws IOException, XmlPullParserException { 16462 int type; 16463 while ((type = parser.next()) != XmlPullParser.START_TAG 16464 && type != XmlPullParser.END_DOCUMENT) { 16465 } 16466 if (type != XmlPullParser.START_TAG) { 16467 // oops didn't find a start tag?! 16468 if (DEBUG_BACKUP) { 16469 Slog.e(TAG, "Didn't find start tag during restore"); 16470 } 16471 return; 16472 } 16473Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16474 // this is supposed to be TAG_PREFERRED_BACKUP 16475 if (!expectedStartTag.equals(parser.getName())) { 16476 if (DEBUG_BACKUP) { 16477 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16478 } 16479 return; 16480 } 16481 16482 // skip interfering stuff, then we're aligned with the backing implementation 16483 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16484Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16485 functor.apply(parser, userId); 16486 } 16487 16488 private interface BlobXmlRestorer { 16489 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16490 } 16491 16492 /** 16493 * Non-Binder method, support for the backup/restore mechanism: write the 16494 * full set of preferred activities in its canonical XML format. Returns the 16495 * XML output as a byte array, or null if there is none. 16496 */ 16497 @Override 16498 public byte[] getPreferredActivityBackup(int userId) { 16499 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16500 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16501 } 16502 16503 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16504 try { 16505 final XmlSerializer serializer = new FastXmlSerializer(); 16506 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16507 serializer.startDocument(null, true); 16508 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16509 16510 synchronized (mPackages) { 16511 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16512 } 16513 16514 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16515 serializer.endDocument(); 16516 serializer.flush(); 16517 } catch (Exception e) { 16518 if (DEBUG_BACKUP) { 16519 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16520 } 16521 return null; 16522 } 16523 16524 return dataStream.toByteArray(); 16525 } 16526 16527 @Override 16528 public void restorePreferredActivities(byte[] backup, int userId) { 16529 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16530 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16531 } 16532 16533 try { 16534 final XmlPullParser parser = Xml.newPullParser(); 16535 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16536 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16537 new BlobXmlRestorer() { 16538 @Override 16539 public void apply(XmlPullParser parser, int userId) 16540 throws XmlPullParserException, IOException { 16541 synchronized (mPackages) { 16542 mSettings.readPreferredActivitiesLPw(parser, userId); 16543 } 16544 } 16545 } ); 16546 } catch (Exception e) { 16547 if (DEBUG_BACKUP) { 16548 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16549 } 16550 } 16551 } 16552 16553 /** 16554 * Non-Binder method, support for the backup/restore mechanism: write the 16555 * default browser (etc) settings in its canonical XML format. Returns the default 16556 * browser XML representation as a byte array, or null if there is none. 16557 */ 16558 @Override 16559 public byte[] getDefaultAppsBackup(int userId) { 16560 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16561 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16562 } 16563 16564 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16565 try { 16566 final XmlSerializer serializer = new FastXmlSerializer(); 16567 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16568 serializer.startDocument(null, true); 16569 serializer.startTag(null, TAG_DEFAULT_APPS); 16570 16571 synchronized (mPackages) { 16572 mSettings.writeDefaultAppsLPr(serializer, userId); 16573 } 16574 16575 serializer.endTag(null, TAG_DEFAULT_APPS); 16576 serializer.endDocument(); 16577 serializer.flush(); 16578 } catch (Exception e) { 16579 if (DEBUG_BACKUP) { 16580 Slog.e(TAG, "Unable to write default apps for backup", e); 16581 } 16582 return null; 16583 } 16584 16585 return dataStream.toByteArray(); 16586 } 16587 16588 @Override 16589 public void restoreDefaultApps(byte[] backup, int userId) { 16590 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16591 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16592 } 16593 16594 try { 16595 final XmlPullParser parser = Xml.newPullParser(); 16596 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16597 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16598 new BlobXmlRestorer() { 16599 @Override 16600 public void apply(XmlPullParser parser, int userId) 16601 throws XmlPullParserException, IOException { 16602 synchronized (mPackages) { 16603 mSettings.readDefaultAppsLPw(parser, userId); 16604 } 16605 } 16606 } ); 16607 } catch (Exception e) { 16608 if (DEBUG_BACKUP) { 16609 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16610 } 16611 } 16612 } 16613 16614 @Override 16615 public byte[] getIntentFilterVerificationBackup(int userId) { 16616 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16617 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16618 } 16619 16620 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16621 try { 16622 final XmlSerializer serializer = new FastXmlSerializer(); 16623 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16624 serializer.startDocument(null, true); 16625 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16626 16627 synchronized (mPackages) { 16628 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16629 } 16630 16631 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16632 serializer.endDocument(); 16633 serializer.flush(); 16634 } catch (Exception e) { 16635 if (DEBUG_BACKUP) { 16636 Slog.e(TAG, "Unable to write default apps for backup", e); 16637 } 16638 return null; 16639 } 16640 16641 return dataStream.toByteArray(); 16642 } 16643 16644 @Override 16645 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16646 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16647 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16648 } 16649 16650 try { 16651 final XmlPullParser parser = Xml.newPullParser(); 16652 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16653 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16654 new BlobXmlRestorer() { 16655 @Override 16656 public void apply(XmlPullParser parser, int userId) 16657 throws XmlPullParserException, IOException { 16658 synchronized (mPackages) { 16659 mSettings.readAllDomainVerificationsLPr(parser, userId); 16660 mSettings.writeLPr(); 16661 } 16662 } 16663 } ); 16664 } catch (Exception e) { 16665 if (DEBUG_BACKUP) { 16666 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16667 } 16668 } 16669 } 16670 16671 @Override 16672 public byte[] getPermissionGrantBackup(int userId) { 16673 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16674 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16675 } 16676 16677 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16678 try { 16679 final XmlSerializer serializer = new FastXmlSerializer(); 16680 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16681 serializer.startDocument(null, true); 16682 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16683 16684 synchronized (mPackages) { 16685 serializeRuntimePermissionGrantsLPr(serializer, userId); 16686 } 16687 16688 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16689 serializer.endDocument(); 16690 serializer.flush(); 16691 } catch (Exception e) { 16692 if (DEBUG_BACKUP) { 16693 Slog.e(TAG, "Unable to write default apps for backup", e); 16694 } 16695 return null; 16696 } 16697 16698 return dataStream.toByteArray(); 16699 } 16700 16701 @Override 16702 public void restorePermissionGrants(byte[] backup, int userId) { 16703 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16704 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16705 } 16706 16707 try { 16708 final XmlPullParser parser = Xml.newPullParser(); 16709 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16710 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16711 new BlobXmlRestorer() { 16712 @Override 16713 public void apply(XmlPullParser parser, int userId) 16714 throws XmlPullParserException, IOException { 16715 synchronized (mPackages) { 16716 processRestoredPermissionGrantsLPr(parser, userId); 16717 } 16718 } 16719 } ); 16720 } catch (Exception e) { 16721 if (DEBUG_BACKUP) { 16722 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16723 } 16724 } 16725 } 16726 16727 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16728 throws IOException { 16729 serializer.startTag(null, TAG_ALL_GRANTS); 16730 16731 final int N = mSettings.mPackages.size(); 16732 for (int i = 0; i < N; i++) { 16733 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16734 boolean pkgGrantsKnown = false; 16735 16736 PermissionsState packagePerms = ps.getPermissionsState(); 16737 16738 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16739 final int grantFlags = state.getFlags(); 16740 // only look at grants that are not system/policy fixed 16741 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16742 final boolean isGranted = state.isGranted(); 16743 // And only back up the user-twiddled state bits 16744 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16745 final String packageName = mSettings.mPackages.keyAt(i); 16746 if (!pkgGrantsKnown) { 16747 serializer.startTag(null, TAG_GRANT); 16748 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16749 pkgGrantsKnown = true; 16750 } 16751 16752 final boolean userSet = 16753 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16754 final boolean userFixed = 16755 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16756 final boolean revoke = 16757 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16758 16759 serializer.startTag(null, TAG_PERMISSION); 16760 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16761 if (isGranted) { 16762 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16763 } 16764 if (userSet) { 16765 serializer.attribute(null, ATTR_USER_SET, "true"); 16766 } 16767 if (userFixed) { 16768 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16769 } 16770 if (revoke) { 16771 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16772 } 16773 serializer.endTag(null, TAG_PERMISSION); 16774 } 16775 } 16776 } 16777 16778 if (pkgGrantsKnown) { 16779 serializer.endTag(null, TAG_GRANT); 16780 } 16781 } 16782 16783 serializer.endTag(null, TAG_ALL_GRANTS); 16784 } 16785 16786 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16787 throws XmlPullParserException, IOException { 16788 String pkgName = null; 16789 int outerDepth = parser.getDepth(); 16790 int type; 16791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16794 continue; 16795 } 16796 16797 final String tagName = parser.getName(); 16798 if (tagName.equals(TAG_GRANT)) { 16799 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16800 if (DEBUG_BACKUP) { 16801 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16802 } 16803 } else if (tagName.equals(TAG_PERMISSION)) { 16804 16805 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16806 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16807 16808 int newFlagSet = 0; 16809 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16810 newFlagSet |= FLAG_PERMISSION_USER_SET; 16811 } 16812 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16813 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16814 } 16815 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16816 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16817 } 16818 if (DEBUG_BACKUP) { 16819 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16820 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16821 } 16822 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16823 if (ps != null) { 16824 // Already installed so we apply the grant immediately 16825 if (DEBUG_BACKUP) { 16826 Slog.v(TAG, " + already installed; applying"); 16827 } 16828 PermissionsState perms = ps.getPermissionsState(); 16829 BasePermission bp = mSettings.mPermissions.get(permName); 16830 if (bp != null) { 16831 if (isGranted) { 16832 perms.grantRuntimePermission(bp, userId); 16833 } 16834 if (newFlagSet != 0) { 16835 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16836 } 16837 } 16838 } else { 16839 // Need to wait for post-restore install to apply the grant 16840 if (DEBUG_BACKUP) { 16841 Slog.v(TAG, " - not yet installed; saving for later"); 16842 } 16843 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16844 isGranted, newFlagSet, userId); 16845 } 16846 } else { 16847 PackageManagerService.reportSettingsProblem(Log.WARN, 16848 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16849 XmlUtils.skipCurrentTag(parser); 16850 } 16851 } 16852 16853 scheduleWriteSettingsLocked(); 16854 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16855 } 16856 16857 @Override 16858 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16859 int sourceUserId, int targetUserId, int flags) { 16860 mContext.enforceCallingOrSelfPermission( 16861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16862 int callingUid = Binder.getCallingUid(); 16863 enforceOwnerRights(ownerPackage, callingUid); 16864 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16865 if (intentFilter.countActions() == 0) { 16866 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16867 return; 16868 } 16869 synchronized (mPackages) { 16870 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16871 ownerPackage, targetUserId, flags); 16872 CrossProfileIntentResolver resolver = 16873 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16874 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16875 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16876 if (existing != null) { 16877 int size = existing.size(); 16878 for (int i = 0; i < size; i++) { 16879 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16880 return; 16881 } 16882 } 16883 } 16884 resolver.addFilter(newFilter); 16885 scheduleWritePackageRestrictionsLocked(sourceUserId); 16886 } 16887 } 16888 16889 @Override 16890 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16891 mContext.enforceCallingOrSelfPermission( 16892 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16893 int callingUid = Binder.getCallingUid(); 16894 enforceOwnerRights(ownerPackage, callingUid); 16895 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16896 synchronized (mPackages) { 16897 CrossProfileIntentResolver resolver = 16898 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16899 ArraySet<CrossProfileIntentFilter> set = 16900 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16901 for (CrossProfileIntentFilter filter : set) { 16902 if (filter.getOwnerPackage().equals(ownerPackage)) { 16903 resolver.removeFilter(filter); 16904 } 16905 } 16906 scheduleWritePackageRestrictionsLocked(sourceUserId); 16907 } 16908 } 16909 16910 // Enforcing that callingUid is owning pkg on userId 16911 private void enforceOwnerRights(String pkg, int callingUid) { 16912 // The system owns everything. 16913 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16914 return; 16915 } 16916 int callingUserId = UserHandle.getUserId(callingUid); 16917 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16918 if (pi == null) { 16919 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16920 + callingUserId); 16921 } 16922 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16923 throw new SecurityException("Calling uid " + callingUid 16924 + " does not own package " + pkg); 16925 } 16926 } 16927 16928 @Override 16929 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16930 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16931 } 16932 16933 private Intent getHomeIntent() { 16934 Intent intent = new Intent(Intent.ACTION_MAIN); 16935 intent.addCategory(Intent.CATEGORY_HOME); 16936 return intent; 16937 } 16938 16939 private IntentFilter getHomeFilter() { 16940 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16941 filter.addCategory(Intent.CATEGORY_HOME); 16942 filter.addCategory(Intent.CATEGORY_DEFAULT); 16943 return filter; 16944 } 16945 16946 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16947 int userId) { 16948 Intent intent = getHomeIntent(); 16949 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16950 PackageManager.GET_META_DATA, userId); 16951 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16952 true, false, false, userId); 16953 16954 allHomeCandidates.clear(); 16955 if (list != null) { 16956 for (ResolveInfo ri : list) { 16957 allHomeCandidates.add(ri); 16958 } 16959 } 16960 return (preferred == null || preferred.activityInfo == null) 16961 ? null 16962 : new ComponentName(preferred.activityInfo.packageName, 16963 preferred.activityInfo.name); 16964 } 16965 16966 @Override 16967 public void setHomeActivity(ComponentName comp, int userId) { 16968 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16969 getHomeActivitiesAsUser(homeActivities, userId); 16970 16971 boolean found = false; 16972 16973 final int size = homeActivities.size(); 16974 final ComponentName[] set = new ComponentName[size]; 16975 for (int i = 0; i < size; i++) { 16976 final ResolveInfo candidate = homeActivities.get(i); 16977 final ActivityInfo info = candidate.activityInfo; 16978 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16979 set[i] = activityName; 16980 if (!found && activityName.equals(comp)) { 16981 found = true; 16982 } 16983 } 16984 if (!found) { 16985 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16986 + userId); 16987 } 16988 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16989 set, comp, userId); 16990 } 16991 16992 private @Nullable String getSetupWizardPackageName() { 16993 final Intent intent = new Intent(Intent.ACTION_MAIN); 16994 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 16995 16996 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 16997 MATCH_SYSTEM_ONLY | MATCH_DISABLED_COMPONENTS, UserHandle.myUserId()); 16998 if (matches.size() == 1) { 16999 return matches.get(0).getComponentInfo().packageName; 17000 } else { 17001 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17002 + ": matches=" + matches); 17003 return null; 17004 } 17005 } 17006 17007 @Override 17008 public void setApplicationEnabledSetting(String appPackageName, 17009 int newState, int flags, int userId, String callingPackage) { 17010 if (!sUserManager.exists(userId)) return; 17011 if (callingPackage == null) { 17012 callingPackage = Integer.toString(Binder.getCallingUid()); 17013 } 17014 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17015 } 17016 17017 @Override 17018 public void setComponentEnabledSetting(ComponentName componentName, 17019 int newState, int flags, int userId) { 17020 if (!sUserManager.exists(userId)) return; 17021 setEnabledSetting(componentName.getPackageName(), 17022 componentName.getClassName(), newState, flags, userId, null); 17023 } 17024 17025 private void setEnabledSetting(final String packageName, String className, int newState, 17026 final int flags, int userId, String callingPackage) { 17027 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17028 || newState == COMPONENT_ENABLED_STATE_ENABLED 17029 || newState == COMPONENT_ENABLED_STATE_DISABLED 17030 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17031 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17032 throw new IllegalArgumentException("Invalid new component state: " 17033 + newState); 17034 } 17035 PackageSetting pkgSetting; 17036 final int uid = Binder.getCallingUid(); 17037 final int permission = mContext.checkCallingOrSelfPermission( 17038 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17039 enforceCrossUserPermission(uid, userId, 17040 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17041 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17042 boolean sendNow = false; 17043 boolean isApp = (className == null); 17044 String componentName = isApp ? packageName : className; 17045 int packageUid = -1; 17046 ArrayList<String> components; 17047 17048 // writer 17049 synchronized (mPackages) { 17050 pkgSetting = mSettings.mPackages.get(packageName); 17051 if (pkgSetting == null) { 17052 if (className == null) { 17053 throw new IllegalArgumentException("Unknown package: " + packageName); 17054 } 17055 throw new IllegalArgumentException( 17056 "Unknown component: " + packageName + "/" + className); 17057 } 17058 // Allow root and verify that userId is not being specified by a different user 17059 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17060 throw new SecurityException( 17061 "Permission Denial: attempt to change component state from pid=" 17062 + Binder.getCallingPid() 17063 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17064 } 17065 if (className == null) { 17066 // We're dealing with an application/package level state change 17067 if (pkgSetting.getEnabled(userId) == newState) { 17068 // Nothing to do 17069 return; 17070 } 17071 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17072 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17073 // Don't care about who enables an app. 17074 callingPackage = null; 17075 } 17076 pkgSetting.setEnabled(newState, userId, callingPackage); 17077 // pkgSetting.pkg.mSetEnabled = newState; 17078 } else { 17079 // We're dealing with a component level state change 17080 // First, verify that this is a valid class name. 17081 PackageParser.Package pkg = pkgSetting.pkg; 17082 if (pkg == null || !pkg.hasComponentClassName(className)) { 17083 if (pkg != null && 17084 pkg.applicationInfo.targetSdkVersion >= 17085 Build.VERSION_CODES.JELLY_BEAN) { 17086 throw new IllegalArgumentException("Component class " + className 17087 + " does not exist in " + packageName); 17088 } else { 17089 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17090 + className + " does not exist in " + packageName); 17091 } 17092 } 17093 switch (newState) { 17094 case COMPONENT_ENABLED_STATE_ENABLED: 17095 if (!pkgSetting.enableComponentLPw(className, userId)) { 17096 return; 17097 } 17098 break; 17099 case COMPONENT_ENABLED_STATE_DISABLED: 17100 if (!pkgSetting.disableComponentLPw(className, userId)) { 17101 return; 17102 } 17103 break; 17104 case COMPONENT_ENABLED_STATE_DEFAULT: 17105 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17106 return; 17107 } 17108 break; 17109 default: 17110 Slog.e(TAG, "Invalid new component state: " + newState); 17111 return; 17112 } 17113 } 17114 scheduleWritePackageRestrictionsLocked(userId); 17115 components = mPendingBroadcasts.get(userId, packageName); 17116 final boolean newPackage = components == null; 17117 if (newPackage) { 17118 components = new ArrayList<String>(); 17119 } 17120 if (!components.contains(componentName)) { 17121 components.add(componentName); 17122 } 17123 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17124 sendNow = true; 17125 // Purge entry from pending broadcast list if another one exists already 17126 // since we are sending one right away. 17127 mPendingBroadcasts.remove(userId, packageName); 17128 } else { 17129 if (newPackage) { 17130 mPendingBroadcasts.put(userId, packageName, components); 17131 } 17132 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17133 // Schedule a message 17134 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17135 } 17136 } 17137 } 17138 17139 long callingId = Binder.clearCallingIdentity(); 17140 try { 17141 if (sendNow) { 17142 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17143 sendPackageChangedBroadcast(packageName, 17144 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17145 } 17146 } finally { 17147 Binder.restoreCallingIdentity(callingId); 17148 } 17149 } 17150 17151 @Override 17152 public void flushPackageRestrictionsAsUser(int userId) { 17153 if (!sUserManager.exists(userId)) { 17154 return; 17155 } 17156 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17157 false /* checkShell */, "flushPackageRestrictions"); 17158 synchronized (mPackages) { 17159 mSettings.writePackageRestrictionsLPr(userId); 17160 mDirtyUsers.remove(userId); 17161 if (mDirtyUsers.isEmpty()) { 17162 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17163 } 17164 } 17165 } 17166 17167 private void sendPackageChangedBroadcast(String packageName, 17168 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17169 if (DEBUG_INSTALL) 17170 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17171 + componentNames); 17172 Bundle extras = new Bundle(4); 17173 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17174 String nameList[] = new String[componentNames.size()]; 17175 componentNames.toArray(nameList); 17176 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17177 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17178 extras.putInt(Intent.EXTRA_UID, packageUid); 17179 // If this is not reporting a change of the overall package, then only send it 17180 // to registered receivers. We don't want to launch a swath of apps for every 17181 // little component state change. 17182 final int flags = !componentNames.contains(packageName) 17183 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17184 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17185 new int[] {UserHandle.getUserId(packageUid)}); 17186 } 17187 17188 @Override 17189 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17190 if (!sUserManager.exists(userId)) return; 17191 final int uid = Binder.getCallingUid(); 17192 final int permission = mContext.checkCallingOrSelfPermission( 17193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17194 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17195 enforceCrossUserPermission(uid, userId, 17196 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17197 // writer 17198 synchronized (mPackages) { 17199 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17200 allowedByPermission, uid, userId)) { 17201 scheduleWritePackageRestrictionsLocked(userId); 17202 } 17203 } 17204 } 17205 17206 @Override 17207 public String getInstallerPackageName(String packageName) { 17208 // reader 17209 synchronized (mPackages) { 17210 return mSettings.getInstallerPackageNameLPr(packageName); 17211 } 17212 } 17213 17214 @Override 17215 public int getApplicationEnabledSetting(String packageName, 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 enabled"); 17220 // reader 17221 synchronized (mPackages) { 17222 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17223 } 17224 } 17225 17226 @Override 17227 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17228 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17229 int uid = Binder.getCallingUid(); 17230 enforceCrossUserPermission(uid, userId, 17231 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17232 // reader 17233 synchronized (mPackages) { 17234 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17235 } 17236 } 17237 17238 @Override 17239 public void enterSafeMode() { 17240 enforceSystemOrRoot("Only the system can request entering safe mode"); 17241 17242 if (!mSystemReady) { 17243 mSafeMode = true; 17244 } 17245 } 17246 17247 @Override 17248 public void systemReady() { 17249 mSystemReady = true; 17250 17251 // Read the compatibilty setting when the system is ready. 17252 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17253 mContext.getContentResolver(), 17254 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17255 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17256 if (DEBUG_SETTINGS) { 17257 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17258 } 17259 17260 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17261 17262 synchronized (mPackages) { 17263 // Verify that all of the preferred activity components actually 17264 // exist. It is possible for applications to be updated and at 17265 // that point remove a previously declared activity component that 17266 // had been set as a preferred activity. We try to clean this up 17267 // the next time we encounter that preferred activity, but it is 17268 // possible for the user flow to never be able to return to that 17269 // situation so here we do a sanity check to make sure we haven't 17270 // left any junk around. 17271 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17272 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17273 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17274 removed.clear(); 17275 for (PreferredActivity pa : pir.filterSet()) { 17276 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17277 removed.add(pa); 17278 } 17279 } 17280 if (removed.size() > 0) { 17281 for (int r=0; r<removed.size(); r++) { 17282 PreferredActivity pa = removed.get(r); 17283 Slog.w(TAG, "Removing dangling preferred activity: " 17284 + pa.mPref.mComponent); 17285 pir.removeFilter(pa); 17286 } 17287 mSettings.writePackageRestrictionsLPr( 17288 mSettings.mPreferredActivities.keyAt(i)); 17289 } 17290 } 17291 17292 for (int userId : UserManagerService.getInstance().getUserIds()) { 17293 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17294 grantPermissionsUserIds = ArrayUtils.appendInt( 17295 grantPermissionsUserIds, userId); 17296 } 17297 } 17298 } 17299 sUserManager.systemReady(); 17300 17301 // If we upgraded grant all default permissions before kicking off. 17302 for (int userId : grantPermissionsUserIds) { 17303 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17304 } 17305 17306 // Kick off any messages waiting for system ready 17307 if (mPostSystemReadyMessages != null) { 17308 for (Message msg : mPostSystemReadyMessages) { 17309 msg.sendToTarget(); 17310 } 17311 mPostSystemReadyMessages = null; 17312 } 17313 17314 // Watch for external volumes that come and go over time 17315 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17316 storage.registerListener(mStorageListener); 17317 17318 mInstallerService.systemReady(); 17319 mPackageDexOptimizer.systemReady(); 17320 17321 MountServiceInternal mountServiceInternal = LocalServices.getService( 17322 MountServiceInternal.class); 17323 mountServiceInternal.addExternalStoragePolicy( 17324 new MountServiceInternal.ExternalStorageMountPolicy() { 17325 @Override 17326 public int getMountMode(int uid, String packageName) { 17327 if (Process.isIsolated(uid)) { 17328 return Zygote.MOUNT_EXTERNAL_NONE; 17329 } 17330 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17331 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17332 } 17333 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17334 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17335 } 17336 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17337 return Zygote.MOUNT_EXTERNAL_READ; 17338 } 17339 return Zygote.MOUNT_EXTERNAL_WRITE; 17340 } 17341 17342 @Override 17343 public boolean hasExternalStorage(int uid, String packageName) { 17344 return true; 17345 } 17346 }); 17347 } 17348 17349 @Override 17350 public boolean isSafeMode() { 17351 return mSafeMode; 17352 } 17353 17354 @Override 17355 public boolean hasSystemUidErrors() { 17356 return mHasSystemUidErrors; 17357 } 17358 17359 static String arrayToString(int[] array) { 17360 StringBuffer buf = new StringBuffer(128); 17361 buf.append('['); 17362 if (array != null) { 17363 for (int i=0; i<array.length; i++) { 17364 if (i > 0) buf.append(", "); 17365 buf.append(array[i]); 17366 } 17367 } 17368 buf.append(']'); 17369 return buf.toString(); 17370 } 17371 17372 static class DumpState { 17373 public static final int DUMP_LIBS = 1 << 0; 17374 public static final int DUMP_FEATURES = 1 << 1; 17375 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17376 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17377 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17378 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17379 public static final int DUMP_PERMISSIONS = 1 << 6; 17380 public static final int DUMP_PACKAGES = 1 << 7; 17381 public static final int DUMP_SHARED_USERS = 1 << 8; 17382 public static final int DUMP_MESSAGES = 1 << 9; 17383 public static final int DUMP_PROVIDERS = 1 << 10; 17384 public static final int DUMP_VERIFIERS = 1 << 11; 17385 public static final int DUMP_PREFERRED = 1 << 12; 17386 public static final int DUMP_PREFERRED_XML = 1 << 13; 17387 public static final int DUMP_KEYSETS = 1 << 14; 17388 public static final int DUMP_VERSION = 1 << 15; 17389 public static final int DUMP_INSTALLS = 1 << 16; 17390 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17391 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17392 17393 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17394 17395 private int mTypes; 17396 17397 private int mOptions; 17398 17399 private boolean mTitlePrinted; 17400 17401 private SharedUserSetting mSharedUser; 17402 17403 public boolean isDumping(int type) { 17404 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17405 return true; 17406 } 17407 17408 return (mTypes & type) != 0; 17409 } 17410 17411 public void setDump(int type) { 17412 mTypes |= type; 17413 } 17414 17415 public boolean isOptionEnabled(int option) { 17416 return (mOptions & option) != 0; 17417 } 17418 17419 public void setOptionEnabled(int option) { 17420 mOptions |= option; 17421 } 17422 17423 public boolean onTitlePrinted() { 17424 final boolean printed = mTitlePrinted; 17425 mTitlePrinted = true; 17426 return printed; 17427 } 17428 17429 public boolean getTitlePrinted() { 17430 return mTitlePrinted; 17431 } 17432 17433 public void setTitlePrinted(boolean enabled) { 17434 mTitlePrinted = enabled; 17435 } 17436 17437 public SharedUserSetting getSharedUser() { 17438 return mSharedUser; 17439 } 17440 17441 public void setSharedUser(SharedUserSetting user) { 17442 mSharedUser = user; 17443 } 17444 } 17445 17446 @Override 17447 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17448 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17449 (new PackageManagerShellCommand(this)).exec( 17450 this, in, out, err, args, resultReceiver); 17451 } 17452 17453 @Override 17454 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17455 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17456 != PackageManager.PERMISSION_GRANTED) { 17457 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17458 + Binder.getCallingPid() 17459 + ", uid=" + Binder.getCallingUid() 17460 + " without permission " 17461 + android.Manifest.permission.DUMP); 17462 return; 17463 } 17464 17465 DumpState dumpState = new DumpState(); 17466 boolean fullPreferred = false; 17467 boolean checkin = false; 17468 17469 String packageName = null; 17470 ArraySet<String> permissionNames = null; 17471 17472 int opti = 0; 17473 while (opti < args.length) { 17474 String opt = args[opti]; 17475 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17476 break; 17477 } 17478 opti++; 17479 17480 if ("-a".equals(opt)) { 17481 // Right now we only know how to print all. 17482 } else if ("-h".equals(opt)) { 17483 pw.println("Package manager dump options:"); 17484 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17485 pw.println(" --checkin: dump for a checkin"); 17486 pw.println(" -f: print details of intent filters"); 17487 pw.println(" -h: print this help"); 17488 pw.println(" cmd may be one of:"); 17489 pw.println(" l[ibraries]: list known shared libraries"); 17490 pw.println(" f[eatures]: list device features"); 17491 pw.println(" k[eysets]: print known keysets"); 17492 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17493 pw.println(" perm[issions]: dump permissions"); 17494 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17495 pw.println(" pref[erred]: print preferred package settings"); 17496 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17497 pw.println(" prov[iders]: dump content providers"); 17498 pw.println(" p[ackages]: dump installed packages"); 17499 pw.println(" s[hared-users]: dump shared user IDs"); 17500 pw.println(" m[essages]: print collected runtime messages"); 17501 pw.println(" v[erifiers]: print package verifier info"); 17502 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17503 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17504 pw.println(" version: print database version info"); 17505 pw.println(" write: write current settings now"); 17506 pw.println(" installs: details about install sessions"); 17507 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17508 pw.println(" <package.name>: info about given package"); 17509 return; 17510 } else if ("--checkin".equals(opt)) { 17511 checkin = true; 17512 } else if ("-f".equals(opt)) { 17513 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17514 } else { 17515 pw.println("Unknown argument: " + opt + "; use -h for help"); 17516 } 17517 } 17518 17519 // Is the caller requesting to dump a particular piece of data? 17520 if (opti < args.length) { 17521 String cmd = args[opti]; 17522 opti++; 17523 // Is this a package name? 17524 if ("android".equals(cmd) || cmd.contains(".")) { 17525 packageName = cmd; 17526 // When dumping a single package, we always dump all of its 17527 // filter information since the amount of data will be reasonable. 17528 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17529 } else if ("check-permission".equals(cmd)) { 17530 if (opti >= args.length) { 17531 pw.println("Error: check-permission missing permission argument"); 17532 return; 17533 } 17534 String perm = args[opti]; 17535 opti++; 17536 if (opti >= args.length) { 17537 pw.println("Error: check-permission missing package argument"); 17538 return; 17539 } 17540 String pkg = args[opti]; 17541 opti++; 17542 int user = UserHandle.getUserId(Binder.getCallingUid()); 17543 if (opti < args.length) { 17544 try { 17545 user = Integer.parseInt(args[opti]); 17546 } catch (NumberFormatException e) { 17547 pw.println("Error: check-permission user argument is not a number: " 17548 + args[opti]); 17549 return; 17550 } 17551 } 17552 pw.println(checkPermission(perm, pkg, user)); 17553 return; 17554 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17555 dumpState.setDump(DumpState.DUMP_LIBS); 17556 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17557 dumpState.setDump(DumpState.DUMP_FEATURES); 17558 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17559 if (opti >= args.length) { 17560 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17561 | DumpState.DUMP_SERVICE_RESOLVERS 17562 | DumpState.DUMP_RECEIVER_RESOLVERS 17563 | DumpState.DUMP_CONTENT_RESOLVERS); 17564 } else { 17565 while (opti < args.length) { 17566 String name = args[opti]; 17567 if ("a".equals(name) || "activity".equals(name)) { 17568 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17569 } else if ("s".equals(name) || "service".equals(name)) { 17570 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17571 } else if ("r".equals(name) || "receiver".equals(name)) { 17572 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17573 } else if ("c".equals(name) || "content".equals(name)) { 17574 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17575 } else { 17576 pw.println("Error: unknown resolver table type: " + name); 17577 return; 17578 } 17579 opti++; 17580 } 17581 } 17582 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17583 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17584 } else if ("permission".equals(cmd)) { 17585 if (opti >= args.length) { 17586 pw.println("Error: permission requires permission name"); 17587 return; 17588 } 17589 permissionNames = new ArraySet<>(); 17590 while (opti < args.length) { 17591 permissionNames.add(args[opti]); 17592 opti++; 17593 } 17594 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17595 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17596 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17597 dumpState.setDump(DumpState.DUMP_PREFERRED); 17598 } else if ("preferred-xml".equals(cmd)) { 17599 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17600 if (opti < args.length && "--full".equals(args[opti])) { 17601 fullPreferred = true; 17602 opti++; 17603 } 17604 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17605 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17606 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17607 dumpState.setDump(DumpState.DUMP_PACKAGES); 17608 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17609 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17610 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17611 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17612 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17613 dumpState.setDump(DumpState.DUMP_MESSAGES); 17614 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17615 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17616 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17617 || "intent-filter-verifiers".equals(cmd)) { 17618 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17619 } else if ("version".equals(cmd)) { 17620 dumpState.setDump(DumpState.DUMP_VERSION); 17621 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17622 dumpState.setDump(DumpState.DUMP_KEYSETS); 17623 } else if ("installs".equals(cmd)) { 17624 dumpState.setDump(DumpState.DUMP_INSTALLS); 17625 } else if ("write".equals(cmd)) { 17626 synchronized (mPackages) { 17627 mSettings.writeLPr(); 17628 pw.println("Settings written."); 17629 return; 17630 } 17631 } 17632 } 17633 17634 if (checkin) { 17635 pw.println("vers,1"); 17636 } 17637 17638 // reader 17639 synchronized (mPackages) { 17640 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17641 if (!checkin) { 17642 if (dumpState.onTitlePrinted()) 17643 pw.println(); 17644 pw.println("Database versions:"); 17645 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17646 } 17647 } 17648 17649 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17650 if (!checkin) { 17651 if (dumpState.onTitlePrinted()) 17652 pw.println(); 17653 pw.println("Verifiers:"); 17654 pw.print(" Required: "); 17655 pw.print(mRequiredVerifierPackage); 17656 pw.print(" (uid="); 17657 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17658 UserHandle.USER_SYSTEM)); 17659 pw.println(")"); 17660 } else if (mRequiredVerifierPackage != null) { 17661 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17662 pw.print(","); 17663 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17664 UserHandle.USER_SYSTEM)); 17665 } 17666 } 17667 17668 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17669 packageName == null) { 17670 if (mIntentFilterVerifierComponent != null) { 17671 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17672 if (!checkin) { 17673 if (dumpState.onTitlePrinted()) 17674 pw.println(); 17675 pw.println("Intent Filter Verifier:"); 17676 pw.print(" Using: "); 17677 pw.print(verifierPackageName); 17678 pw.print(" (uid="); 17679 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17680 UserHandle.USER_SYSTEM)); 17681 pw.println(")"); 17682 } else if (verifierPackageName != null) { 17683 pw.print("ifv,"); pw.print(verifierPackageName); 17684 pw.print(","); 17685 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17686 UserHandle.USER_SYSTEM)); 17687 } 17688 } else { 17689 pw.println(); 17690 pw.println("No Intent Filter Verifier available!"); 17691 } 17692 } 17693 17694 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17695 boolean printedHeader = false; 17696 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17697 while (it.hasNext()) { 17698 String name = it.next(); 17699 SharedLibraryEntry ent = mSharedLibraries.get(name); 17700 if (!checkin) { 17701 if (!printedHeader) { 17702 if (dumpState.onTitlePrinted()) 17703 pw.println(); 17704 pw.println("Libraries:"); 17705 printedHeader = true; 17706 } 17707 pw.print(" "); 17708 } else { 17709 pw.print("lib,"); 17710 } 17711 pw.print(name); 17712 if (!checkin) { 17713 pw.print(" -> "); 17714 } 17715 if (ent.path != null) { 17716 if (!checkin) { 17717 pw.print("(jar) "); 17718 pw.print(ent.path); 17719 } else { 17720 pw.print(",jar,"); 17721 pw.print(ent.path); 17722 } 17723 } else { 17724 if (!checkin) { 17725 pw.print("(apk) "); 17726 pw.print(ent.apk); 17727 } else { 17728 pw.print(",apk,"); 17729 pw.print(ent.apk); 17730 } 17731 } 17732 pw.println(); 17733 } 17734 } 17735 17736 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17737 if (dumpState.onTitlePrinted()) 17738 pw.println(); 17739 if (!checkin) { 17740 pw.println("Features:"); 17741 } 17742 17743 for (FeatureInfo feat : mAvailableFeatures.values()) { 17744 if (checkin) { 17745 pw.print("feat,"); 17746 pw.print(feat.name); 17747 pw.print(","); 17748 pw.println(feat.version); 17749 } else { 17750 pw.print(" "); 17751 pw.print(feat.name); 17752 if (feat.version > 0) { 17753 pw.print(" version="); 17754 pw.print(feat.version); 17755 } 17756 pw.println(); 17757 } 17758 } 17759 } 17760 17761 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17762 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17763 : "Activity Resolver Table:", " ", packageName, 17764 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17765 dumpState.setTitlePrinted(true); 17766 } 17767 } 17768 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17769 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17770 : "Receiver Resolver Table:", " ", packageName, 17771 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17772 dumpState.setTitlePrinted(true); 17773 } 17774 } 17775 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17776 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17777 : "Service Resolver Table:", " ", packageName, 17778 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17779 dumpState.setTitlePrinted(true); 17780 } 17781 } 17782 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17783 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17784 : "Provider Resolver Table:", " ", packageName, 17785 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17786 dumpState.setTitlePrinted(true); 17787 } 17788 } 17789 17790 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17791 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17792 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17793 int user = mSettings.mPreferredActivities.keyAt(i); 17794 if (pir.dump(pw, 17795 dumpState.getTitlePrinted() 17796 ? "\nPreferred Activities User " + user + ":" 17797 : "Preferred Activities User " + user + ":", " ", 17798 packageName, true, false)) { 17799 dumpState.setTitlePrinted(true); 17800 } 17801 } 17802 } 17803 17804 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17805 pw.flush(); 17806 FileOutputStream fout = new FileOutputStream(fd); 17807 BufferedOutputStream str = new BufferedOutputStream(fout); 17808 XmlSerializer serializer = new FastXmlSerializer(); 17809 try { 17810 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17811 serializer.startDocument(null, true); 17812 serializer.setFeature( 17813 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17814 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17815 serializer.endDocument(); 17816 serializer.flush(); 17817 } catch (IllegalArgumentException e) { 17818 pw.println("Failed writing: " + e); 17819 } catch (IllegalStateException e) { 17820 pw.println("Failed writing: " + e); 17821 } catch (IOException e) { 17822 pw.println("Failed writing: " + e); 17823 } 17824 } 17825 17826 if (!checkin 17827 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17828 && packageName == null) { 17829 pw.println(); 17830 int count = mSettings.mPackages.size(); 17831 if (count == 0) { 17832 pw.println("No applications!"); 17833 pw.println(); 17834 } else { 17835 final String prefix = " "; 17836 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17837 if (allPackageSettings.size() == 0) { 17838 pw.println("No domain preferred apps!"); 17839 pw.println(); 17840 } else { 17841 pw.println("App verification status:"); 17842 pw.println(); 17843 count = 0; 17844 for (PackageSetting ps : allPackageSettings) { 17845 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17846 if (ivi == null || ivi.getPackageName() == null) continue; 17847 pw.println(prefix + "Package: " + ivi.getPackageName()); 17848 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17849 pw.println(prefix + "Status: " + ivi.getStatusString()); 17850 pw.println(); 17851 count++; 17852 } 17853 if (count == 0) { 17854 pw.println(prefix + "No app verification established."); 17855 pw.println(); 17856 } 17857 for (int userId : sUserManager.getUserIds()) { 17858 pw.println("App linkages for user " + userId + ":"); 17859 pw.println(); 17860 count = 0; 17861 for (PackageSetting ps : allPackageSettings) { 17862 final long status = ps.getDomainVerificationStatusForUser(userId); 17863 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17864 continue; 17865 } 17866 pw.println(prefix + "Package: " + ps.name); 17867 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17868 String statusStr = IntentFilterVerificationInfo. 17869 getStatusStringFromValue(status); 17870 pw.println(prefix + "Status: " + statusStr); 17871 pw.println(); 17872 count++; 17873 } 17874 if (count == 0) { 17875 pw.println(prefix + "No configured app linkages."); 17876 pw.println(); 17877 } 17878 } 17879 } 17880 } 17881 } 17882 17883 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17884 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17885 if (packageName == null && permissionNames == null) { 17886 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17887 if (iperm == 0) { 17888 if (dumpState.onTitlePrinted()) 17889 pw.println(); 17890 pw.println("AppOp Permissions:"); 17891 } 17892 pw.print(" AppOp Permission "); 17893 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17894 pw.println(":"); 17895 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17896 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17897 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17898 } 17899 } 17900 } 17901 } 17902 17903 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17904 boolean printedSomething = false; 17905 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17906 if (packageName != null && !packageName.equals(p.info.packageName)) { 17907 continue; 17908 } 17909 if (!printedSomething) { 17910 if (dumpState.onTitlePrinted()) 17911 pw.println(); 17912 pw.println("Registered ContentProviders:"); 17913 printedSomething = true; 17914 } 17915 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17916 pw.print(" "); pw.println(p.toString()); 17917 } 17918 printedSomething = false; 17919 for (Map.Entry<String, PackageParser.Provider> entry : 17920 mProvidersByAuthority.entrySet()) { 17921 PackageParser.Provider p = entry.getValue(); 17922 if (packageName != null && !packageName.equals(p.info.packageName)) { 17923 continue; 17924 } 17925 if (!printedSomething) { 17926 if (dumpState.onTitlePrinted()) 17927 pw.println(); 17928 pw.println("ContentProvider Authorities:"); 17929 printedSomething = true; 17930 } 17931 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17932 pw.print(" "); pw.println(p.toString()); 17933 if (p.info != null && p.info.applicationInfo != null) { 17934 final String appInfo = p.info.applicationInfo.toString(); 17935 pw.print(" applicationInfo="); pw.println(appInfo); 17936 } 17937 } 17938 } 17939 17940 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17941 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17942 } 17943 17944 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17945 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17946 } 17947 17948 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17949 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17950 } 17951 17952 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17953 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17954 } 17955 17956 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17957 // XXX should handle packageName != null by dumping only install data that 17958 // the given package is involved with. 17959 if (dumpState.onTitlePrinted()) pw.println(); 17960 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17961 } 17962 17963 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17964 if (dumpState.onTitlePrinted()) pw.println(); 17965 mSettings.dumpReadMessagesLPr(pw, dumpState); 17966 17967 pw.println(); 17968 pw.println("Package warning messages:"); 17969 BufferedReader in = null; 17970 String line = null; 17971 try { 17972 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17973 while ((line = in.readLine()) != null) { 17974 if (line.contains("ignored: updated version")) continue; 17975 pw.println(line); 17976 } 17977 } catch (IOException ignored) { 17978 } finally { 17979 IoUtils.closeQuietly(in); 17980 } 17981 } 17982 17983 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17984 BufferedReader in = null; 17985 String line = null; 17986 try { 17987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17988 while ((line = in.readLine()) != null) { 17989 if (line.contains("ignored: updated version")) continue; 17990 pw.print("msg,"); 17991 pw.println(line); 17992 } 17993 } catch (IOException ignored) { 17994 } finally { 17995 IoUtils.closeQuietly(in); 17996 } 17997 } 17998 } 17999 } 18000 18001 private String dumpDomainString(String packageName) { 18002 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18003 .getList(); 18004 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18005 18006 ArraySet<String> result = new ArraySet<>(); 18007 if (iviList.size() > 0) { 18008 for (IntentFilterVerificationInfo ivi : iviList) { 18009 for (String host : ivi.getDomains()) { 18010 result.add(host); 18011 } 18012 } 18013 } 18014 if (filters != null && filters.size() > 0) { 18015 for (IntentFilter filter : filters) { 18016 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18017 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18018 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18019 result.addAll(filter.getHostsList()); 18020 } 18021 } 18022 } 18023 18024 StringBuilder sb = new StringBuilder(result.size() * 16); 18025 for (String domain : result) { 18026 if (sb.length() > 0) sb.append(" "); 18027 sb.append(domain); 18028 } 18029 return sb.toString(); 18030 } 18031 18032 // ------- apps on sdcard specific code ------- 18033 static final boolean DEBUG_SD_INSTALL = false; 18034 18035 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18036 18037 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18038 18039 private boolean mMediaMounted = false; 18040 18041 static String getEncryptKey() { 18042 try { 18043 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18044 SD_ENCRYPTION_KEYSTORE_NAME); 18045 if (sdEncKey == null) { 18046 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18047 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18048 if (sdEncKey == null) { 18049 Slog.e(TAG, "Failed to create encryption keys"); 18050 return null; 18051 } 18052 } 18053 return sdEncKey; 18054 } catch (NoSuchAlgorithmException nsae) { 18055 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18056 return null; 18057 } catch (IOException ioe) { 18058 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18059 return null; 18060 } 18061 } 18062 18063 /* 18064 * Update media status on PackageManager. 18065 */ 18066 @Override 18067 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18068 int callingUid = Binder.getCallingUid(); 18069 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18070 throw new SecurityException("Media status can only be updated by the system"); 18071 } 18072 // reader; this apparently protects mMediaMounted, but should probably 18073 // be a different lock in that case. 18074 synchronized (mPackages) { 18075 Log.i(TAG, "Updating external media status from " 18076 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18077 + (mediaStatus ? "mounted" : "unmounted")); 18078 if (DEBUG_SD_INSTALL) 18079 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18080 + ", mMediaMounted=" + mMediaMounted); 18081 if (mediaStatus == mMediaMounted) { 18082 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18083 : 0, -1); 18084 mHandler.sendMessage(msg); 18085 return; 18086 } 18087 mMediaMounted = mediaStatus; 18088 } 18089 // Queue up an async operation since the package installation may take a 18090 // little while. 18091 mHandler.post(new Runnable() { 18092 public void run() { 18093 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18094 } 18095 }); 18096 } 18097 18098 /** 18099 * Called by MountService when the initial ASECs to scan are available. 18100 * Should block until all the ASEC containers are finished being scanned. 18101 */ 18102 public void scanAvailableAsecs() { 18103 updateExternalMediaStatusInner(true, false, false); 18104 } 18105 18106 /* 18107 * Collect information of applications on external media, map them against 18108 * existing containers and update information based on current mount status. 18109 * Please note that we always have to report status if reportStatus has been 18110 * set to true especially when unloading packages. 18111 */ 18112 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18113 boolean externalStorage) { 18114 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18115 int[] uidArr = EmptyArray.INT; 18116 18117 final String[] list = PackageHelper.getSecureContainerList(); 18118 if (ArrayUtils.isEmpty(list)) { 18119 Log.i(TAG, "No secure containers found"); 18120 } else { 18121 // Process list of secure containers and categorize them 18122 // as active or stale based on their package internal state. 18123 18124 // reader 18125 synchronized (mPackages) { 18126 for (String cid : list) { 18127 // Leave stages untouched for now; installer service owns them 18128 if (PackageInstallerService.isStageName(cid)) continue; 18129 18130 if (DEBUG_SD_INSTALL) 18131 Log.i(TAG, "Processing container " + cid); 18132 String pkgName = getAsecPackageName(cid); 18133 if (pkgName == null) { 18134 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18135 continue; 18136 } 18137 if (DEBUG_SD_INSTALL) 18138 Log.i(TAG, "Looking for pkg : " + pkgName); 18139 18140 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18141 if (ps == null) { 18142 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18143 continue; 18144 } 18145 18146 /* 18147 * Skip packages that are not external if we're unmounting 18148 * external storage. 18149 */ 18150 if (externalStorage && !isMounted && !isExternal(ps)) { 18151 continue; 18152 } 18153 18154 final AsecInstallArgs args = new AsecInstallArgs(cid, 18155 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18156 // The package status is changed only if the code path 18157 // matches between settings and the container id. 18158 if (ps.codePathString != null 18159 && ps.codePathString.startsWith(args.getCodePath())) { 18160 if (DEBUG_SD_INSTALL) { 18161 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18162 + " at code path: " + ps.codePathString); 18163 } 18164 18165 // We do have a valid package installed on sdcard 18166 processCids.put(args, ps.codePathString); 18167 final int uid = ps.appId; 18168 if (uid != -1) { 18169 uidArr = ArrayUtils.appendInt(uidArr, uid); 18170 } 18171 } else { 18172 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18173 + ps.codePathString); 18174 } 18175 } 18176 } 18177 18178 Arrays.sort(uidArr); 18179 } 18180 18181 // Process packages with valid entries. 18182 if (isMounted) { 18183 if (DEBUG_SD_INSTALL) 18184 Log.i(TAG, "Loading packages"); 18185 loadMediaPackages(processCids, uidArr, externalStorage); 18186 startCleaningPackages(); 18187 mInstallerService.onSecureContainersAvailable(); 18188 } else { 18189 if (DEBUG_SD_INSTALL) 18190 Log.i(TAG, "Unloading packages"); 18191 unloadMediaPackages(processCids, uidArr, reportStatus); 18192 } 18193 } 18194 18195 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18196 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18197 final int size = infos.size(); 18198 final String[] packageNames = new String[size]; 18199 final int[] packageUids = new int[size]; 18200 for (int i = 0; i < size; i++) { 18201 final ApplicationInfo info = infos.get(i); 18202 packageNames[i] = info.packageName; 18203 packageUids[i] = info.uid; 18204 } 18205 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18206 finishedReceiver); 18207 } 18208 18209 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18210 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18211 sendResourcesChangedBroadcast(mediaStatus, replacing, 18212 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18213 } 18214 18215 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18216 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18217 int size = pkgList.length; 18218 if (size > 0) { 18219 // Send broadcasts here 18220 Bundle extras = new Bundle(); 18221 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18222 if (uidArr != null) { 18223 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18224 } 18225 if (replacing) { 18226 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18227 } 18228 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18229 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18230 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18231 } 18232 } 18233 18234 /* 18235 * Look at potentially valid container ids from processCids If package 18236 * information doesn't match the one on record or package scanning fails, 18237 * the cid is added to list of removeCids. We currently don't delete stale 18238 * containers. 18239 */ 18240 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18241 boolean externalStorage) { 18242 ArrayList<String> pkgList = new ArrayList<String>(); 18243 Set<AsecInstallArgs> keys = processCids.keySet(); 18244 18245 for (AsecInstallArgs args : keys) { 18246 String codePath = processCids.get(args); 18247 if (DEBUG_SD_INSTALL) 18248 Log.i(TAG, "Loading container : " + args.cid); 18249 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18250 try { 18251 // Make sure there are no container errors first. 18252 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18253 Slog.e(TAG, "Failed to mount cid : " + args.cid 18254 + " when installing from sdcard"); 18255 continue; 18256 } 18257 // Check code path here. 18258 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18259 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18260 + " does not match one in settings " + codePath); 18261 continue; 18262 } 18263 // Parse package 18264 int parseFlags = mDefParseFlags; 18265 if (args.isExternalAsec()) { 18266 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18267 } 18268 if (args.isFwdLocked()) { 18269 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18270 } 18271 18272 synchronized (mInstallLock) { 18273 PackageParser.Package pkg = null; 18274 try { 18275 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18276 } catch (PackageManagerException e) { 18277 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18278 } 18279 // Scan the package 18280 if (pkg != null) { 18281 /* 18282 * TODO why is the lock being held? doPostInstall is 18283 * called in other places without the lock. This needs 18284 * to be straightened out. 18285 */ 18286 // writer 18287 synchronized (mPackages) { 18288 retCode = PackageManager.INSTALL_SUCCEEDED; 18289 pkgList.add(pkg.packageName); 18290 // Post process args 18291 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18292 pkg.applicationInfo.uid); 18293 } 18294 } else { 18295 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18296 } 18297 } 18298 18299 } finally { 18300 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18301 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18302 } 18303 } 18304 } 18305 // writer 18306 synchronized (mPackages) { 18307 // If the platform SDK has changed since the last time we booted, 18308 // we need to re-grant app permission to catch any new ones that 18309 // appear. This is really a hack, and means that apps can in some 18310 // cases get permissions that the user didn't initially explicitly 18311 // allow... it would be nice to have some better way to handle 18312 // this situation. 18313 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18314 : mSettings.getInternalVersion(); 18315 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18316 : StorageManager.UUID_PRIVATE_INTERNAL; 18317 18318 int updateFlags = UPDATE_PERMISSIONS_ALL; 18319 if (ver.sdkVersion != mSdkVersion) { 18320 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18321 + mSdkVersion + "; regranting permissions for external"); 18322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18323 } 18324 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18325 18326 // Yay, everything is now upgraded 18327 ver.forceCurrent(); 18328 18329 // can downgrade to reader 18330 // Persist settings 18331 mSettings.writeLPr(); 18332 } 18333 // Send a broadcast to let everyone know we are done processing 18334 if (pkgList.size() > 0) { 18335 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18336 } 18337 } 18338 18339 /* 18340 * Utility method to unload a list of specified containers 18341 */ 18342 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18343 // Just unmount all valid containers. 18344 for (AsecInstallArgs arg : cidArgs) { 18345 synchronized (mInstallLock) { 18346 arg.doPostDeleteLI(false); 18347 } 18348 } 18349 } 18350 18351 /* 18352 * Unload packages mounted on external media. This involves deleting package 18353 * data from internal structures, sending broadcasts about disabled packages, 18354 * gc'ing to free up references, unmounting all secure containers 18355 * corresponding to packages on external media, and posting a 18356 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18357 * that we always have to post this message if status has been requested no 18358 * matter what. 18359 */ 18360 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18361 final boolean reportStatus) { 18362 if (DEBUG_SD_INSTALL) 18363 Log.i(TAG, "unloading media packages"); 18364 ArrayList<String> pkgList = new ArrayList<String>(); 18365 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18366 final Set<AsecInstallArgs> keys = processCids.keySet(); 18367 for (AsecInstallArgs args : keys) { 18368 String pkgName = args.getPackageName(); 18369 if (DEBUG_SD_INSTALL) 18370 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18371 // Delete package internally 18372 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18373 synchronized (mInstallLock) { 18374 boolean res = deletePackageLI(pkgName, null, false, null, 18375 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18376 if (res) { 18377 pkgList.add(pkgName); 18378 } else { 18379 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18380 failedList.add(args); 18381 } 18382 } 18383 } 18384 18385 // reader 18386 synchronized (mPackages) { 18387 // We didn't update the settings after removing each package; 18388 // write them now for all packages. 18389 mSettings.writeLPr(); 18390 } 18391 18392 // We have to absolutely send UPDATED_MEDIA_STATUS only 18393 // after confirming that all the receivers processed the ordered 18394 // broadcast when packages get disabled, force a gc to clean things up. 18395 // and unload all the containers. 18396 if (pkgList.size() > 0) { 18397 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18398 new IIntentReceiver.Stub() { 18399 public void performReceive(Intent intent, int resultCode, String data, 18400 Bundle extras, boolean ordered, boolean sticky, 18401 int sendingUser) throws RemoteException { 18402 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18403 reportStatus ? 1 : 0, 1, keys); 18404 mHandler.sendMessage(msg); 18405 } 18406 }); 18407 } else { 18408 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18409 keys); 18410 mHandler.sendMessage(msg); 18411 } 18412 } 18413 18414 private void loadPrivatePackages(final VolumeInfo vol) { 18415 mHandler.post(new Runnable() { 18416 @Override 18417 public void run() { 18418 loadPrivatePackagesInner(vol); 18419 } 18420 }); 18421 } 18422 18423 private void loadPrivatePackagesInner(VolumeInfo vol) { 18424 final String volumeUuid = vol.fsUuid; 18425 if (TextUtils.isEmpty(volumeUuid)) { 18426 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18427 return; 18428 } 18429 18430 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18431 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18432 18433 final VersionInfo ver; 18434 final List<PackageSetting> packages; 18435 synchronized (mPackages) { 18436 ver = mSettings.findOrCreateVersion(volumeUuid); 18437 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18438 } 18439 18440 // TODO: introduce a new concept similar to "frozen" to prevent these 18441 // apps from being launched until after data has been fully reconciled 18442 for (PackageSetting ps : packages) { 18443 synchronized (mInstallLock) { 18444 final PackageParser.Package pkg; 18445 try { 18446 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18447 loaded.add(pkg.applicationInfo); 18448 18449 } catch (PackageManagerException e) { 18450 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18451 } 18452 18453 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18454 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18455 } 18456 } 18457 } 18458 18459 // Reconcile app data for all started/unlocked users 18460 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18461 final UserManager um = mContext.getSystemService(UserManager.class); 18462 for (UserInfo user : um.getUsers()) { 18463 final int flags; 18464 if (um.isUserUnlocked(user.id)) { 18465 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18466 } else if (um.isUserRunning(user.id)) { 18467 flags = StorageManager.FLAG_STORAGE_DE; 18468 } else { 18469 continue; 18470 } 18471 18472 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18473 reconcileAppsData(volumeUuid, user.id, flags); 18474 } 18475 18476 synchronized (mPackages) { 18477 int updateFlags = UPDATE_PERMISSIONS_ALL; 18478 if (ver.sdkVersion != mSdkVersion) { 18479 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18480 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18481 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18482 } 18483 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18484 18485 // Yay, everything is now upgraded 18486 ver.forceCurrent(); 18487 18488 mSettings.writeLPr(); 18489 } 18490 18491 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18492 sendResourcesChangedBroadcast(true, false, loaded, null); 18493 } 18494 18495 private void unloadPrivatePackages(final VolumeInfo vol) { 18496 mHandler.post(new Runnable() { 18497 @Override 18498 public void run() { 18499 unloadPrivatePackagesInner(vol); 18500 } 18501 }); 18502 } 18503 18504 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18505 final String volumeUuid = vol.fsUuid; 18506 if (TextUtils.isEmpty(volumeUuid)) { 18507 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18508 return; 18509 } 18510 18511 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18512 synchronized (mInstallLock) { 18513 synchronized (mPackages) { 18514 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18515 for (PackageSetting ps : packages) { 18516 if (ps.pkg == null) continue; 18517 18518 final ApplicationInfo info = ps.pkg.applicationInfo; 18519 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18520 if (deletePackageLI(ps.name, null, false, null, 18521 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18522 unloaded.add(info); 18523 } else { 18524 Slog.w(TAG, "Failed to unload " + ps.codePath); 18525 } 18526 } 18527 18528 mSettings.writeLPr(); 18529 } 18530 } 18531 18532 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18533 sendResourcesChangedBroadcast(false, false, unloaded, null); 18534 } 18535 18536 /** 18537 * Examine all users present on given mounted volume, and destroy data 18538 * belonging to users that are no longer valid, or whose user ID has been 18539 * recycled. 18540 */ 18541 private void reconcileUsers(String volumeUuid) { 18542 // TODO: also reconcile DE directories 18543 final File[] files = FileUtils 18544 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18545 for (File file : files) { 18546 if (!file.isDirectory()) continue; 18547 18548 final int userId; 18549 final UserInfo info; 18550 try { 18551 userId = Integer.parseInt(file.getName()); 18552 info = sUserManager.getUserInfo(userId); 18553 } catch (NumberFormatException e) { 18554 Slog.w(TAG, "Invalid user directory " + file); 18555 continue; 18556 } 18557 18558 boolean destroyUser = false; 18559 if (info == null) { 18560 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18561 + " because no matching user was found"); 18562 destroyUser = true; 18563 } else { 18564 try { 18565 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18566 } catch (IOException e) { 18567 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18568 + " because we failed to enforce serial number: " + e); 18569 destroyUser = true; 18570 } 18571 } 18572 18573 if (destroyUser) { 18574 synchronized (mInstallLock) { 18575 try { 18576 mInstaller.removeUserDataDirs(volumeUuid, userId); 18577 } catch (InstallerException e) { 18578 Slog.w(TAG, "Failed to clean up user dirs", e); 18579 } 18580 } 18581 } 18582 } 18583 } 18584 18585 private void assertPackageKnown(String volumeUuid, String packageName) 18586 throws PackageManagerException { 18587 synchronized (mPackages) { 18588 final PackageSetting ps = mSettings.mPackages.get(packageName); 18589 if (ps == null) { 18590 throw new PackageManagerException("Package " + packageName + " is unknown"); 18591 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18592 throw new PackageManagerException( 18593 "Package " + packageName + " found on unknown volume " + volumeUuid 18594 + "; expected volume " + ps.volumeUuid); 18595 } 18596 } 18597 } 18598 18599 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18600 throws PackageManagerException { 18601 synchronized (mPackages) { 18602 final PackageSetting ps = mSettings.mPackages.get(packageName); 18603 if (ps == null) { 18604 throw new PackageManagerException("Package " + packageName + " is unknown"); 18605 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18606 throw new PackageManagerException( 18607 "Package " + packageName + " found on unknown volume " + volumeUuid 18608 + "; expected volume " + ps.volumeUuid); 18609 } else if (!ps.getInstalled(userId)) { 18610 throw new PackageManagerException( 18611 "Package " + packageName + " not installed for user " + userId); 18612 } 18613 } 18614 } 18615 18616 /** 18617 * Examine all apps present on given mounted volume, and destroy apps that 18618 * aren't expected, either due to uninstallation or reinstallation on 18619 * another volume. 18620 */ 18621 private void reconcileApps(String volumeUuid) { 18622 final File[] files = FileUtils 18623 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18624 for (File file : files) { 18625 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18626 && !PackageInstallerService.isStageName(file.getName()); 18627 if (!isPackage) { 18628 // Ignore entries which are not packages 18629 continue; 18630 } 18631 18632 try { 18633 final PackageLite pkg = PackageParser.parsePackageLite(file, 18634 PackageParser.PARSE_MUST_BE_APK); 18635 assertPackageKnown(volumeUuid, pkg.packageName); 18636 18637 } catch (PackageParserException | PackageManagerException e) { 18638 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18639 synchronized (mInstallLock) { 18640 removeCodePathLI(file); 18641 } 18642 } 18643 } 18644 } 18645 18646 /** 18647 * Reconcile all app data for the given user. 18648 * <p> 18649 * Verifies that directories exist and that ownership and labeling is 18650 * correct for all installed apps on all mounted volumes. 18651 */ 18652 void reconcileAppsData(int userId, int flags) { 18653 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18654 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18655 final String volumeUuid = vol.getFsUuid(); 18656 reconcileAppsData(volumeUuid, userId, flags); 18657 } 18658 } 18659 18660 /** 18661 * Reconcile all app data on given mounted volume. 18662 * <p> 18663 * Destroys app data that isn't expected, either due to uninstallation or 18664 * reinstallation on another volume. 18665 * <p> 18666 * Verifies that directories exist and that ownership and labeling is 18667 * correct for all installed apps. 18668 */ 18669 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18670 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18671 + Integer.toHexString(flags)); 18672 18673 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18674 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18675 18676 boolean restoreconNeeded = false; 18677 18678 // First look for stale data that doesn't belong, and check if things 18679 // have changed since we did our last restorecon 18680 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18681 if (!isUserKeyUnlocked(userId)) { 18682 throw new RuntimeException( 18683 "Yikes, someone asked us to reconcile CE storage while " + userId 18684 + " was still locked; this would have caused massive data loss!"); 18685 } 18686 18687 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18688 18689 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18690 for (File file : files) { 18691 final String packageName = file.getName(); 18692 try { 18693 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18694 } catch (PackageManagerException e) { 18695 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18696 synchronized (mInstallLock) { 18697 destroyAppDataLI(volumeUuid, packageName, userId, 18698 StorageManager.FLAG_STORAGE_CE); 18699 } 18700 } 18701 } 18702 } 18703 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18704 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18705 18706 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18707 for (File file : files) { 18708 final String packageName = file.getName(); 18709 try { 18710 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18711 } catch (PackageManagerException e) { 18712 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18713 synchronized (mInstallLock) { 18714 destroyAppDataLI(volumeUuid, packageName, userId, 18715 StorageManager.FLAG_STORAGE_DE); 18716 } 18717 } 18718 } 18719 } 18720 18721 // Ensure that data directories are ready to roll for all packages 18722 // installed for this volume and user 18723 final List<PackageSetting> packages; 18724 synchronized (mPackages) { 18725 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18726 } 18727 int preparedCount = 0; 18728 for (PackageSetting ps : packages) { 18729 final String packageName = ps.name; 18730 if (ps.pkg == null) { 18731 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18732 // TODO: might be due to legacy ASEC apps; we should circle back 18733 // and reconcile again once they're scanned 18734 continue; 18735 } 18736 18737 if (ps.getInstalled(userId)) { 18738 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18739 18740 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18741 // We may have just shuffled around app data directories, so 18742 // prepare them one more time 18743 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18744 } 18745 18746 preparedCount++; 18747 } 18748 } 18749 18750 if (restoreconNeeded) { 18751 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18752 SELinuxMMAC.setRestoreconDone(ceDir); 18753 } 18754 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18755 SELinuxMMAC.setRestoreconDone(deDir); 18756 } 18757 } 18758 18759 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18760 + " packages; restoreconNeeded was " + restoreconNeeded); 18761 } 18762 18763 /** 18764 * Prepare app data for the given app just after it was installed or 18765 * upgraded. This method carefully only touches users that it's installed 18766 * for, and it forces a restorecon to handle any seinfo changes. 18767 * <p> 18768 * Verifies that directories exist and that ownership and labeling is 18769 * correct for all installed apps. If there is an ownership mismatch, it 18770 * will try recovering system apps by wiping data; third-party app data is 18771 * left intact. 18772 * <p> 18773 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18774 */ 18775 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18776 prepareAppDataAfterInstallInternal(pkg); 18777 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18778 for (int i = 0; i < childCount; i++) { 18779 PackageParser.Package childPackage = pkg.childPackages.get(i); 18780 prepareAppDataAfterInstallInternal(childPackage); 18781 } 18782 } 18783 18784 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18785 final PackageSetting ps; 18786 synchronized (mPackages) { 18787 ps = mSettings.mPackages.get(pkg.packageName); 18788 mSettings.writeKernelMappingLPr(ps); 18789 } 18790 18791 final UserManager um = mContext.getSystemService(UserManager.class); 18792 for (UserInfo user : um.getUsers()) { 18793 final int flags; 18794 if (um.isUserUnlocked(user.id)) { 18795 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18796 } else if (um.isUserRunning(user.id)) { 18797 flags = StorageManager.FLAG_STORAGE_DE; 18798 } else { 18799 continue; 18800 } 18801 18802 if (ps.getInstalled(user.id)) { 18803 // Whenever an app changes, force a restorecon of its data 18804 // TODO: when user data is locked, mark that we're still dirty 18805 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18806 } 18807 } 18808 } 18809 18810 /** 18811 * Prepare app data for the given app. 18812 * <p> 18813 * Verifies that directories exist and that ownership and labeling is 18814 * correct for all installed apps. If there is an ownership mismatch, this 18815 * will try recovering system apps by wiping data; third-party app data is 18816 * left intact. 18817 */ 18818 private void prepareAppData(String volumeUuid, int userId, int flags, 18819 PackageParser.Package pkg, boolean restoreconNeeded) { 18820 if (DEBUG_APP_DATA) { 18821 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18822 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18823 } 18824 18825 final String packageName = pkg.packageName; 18826 final ApplicationInfo app = pkg.applicationInfo; 18827 final int appId = UserHandle.getAppId(app.uid); 18828 18829 Preconditions.checkNotNull(app.seinfo); 18830 18831 synchronized (mInstallLock) { 18832 try { 18833 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18834 appId, app.seinfo, app.targetSdkVersion); 18835 } catch (InstallerException e) { 18836 if (app.isSystemApp()) { 18837 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18838 + ", but trying to recover: " + e); 18839 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18840 try { 18841 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18842 appId, app.seinfo, app.targetSdkVersion); 18843 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18844 } catch (InstallerException e2) { 18845 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18846 } 18847 } else { 18848 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18849 } 18850 } 18851 18852 if (restoreconNeeded) { 18853 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18854 } 18855 18856 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18857 // Create a native library symlink only if we have native libraries 18858 // and if the native libraries are 32 bit libraries. We do not provide 18859 // this symlink for 64 bit libraries. 18860 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18861 final String nativeLibPath = app.nativeLibraryDir; 18862 try { 18863 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18864 nativeLibPath, userId); 18865 } catch (InstallerException e) { 18866 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18867 } 18868 } 18869 } 18870 } 18871 } 18872 18873 /** 18874 * For system apps on non-FBE devices, this method migrates any existing 18875 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18876 * requested by the app. 18877 */ 18878 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18879 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18880 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18881 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18882 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18883 synchronized (mInstallLock) { 18884 try { 18885 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18886 } catch (InstallerException e) { 18887 logCriticalInfo(Log.WARN, 18888 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18889 } 18890 } 18891 return true; 18892 } else { 18893 return false; 18894 } 18895 } 18896 18897 private void unfreezePackage(String packageName) { 18898 synchronized (mPackages) { 18899 final PackageSetting ps = mSettings.mPackages.get(packageName); 18900 if (ps != null) { 18901 ps.frozen = false; 18902 } 18903 } 18904 } 18905 18906 @Override 18907 public int movePackage(final String packageName, final String volumeUuid) { 18908 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18909 18910 final int moveId = mNextMoveId.getAndIncrement(); 18911 mHandler.post(new Runnable() { 18912 @Override 18913 public void run() { 18914 try { 18915 movePackageInternal(packageName, volumeUuid, moveId); 18916 } catch (PackageManagerException e) { 18917 Slog.w(TAG, "Failed to move " + packageName, e); 18918 mMoveCallbacks.notifyStatusChanged(moveId, 18919 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18920 } 18921 } 18922 }); 18923 return moveId; 18924 } 18925 18926 private void movePackageInternal(final String packageName, final String volumeUuid, 18927 final int moveId) throws PackageManagerException { 18928 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18929 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18930 final PackageManager pm = mContext.getPackageManager(); 18931 18932 final boolean currentAsec; 18933 final String currentVolumeUuid; 18934 final File codeFile; 18935 final String installerPackageName; 18936 final String packageAbiOverride; 18937 final int appId; 18938 final String seinfo; 18939 final String label; 18940 final int targetSdkVersion; 18941 18942 // reader 18943 synchronized (mPackages) { 18944 final PackageParser.Package pkg = mPackages.get(packageName); 18945 final PackageSetting ps = mSettings.mPackages.get(packageName); 18946 if (pkg == null || ps == null) { 18947 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18948 } 18949 18950 if (pkg.applicationInfo.isSystemApp()) { 18951 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18952 "Cannot move system application"); 18953 } 18954 18955 if (pkg.applicationInfo.isExternalAsec()) { 18956 currentAsec = true; 18957 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18958 } else if (pkg.applicationInfo.isForwardLocked()) { 18959 currentAsec = true; 18960 currentVolumeUuid = "forward_locked"; 18961 } else { 18962 currentAsec = false; 18963 currentVolumeUuid = ps.volumeUuid; 18964 18965 final File probe = new File(pkg.codePath); 18966 final File probeOat = new File(probe, "oat"); 18967 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18968 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18969 "Move only supported for modern cluster style installs"); 18970 } 18971 } 18972 18973 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18974 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18975 "Package already moved to " + volumeUuid); 18976 } 18977 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18978 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18979 "Device admin cannot be moved"); 18980 } 18981 18982 if (ps.frozen) { 18983 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18984 "Failed to move already frozen package"); 18985 } 18986 ps.frozen = true; 18987 18988 codeFile = new File(pkg.codePath); 18989 installerPackageName = ps.installerPackageName; 18990 packageAbiOverride = ps.cpuAbiOverrideString; 18991 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18992 seinfo = pkg.applicationInfo.seinfo; 18993 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18994 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18995 } 18996 18997 // Now that we're guarded by frozen state, kill app during move 18998 final long token = Binder.clearCallingIdentity(); 18999 try { 19000 killApplication(packageName, appId, "move pkg"); 19001 } finally { 19002 Binder.restoreCallingIdentity(token); 19003 } 19004 19005 final Bundle extras = new Bundle(); 19006 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19007 extras.putString(Intent.EXTRA_TITLE, label); 19008 mMoveCallbacks.notifyCreated(moveId, extras); 19009 19010 int installFlags; 19011 final boolean moveCompleteApp; 19012 final File measurePath; 19013 19014 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19015 installFlags = INSTALL_INTERNAL; 19016 moveCompleteApp = !currentAsec; 19017 measurePath = Environment.getDataAppDirectory(volumeUuid); 19018 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19019 installFlags = INSTALL_EXTERNAL; 19020 moveCompleteApp = false; 19021 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19022 } else { 19023 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19024 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19025 || !volume.isMountedWritable()) { 19026 unfreezePackage(packageName); 19027 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19028 "Move location not mounted private volume"); 19029 } 19030 19031 Preconditions.checkState(!currentAsec); 19032 19033 installFlags = INSTALL_INTERNAL; 19034 moveCompleteApp = true; 19035 measurePath = Environment.getDataAppDirectory(volumeUuid); 19036 } 19037 19038 final PackageStats stats = new PackageStats(null, -1); 19039 synchronized (mInstaller) { 19040 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19041 unfreezePackage(packageName); 19042 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19043 "Failed to measure package size"); 19044 } 19045 } 19046 19047 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19048 + stats.dataSize); 19049 19050 final long startFreeBytes = measurePath.getFreeSpace(); 19051 final long sizeBytes; 19052 if (moveCompleteApp) { 19053 sizeBytes = stats.codeSize + stats.dataSize; 19054 } else { 19055 sizeBytes = stats.codeSize; 19056 } 19057 19058 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19059 unfreezePackage(packageName); 19060 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19061 "Not enough free space to move"); 19062 } 19063 19064 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19065 19066 final CountDownLatch installedLatch = new CountDownLatch(1); 19067 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19068 @Override 19069 public void onUserActionRequired(Intent intent) throws RemoteException { 19070 throw new IllegalStateException(); 19071 } 19072 19073 @Override 19074 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19075 Bundle extras) throws RemoteException { 19076 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19077 + PackageManager.installStatusToString(returnCode, msg)); 19078 19079 installedLatch.countDown(); 19080 19081 // Regardless of success or failure of the move operation, 19082 // always unfreeze the package 19083 unfreezePackage(packageName); 19084 19085 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19086 switch (status) { 19087 case PackageInstaller.STATUS_SUCCESS: 19088 mMoveCallbacks.notifyStatusChanged(moveId, 19089 PackageManager.MOVE_SUCCEEDED); 19090 break; 19091 case PackageInstaller.STATUS_FAILURE_STORAGE: 19092 mMoveCallbacks.notifyStatusChanged(moveId, 19093 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19094 break; 19095 default: 19096 mMoveCallbacks.notifyStatusChanged(moveId, 19097 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19098 break; 19099 } 19100 } 19101 }; 19102 19103 final MoveInfo move; 19104 if (moveCompleteApp) { 19105 // Kick off a thread to report progress estimates 19106 new Thread() { 19107 @Override 19108 public void run() { 19109 while (true) { 19110 try { 19111 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19112 break; 19113 } 19114 } catch (InterruptedException ignored) { 19115 } 19116 19117 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19118 final int progress = 10 + (int) MathUtils.constrain( 19119 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19120 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19121 } 19122 } 19123 }.start(); 19124 19125 final String dataAppName = codeFile.getName(); 19126 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19127 dataAppName, appId, seinfo, targetSdkVersion); 19128 } else { 19129 move = null; 19130 } 19131 19132 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19133 19134 final Message msg = mHandler.obtainMessage(INIT_COPY); 19135 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19136 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19137 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19138 packageAbiOverride, null); 19139 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19140 msg.obj = params; 19141 19142 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19143 System.identityHashCode(msg.obj)); 19144 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19145 System.identityHashCode(msg.obj)); 19146 19147 mHandler.sendMessage(msg); 19148 } 19149 19150 @Override 19151 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19153 19154 final int realMoveId = mNextMoveId.getAndIncrement(); 19155 final Bundle extras = new Bundle(); 19156 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19157 mMoveCallbacks.notifyCreated(realMoveId, extras); 19158 19159 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19160 @Override 19161 public void onCreated(int moveId, Bundle extras) { 19162 // Ignored 19163 } 19164 19165 @Override 19166 public void onStatusChanged(int moveId, int status, long estMillis) { 19167 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19168 } 19169 }; 19170 19171 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19172 storage.setPrimaryStorageUuid(volumeUuid, callback); 19173 return realMoveId; 19174 } 19175 19176 @Override 19177 public int getMoveStatus(int moveId) { 19178 mContext.enforceCallingOrSelfPermission( 19179 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19180 return mMoveCallbacks.mLastStatus.get(moveId); 19181 } 19182 19183 @Override 19184 public void registerMoveCallback(IPackageMoveObserver callback) { 19185 mContext.enforceCallingOrSelfPermission( 19186 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19187 mMoveCallbacks.register(callback); 19188 } 19189 19190 @Override 19191 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19192 mContext.enforceCallingOrSelfPermission( 19193 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19194 mMoveCallbacks.unregister(callback); 19195 } 19196 19197 @Override 19198 public boolean setInstallLocation(int loc) { 19199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19200 null); 19201 if (getInstallLocation() == loc) { 19202 return true; 19203 } 19204 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19205 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19206 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19207 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19208 return true; 19209 } 19210 return false; 19211 } 19212 19213 @Override 19214 public int getInstallLocation() { 19215 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19216 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19217 PackageHelper.APP_INSTALL_AUTO); 19218 } 19219 19220 /** Called by UserManagerService */ 19221 void cleanUpUser(UserManagerService userManager, int userHandle) { 19222 synchronized (mPackages) { 19223 mDirtyUsers.remove(userHandle); 19224 mUserNeedsBadging.delete(userHandle); 19225 mSettings.removeUserLPw(userHandle); 19226 mPendingBroadcasts.remove(userHandle); 19227 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19228 } 19229 synchronized (mInstallLock) { 19230 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19231 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19232 final String volumeUuid = vol.getFsUuid(); 19233 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19234 try { 19235 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19236 } catch (InstallerException e) { 19237 Slog.w(TAG, "Failed to remove user data", e); 19238 } 19239 } 19240 synchronized (mPackages) { 19241 removeUnusedPackagesLILPw(userManager, userHandle); 19242 } 19243 } 19244 } 19245 19246 /** 19247 * We're removing userHandle and would like to remove any downloaded packages 19248 * that are no longer in use by any other user. 19249 * @param userHandle the user being removed 19250 */ 19251 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19252 final boolean DEBUG_CLEAN_APKS = false; 19253 int [] users = userManager.getUserIds(); 19254 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19255 while (psit.hasNext()) { 19256 PackageSetting ps = psit.next(); 19257 if (ps.pkg == null) { 19258 continue; 19259 } 19260 final String packageName = ps.pkg.packageName; 19261 // Skip over if system app 19262 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19263 continue; 19264 } 19265 if (DEBUG_CLEAN_APKS) { 19266 Slog.i(TAG, "Checking package " + packageName); 19267 } 19268 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19269 if (keep) { 19270 if (DEBUG_CLEAN_APKS) { 19271 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19272 } 19273 } else { 19274 for (int i = 0; i < users.length; i++) { 19275 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19276 keep = true; 19277 if (DEBUG_CLEAN_APKS) { 19278 Slog.i(TAG, " Keeping package " + packageName + " for user " 19279 + users[i]); 19280 } 19281 break; 19282 } 19283 } 19284 } 19285 if (!keep) { 19286 if (DEBUG_CLEAN_APKS) { 19287 Slog.i(TAG, " Removing package " + packageName); 19288 } 19289 mHandler.post(new Runnable() { 19290 public void run() { 19291 deletePackageX(packageName, userHandle, 0); 19292 } //end run 19293 }); 19294 } 19295 } 19296 } 19297 19298 /** Called by UserManagerService */ 19299 void createNewUser(int userHandle) { 19300 synchronized (mInstallLock) { 19301 try { 19302 mInstaller.createUserConfig(userHandle); 19303 } catch (InstallerException e) { 19304 Slog.w(TAG, "Failed to create user config", e); 19305 } 19306 mSettings.createNewUserLI(this, mInstaller, userHandle); 19307 } 19308 synchronized (mPackages) { 19309 applyFactoryDefaultBrowserLPw(userHandle); 19310 primeDomainVerificationsLPw(userHandle); 19311 } 19312 } 19313 19314 void newUserCreated(final int userHandle) { 19315 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19316 // If permission review for legacy apps is required, we represent 19317 // dagerous permissions for such apps as always granted runtime 19318 // permissions to keep per user flag state whether review is needed. 19319 // Hence, if a new user is added we have to propagate dangerous 19320 // permission grants for these legacy apps. 19321 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19322 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19323 | UPDATE_PERMISSIONS_REPLACE_ALL); 19324 } 19325 } 19326 19327 @Override 19328 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19329 mContext.enforceCallingOrSelfPermission( 19330 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19331 "Only package verification agents can read the verifier device identity"); 19332 19333 synchronized (mPackages) { 19334 return mSettings.getVerifierDeviceIdentityLPw(); 19335 } 19336 } 19337 19338 @Override 19339 public void setPermissionEnforced(String permission, boolean enforced) { 19340 // TODO: Now that we no longer change GID for storage, this should to away. 19341 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19342 "setPermissionEnforced"); 19343 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19344 synchronized (mPackages) { 19345 if (mSettings.mReadExternalStorageEnforced == null 19346 || mSettings.mReadExternalStorageEnforced != enforced) { 19347 mSettings.mReadExternalStorageEnforced = enforced; 19348 mSettings.writeLPr(); 19349 } 19350 } 19351 // kill any non-foreground processes so we restart them and 19352 // grant/revoke the GID. 19353 final IActivityManager am = ActivityManagerNative.getDefault(); 19354 if (am != null) { 19355 final long token = Binder.clearCallingIdentity(); 19356 try { 19357 am.killProcessesBelowForeground("setPermissionEnforcement"); 19358 } catch (RemoteException e) { 19359 } finally { 19360 Binder.restoreCallingIdentity(token); 19361 } 19362 } 19363 } else { 19364 throw new IllegalArgumentException("No selective enforcement for " + permission); 19365 } 19366 } 19367 19368 @Override 19369 @Deprecated 19370 public boolean isPermissionEnforced(String permission) { 19371 return true; 19372 } 19373 19374 @Override 19375 public boolean isStorageLow() { 19376 final long token = Binder.clearCallingIdentity(); 19377 try { 19378 final DeviceStorageMonitorInternal 19379 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19380 if (dsm != null) { 19381 return dsm.isMemoryLow(); 19382 } else { 19383 return false; 19384 } 19385 } finally { 19386 Binder.restoreCallingIdentity(token); 19387 } 19388 } 19389 19390 @Override 19391 public IPackageInstaller getPackageInstaller() { 19392 return mInstallerService; 19393 } 19394 19395 private boolean userNeedsBadging(int userId) { 19396 int index = mUserNeedsBadging.indexOfKey(userId); 19397 if (index < 0) { 19398 final UserInfo userInfo; 19399 final long token = Binder.clearCallingIdentity(); 19400 try { 19401 userInfo = sUserManager.getUserInfo(userId); 19402 } finally { 19403 Binder.restoreCallingIdentity(token); 19404 } 19405 final boolean b; 19406 if (userInfo != null && userInfo.isManagedProfile()) { 19407 b = true; 19408 } else { 19409 b = false; 19410 } 19411 mUserNeedsBadging.put(userId, b); 19412 return b; 19413 } 19414 return mUserNeedsBadging.valueAt(index); 19415 } 19416 19417 @Override 19418 public KeySet getKeySetByAlias(String packageName, String alias) { 19419 if (packageName == null || alias == null) { 19420 return null; 19421 } 19422 synchronized(mPackages) { 19423 final PackageParser.Package pkg = mPackages.get(packageName); 19424 if (pkg == null) { 19425 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19426 throw new IllegalArgumentException("Unknown package: " + packageName); 19427 } 19428 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19429 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19430 } 19431 } 19432 19433 @Override 19434 public KeySet getSigningKeySet(String packageName) { 19435 if (packageName == null) { 19436 return null; 19437 } 19438 synchronized(mPackages) { 19439 final PackageParser.Package pkg = mPackages.get(packageName); 19440 if (pkg == null) { 19441 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19442 throw new IllegalArgumentException("Unknown package: " + packageName); 19443 } 19444 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19445 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19446 throw new SecurityException("May not access signing KeySet of other apps."); 19447 } 19448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19449 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19450 } 19451 } 19452 19453 @Override 19454 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19455 if (packageName == null || ks == null) { 19456 return false; 19457 } 19458 synchronized(mPackages) { 19459 final PackageParser.Package pkg = mPackages.get(packageName); 19460 if (pkg == null) { 19461 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19462 throw new IllegalArgumentException("Unknown package: " + packageName); 19463 } 19464 IBinder ksh = ks.getToken(); 19465 if (ksh instanceof KeySetHandle) { 19466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19467 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19468 } 19469 return false; 19470 } 19471 } 19472 19473 @Override 19474 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19475 if (packageName == null || ks == null) { 19476 return false; 19477 } 19478 synchronized(mPackages) { 19479 final PackageParser.Package pkg = mPackages.get(packageName); 19480 if (pkg == null) { 19481 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19482 throw new IllegalArgumentException("Unknown package: " + packageName); 19483 } 19484 IBinder ksh = ks.getToken(); 19485 if (ksh instanceof KeySetHandle) { 19486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19487 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19488 } 19489 return false; 19490 } 19491 } 19492 19493 private void deletePackageIfUnusedLPr(final String packageName) { 19494 PackageSetting ps = mSettings.mPackages.get(packageName); 19495 if (ps == null) { 19496 return; 19497 } 19498 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19499 // TODO Implement atomic delete if package is unused 19500 // It is currently possible that the package will be deleted even if it is installed 19501 // after this method returns. 19502 mHandler.post(new Runnable() { 19503 public void run() { 19504 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19505 } 19506 }); 19507 } 19508 } 19509 19510 /** 19511 * Check and throw if the given before/after packages would be considered a 19512 * downgrade. 19513 */ 19514 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19515 throws PackageManagerException { 19516 if (after.versionCode < before.mVersionCode) { 19517 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19518 "Update version code " + after.versionCode + " is older than current " 19519 + before.mVersionCode); 19520 } else if (after.versionCode == before.mVersionCode) { 19521 if (after.baseRevisionCode < before.baseRevisionCode) { 19522 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19523 "Update base revision code " + after.baseRevisionCode 19524 + " is older than current " + before.baseRevisionCode); 19525 } 19526 19527 if (!ArrayUtils.isEmpty(after.splitNames)) { 19528 for (int i = 0; i < after.splitNames.length; i++) { 19529 final String splitName = after.splitNames[i]; 19530 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19531 if (j != -1) { 19532 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19533 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19534 "Update split " + splitName + " revision code " 19535 + after.splitRevisionCodes[i] + " is older than current " 19536 + before.splitRevisionCodes[j]); 19537 } 19538 } 19539 } 19540 } 19541 } 19542 } 19543 19544 private static class MoveCallbacks extends Handler { 19545 private static final int MSG_CREATED = 1; 19546 private static final int MSG_STATUS_CHANGED = 2; 19547 19548 private final RemoteCallbackList<IPackageMoveObserver> 19549 mCallbacks = new RemoteCallbackList<>(); 19550 19551 private final SparseIntArray mLastStatus = new SparseIntArray(); 19552 19553 public MoveCallbacks(Looper looper) { 19554 super(looper); 19555 } 19556 19557 public void register(IPackageMoveObserver callback) { 19558 mCallbacks.register(callback); 19559 } 19560 19561 public void unregister(IPackageMoveObserver callback) { 19562 mCallbacks.unregister(callback); 19563 } 19564 19565 @Override 19566 public void handleMessage(Message msg) { 19567 final SomeArgs args = (SomeArgs) msg.obj; 19568 final int n = mCallbacks.beginBroadcast(); 19569 for (int i = 0; i < n; i++) { 19570 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19571 try { 19572 invokeCallback(callback, msg.what, args); 19573 } catch (RemoteException ignored) { 19574 } 19575 } 19576 mCallbacks.finishBroadcast(); 19577 args.recycle(); 19578 } 19579 19580 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19581 throws RemoteException { 19582 switch (what) { 19583 case MSG_CREATED: { 19584 callback.onCreated(args.argi1, (Bundle) args.arg2); 19585 break; 19586 } 19587 case MSG_STATUS_CHANGED: { 19588 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19589 break; 19590 } 19591 } 19592 } 19593 19594 private void notifyCreated(int moveId, Bundle extras) { 19595 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19596 19597 final SomeArgs args = SomeArgs.obtain(); 19598 args.argi1 = moveId; 19599 args.arg2 = extras; 19600 obtainMessage(MSG_CREATED, args).sendToTarget(); 19601 } 19602 19603 private void notifyStatusChanged(int moveId, int status) { 19604 notifyStatusChanged(moveId, status, -1); 19605 } 19606 19607 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19608 Slog.v(TAG, "Move " + moveId + " status " + status); 19609 19610 final SomeArgs args = SomeArgs.obtain(); 19611 args.argi1 = moveId; 19612 args.argi2 = status; 19613 args.arg3 = estMillis; 19614 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19615 19616 synchronized (mLastStatus) { 19617 mLastStatus.put(moveId, status); 19618 } 19619 } 19620 } 19621 19622 private final static class OnPermissionChangeListeners extends Handler { 19623 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19624 19625 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19626 new RemoteCallbackList<>(); 19627 19628 public OnPermissionChangeListeners(Looper looper) { 19629 super(looper); 19630 } 19631 19632 @Override 19633 public void handleMessage(Message msg) { 19634 switch (msg.what) { 19635 case MSG_ON_PERMISSIONS_CHANGED: { 19636 final int uid = msg.arg1; 19637 handleOnPermissionsChanged(uid); 19638 } break; 19639 } 19640 } 19641 19642 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19643 mPermissionListeners.register(listener); 19644 19645 } 19646 19647 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19648 mPermissionListeners.unregister(listener); 19649 } 19650 19651 public void onPermissionsChanged(int uid) { 19652 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19653 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19654 } 19655 } 19656 19657 private void handleOnPermissionsChanged(int uid) { 19658 final int count = mPermissionListeners.beginBroadcast(); 19659 try { 19660 for (int i = 0; i < count; i++) { 19661 IOnPermissionsChangeListener callback = mPermissionListeners 19662 .getBroadcastItem(i); 19663 try { 19664 callback.onPermissionsChanged(uid); 19665 } catch (RemoteException e) { 19666 Log.e(TAG, "Permission listener is dead", e); 19667 } 19668 } 19669 } finally { 19670 mPermissionListeners.finishBroadcast(); 19671 } 19672 } 19673 } 19674 19675 private class PackageManagerInternalImpl extends PackageManagerInternal { 19676 @Override 19677 public void setLocationPackagesProvider(PackagesProvider provider) { 19678 synchronized (mPackages) { 19679 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19680 } 19681 } 19682 19683 @Override 19684 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19685 synchronized (mPackages) { 19686 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19687 } 19688 } 19689 19690 @Override 19691 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19692 synchronized (mPackages) { 19693 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19694 } 19695 } 19696 19697 @Override 19698 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19699 synchronized (mPackages) { 19700 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19701 } 19702 } 19703 19704 @Override 19705 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19706 synchronized (mPackages) { 19707 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19708 } 19709 } 19710 19711 @Override 19712 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19713 synchronized (mPackages) { 19714 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19715 } 19716 } 19717 19718 @Override 19719 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19720 synchronized (mPackages) { 19721 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19722 packageName, userId); 19723 } 19724 } 19725 19726 @Override 19727 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19728 synchronized (mPackages) { 19729 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19730 packageName, userId); 19731 } 19732 } 19733 19734 @Override 19735 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19736 synchronized (mPackages) { 19737 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19738 packageName, userId); 19739 } 19740 } 19741 19742 @Override 19743 public void setKeepUninstalledPackages(final List<String> packageList) { 19744 Preconditions.checkNotNull(packageList); 19745 List<String> removedFromList = null; 19746 synchronized (mPackages) { 19747 if (mKeepUninstalledPackages != null) { 19748 final int packagesCount = mKeepUninstalledPackages.size(); 19749 for (int i = 0; i < packagesCount; i++) { 19750 String oldPackage = mKeepUninstalledPackages.get(i); 19751 if (packageList != null && packageList.contains(oldPackage)) { 19752 continue; 19753 } 19754 if (removedFromList == null) { 19755 removedFromList = new ArrayList<>(); 19756 } 19757 removedFromList.add(oldPackage); 19758 } 19759 } 19760 mKeepUninstalledPackages = new ArrayList<>(packageList); 19761 if (removedFromList != null) { 19762 final int removedCount = removedFromList.size(); 19763 for (int i = 0; i < removedCount; i++) { 19764 deletePackageIfUnusedLPr(removedFromList.get(i)); 19765 } 19766 } 19767 } 19768 } 19769 19770 @Override 19771 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19772 synchronized (mPackages) { 19773 // If we do not support permission review, done. 19774 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19775 return false; 19776 } 19777 19778 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19779 if (packageSetting == null) { 19780 return false; 19781 } 19782 19783 // Permission review applies only to apps not supporting the new permission model. 19784 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19785 return false; 19786 } 19787 19788 // Legacy apps have the permission and get user consent on launch. 19789 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19790 return permissionsState.isPermissionReviewRequired(userId); 19791 } 19792 } 19793 19794 @Override 19795 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19796 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19797 } 19798 19799 @Override 19800 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19801 int userId) { 19802 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19803 } 19804 } 19805 19806 @Override 19807 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19808 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19809 synchronized (mPackages) { 19810 final long identity = Binder.clearCallingIdentity(); 19811 try { 19812 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19813 packageNames, userId); 19814 } finally { 19815 Binder.restoreCallingIdentity(identity); 19816 } 19817 } 19818 } 19819 19820 private static void enforceSystemOrPhoneCaller(String tag) { 19821 int callingUid = Binder.getCallingUid(); 19822 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19823 throw new SecurityException( 19824 "Cannot call " + tag + " from UID " + callingUid); 19825 } 19826 } 19827 19828 boolean isHistoricalPackageUsageAvailable() { 19829 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19830 } 19831 19832 /** 19833 * Return a <b>copy</b> of the collection of packages known to the package manager. 19834 * @return A copy of the values of mPackages. 19835 */ 19836 Collection<PackageParser.Package> getPackages() { 19837 synchronized (mPackages) { 19838 return new ArrayList<>(mPackages.values()); 19839 } 19840 } 19841 19842 /** 19843 * Logs process start information (including base APK hash) to the security log. 19844 * @hide 19845 */ 19846 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19847 String apkFile, int pid) { 19848 if (!SecurityLog.isLoggingEnabled()) { 19849 return; 19850 } 19851 Bundle data = new Bundle(); 19852 data.putLong("startTimestamp", System.currentTimeMillis()); 19853 data.putString("processName", processName); 19854 data.putInt("uid", uid); 19855 data.putString("seinfo", seinfo); 19856 data.putString("apkFile", apkFile); 19857 data.putInt("pid", pid); 19858 Message msg = mProcessLoggingHandler.obtainMessage( 19859 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19860 msg.setData(data); 19861 mProcessLoggingHandler.sendMessage(msg); 19862 } 19863} 19864